Compare commits

..
5 Commits
Author SHA1 Message Date
randy 81e688be9b Record per-step timings of offline/terrain builds
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 38s
Live in build-status while running; every finished build (done or
error) is appended to data/build_history.jsonl with its step timings,
regions, thread count and, for offline builds, the tail of Planetiler's
output (its own per-phase summary). GET /api/build-history, shown in the
debug panel, gives a baseline to compare later builds against.
2026-11-12 11:54:49 +01:00
randy 7429e4ae33 Zip upload: reject archives over 500 MB uncompressed
Sums the entries' declared sizes before extracting anything; rubyzip's
own validate_entry_sizes (on by default) catches an entry that inflates
past what it declared.
2026-11-12 11:54:49 +01:00
randy ca2e67599b Sun & moon chart: click the topbar's sun readout
A horizon-style chart drawn from the vendored suncalc, so fully offline:
real sun and moon altitude over the 24 h around solar noon, sunrise/
sunset lines, dawn/noon/dusk on the time axis, the moon in its current
phase, plus moonrise/set, phase and current sun/moon position below.
Polar day/night now shows as a label instead of hiding the readout.
2026-11-12 11:54:49 +01:00
randy cf483d183c Add a logged-in-only status/debug panel at the bottom of the sidebar
Dumps every read-only status endpoint (health, offline/terrain build
status, regions, caches, hiking trails, kiwix, plugins, GNSS, LiveTrack)
as JSON, refreshed every 5s while open so a running build's progress
shows live.
2026-11-12 11:37:42 +01:00
randy 0051a0337c Search: look through all saved layers and offline hiking trails
GET /api/search (lib/maptool/search.rb) matches feature name and
description, case- and diacritics-insensitive, across every file in
Tracks & Points (shown or not) and every offline hiking-trails country.
Parsed features are cached in memory per file by mtime.

The search box now queries local sources and Nominatim side by side,
labels each result with where it was found, lets you untick sources,
and switches a result's layer on if it was off before zooming to it.
2026-11-12 11:37:42 +01:00
18 changed files with 826 additions and 35 deletions

No files matched your search

