diff --git a/TODO.adoc b/TODO.adoc index 8393d04..2336a11 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -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 * [ ] 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) Deprioritized for now — revisit after the sections above land. diff --git a/app.rb b/app.rb index 6009f41..208b51c 100644 --- a/app.rb +++ b/app.rb @@ -13,6 +13,7 @@ require_relative "lib/maptool/livetrack_client" require_relative "lib/maptool/kiwix" require_relative "lib/maptool/plugins" require_relative "lib/maptool/pmtiles_builder" +require_relative "lib/maptool/search" module Maptool # Only /login, /auth/callback and /logout ever write to session @@ -419,6 +420,15 @@ module Maptool send_file path, type: "application/geo+json" 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 # 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 diff --git a/lib/maptool/search.rb b/lib/maptool/search.rb new file mode 100644 index 0000000..a9dfe3a --- /dev/null +++ b/lib/maptool/search.rb @@ -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 diff --git a/public/css/style.css b/public/css/style.css index 3271029..052a09a 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1164,6 +1164,22 @@ html, body { 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 { position: relative; } diff --git a/public/js/gpx.js b/public/js/gpx.js index e0d3938..dcffba3 100644 --- a/public/js/gpx.js +++ b/public/js/gpx.js @@ -301,6 +301,7 @@ export class GpxPanelControl { const checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.checked = this._visible.has(file.path); + checkbox.dataset.path = file.path; checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox)); // Just the real, as-uploaded name — it used to grow a ".geojson" suffix // once cached (matching the real ".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) { if (visible) { this._visible.add(path); diff --git a/public/js/hiking_trails.js b/public/js/hiking_trails.js index bb92dc9..814829a 100644 --- a/public/js/hiking_trails.js +++ b/public/js/hiking_trails.js @@ -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) { this._active = active; if (active) this._addOnlineLayer(); diff --git a/public/js/map.js b/public/js/map.js index ecd8807..91e566a 100644 --- a/public/js/map.js +++ b/public/js/map.js @@ -444,7 +444,8 @@ const SLOVAKIA_BOUNDS = [ [16.83, 47.73], [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"); // showCompass: false — this map never rotates, so a bearing-reset button // (NavigationControl's default third button) would just be dead weight. @@ -545,9 +546,14 @@ const profilePanel = new TrackProfilePanel(map); profilePanel.mount(); sidebar.insertAdjacentHTML("beforeend", ``); -new GpxPanelControl(map, profilePanel).mount(sidebar); +const gpxPanel = new GpxPanelControl(map, profilePanel); +gpxPanel.mount(sidebar); const overlaysControl = new OverlaysControl(map); overlaysControl.mount(sidebar); +searchControl.setLayerOpeners({ + layers: (path) => gpxPanel.show(path), + hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code), +}); pitchToggle.setOverlaysControl(overlaysControl); // Running a plugin needs a login (POST /api/plugins/:name/run) — same // "hide the write-only affordance" story as NotesControl above. diff --git a/public/js/overlays.js b/public/js/overlays.js index dbc0ed5..9033ed2 100644 --- a/public/js/overlays.js +++ b/public/js/overlays.js @@ -249,6 +249,10 @@ export class OverlaysControl { this._hikingTrails.setOfflineCountries(countries); } + showHikingTrailsCountry(code) { + this._hikingTrails.showCountry(code); + } + // Called by map.js's PitchToggleControl whenever the 3D pitch toggle // changes, so raised terrain follows the camera tilt rather than needing // the "Terrain shading" checkbox re-clicked to notice. diff --git a/public/js/search.js b/public/js/search.js index a4b72ad..b481edb 100644 --- a/public/js/search.js +++ b/public/js/search.js @@ -8,14 +8,32 @@ const NOMINATIM_API = "https://nominatim.openstreetmap.org/search"; // there with no network round-trip. 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. -// Online only, like this app's other non-basemap online features (Radar, -// the Wikipedia layer) — no offline geocoding index to fall back to. -// Nominatim: OpenStreetMap's own geocoder, free, no API key, matching the -// online basemap's own OSM-derived style already used here. +// Every result says where it was found; picking one from a layer that's +// currently switched off switches it on (see setLayerOpeners). export class SearchControl { constructor() { 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) { @@ -28,6 +46,13 @@ export class SearchControl {
+
+ ${SOURCES.map( + (source) => ` + + `, + ).join("")} +
`; @@ -41,6 +66,13 @@ export class SearchControl { event.preventDefault(); 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; } @@ -67,44 +99,87 @@ export class SearchControl { const coords = query.match(COORD_PATTERN); if (coords) { this._resultsEl.innerHTML = ""; - this._jumpTo(Number(coords[1]), Number(coords[2])); + this._jumpTo({ lat: Number(coords[1]), lng: Number(coords[2]) }); return; } this._resultsEl.innerHTML = `
  • Searching…
  • `; - 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 { const url = new URL(NOMINATIM_API); url.searchParams.set("q", query); url.searchParams.set("format", "jsonv2"); 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 { - this._resultsEl.innerHTML = `
  • Search unavailable — check your connection.
  • `; - return; + return [{ status: "Online search unavailable — no connection." }]; } - this._renderResults(places); } - _renderResults(places) { - this._results = places; - if (places.length === 0) { + _renderResults(results) { + this._results = results; + if (results.length === 0) { this._resultsEl.innerHTML = `
  • No results
  • `; return; } - this._resultsEl.innerHTML = places - .map((place, i) => `
  • ${escapeHtml(place.display_name)}
  • `) + this._resultsEl.innerHTML = results + .map((result, i) => + result.status + ? `
  • ${escapeHtml(result.status)}
  • ` + : `
  • + ${escapeHtml(result.name)} + ${escapeHtml(result.where)} +
  • `, + ) .join(""); this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => { el.addEventListener("click", () => { - const place = this._results[Number(el.dataset.index)]; - this._jumpTo(Number(place.lat), Number(place.lon)); + const result = this._results[Number(el.dataset.index)]; + result.open?.(); + this._jumpTo(result); }); }); } - _jumpTo(lat, lng) { - this._map.flyTo({ center: [lng, lat], zoom: Math.max(this._map.getZoom(), 14) }); + _jumpTo({ lat, lng, bbox }) { + 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._button.classList.remove("active"); } diff --git a/test/test_search.rb b/test/test_search.rb new file mode 100644 index 0000000..aff07a9 --- /dev/null +++ b/test/test_search.rb @@ -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