+10
View File
@@ -59,6 +59,16 @@ independence from connectivity.
** [x] Fixed: the Unigrid Matrix category filter only re-sliced the *points* source (`_applyCategoryFilter`) — toggling the "Note" category off hid point notes but not polygon/line ones sharing that category. `_linesByPath` now tracks those alongside `_pointsByPath`, re-sliced/scanned the same way ** [x] Fixed: the Unigrid Matrix category filter only re-sliced the *points* source (`_applyCategoryFilter`) — toggling the "Note" category off hid point notes but not polygon/line ones sharing that category. `_linesByPath` now tracks those alongside `_pointsByPath`, re-sliced/scanned the same way
* [ ] Offline satellite tile caching (e.g. ESRI) for a selected route area — key for judging surface quality and obstacles when wild camping * [ ] Offline satellite tile caching (e.g. ESRI) for a selected route area — key for judging surface quality and obstacles when wild camping
== Search
* [ ] Unified search box — one query across every data source, not just what's currently on the map. `GET /api/search` (`lib/maptool/search.rb`) for local sources, online ones queried from the browser (`public/js/search.js`)
** [x] Every layer under Tracks & Points (GPX, FIT, GeoJSON, notes, plugin output) and offline hiking trails — shown *and* hidden ones. Matches name + description, case/diacritics-insensitive ("kosice" finds "Košice"); parsed features cached in memory per file by mtime
** [ ] Offline vector data — `offline.pmtiles` is tiles, not searchable by name; extract named places/POIs from the same Geofabrik `.osm.pbf` with `osmium tags-filter` during the offline build (same pattern as `HikingTrails`) into a per-country index, then one more key in `Search::SOURCES`. Probably needs SQLite FTS5 (`sqlite3` gem) at that size instead of the in-memory scan
** [x] Every result shows where it was found (layer file / "Hiking trails SK" / "Online · Nominatim"); clicking one zooms to it (fitBounds for a track) and switches its layer on if it was off
** [x] Source checklist in the search panel (all on by default), re-runs the search on change
** [x] Online sources pluggable — one more entry in search.js's `SOURCES`; Nominatim already in, its failure only adds a "no connection" line under the local results
** [ ] Kiwix as a source (its geo/full-text search already backs `GET /api/kiwix/nearby`)
== Nice to have (later) == Nice to have (later)
Deprioritized for now — revisit after the sections above land. Deprioritized for now — revisit after the sections above land.
+25 -2
View File
@@ -13,6 +13,7 @@ require_relative "lib/maptool/livetrack_client"
require_relative "lib/maptool/kiwix" require_relative "lib/maptool/kiwix"
require_relative "lib/maptool/plugins" require_relative "lib/maptool/plugins"
require_relative "lib/maptool/pmtiles_builder" require_relative "lib/maptool/pmtiles_builder"
require_relative "lib/maptool/search"
module Maptool module Maptool
# Only /login, /auth/callback and /logout ever write to session # Only /login, /auth/callback and /logout ever write to session
@@ -172,12 +173,19 @@ module Maptool
"#{request.base_url}/auth/callback" "#{request.base_url}/auth/callback"
end end
# Zip-bomb guard: the entries' *declared* uncompressed sizes are summed
# before anything is extracted, and rubyzip itself (validate_entry_sizes,
# on by default) raises Zip::EntrySizeError if an entry inflates past
# what it declared — so a lying header can't sneak past this either.
MAX_ZIP_UNCOMPRESSED = 500 * 1024 * 1024
def save_zip_entries(folder:, io:) def save_zip_entries(folder:, io:)
paths = [] paths = []
Zip::File.open_buffer(io) do |zip| Zip::File.open_buffer(io) do |zip|
zip.each do |entry| entries = zip.select { |entry| entry.file? && GpxStore::TRACK_EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } }
next unless entry.file? && GpxStore::TRACK_EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } halt 413, json(error: "zip contents too large") if entries.sum(&:size) > MAX_ZIP_UNCOMPRESSED
entries.each do |entry|
paths << GPX_STORE.save(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read)) paths << GPX_STORE.save(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read))
end end
end end
@@ -312,6 +320,12 @@ module Maptool
json PmtilesBuilder.offline_status json PmtilesBuilder.offline_status
end end
# Per-step timings of past offline/terrain builds, newest first — the
# "benchmark" to compare a later build against (debug panel).
get "/api/build-history" do
json PmtilesBuilder.build_history(DATA_DIR)
end
# Deletes offline.pmtiles plus its whole per-country download cache — # Deletes offline.pmtiles plus its whole per-country download cache —
# a manual "reclaim the space"/"start over" action, distinct from # a manual "reclaim the space"/"start over" action, distinct from
# unticking countries in the region picker (which only changes what a # unticking countries in the region picker (which only changes what a
@@ -419,6 +433,15 @@ module Maptool
send_file path, type: "application/geo+json" send_file path, type: "application/geo+json"
end end
# The search box's local half (public/js/search.js) — every saved
# layer, shown or not, plus offline hiking trails. Read-only and
# login-free like the tree listing: viewing needs no account.
get "/api/search" do
sources = params[:sources].to_s.split(",")
sources = Search::SOURCES.keys if sources.empty?
json results: Search.query(params[:q], gpx_store: GPX_STORE, data_dir: DATA_DIR, sources: sources)
end
# Pinged once per page load (public/js/map.js) — url is a same-origin # Pinged once per page load (public/js/map.js) — url is a same-origin
# path (not kiwix-serve's own address, which the browser can't reach # path (not kiwix-serve's own address, which the browser can't reach
# directly behind the reverse proxy in front of this app), proxied by # directly behind the reverse proxy in front of this app), proxied by
+88 -9
View File
@@ -105,13 +105,58 @@ module Maptool
TERRAIN_MUTEX = Mutex.new TERRAIN_MUTEX = Mutex.new
def self.offline_status def self.offline_status
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.dup } OFFLINE_MUTEX.synchronize { with_live_timings(OFFLINE_STATUS) }
end end
def self.terrain_status def self.terrain_status
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.dup } TERRAIN_MUTEX.synchronize { with_live_timings(TERRAIN_STATUS) }
end end
# While running, status[:steps] holds raw [label, monotonic start]
# pairs — rendered here into per-step seconds, the running one counting
# up, so the debug panel shows where a build is spending its time.
def self.with_live_timings(status)
copy = status.dup
steps = copy.delete(:steps)
copy[:timings] = step_durations(steps, monotonic_now) if steps
copy
end
private_class_method :with_live_timings
# --- build history ("benchmark") ---
# One JSON line per finished build (offline or terrain, done or error)
# with per-step timings — a record to compare later builds against,
# e.g. after tuning Planetiler's JVM heap. Kept across redeploys since
# it lives in data/.
def self.build_history_path(data_dir)
File.join(data_dir, "build_history.jsonl")
end
# Newest first.
def self.build_history(data_dir, limit: 50)
path = build_history_path(data_dir)
return [] unless File.exist?(path)
File.readlines(path).last(limit).reverse.filter_map do |line|
JSON.parse(line)
rescue JSON::ParserError
nil
end
end
def self.monotonic_now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
private_class_method :monotonic_now
def self.step_durations(steps, finished)
steps.each_with_index.map do |(label, started), i|
{ step: label, seconds: ((steps[i + 1]&.last || finished) - started).round(1) }
end
end
private_class_method :step_durations
# Test-only: the status hashes are process-wide state (same caveat as # Test-only: the status hashes are process-wide state (same caveat as
# GPX_STORE/LIVETRACK_STORE in app.rb), so the suite needs a way to # GPX_STORE/LIVETRACK_STORE in app.rb), so the suite needs a way to
# reset them between tests the way AppTestHelper#teardown already does # reset them between tests the way AppTestHelper#teardown already does
@@ -196,7 +241,7 @@ module Maptool
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS) begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
Thread.new do Thread.new do
run_job(OFFLINE_MUTEX, OFFLINE_STATUS) do |report_step| run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step) extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
end end
end end
@@ -210,7 +255,7 @@ module Maptool
begin_run!(TERRAIN_MUTEX, TERRAIN_STATUS) begin_run!(TERRAIN_MUTEX, TERRAIN_STATUS)
Thread.new do Thread.new do
run_job(TERRAIN_MUTEX, TERRAIN_STATUS) do |report_step| run_job(TERRAIN_MUTEX, TERRAIN_STATUS, kind: "terrain", data_dir: data_dir, regions: codes) do |report_step|
build_terrain_pmtiles(codes, data_dir, fetch_manifest, report_step) build_terrain_pmtiles(codes, data_dir, fetch_manifest, report_step)
end end
end end
@@ -229,15 +274,44 @@ module Maptool
# SK (1/2)", "tiling with planetiler", ...) — surfaced as status[:step] # SK (1/2)", "tiling with planetiler", ...) — surfaced as status[:step]
# so GET .../build-status can show progress beyond just "running since # so GET .../build-status can show progress beyond just "running since
# X" (see docs/development.adoc). # X" (see docs/development.adoc).
def self.run_job(mutex, status) #
report_step = ->(text) { mutex.synchronize { status[:step] = text } } # Each step's wall time is recorded too (label without its "— done: …"
yield report_step # progress suffix) and the whole run appended to the build history
# above. The block may return { log: "..." } — Planetiler's own closing
# summary, with its per-phase breakdown — to keep alongside.
def self.run_job(mutex, status, kind:, data_dir:, regions:)
started = monotonic_now
steps = []
report_step = lambda do |text|
mutex.synchronize do
steps << [text.split(" — ").first, monotonic_now]
status[:step] = text
status[:steps] = steps
end
end
result = yield report_step
mutex.synchronize { status.merge!(state: "done", finished_at: Time.now.utc.iso8601).delete(:message) } mutex.synchronize { status.merge!(state: "done", finished_at: Time.now.utc.iso8601).delete(:message) }
rescue => e rescue => e
mutex.synchronize { status.merge!(state: "error", finished_at: Time.now.utc.iso8601, message: e.message) } mutex.synchronize { status.merge!(state: "error", finished_at: Time.now.utc.iso8601, message: e.message) }
ensure ensure
mutex.synchronize { status.delete(:step) } mutex.synchronize do
status.delete(:step)
status.delete(:steps)
finished = monotonic_now
status[:timings] = step_durations(steps, finished)
status[:total_seconds] = (finished - started).round(1)
record_build(data_dir, kind: kind, regions: regions, status: status, log: result.is_a?(Hash) ? result[:log] : nil)
end end
end
def self.record_build(data_dir, kind:, regions:, status:, log:)
entry = { kind: kind, regions: regions, threads: Etc.nprocessors, log: log }
.merge(status.slice(:state, :started_at, :finished_at, :total_seconds, :timings, :message)).compact
File.open(build_history_path(data_dir), "a") { |f| f.puts(JSON.generate(entry)) }
rescue SystemCallError
nil # a history write failing must never turn a finished build into an error
end
private_class_method :record_build
private_class_method :run_job private_class_method :run_job
# --- offline.pmtiles --- # --- offline.pmtiles ---
@@ -287,12 +361,13 @@ module Maptool
# leaving most of a many-core host idle — Etc.nprocessors asks the # leaving most of a many-core host idle — Etc.nprocessors asks the
# OS directly (sched_getaffinity on Linux), which correctly reflects # OS directly (sched_getaffinity on Linux), which correctly reflects
# whatever's actually usable by this process even under a container. # whatever's actually usable by this process even under a container.
run_planetiler!("--osm-path=#{osm_path}", "--output=#{tmp_path}", "--download", "--threads=#{Etc.nprocessors}") planetiler_log = run_planetiler!("--osm-path=#{osm_path}", "--output=#{tmp_path}", "--download", "--threads=#{Etc.nprocessors}")
File.rename(tmp_path, File.join(data_dir, "offline.pmtiles")) File.rename(tmp_path, File.join(data_dir, "offline.pmtiles"))
File.write(offline_meta_path(data_dir), JSON.generate(sources: sources.map { |s| s.slice("code", "slug", "last_modified") })) File.write(offline_meta_path(data_dir), JSON.generate(sources: sources.map { |s| s.slice("code", "slug", "last_modified") }))
report_step.call("extracting hiking trails") report_step.call("extracting hiking trails")
extract_hiking_trails(sources, data_dir) extract_hiking_trails(sources, data_dir)
{ log: planetiler_log }
ensure ensure
FileUtils.remove_entry(scratch_dir) if scratch_dir && Dir.exist?(scratch_dir) FileUtils.remove_entry(scratch_dir) if scratch_dir && Dir.exist?(scratch_dir)
File.delete(tmp_path) if tmp_path && File.exist?(tmp_path) File.delete(tmp_path) if tmp_path && File.exist?(tmp_path)
@@ -734,9 +809,13 @@ module Maptool
end end
private_class_method :run_osmium! private_class_method :run_osmium!
# Returns the output's tail — on success that's Planetiler's closing
# summary (per-phase times, memory), kept in the build history.
def self.run_planetiler!(*args) def self.run_planetiler!(*args)
stdout, stderr, status = Open3.capture3(java_bin, "-jar", planetiler_jar, *args) stdout, stderr, status = Open3.capture3(java_bin, "-jar", planetiler_jar, *args)
raise BuildError, "planetiler exited with status #{status.exitstatus}: #{command_output(stdout, stderr)}" unless status.success? raise BuildError, "planetiler exited with status #{status.exitstatus}: #{command_output(stdout, stderr)}" unless status.success?
command_output(stdout, stderr)
rescue Errno::ENOENT, Errno::EACCES => e rescue Errno::ENOENT, Errno::EACCES => e
raise BuildError, "could not run '#{java_bin} -jar #{planetiler_jar}' (#{e.message}) — is Java and planetiler.jar installed? See docs/development.adoc." raise BuildError, "could not run '#{java_bin} -jar #{planetiler_jar}' (#{e.message}) — is Java and planetiler.jar installed? See docs/development.adoc."
end end
+103
View File
@@ -0,0 +1,103 @@
require "json"
require_relative "gpx"
require_relative "fit"
require_relative "pmtiles_builder"
module Maptool
# Server-side half of the search box (public/js/search.js): looks through
# every saved layer, whether it's currently shown on the map or not, and
# every offline hiking-trails country. Online providers (Nominatim) are
# queried by the browser itself, so this route keeps working with no
# uplink at all.
#
# Each source is a name -> a list of [label, ref, file on disk, reader]
# entries (ref is what the browser needs to switch that layer on).
# Adding one (e.g. an offline place-name index pulled from the Geofabrik
# PBF) means adding a key to SOURCES and nothing else.
module Search
LIMIT = 50
SOURCES = {
"layers" => lambda do |gpx_store, _data_dir|
files(gpx_store.tree).map do |path|
[path, path, gpx_store.resolve_file(path), -> { gpx_store.geojson(path) }]
end
end,
"hiking_trails" => lambda do |_gpx_store, data_dir|
PmtilesBuilder.hiking_trails_countries(data_dir).map do |code|
path = PmtilesBuilder.hiking_trails_country_path(data_dir, code)
["Hiking trails #{code}", code, path, -> { File.read(path) }]
end
end,
}.freeze
# path => [mtime, entries] — a country's hiking-trails file runs to tens
# of MB, so it's parsed once per change, not once per keystroke.
# ponytail: unbounded in-memory cache, fine for a handful of files; an
# on-disk/SQLite FTS index once the offline place-name source lands.
@cache = {}
def self.query(text, gpx_store:, data_dir:, sources: SOURCES.keys)
words = normalize(text).split
return [] if words.empty?
results = []
(sources & SOURCES.keys).each do |source|
SOURCES[source].call(gpx_store, data_dir).each do |label, ref, disk_path, read|
entries(disk_path, read).each do |entry|
next unless words.all? { |word| entry[:text].include?(word) }
results << entry.except(:text).merge(source: source, source_label: label, ref: ref)
return results if results.size >= LIMIT
end
end
end
results
end
# Lowercased, diacritics stripped — "kosice" finds "Košice".
def self.normalize(text)
text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase
end
def self.entries(path, read)
mtime = File.mtime(path)
cached = @cache[path]
return cached[1] if cached && cached[0] == mtime
entries = begin
JSON.parse(read.call).fetch("features", []).filter_map { |feature| entry(feature, File.basename(path)) }
rescue JSON::ParserError, Gpx::ParseError, Fit::ParseError, Errno::ENOENT
[]
end
@cache[path] = [mtime, entries]
entries
end
def self.entry(feature, fallback_name)
coords = feature.dig("geometry", "coordinates")
return nil unless coords.is_a?(Array) && !coords.empty?
props = feature["properties"] || {}
name = props["name"].to_s.strip
name = fallback_name if name.empty?
lngs, lats = positions(coords).map { |p| p.first(2) }.transpose
{
name: name,
kind: props["kind"] || feature.dig("geometry", "type"),
bbox: [lngs.min, lats.min, lngs.max, lats.max],
text: normalize("#{name} #{props["description"]}"),
}
end
def self.positions(coords)
coords.first.is_a?(Numeric) ? [coords] : coords.flat_map { |c| positions(c) }
end
def self.files(node)
(node["children"] || []).flat_map do |child|
child["type"] == "folder" ? files(child) : [child["path"]]
end
end
end
end
+151
View File
@@ -91,6 +91,115 @@ html, body {
display: none; display: none;
} }
.topbar__sun {
cursor: pointer;
}
.topbar__sun:hover {
color: #fff;
}
/* Horizon-style sun & moon chart, dropped down from the topbar's sun
readout (sun.js sunChartHtml). */
.sun-chart {
position: fixed;
top: 52px;
left: 50%;
transform: translateX(-50%);
z-index: 30;
width: 340px;
max-width: calc(100vw - 32px);
box-sizing: border-box;
padding: 10px;
background: #1a1a1a;
color: #ddd;
border-radius: 6px;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);
font-size: 12px;
}
.sun-chart[hidden] {
display: none;
}
.sun-chart__graph {
display: block;
width: 100%;
height: auto;
}
.sun-chart__night {
fill: #262a33;
}
.sun-chart__horizon {
stroke: #888;
stroke-width: 1;
}
.sun-chart__mark {
stroke: #555;
stroke-dasharray: 3 3;
}
.sun-chart__tick {
stroke: #888;
}
.sun-chart__label {
fill: #bbb;
font-size: 9px;
text-anchor: middle;
font-variant-numeric: tabular-nums;
}
.sun-chart__sun-path {
fill: none;
stroke: #666;
stroke-width: 2;
}
.sun-chart__sun-path--day {
stroke: #f2b632;
}
.sun-chart__moon-path {
fill: none;
stroke: #8fa3c7;
stroke-width: 1;
stroke-dasharray: 2 3;
}
.sun-chart__sun {
fill: #f2b632;
}
.sun-chart__moon-shadow {
fill: #3a3f4b;
stroke: #8fa3c7;
stroke-width: 0.5;
}
.sun-chart__moon {
fill: #e8ecf4;
}
.sun-chart__fields {
display: grid;
grid-template-columns: auto 1fr;
gap: 2px 12px;
margin: 8px 0 0;
font-variant-numeric: tabular-nums;
}
.sun-chart__fields dt {
color: #999;
}
.sun-chart__fields dd {
margin: 0;
}
.topbar__offline-status { .topbar__offline-status {
width: 8px; width: 8px;
height: 8px; height: 8px;
@@ -142,6 +251,11 @@ html, body {
position: relative; position: relative;
} }
/* Pinned to the bottom of the rail (the sidebar is a flex column). */
.sidebar-item--bottom {
margin-top: auto;
}
.sidebar-group-label { .sidebar-group-label {
width: 28px; width: 28px;
height: 1px; height: 1px;
@@ -459,6 +573,27 @@ html, body {
} }
} }
.debug-panel__body {
padding: 8px 12px;
overflow-y: auto;
}
.debug-panel__body summary {
cursor: pointer;
font-family: monospace;
padding: 3px 0;
}
.debug-panel__body pre {
margin: 2px 0 8px;
padding: 6px;
background: #f6f6f6;
border-radius: 4px;
font-size: 11px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.offline-data-panel__body { .offline-data-panel__body {
padding: 8px 12px; padding: 8px 12px;
} }
@@ -1164,6 +1299,22 @@ html, body {
color: #888; color: #888;
} }
.search-panel__sources {
display: flex;
flex-wrap: wrap;
gap: 2px 10px;
margin-top: 6px;
font-size: 12px;
color: #555;
}
.search-panel__where {
display: block;
font-size: 11px;
color: #888;
overflow-wrap: anywhere;
}
.notes-ctrl { .notes-ctrl {
position: relative; position: relative;
} }
+92
View File
@@ -0,0 +1,92 @@
import { DEBUG_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
// Every read-only status endpoint, dumped as raw JSON. No check-update
// routes here — those reach out to Geofabrik/the internet, not just report
// local state.
const ENDPOINTS = [
"/api/health",
"/api/offline-tiles",
"/api/offline-tiles/build-status",
"/api/offline-regions",
"/api/offline-tiles/cache",
"/api/terrain-tiles",
"/api/terrain-tiles/build-status",
"/api/build-history",
"/api/hiking-trails",
"/api/kiwix",
"/api/plugins",
"/api/gnss/position",
"/api/livetrack/sessions",
];
const REFRESH_MS = 5000; // while open — a running build's progress shows up live
// Sidebar icon pinned to the bottom of the rail, logged-in only (map.js).
export class DebugControl {
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item sidebar-item--bottom";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Status / debug" aria-label="Status / debug">${DEBUG_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("debug-panel");
this._body = this._panel.querySelector(".debug-panel__body");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
onlyOneSidePanelOpen(this._panel, () => this._stop());
sidebar.appendChild(this._container);
}
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
if (!open) return this._stop();
this._icon.classList.add("active");
notifySidePanelOpen(this._panel);
this._refresh();
this._timer = setInterval(() => this._refresh(), REFRESH_MS);
}
_stop() {
this._icon.classList.remove("active");
clearInterval(this._timer);
}
async _refresh() {
const sections = await Promise.all(
ENDPOINTS.map(async (url) => {
let text;
try {
const response = await fetch(url);
const body = await response.text();
try {
text = JSON.stringify(JSON.parse(body), null, 2);
} catch {
text = body;
}
if (!response.ok) text = `HTTP ${response.status}\n${text}`;
} catch (error) {
text = `request failed: ${error.message}`;
}
return { url, text };
}),
);
if (this._panel.hidden) return;
// Keep whichever sections the user collapsed collapsed across refreshes.
const closed = new Set([...this._body.querySelectorAll("details:not([open])")].map((el) => el.dataset.url));
this._body.innerHTML = sections
.map(
({ url, text }) => `
<details data-url="${url}" ${closed.has(url) ? "" : "open"}>
<summary>${url}</summary>
<pre>${escapeHtml(text)}</pre>
</details>
`,
)
.join("");
}
}
+10
View File
@@ -301,6 +301,7 @@ export class GpxPanelControl {
const checkbox = document.createElement("input"); const checkbox = document.createElement("input");
checkbox.type = "checkbox"; checkbox.type = "checkbox";
checkbox.checked = this._visible.has(file.path); checkbox.checked = this._visible.has(file.path);
checkbox.dataset.path = file.path;
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox)); checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
// Just the real, as-uploaded name — it used to grow a ".geojson" suffix // Just the real, as-uploaded name — it used to grow a ".geojson" suffix
// once cached (matching the real "<path>.geojson" cache file on disk), // once cached (matching the real "<path>.geojson" cache file on disk),
@@ -482,6 +483,15 @@ export class GpxPanelControl {
}); });
} }
// Called by the search box (search.js) when a result comes from a file
// that isn't shown yet — same as ticking its box in the tree by hand.
show(path) {
if (this._visible.has(path)) return;
const checkbox = [...this._treeContainer.querySelectorAll("input[data-path]")].find((input) => input.dataset.path === path);
if (checkbox) checkbox.checked = true;
this._toggleFile(path, true, checkbox);
}
async _toggleFile(path, visible, checkbox) { async _toggleFile(path, visible, checkbox) {
if (visible) { if (visible) {
this._visible.add(path); this._visible.add(path);
+8
View File
@@ -180,6 +180,14 @@ export class HikingTrailsControl {
}); });
} }
// Search box (search.js) picked a trail from a country that isn't ticked.
showCountry(code) {
const input = [...this._countryList.querySelectorAll("input")].find((el) => el.value === code);
if (!input || input.checked) return;
input.checked = true;
this._toggleCountry(code, true);
}
_toggleOnline(active) { _toggleOnline(active) {
this._active = active; this._active = active;
if (active) this._addOnlineLayer(); if (active) this._addOnlineLayer();
+7
View File
@@ -436,6 +436,13 @@ export const OFFLINE_DATA_ICON = `
// OSM/p4n2gpx category and doubles as the note icon-picker's option list // OSM/p4n2gpx category and doubles as the note icon-picker's option list
// (notes.js), neither of which applies here — every point on this layer // (notes.js), neither of which applies here — every point on this layer
// gets the same one glyph, there's no per-feature category to key it by. // gets the same one glyph, there's no per-feature category to key it by.
// A bug — the status/debug panel (debug.js).
export const DEBUG_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
<rect x="7" y="7" width="10" height="13" rx="5"/>
<path d="M9 7a3 3 0 0 1 6 0M12 11v9M3 13h4M17 13h4M4 7l3 2M20 7l-3 2M4 19l3-2M20 19l-3-2"/>
</svg>`;
export const WIKI_ICON = ` export const WIKI_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"> <svg viewBox="0 0 22 22" fill="currentColor">
<path d="M16.6,20.7c-0.6,0-0.9-0.4-0.9-0.9c0-0.5,0.3-0.9,0.9-0.9c0.3,0,0.5-0.2,0.5-0.5 <path d="M16.6,20.7c-0.6,0-0.9-0.4-0.9-0.9c0-0.5,0.3-0.9,0.9-0.9c0.3,0,0.5-0.2,0.5-0.5
+31 -3
View File
@@ -17,9 +17,10 @@ import { LocateControl } from "/js/locate.js";
import { SearchControl } from "/js/search.js"; import { SearchControl } from "/js/search.js";
import { OfflineDataControl } from "/js/offline_data.js"; import { OfflineDataControl } from "/js/offline_data.js";
import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON } from "/js/icons.js"; import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON } from "/js/icons.js";
import { formatCoords, formatSunInfo } from "/js/sun.js"; import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js"; import { isLoggedIn } from "/js/auth.js";
import { DebugControl } from "/js/debug.js";
import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js";
import OverviewMap from "/vendor/npmap-overview/overview.esm.js"; import OverviewMap from "/vendor/npmap-overview/overview.esm.js";
import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs"; import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs";
@@ -444,7 +445,8 @@ const SLOVAKIA_BOUNDS = [
[16.83, 47.73], [16.83, 47.73],
[22.57, 49.61], [22.57, 49.61],
]; ];
map.addControl(new SearchControl(), "top-left"); const searchControl = new SearchControl();
map.addControl(searchControl, "top-left");
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-left"); map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-left");
// showCompass: false — this map never rotates, so a bearing-reset button // showCompass: false — this map never rotates, so a bearing-reset button
// (NavigationControl's default third button) would just be dead weight. // (NavigationControl's default third button) would just be dead weight.
@@ -516,11 +518,17 @@ coordsLabel.addEventListener("click", async () => {
// plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting // plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting
// down even while the map sits still. // down even while the map sits still.
const sunLabel = document.querySelector(".topbar__sun"); const sunLabel = document.querySelector(".topbar__sun");
const sunChart = document.querySelector(".sun-chart");
const updateSun = () => { const updateSun = () => {
const { lng, lat } = map.getCenter(); const { lng, lat } = map.getCenter();
if (!sunChart.hidden) sunChart.innerHTML = sunChartHtml(lat, lng);
const info = formatSunInfo(lat, lng); const info = formatSunInfo(lat, lng);
sunLabel.hidden = info === null; sunLabel.hidden = info === null;
if (!info) return; if (!info) return;
if (info.polar) {
sunLabel.innerHTML = `<span class="topbar__group"><span class="topbar__icon">${SUNRISE_ICON}</span><span>${info.polar}</span></span>`;
return;
}
const countdownGroup = info.countdown const countdownGroup = info.countdown
? `<span class="topbar__group"><span class="topbar__icon">${PENDING_ICON}</span><span>${info.countdown}</span></span>` ? `<span class="topbar__group"><span class="topbar__icon">${PENDING_ICON}</span><span>${info.countdown}</span></span>`
@@ -530,6 +538,19 @@ const updateSun = () => {
`<span class="topbar__group"><span class="topbar__icon">${SUNSET_ICON}</span><span>${info.sunset}</span></span>` + `<span class="topbar__group"><span class="topbar__icon">${SUNSET_ICON}</span><span>${info.sunset}</span></span>` +
countdownGroup; countdownGroup;
}; };
// Click opens the horizon-style sun & moon chart (sun.js), kept in sync by
// the same moveend/minute tick as the label itself.
sunLabel.addEventListener("click", (event) => {
event.stopPropagation();
sunChart.hidden = !sunChart.hidden;
updateSun();
});
document.addEventListener("click", (event) => {
if (!sunChart.contains(event.target)) sunChart.hidden = true;
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") sunChart.hidden = true;
});
updateSun(); updateSun();
map.on("moveend", updateSun); map.on("moveend", updateSun);
setInterval(updateSun, 60000); setInterval(updateSun, 60000);
@@ -545,9 +566,14 @@ const profilePanel = new TrackProfilePanel(map);
profilePanel.mount(); profilePanel.mount();
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Explorer"></div>`); sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Explorer"></div>`);
new GpxPanelControl(map, profilePanel).mount(sidebar); const gpxPanel = new GpxPanelControl(map, profilePanel);
gpxPanel.mount(sidebar);
const overlaysControl = new OverlaysControl(map); const overlaysControl = new OverlaysControl(map);
overlaysControl.mount(sidebar); overlaysControl.mount(sidebar);
searchControl.setLayerOpeners({
layers: (path) => gpxPanel.show(path),
hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code),
});
pitchToggle.setOverlaysControl(overlaysControl); pitchToggle.setOverlaysControl(overlaysControl);
// Running a plugin needs a login (POST /api/plugins/:name/run) — same // Running a plugin needs a login (POST /api/plugins/:name/run) — same
// "hide the write-only affordance" story as NotesControl above. // "hide the write-only affordance" story as NotesControl above.
@@ -562,6 +588,8 @@ sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title=
gnssControl.mount(sidebar); gnssControl.mount(sidebar);
new LiveTrackPanelControl(map).mount(sidebar); new LiveTrackPanelControl(map).mount(sidebar);
if (isLoggedIn()) new DebugControl().mount(sidebar);
// The sidebar already has a "Base map" icon (opens the same panel) — // The sidebar already has a "Base map" icon (opens the same panel) —
// this is a second entry point for it, grouped with Home/zoom on the map // this is a second entry point for it, grouped with Home/zoom on the map
// itself rather than off in the page's own side rail, matching NPS's // itself rather than off in the page's own side rail, matching NPS's
+4
View File
@@ -249,6 +249,10 @@ export class OverlaysControl {
this._hikingTrails.setOfflineCountries(countries); this._hikingTrails.setOfflineCountries(countries);
} }
showHikingTrailsCountry(code) {
this._hikingTrails.showCountry(code);
}
// Called by map.js's PitchToggleControl whenever the 3D pitch toggle // Called by map.js's PitchToggleControl whenever the 3D pitch toggle
// changes, so raised terrain follows the camera tilt rather than needing // changes, so raised terrain follows the camera tilt rather than needing
// the "Terrain shading" checkbox re-clicked to notice. // the "Terrain shading" checkbox re-clicked to notice.
+94 -19
View File
@@ -8,14 +8,32 @@ const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
// there with no network round-trip. // there with no network round-trip.
const COORD_PATTERN = /^\s*(-?\d+(?:\.\d+)?)\s*[, ]\s*(-?\d+(?:\.\d+)?)\s*$/; const COORD_PATTERN = /^\s*(-?\d+(?:\.\d+)?)\s*[, ]\s*(-?\d+(?:\.\d+)?)\s*$/;
// Sources the search box can look through, all ticked by default. "local"
// ones are answered by GET /api/search (every saved layer, shown or not,
// plus offline hiking trails — works with no uplink); "online" ones are
// queried straight from the browser and just come back empty when there's
// no connection. A new provider is one more entry here (plus, for a local
// one, a key in lib/maptool/search.rb's SOURCES).
const SOURCES = [
{ id: "layers", label: "My layers", local: true },
{ id: "hiking_trails", label: "Hiking trails", local: true },
{ id: "nominatim", label: "Online (Nominatim)", local: false },
];
// A place-name/coordinate search box, matching NPS's own Park Tiles viewer. // A place-name/coordinate search box, matching NPS's own Park Tiles viewer.
// Online only, like this app's other non-basemap online features (Radar, // Every result says where it was found; picking one from a layer that's
// the Wikipedia layer) — no offline geocoding index to fall back to. // currently switched off switches it on (see setLayerOpeners).
// Nominatim: OpenStreetMap's own geocoder, free, no API key, matching the
// online basemap's own OSM-derived style already used here.
export class SearchControl { export class SearchControl {
constructor() { constructor() {
this._results = []; this._results = [];
this._enabled = new Set(SOURCES.map((source) => source.id));
this._openers = {};
}
// { layers: (path) => ..., hiking_trails: (code) => ... } — set from
// map.js once the panels owning those layers exist.
setLayerOpeners(openers) {
this._openers = openers;
} }
onAdd(map) { onAdd(map) {
@@ -28,6 +46,13 @@ export class SearchControl {
<form class="search-panel__form"> <form class="search-panel__form">
<input type="text" class="search-panel__input" placeholder="Search, or lat, lng"> <input type="text" class="search-panel__input" placeholder="Search, or lat, lng">
</form> </form>
<div class="search-panel__sources">
${SOURCES.map(
(source) => `
<label><input type="checkbox" value="${source.id}" checked> ${escapeHtml(source.label)}</label>
`,
).join("")}
</div>
<ul class="search-panel__results"></ul> <ul class="search-panel__results"></ul>
</div> </div>
`; `;
@@ -41,6 +66,13 @@ export class SearchControl {
event.preventDefault(); event.preventDefault();
this._search(); this._search();
}); });
this._container.querySelectorAll(".search-panel__sources input").forEach((input) => {
input.addEventListener("change", () => {
if (input.checked) this._enabled.add(input.value);
else this._enabled.delete(input.value);
if (this._input.value.trim()) this._search();
});
});
return this._container; return this._container;
} }
@@ -67,44 +99,87 @@ export class SearchControl {
const coords = query.match(COORD_PATTERN); const coords = query.match(COORD_PATTERN);
if (coords) { if (coords) {
this._resultsEl.innerHTML = ""; this._resultsEl.innerHTML = "";
this._jumpTo(Number(coords[1]), Number(coords[2])); this._jumpTo({ lat: Number(coords[1]), lng: Number(coords[2]) });
return; return;
} }
this._resultsEl.innerHTML = `<li class="search-panel__status">Searching…</li>`; this._resultsEl.innerHTML = `<li class="search-panel__status">Searching…</li>`;
let places; const local = SOURCES.filter((source) => source.local && this._enabled.has(source.id)).map((source) => source.id);
const [localResults, onlineResults] = await Promise.all([
local.length ? this._searchLocal(query, local) : [],
this._enabled.has("nominatim") ? this._searchNominatim(query) : [],
]);
if (this._input.value.trim() !== query) return; // a newer search started meanwhile
this._renderResults([...localResults, ...onlineResults]);
}
async _searchLocal(query, sources) {
try {
const url = new URL("/api/search", window.location.origin);
url.searchParams.set("q", query);
url.searchParams.set("sources", sources.join(","));
const { results } = await (await fetch(url)).json();
return results.map((result) => ({
name: result.name,
where: result.source_label,
bbox: result.bbox,
open: () => this._openers[result.source]?.(result.ref),
}));
} catch {
return [{ status: "Local search failed." }];
}
}
async _searchNominatim(query) {
try { try {
const url = new URL(NOMINATIM_API); const url = new URL(NOMINATIM_API);
url.searchParams.set("q", query); url.searchParams.set("q", query);
url.searchParams.set("format", "jsonv2"); url.searchParams.set("format", "jsonv2");
url.searchParams.set("limit", "5"); url.searchParams.set("limit", "5");
places = await (await fetch(url)).json(); const places = await (await fetch(url)).json();
return places.map((place) => ({
name: place.display_name,
where: "Online · Nominatim",
lat: Number(place.lat),
lng: Number(place.lon),
}));
} catch { } catch {
this._resultsEl.innerHTML = `<li class="search-panel__status">Search unavailable — check your connection.</li>`; return [{ status: "Online search unavailable — no connection." }];
return;
} }
this._renderResults(places);
} }
_renderResults(places) { _renderResults(results) {
this._results = places; this._results = results;
if (places.length === 0) { if (results.length === 0) {
this._resultsEl.innerHTML = `<li class="search-panel__status">No results</li>`; this._resultsEl.innerHTML = `<li class="search-panel__status">No results</li>`;
return; return;
} }
this._resultsEl.innerHTML = places this._resultsEl.innerHTML = results
.map((place, i) => `<li class="search-panel__result" data-index="${i}">${escapeHtml(place.display_name)}</li>`) .map((result, i) =>
result.status
? `<li class="search-panel__status">${escapeHtml(result.status)}</li>`
: `<li class="search-panel__result" data-index="${i}">
${escapeHtml(result.name)}
<span class="search-panel__where">${escapeHtml(result.where)}</span>
</li>`,
)
.join(""); .join("");
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => { this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
el.addEventListener("click", () => { el.addEventListener("click", () => {
const place = this._results[Number(el.dataset.index)]; const result = this._results[Number(el.dataset.index)];
this._jumpTo(Number(place.lat), Number(place.lon)); result.open?.();
this._jumpTo(result);
}); });
}); });
} }
_jumpTo(lat, lng) { _jumpTo({ lat, lng, bbox }) {
this._map.flyTo({ center: [lng, lat], zoom: Math.max(this._map.getZoom(), 14) }); if (bbox && (bbox[0] !== bbox[2] || bbox[1] !== bbox[3])) {
this._map.fitBounds(bbox, { padding: 40, maxZoom: 15 });
} else {
const [x, y] = bbox || [lng, lat];
this._map.flyTo({ center: [x, y], zoom: Math.max(this._map.getZoom(), 14) });
}
this._panel.hidden = true; this._panel.hidden = true;
this._button.classList.remove("active"); this._button.classList.remove("active");
} }
+109 -1
View File
@@ -1,4 +1,4 @@
import { getTimes } from "/vendor/suncalc/suncalc.js"; import { getMoonIllumination, getMoonPosition, getMoonTimes, getPosition, getTimes } from "/vendor/suncalc/suncalc.js";
// A Locus Pro-style toolbar readout: DMS coordinates (plain decimal degrees // A Locus Pro-style toolbar readout: DMS coordinates (plain decimal degrees
// read less like a "GPS unit" and are harder to scan at a glance) plus // read less like a "GPS unit" and are harder to scan at a glance) plus
@@ -50,6 +50,10 @@ const DAY_MS = 24 * 60 * 60 * 1000;
// front of each rather than this module owning any markup. // front of each rather than this module owning any markup.
export function formatSunInfo(lat, lng, now = new Date()) { export function formatSunInfo(lat, lng, now = new Date()) {
const today = getTimes(now, lat, lng); const today = getTimes(now, lat, lng);
// Polar day/night: no rise/set to count down to, but still worth a label
// — it's also what opens the sun/moon chart below.
if (today.alwaysUp) return { polar: "Polar day" };
if (today.alwaysDown) return { polar: "Polar night" };
if (today.sunrise === null || today.sunset === null) return null; if (today.sunrise === null || today.sunset === null) return null;
let next; let next;
@@ -69,3 +73,107 @@ export function formatSunInfo(lat, lng, now = new Date()) {
countdown: next ? `${formatCountdown(next.at - now)} to ${next.label}` : null, countdown: next ? `${formatCountdown(next.at - now)} to ${next.label}` : null,
}; };
} }
// --- Sun & moon chart (click on the topbar's sun readout) ----------------
// Horizon-card style: 24 h centered on the solar noon nearest to now, real
// sun/moon altitudes from suncalc (vendored, so fully offline), horizon at
// 0°, sunrise/sunset lines, the moon drawn in its current phase. Times are
// in the browser's own time zone, same as the topbar readout.
const STEP_MS = 10 * 60 * 1000;
const W = 320;
const H = 130;
const LABEL_BAND = 14; // above the graph: sunrise/sunset; below it: dawn, solar noon, dusk
const PHASE_NAMES = [
"New moon", "Waxing crescent", "First quarter", "Waxing gibbous",
"Full moon", "Waning gibbous", "Last quarter", "Waning crescent",
];
function phaseName(phase) {
return PHASE_NAMES[Math.round(phase * 8) % 8];
}
// Lit part of a moon disk of radius r centered on 0,0: the bright half
// (right side; the caller mirrors it while waning) closed by the
// terminator, an elliptical arc whose width follows the phase.
// ponytail: northern-hemisphere orientation, no tilt from
// getMoonIllumination().angle - parallacticAngle — add if this travels south.
export function moonPhasePath(phase, r) {
const rx = (r * Math.abs(Math.cos(2 * Math.PI * phase))).toFixed(2);
const gibbous = phase > 0.25 && phase < 0.75 ? 1 : 0;
return `M0,${-r} A${r},${r} 0 0 1 0,${r} A${rx},${r} 0 0 ${gibbous} 0,${-r}Z`;
}
function nearestSolarNoon(now, lat, lng) {
const noon = getTimes(now, lat, lng).solarNoon;
if (now - noon > DAY_MS / 2) return getTimes(new Date(now.getTime() + DAY_MS), lat, lng).solarNoon;
if (noon - now > DAY_MS / 2) return getTimes(new Date(now.getTime() - DAY_MS), lat, lng).solarNoon;
return noon;
}
const time = (date) => (date ? formatTime(date) : "—");
const degrees = (value) => `${Math.round(value)}°`;
export function sunChartHtml(lat, lng, now = new Date()) {
const noon = nearestSolarNoon(now, lat, lng);
const start = noon.getTime() - DAY_MS / 2;
const samples = [];
for (let t = start; t <= start + DAY_MS; t += STEP_MS) {
const date = new Date(t);
samples.push({ t, sun: getPosition(date, lat, lng).altitude, moon: getMoonPosition(date, lat, lng).altitude });
}
const alts = samples.flatMap((sample) => [sample.sun, sample.moon]);
const top = Math.max(...alts, 10) + 8;
const bottom = Math.min(...alts, -10) - 8;
const x = (t) => (((t - start) / DAY_MS) * W).toFixed(1);
const y = (alt) => (((top - alt) / (top - bottom)) * H).toFixed(1);
const path = (key) => samples.map((sample, i) => `${i ? "L" : "M"}${x(sample.t)},${y(sample[key])}`).join("");
const sunTimes = getTimes(noon, lat, lng);
const moonTimes = getMoonTimes(noon, lat, lng);
const sunNow = getPosition(now, lat, lng);
const moonNow = getMoonPosition(now, lat, lng);
const illumination = getMoonIllumination(now);
const horizon = y(0);
const inWindow = (date) => date && date.getTime() >= start && date.getTime() <= start + DAY_MS;
const marker = (date) =>
inWindow(date) ? `<line class="sun-chart__mark" x1="${x(date.getTime())}" x2="${x(date.getTime())}" y1="0" y2="${H}"/>` : "";
const tick = (date) =>
inWindow(date) ? `<line class="sun-chart__tick" x1="${x(date.getTime())}" x2="${x(date.getTime())}" y1="${H - 5}" y2="${H}"/>` : "";
// Kept clear of the edges so a label for an event near the window's
// ends doesn't get cut off.
const label = (date, name, y) =>
inWindow(date)
? `<text class="sun-chart__label" x="${Math.min(Math.max(x(date.getTime()), 34), W - 34)}" y="${y}">${name} ${time(date)}</text>`
: "";
const svg = `
<svg class="sun-chart__graph" viewBox="0 ${-LABEL_BAND} ${W} ${H + 2 * LABEL_BAND}" role="img" aria-label="Sun and moon altitude over the day">
<defs><clipPath id="sun-chart-day"><rect width="${W}" height="${horizon}"/></clipPath></defs>
<rect class="sun-chart__night" y="${horizon}" width="${W}" height="${H - horizon}"/>
${marker(sunTimes.sunrise)}${marker(sunTimes.sunset)}
${tick(sunTimes.dawn)}${tick(sunTimes.solarNoon)}${tick(sunTimes.dusk)}
${label(sunTimes.sunrise, "Sunrise", -4)}${label(sunTimes.sunset, "Sunset", -4)}
${label(sunTimes.dawn, "Dawn", H + 10)}${label(sunTimes.solarNoon, "Noon", H + 10)}${label(sunTimes.dusk, "Dusk", H + 10)}
<path class="sun-chart__moon-path" d="${path("moon")}"/>
<path class="sun-chart__sun-path" d="${path("sun")}"/>
<path class="sun-chart__sun-path sun-chart__sun-path--day" d="${path("sun")}" clip-path="url(#sun-chart-day)"/>
<line class="sun-chart__horizon" x1="0" x2="${W}" y1="${horizon}" y2="${horizon}"/>
<circle class="sun-chart__sun" cx="${x(now.getTime())}" cy="${y(sunNow.altitude)}" r="7"/>
<g transform="translate(${x(now.getTime())},${y(moonNow.altitude)})">
<circle class="sun-chart__moon-shadow" r="7"/>
<path class="sun-chart__moon" d="${moonPhasePath(illumination.phase, 7)}"${illumination.waxing ? "" : ` transform="scale(-1,1)"`}/>
</g>
</svg>`;
const field = (label, value) => `<dt>${label}</dt><dd>${value}</dd>`;
return `${svg}
<dl class="sun-chart__fields">
${field("Sun now", `${degrees(sunNow.altitude)} alt · ${degrees(sunNow.azimuth)} az`)}
${field("Moonrise", time(moonTimes.rise))}
${field("Moonset", time(moonTimes.set))}
${field("Moon", `${phaseName(illumination.phase)} · ${Math.round(illumination.fraction * 100)}%`)}
${field("Moon now", `${degrees(moonNow.altitude)} alt · ${degrees(moonNow.azimuth)} az`)}
</dl>`;
}
+14
View File
@@ -198,6 +198,20 @@ class AppTest < Minitest::Test
refute_includes names, "readme.txt" refute_includes names, "readme.txt"
end end
def test_zip_whose_contents_exceed_the_size_limit_is_rejected_before_saving_anything
zip_bytes = build_zip("big.gpx" => "x" * 2048)
original = Maptool::App::MAX_ZIP_UNCOMPRESSED
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, 1024)
response = post_file("/api/gpx", filename: "bomb.zip", content: zip_bytes, content_type: "application/zip", env: logged_in_env)
assert_equal 413, response.status
assert_empty json_body(request.get("/api/gpx/tree"))["children"]
ensure
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original)
end
def test_corrupt_zip_is_rejected def test_corrupt_zip_is_rejected
response = post_file("/api/gpx", filename: "bad.zip", content: "not a zip", content_type: "application/zip", env: logged_in_env) response = post_file("/api/gpx", filename: "bad.zip", content: "not a zip", content_type: "application/zip", env: logged_in_env)
assert_equal 400, response.status assert_equal 400, response.status
+15
View File
@@ -216,6 +216,21 @@ class PmtilesBuilderTest < Minitest::Test
) )
end end
def test_finished_builds_are_recorded_with_per_step_timings_newest_first
select_regions("SK")
Maptool::PmtilesBuilder.build_offline(data_dir: @data_dir, download_extract: fake_download).join
ENV["JAVA_BIN"] = @java_fail
Maptool::PmtilesBuilder.build_offline(data_dir: @data_dir, download_extract: fake_download).join
failed, done = Maptool::PmtilesBuilder.build_history(@data_dir)
assert_equal ["error", "done"], [failed["state"], done["state"]]
assert_equal ["offline", ["SK"]], done.values_at("kind", "regions")
assert_equal ["fetching SK (1/1)", "tiling with planetiler", "extracting hiking trails"], done["timings"].map { |t| t["step"] }
assert(done["timings"].all? { |t| t["seconds"] >= 0 })
assert done.key?("log")
assert_match(/boom/, failed["message"])
end
def test_build_offline_also_writes_a_per_country_hiking_trails_geojson def test_build_offline_also_writes_a_per_country_hiking_trails_geojson
select_regions("SK") select_regions("SK")
thread = Maptool::PmtilesBuilder.build_offline(data_dir: @data_dir, download_extract: fake_download) thread = Maptool::PmtilesBuilder.build_offline(data_dir: @data_dir, download_extract: fake_download)
+53
View File
@@ -0,0 +1,53 @@
require_relative "test_helper"
require "maptool/gpx_store"
require "maptool/search"
require "stringio"
class SearchTest < Minitest::Test
def setup
@data_dir = Dir.mktmpdir
@store = Maptool::GpxStore.new(File.join(@data_dir, "gpx"))
camp = { "type" => "FeatureCollection", "features" => [
point("Kemp Košice", 21.26, 48.72, "pitná voda"),
{ "type" => "Feature", "properties" => { "kind" => "track" },
"geometry" => { "type" => "LineString", "coordinates" => [[17.0, 48.0, 150], [18.0, 49.0, 300]] } },
] }
@store.save(folder: "trips", filename: "camps.geojson", io: StringIO.new(JSON.generate(camp)))
trails = File.join(@data_dir, "hiking_trails")
FileUtils.mkdir_p(trails)
File.write(File.join(trails, "SK.geojson"),
JSON.generate("type" => "FeatureCollection", "features" => [point("Cesta hrdinov SNP", 19.0, 48.8)]))
end
def test_finds_across_sources_ignoring_case_and_diacritics_and_says_where
layer = search("kosice")
assert_equal [["Kemp Košice", "layers", "trips/camps.geojson"]], layer.map { |r| r.values_at(:name, :source, :ref) }
trail = search("snp hrdinov").first
assert_equal ["hiking_trails", "SK", "Hiking trails SK"], trail.values_at(:source, :ref, :source_label)
end
def test_matches_description_and_falls_back_to_file_name_with_bbox
assert_equal ["Kemp Košice"], search("voda").map { |r| r[:name] }
track = search("camps").first
assert_equal [17.0, 48.0, 18.0, 49.0], track[:bbox]
end
def test_source_filter_and_blank_query
assert_empty search("snp", sources: ["layers"])
assert_empty search(" ")
end
private
def search(text, **opts)
Maptool::Search.query(text, gpx_store: @store, data_dir: @data_dir, **opts)
end
def point(name, lng, lat, description = nil)
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => [lng, lat] },
"properties" => { "name" => name, "description" => description }.compact }
end
end
+11 -1
View File
@@ -3,8 +3,9 @@
<span class="topbar__brand" title="rev <%= revision %>">MapTool</span> <span class="topbar__brand" title="rev <%= revision %>">MapTool</span>
<span class="topbar__center"> <span class="topbar__center">
<span class="topbar__coords"></span> <span class="topbar__coords"></span>
<span class="topbar__sun" hidden></span> <span class="topbar__sun" title="Sun &amp; moon" hidden></span>
</span> </span>
<div class="sun-chart" hidden></div>
<span class="topbar__offline-status" hidden></span> <span class="topbar__offline-status" hidden></span>
<div class="topbar__auth"> <div class="topbar__auth">
<% if logged_in %> <% if logged_in %>
@@ -94,6 +95,15 @@
<ul class="livetrack-panel__list"></ul> <ul class="livetrack-panel__list"></ul>
</div> </div>
<div id="debug-panel" class="basemap-panel" hidden>
<div class="basemap-panel__header">
<strong>Status / debug</strong>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div>
<!-- Filled by DebugControl (public/js/debug.js), logged-in only. -->
<div class="debug-panel__body"></div>
</div>
<div id="offline-data-panel" class="basemap-panel" hidden> <div id="offline-data-panel" class="basemap-panel" hidden>
<div class="basemap-panel__header"> <div class="basemap-panel__header">
<strong>Offline data</strong> <strong>Offline data</strong>
+1
View File
@@ -41,6 +41,7 @@
"/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>", "/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>",
"/js/measure.js": "/js/measure.js?v=<%= ASSET_VERSION %>", "/js/measure.js": "/js/measure.js?v=<%= ASSET_VERSION %>",
"/js/notes.js": "/js/notes.js?v=<%= ASSET_VERSION %>", "/js/notes.js": "/js/notes.js?v=<%= ASSET_VERSION %>",
"/js/debug.js": "/js/debug.js?v=<%= ASSET_VERSION %>",
"/js/offline_data.js": "/js/offline_data.js?v=<%= ASSET_VERSION %>", "/js/offline_data.js": "/js/offline_data.js?v=<%= ASSET_VERSION %>",
"/js/overlays.js": "/js/overlays.js?v=<%= ASSET_VERSION %>", "/js/overlays.js": "/js/overlays.js?v=<%= ASSET_VERSION %>",
"/js/panels.js": "/js/panels.js?v=<%= ASSET_VERSION %>", "/js/panels.js": "/js/panels.js?v=<%= ASSET_VERSION %>",