Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25b87b94fe | ||
|
|
e2461f794c |
No files matched your search
@@ -63,13 +63,20 @@ independence from connectivity.
|
|||||||
|
|
||||||
* [x] 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] 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
|
** [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
|
||||||
** [x] Offline vector data — every named OSM object in each country's Geofabrik `.osm.pbf` (`osmium tags-filter nwr/name` + `osmium export -f geojsonseq`) into a SQLite FTS5 index, `data/places/<CODE>.sqlite` (`lib/maptool/places.rb`), built as the last offline-build step ("indexing places") and cached by mtime like hiking trails. Prefix + diacritics-insensitive matching, street segments merged per ~2 km cell; named buildings and land-use areas dropped (unless they're also a shop/amenity/…), names searchable without their apostrophes ("mcdonalds") and by `brand`. `Places::SCHEMA_VERSION` makes `rake places:index` rebuild older indexes by itself
|
** [x] Offline vector data — every named OSM object in each country's Geofabrik `.osm.pbf` (`osmium tags-filter nwr/name` + `osmium export -f geojsonseq`) into a SQLite FTS5 index, `data/places/<CODE>.sqlite` (`lib/maptool/places.rb`), built as the last offline-build step ("indexing places") and cached by mtime like hiking trails. Prefix + diacritics-insensitive matching, street segments merged per ~2 km cell; named buildings, land-use areas, `place=locality`/`isolated_dwelling` and objects with no recognized kind dropped (a shop in a building stays), names searchable without their apostrophes ("mcdonalds") and by `brand`. `Places::SCHEMA_VERSION` makes `rake places:index` rebuild older indexes by itself
|
||||||
** [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] 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] 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
|
** [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
|
||||||
** [x] Kiwix as a source — full-text search of the ZIM (`Kiwix.search`), each hit's coordinates read from its page like the Wikipedia layer does; clicking opens the article (and jumps to it when it has coordinates)
|
** [x] Kiwix as a source — full-text search of the ZIM (`Kiwix.search`), each hit's coordinates read from its page like the Wikipedia layer does; clicking opens the article (and jumps to it when it has coordinates)
|
||||||
** [x] Nearest first — every result carries its distance from the map center and the list is sorted by it across all sources; settlements count as closer (city x0.01 … suburb x0.3, `Places::DISTANCE_WEIGHT`) so a town's name still finds the town. Nominatim gets the visible area as a (non-restricting) `viewbox`
|
** [x] Nearest first — every result carries its distance from the map center and the list is sorted by it across all sources; settlements count as closer (city x0.01 … suburb x0.3, `Places::DISTANCE_WEIGHT`) so a town's name still finds the town. Nominatim gets the visible area as a (non-restricting) `viewbox`
|
||||||
|
|
||||||
|
== Sync with OsmAnd / Locus / mapy.com
|
||||||
|
|
||||||
|
* [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)
|
||||||
|
* [ ] Item-based library replacing the file-based `GpxStore` — design in `docs/library-design.adoc`
|
||||||
|
* [ ] Change feed + GPX export flavors for OsmAnd/Locus
|
||||||
|
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
|
||||||
|
|
||||||
== 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.
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ module Maptool
|
|||||||
|
|
||||||
class App < Sinatra::Base
|
class App < Sinatra::Base
|
||||||
set :public_folder, File.join(__dir__, "public")
|
set :public_folder, File.join(__dir__, "public")
|
||||||
|
# The PWA manifest (public/manifest.webmanifest) — Rack doesn't know
|
||||||
|
# this extension and would serve it as application/octet-stream.
|
||||||
|
mime_type :webmanifest, "application/manifest+json"
|
||||||
set :views, File.join(__dir__, "views")
|
set :views, File.join(__dir__, "views")
|
||||||
|
|
||||||
# sinatra/json defaults to MultiJson, whose `encode` (what
|
# sinatra/json defaults to MultiJson, whose `encode` (what
|
||||||
@@ -250,6 +253,14 @@ module Maptool
|
|||||||
erb :index, locals: { logged_in: logged_in?, user: session[:user], revision: REVISION }
|
erb :index, locals: { logged_in: logged_in?, user: session[:user], revision: REVISION }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# A share to the installed app normally never reaches the server: the
|
||||||
|
# service worker (public/sw.js) takes the POST, parks the files and
|
||||||
|
# opens the app. Only lands here if no worker is running yet — back to
|
||||||
|
# the map rather than a 404, the share just has to be repeated.
|
||||||
|
post "/share-target" do
|
||||||
|
redirect "/", 303
|
||||||
|
end
|
||||||
|
|
||||||
get "/api/health" do
|
get "/api/health" do
|
||||||
json status: "ok", revision: REVISION
|
json status: "ok", revision: REVISION
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,319 @@
|
|||||||
|
= Library: data model for tracks, points and sync (design)
|
||||||
|
:toc:
|
||||||
|
:toclevels: 2
|
||||||
|
|
||||||
|
Status: *proposal, not implemented.* Replaces the file-based store behind
|
||||||
|
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
|
||||||
|
Map and the MapTool web app can all be synced against.
|
||||||
|
|
||||||
|
== Why
|
||||||
|
|
||||||
|
The same tracks and points live in three places — MapTool, OsmAnd+ and
|
||||||
|
Locus Map on the phone/tablet — each edited independently. Today the unit
|
||||||
|
of storage in MapTool is a *file* (a `.gpx`/`.fit`/`.geojson` in a folder),
|
||||||
|
and nothing inside a file has a stable identity, a change time, or a
|
||||||
|
record of having been deleted. That's fine for "upload and look at it",
|
||||||
|
but any sync needs to answer _which point changed, where, and since
|
||||||
|
when_ — impossible when the smallest thing we know about is a whole file.
|
||||||
|
|
||||||
|
Goals:
|
||||||
|
|
||||||
|
* One folder tree with points and tracks mixed in it (Locus-style
|
||||||
|
"project" folders).
|
||||||
|
* Every point and track an item with a stable id, timestamps and a
|
||||||
|
tombstone on delete.
|
||||||
|
* A change feed that a sync client (Android app, the PWA) can poll.
|
||||||
|
* Import/export to GPX that round-trips what OsmAnd and Locus care about
|
||||||
|
(folders, names, descriptions, colors, icons).
|
||||||
|
|
||||||
|
Non-goals (for now): real-time collaboration, merging concurrent edits
|
||||||
|
field by field, syncing hiking trails / offline map data (those are
|
||||||
|
derived, not user data), LiveTrack sessions.
|
||||||
|
|
||||||
|
== How the apps model their data
|
||||||
|
|
||||||
|
=== Locus Map 4
|
||||||
|
|
||||||
|
* One *library*: a tree of folders and subfolders in which tracks,
|
||||||
|
planned routes and points can be mixed. The separate points/tracks tabs
|
||||||
|
of Locus 3 are gone.
|
||||||
|
* Nesting: 3 levels free, 6 with Premium.
|
||||||
|
* Items can be filtered by type (only tracks / only points) for display.
|
||||||
|
* Exporting a folder exports all of its content into one file.
|
||||||
|
* Syncs every change to Locus' own web library (no public API known).
|
||||||
|
* App data (`waypoints.db`, `tracks.db`) is SQLite, but not a supported
|
||||||
|
integration point; the Locus API is mainly for *sending* points/tracks
|
||||||
|
into Locus.
|
||||||
|
|
||||||
|
Sources: https://docs.locusmap.app/doku.php/manual:user_guide:my_library[My Library],
|
||||||
|
https://www.locusmap.app/the-new-library-brings-major-improvements-to-your-data-management/[blog],
|
||||||
|
https://github.com/asamm/locus-api[locus-api].
|
||||||
|
|
||||||
|
=== OsmAnd+
|
||||||
|
|
||||||
|
* *Favorites* (points) in folders/groups, nested ("Travel / Italy /
|
||||||
|
Rome"); a name must be unique within its folder. Each has address,
|
||||||
|
description, icon, color and background shape, defaulting to the
|
||||||
|
folder's. Stored as GPX `<wpt>` with `osmand:icon`, `osmand:color`,
|
||||||
|
`osmand:background`, `osmand:address` extensions.
|
||||||
|
* *Tracks* are separate GPX files in track folders (plus "smart folders",
|
||||||
|
virtual filters). A track file can carry its own waypoints.
|
||||||
|
* Points and tracks are *not* mixed: a "project" maps to a favorites
|
||||||
|
folder plus a track folder of the same name.
|
||||||
|
* AIDL API: add/update/remove favorites and favorite groups, import/show
|
||||||
|
GPX. Whether it can *list* existing favorites/tracks is unverified —
|
||||||
|
check `osmand-api-demo` before relying on reading from OsmAnd.
|
||||||
|
|
||||||
|
Sources: https://docs.osmand.net/docs/user/personal/favorites[Favorites],
|
||||||
|
https://docs.osmand.net/docs/user/personal/tracks/[Tracks],
|
||||||
|
https://docs.osmand.net/docs/technical/osmand-api-sdk[API/SDK].
|
||||||
|
|
||||||
|
=== mapy.com
|
||||||
|
|
||||||
|
No API. Data arrives by exporting/sharing a GPX from the app — the PWA
|
||||||
|
share target (`public/sw.js`, `public/js/share_import.js`) covers that.
|
||||||
|
|
||||||
|
=== What that means for us
|
||||||
|
|
||||||
|
Locus' model is the most general: a folder tree with mixed items. OsmAnd
|
||||||
|
fits into it by splitting each folder into "its points" (a favorites
|
||||||
|
folder) and "its tracks" (a track folder). So MapTool adopts Locus' shape
|
||||||
|
and maps to OsmAnd on export/sync.
|
||||||
|
|
||||||
|
== Current model (GpxStore) and its gaps
|
||||||
|
|
||||||
|
* `data/gpx/` folder tree; each file is a `.gpx`, `.fit` or `.geojson`,
|
||||||
|
converted to a GeoJSON FeatureCollection (cached as `*.gpx.geojson`).
|
||||||
|
* A file mixes tracks/routes (`LineString`/`MultiLineString`) and
|
||||||
|
waypoints (`Point`), each with `properties`: `kind`, `name`,
|
||||||
|
`description`, `time`, `category`, `color`, `icon` (OsmAnd icon keys,
|
||||||
|
e.g. `amenity_parking`), `photos`, `activity_type`.
|
||||||
|
* Notes (`notes.js`) are Features appended to a `.geojson` "layer" file,
|
||||||
|
the only ones with an `id`.
|
||||||
|
* Plugin output and Overpass POIs land as `.geojson` files the same way.
|
||||||
|
|
||||||
|
Gaps: no per-item id (except notes), no `updated_at`, no tombstones, the
|
||||||
|
file is the unit of move/delete/visibility, folder styling doesn't exist,
|
||||||
|
a file's name is doubling as a "collection" name.
|
||||||
|
|
||||||
|
== Proposed model
|
||||||
|
|
||||||
|
Stored in SQLite, `data/library.sqlite` (the `sqlite3` gem is already a
|
||||||
|
dependency for the place index).
|
||||||
|
|
||||||
|
=== Folders
|
||||||
|
|
||||||
|
[source,sql]
|
||||||
|
----
|
||||||
|
CREATE TABLE folders (
|
||||||
|
id TEXT PRIMARY KEY, -- uuid
|
||||||
|
parent_id TEXT REFERENCES folders(id),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
color TEXT, -- default for items inside
|
||||||
|
icon TEXT, -- OsmAnd icon key
|
||||||
|
visible INTEGER NOT NULL DEFAULT 1,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
deleted_at TEXT,
|
||||||
|
UNIQUE (parent_id, name)
|
||||||
|
);
|
||||||
|
----
|
||||||
|
|
||||||
|
Depth capped at 6 so a tree always fits Locus Premium (warn above 3).
|
||||||
|
|
||||||
|
=== Items
|
||||||
|
|
||||||
|
[source,sql]
|
||||||
|
----
|
||||||
|
CREATE TABLE items (
|
||||||
|
id TEXT PRIMARY KEY, -- uuid
|
||||||
|
folder_id TEXT NOT NULL REFERENCES folders(id),
|
||||||
|
type TEXT NOT NULL, -- 'point' | 'track' | 'route'
|
||||||
|
name TEXT,
|
||||||
|
description TEXT,
|
||||||
|
geometry TEXT NOT NULL, -- GeoJSON geometry (Point / LineString / MultiLineString)
|
||||||
|
properties TEXT NOT NULL DEFAULT '{}', -- JSON: color, icon, width, category, time,
|
||||||
|
-- activity_type, photos, address, ...
|
||||||
|
bbox TEXT NOT NULL, -- [w,s,e,n], for search and the map
|
||||||
|
fingerprint TEXT NOT NULL, -- hash of type + rounded geometry, for dedupe
|
||||||
|
source_id TEXT REFERENCES sources(id), -- the uploaded file it came from, if any
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
deleted_at TEXT,
|
||||||
|
rev INTEGER NOT NULL -- global change counter at last write
|
||||||
|
);
|
||||||
|
CREATE INDEX items_rev ON items(rev);
|
||||||
|
----
|
||||||
|
|
||||||
|
* `type`: `track` = recorded (has timestamps/elevation), `route` =
|
||||||
|
planned. Both lines; the split matters to Locus and for stats.
|
||||||
|
* A recorded track keeps per-point time/elevation inside `geometry`'s
|
||||||
|
coordinates (`[lng, lat, ele]`) plus a parallel `properties.times`
|
||||||
|
array — what the elevation profile needs today.
|
||||||
|
* `properties` stays an open JSON bag so a GPX extension we don't model
|
||||||
|
(Locus/OsmAnd specific) survives a round trip unchanged.
|
||||||
|
|
||||||
|
=== Sources (original files)
|
||||||
|
|
||||||
|
[source,sql]
|
||||||
|
----
|
||||||
|
CREATE TABLE sources (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
filename TEXT NOT NULL,
|
||||||
|
path TEXT NOT NULL, -- data/library/sources/<id>/<filename>
|
||||||
|
imported_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
----
|
||||||
|
|
||||||
|
An upload is still kept as-is (for "download original"), but what the
|
||||||
|
app works with is the items extracted from it. Deleting items never
|
||||||
|
deletes the source; deleting a source is a separate admin action.
|
||||||
|
|
||||||
|
=== Links to other apps
|
||||||
|
|
||||||
|
[source,sql]
|
||||||
|
----
|
||||||
|
CREATE TABLE item_links (
|
||||||
|
item_id TEXT NOT NULL REFERENCES items(id),
|
||||||
|
app TEXT NOT NULL, -- 'osmand' | 'locus' | ...
|
||||||
|
device TEXT NOT NULL, -- one phone/tablet
|
||||||
|
external_ref TEXT NOT NULL, -- the app's id / favorite name+group / GPX path
|
||||||
|
synced_rev INTEGER NOT NULL, -- our rev when last pushed/pulled
|
||||||
|
PRIMARY KEY (item_id, app, device)
|
||||||
|
);
|
||||||
|
----
|
||||||
|
|
||||||
|
Neither app gives us our id back, so this table — kept by the sync
|
||||||
|
client, reported to the server — is how "this OsmAnd favorite" and "this
|
||||||
|
MapTool point" stay the same thing.
|
||||||
|
|
||||||
|
=== Change counter
|
||||||
|
|
||||||
|
A single `rev` sequence (a one-row table, incremented in the same
|
||||||
|
transaction as every write) stamped on each folder/item write. `rev` —
|
||||||
|
not wall-clock time — is what clients sync against, so clock skew on a
|
||||||
|
phone can't skip a change.
|
||||||
|
|
||||||
|
== API
|
||||||
|
|
||||||
|
[cols="1,2"]
|
||||||
|
|===
|
||||||
|
| Route | Purpose
|
||||||
|
|
||||||
|
| `GET /api/library/tree`
|
||||||
|
| Folders with item counts (replaces `/api/gpx/tree`).
|
||||||
|
|
||||||
|
| `GET /api/library/folders/:id/items.geojson`
|
||||||
|
| A folder's items as a FeatureCollection, `id`/`folder_id`/`updated_at`
|
||||||
|
in `properties` — what the map draws.
|
||||||
|
|
||||||
|
| `POST /api/library/import`
|
||||||
|
| Multipart upload (GPX/FIT/GeoJSON/ZIP) into a folder: stores the
|
||||||
|
source, extracts items, skips items whose `fingerprint` already exists
|
||||||
|
in that folder (re-sharing the same track from OsmAnd doesn't
|
||||||
|
duplicate it).
|
||||||
|
|
||||||
|
| `PUT /api/library/items/:id`, `DELETE ...`
|
||||||
|
| Edit (name, description, style, move to folder) / tombstone. `PUT`
|
||||||
|
carries the `rev` the client last saw; an older one gets `409` with
|
||||||
|
the current item.
|
||||||
|
|
||||||
|
| `GET /api/library/changes?since=<rev>`
|
||||||
|
| Folders and items (including tombstones) with `rev > since`, plus the
|
||||||
|
new high-water `rev`. The sync feed.
|
||||||
|
|
||||||
|
| `GET /api/library/folders/:id/export.gpx?flavor=locus\|osmand`
|
||||||
|
| GPX of a folder for an app (see mapping below).
|
||||||
|
|===
|
||||||
|
|
||||||
|
== Mapping to the apps
|
||||||
|
|
||||||
|
=== GPX in (import, share target)
|
||||||
|
|
||||||
|
* `<wpt>` → point; `<trk>` → track; `<rte>` → route.
|
||||||
|
* `<type>` → `properties.category`; `osmand:color`/`locus:` color and
|
||||||
|
`osmand:icon` → `color`/`icon` (already parsed by `Gpx.waypoint_style`).
|
||||||
|
* Folder: the one picked in the import dialog; a GPX's own waypoint
|
||||||
|
groups (OsmAnd's per-folder favorites export) become subfolders.
|
||||||
|
* FIT → one track. GeoJSON → items by geometry type.
|
||||||
|
|
||||||
|
=== Locus
|
||||||
|
|
||||||
|
Folder ⇄ folder, 1:1. Export a folder as one GPX with tracks and points
|
||||||
|
together (Locus imports it into a folder). Locus-specific extensions
|
||||||
|
(`locus:icon`, track style) are kept in `properties` and written back.
|
||||||
|
|
||||||
|
=== OsmAnd
|
||||||
|
|
||||||
|
* A folder's *points* → favorites group with the folder path as its
|
||||||
|
name ("Van / Croatia 2026"), written as GPX `<wpt>` with `osmand:`
|
||||||
|
extensions. OsmAnd requires unique names per group → duplicates get
|
||||||
|
" (2)" appended on export only.
|
||||||
|
* A folder's *tracks/routes* → one GPX per item in a track folder with
|
||||||
|
the same path (`tracks/Van/Croatia 2026/<name>.gpx`), track color/width
|
||||||
|
in the GPX `<extensions>` (exact `osmand:` tag names to verify against
|
||||||
|
a file exported from OsmAnd).
|
||||||
|
|
||||||
|
== Sync (later phase)
|
||||||
|
|
||||||
|
* Direction 1 — MapTool → apps: the Android sync client polls
|
||||||
|
`/changes`, pushes new/changed items into OsmAnd (AIDL: favorites,
|
||||||
|
GPX import) and Locus (locus-api: points/tracks into a folder), and
|
||||||
|
records `item_links`. Deletes: remove via the API where it allows it.
|
||||||
|
* Direction 2 — apps → MapTool: for now, *sharing* from the app (PWA
|
||||||
|
share target) — fingerprint dedupe makes re-sharing safe. Automatic
|
||||||
|
reading from the apps only if their APIs turn out to allow listing
|
||||||
|
data (open question above).
|
||||||
|
* Conflicts: last writer by `rev` wins per item; the losing version goes
|
||||||
|
to an `item_history` table so nothing is silently lost.
|
||||||
|
|
||||||
|
== Migration from GpxStore
|
||||||
|
|
||||||
|
One-off rake task, idempotent, `data/gpx/` left untouched until verified:
|
||||||
|
|
||||||
|
. Each directory under `data/gpx/` → a folder (same path).
|
||||||
|
. Each file → a subfolder named after the file (without extension), its
|
||||||
|
features → items in it; the file → a `sources` row. (Alternative: put
|
||||||
|
items straight into the directory's folder — see open questions.)
|
||||||
|
. Notes' existing `properties.id` reused as the item id, so links to
|
||||||
|
them survive.
|
||||||
|
. Category/icon/color carried over in `properties`.
|
||||||
|
|
||||||
|
Then the app switches to the library; `GpxStore` and `/api/gpx/*` are
|
||||||
|
removed once nothing uses them.
|
||||||
|
|
||||||
|
== What changes in the code
|
||||||
|
|
||||||
|
* `lib/maptool/library.rb` (new): schema, import (reusing `Gpx`, `Fit`,
|
||||||
|
`Geojson` parsing), queries, change feed, GPX export.
|
||||||
|
* `app.rb`: `/api/library/*` instead of `/api/gpx/*`.
|
||||||
|
* `public/js/gpx.js`: tree of folders → items (visibility per folder
|
||||||
|
and per item, item rename/move/delete), map sources per folder.
|
||||||
|
* `public/js/notes.js`: create/edit items instead of appending to a
|
||||||
|
layer file.
|
||||||
|
* `lib/maptool/search.rb`: the "layers" source queries `items` (an FTS
|
||||||
|
table over name/description) instead of scanning files in memory.
|
||||||
|
* Plugins: output imported via the same import path.
|
||||||
|
* `share_import.js`: posts to `/api/library/import`.
|
||||||
|
|
||||||
|
== Phases
|
||||||
|
|
||||||
|
. Library schema + import + read-only map view, migration task, behind
|
||||||
|
the same UI (tree shows folders/items). Old store still present.
|
||||||
|
. Editing (rename, move, delete, style) + notes on the library; remove
|
||||||
|
`GpxStore`.
|
||||||
|
. Change feed + GPX export flavors for OsmAnd/Locus.
|
||||||
|
. Android sync client (one direction), then the other direction if the
|
||||||
|
app APIs allow it.
|
||||||
|
|
||||||
|
== Open questions
|
||||||
|
|
||||||
|
* Migration: one subfolder per old file, or the file's items flattened
|
||||||
|
into its directory's folder?
|
||||||
|
* Should a recorded track keep its own waypoints as children (GPX-style)
|
||||||
|
or as independent points in the same folder (Locus-style)? Proposed:
|
||||||
|
independent points.
|
||||||
|
* Folder depth over 3 — fine to require Locus Premium?
|
||||||
|
* Does OsmAnd's AIDL API list existing favorites/tracks? Does locus-api
|
||||||
|
read points/tracks by folder? Decides whether direction 2 can be
|
||||||
|
automatic.
|
||||||
+13
-7
@@ -16,17 +16,23 @@ module Maptool
|
|||||||
# Bumped whenever the table layout or what goes into it changes —
|
# Bumped whenever the table layout or what goes into it changes —
|
||||||
# PmtilesBuilder rebuilds an index whose user_version is older, so a
|
# PmtilesBuilder rebuilds an index whose user_version is older, so a
|
||||||
# plain `rake places:index` picks the change up.
|
# plain `rake places:index` picks the change up.
|
||||||
SCHEMA_VERSION = 2
|
SCHEMA_VERSION = 3
|
||||||
|
|
||||||
# Most to least important; the first key a feature carries decides
|
# Most to least important; the first key a feature carries decides
|
||||||
# its kind and rank. Within "place", the value refines it further.
|
# its kind and rank. Within "place", the value refines it further.
|
||||||
KIND_KEYS = %w[place natural tourism amenity historic leisure shop aeroway railway highway waterway
|
KIND_KEYS = %w[place natural tourism amenity historic leisure shop aeroway railway highway waterway
|
||||||
boundary landuse man_made office building].freeze
|
boundary landuse man_made office building].freeze
|
||||||
# Named buildings and land-use areas (a farm's fields, an industrial
|
# Named buildings and land-use areas (a farm's fields, an industrial
|
||||||
# estate) are a large share of every country's index and nobody looks
|
# estate) are noise in results — nobody looks for them by name — so
|
||||||
# for them by name — dropped, but only when that's what the object
|
# they're dropped, but only when that's what the object *is*: a
|
||||||
# *is*: a supermarket drawn as a building is still shop=supermarket.
|
# supermarket drawn as a building is still shop=supermarket. (Measured:
|
||||||
|
# only ~1-7% of an index's size, so this is about result quality.)
|
||||||
SKIPPED_KEYS = %w[landuse building].freeze
|
SKIPPED_KEYS = %w[landuse building].freeze
|
||||||
|
# Same idea, measured on France (5.3M rows): place=locality (~10%,
|
||||||
|
# mostly cadastral names of fields and woods) and isolated_dwelling
|
||||||
|
# (~5%, single farms/houses) — plus anything named but with none of
|
||||||
|
# KIND_KEYS (~4%: bus route relations and the like).
|
||||||
|
SKIPPED_PLACES = %w[locality isolated_dwelling].freeze
|
||||||
APOSTROPHES = "'’ʼ`"
|
APOSTROPHES = "'’ʼ`"
|
||||||
PLACE_RANK = { "city" => 0, "town" => 1, "village" => 2, "suburb" => 3, "hamlet" => 3 }.freeze
|
PLACE_RANK = { "city" => 0, "town" => 1, "village" => 2, "suburb" => 3, "hamlet" => 3 }.freeze
|
||||||
# How much closer a settlement counts as when results are ordered by
|
# How much closer a settlement counts as when results are ordered by
|
||||||
@@ -108,7 +114,8 @@ module Maptool
|
|||||||
geometry = feature["geometry"] || {}
|
geometry = feature["geometry"] || {}
|
||||||
coords = geometry["coordinates"]
|
coords = geometry["coordinates"]
|
||||||
key = KIND_KEYS.find { |k| tags[k] }
|
key = KIND_KEYS.find { |k| tags[k] }
|
||||||
return nil if name.empty? || !coords.is_a?(Array) || coords.empty? || SKIPPED_KEYS.include?(key)
|
return nil if name.empty? || !coords.is_a?(Array) || coords.empty? || key.nil? || SKIPPED_KEYS.include?(key)
|
||||||
|
return nil if key == "place" && SKIPPED_PLACES.include?(tags["place"])
|
||||||
|
|
||||||
points = positions(coords)
|
points = positions(coords)
|
||||||
lngs, lats = points.map { |p| p.first(2) }.transpose
|
lngs, lats = points.map { |p| p.first(2) }.transpose
|
||||||
@@ -119,8 +126,7 @@ module Maptool
|
|||||||
lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
|
lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
|
||||||
|
|
||||||
value = tags[key].to_s
|
value = tags[key].to_s
|
||||||
kind = if key.nil? then ""
|
kind = if key == "highway" && geometry["type"] != "Point" then "street"
|
||||||
elsif key == "highway" && geometry["type"] != "Point" then "street"
|
|
||||||
else value.tr("_", " ")
|
else value.tr("_", " ")
|
||||||
end
|
end
|
||||||
importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key]
|
importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key]
|
||||||
|
|||||||
@@ -99,6 +99,63 @@ html, body {
|
|||||||
color: #fff;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Files shared to the installed app (share_import.js), waiting to be
|
||||||
|
imported. */
|
||||||
|
.share-import {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 16px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
z-index: 40;
|
||||||
|
width: 320px;
|
||||||
|
max-width: calc(100vw - 32px);
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 12px;
|
||||||
|
background: #1a1a1a;
|
||||||
|
color: #ddd;
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-import__files {
|
||||||
|
margin: 6px 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
max-height: 120px;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-import__folder {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-import__folder input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 4px 6px;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-import__actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-import__actions a {
|
||||||
|
color: #8fb8ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-import__status {
|
||||||
|
margin: 8px 0 0;
|
||||||
|
color: #f2a29a;
|
||||||
|
}
|
||||||
|
|
||||||
/* Horizon-style sun & moon chart, dropped down from the topbar's sun
|
/* Horizon-style sun & moon chart, dropped down from the topbar's sun
|
||||||
readout (sun.js sunChartHtml). */
|
readout (sun.js sunChartHtml). */
|
||||||
.sun-chart {
|
.sun-chart {
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
@@ -0,0 +1,9 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<!-- Full-bleed background so the same file works as a maskable icon;
|
||||||
|
the artwork stays inside the central 80% safe zone. -->
|
||||||
|
<rect width="512" height="512" fill="#1a1a1a"/>
|
||||||
|
<path d="M120 380 C 170 330, 200 400, 250 350 S 330 300, 300 250" fill="none" stroke="#f2b632"
|
||||||
|
stroke-width="18" stroke-linecap="round" stroke-dasharray="2 34"/>
|
||||||
|
<path d="M330 110 a 70 70 0 0 1 70 70 c 0 52 -70 128 -70 128 s -70 -76 -70 -128 a 70 70 0 0 1 70 -70 z" fill="#fff"/>
|
||||||
|
<circle cx="330" cy="180" r="26" fill="#1a1a1a"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 599 B |
+17
-3
@@ -957,10 +957,11 @@ export class GpxPanelControl {
|
|||||||
// file already in this app's own shape (e.g. a previous /api/gpx/file
|
// file already in this app's own shape (e.g. a previous /api/gpx/file
|
||||||
// response, saved and re-uploaded) can skip GPX/FIT entirely.
|
// response, saved and re-uploaded) can skip GPX/FIT entirely.
|
||||||
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
|
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
|
||||||
if (files.length === 0) return;
|
if (files.length === 0) return [];
|
||||||
|
|
||||||
let tree = null;
|
let tree = null;
|
||||||
let failed = 0;
|
let failed = 0;
|
||||||
|
const uploaded = [];
|
||||||
|
|
||||||
for (const [index, file] of files.entries()) {
|
for (const [index, file] of files.entries()) {
|
||||||
this._setStatus(files.length === 1 ? "Uploading…" : `Uploading ${index + 1} of ${files.length}…`);
|
this._setStatus(files.length === 1 ? "Uploading…" : `Uploading ${index + 1} of ${files.length}…`);
|
||||||
@@ -978,10 +979,12 @@ export class GpxPanelControl {
|
|||||||
const xhr = await uploadFile(formData, () => this._setStatus("Converting…"));
|
const xhr = await uploadFile(formData, () => this._setStatus("Converting…"));
|
||||||
if (xhr.status === 401) {
|
if (xhr.status === 401) {
|
||||||
window.location.href = "/login";
|
window.location.href = "/login";
|
||||||
return;
|
return uploaded;
|
||||||
}
|
}
|
||||||
if (xhr.status < 200 || xhr.status >= 300) throw new Error("upload failed");
|
if (xhr.status < 200 || xhr.status >= 300) throw new Error("upload failed");
|
||||||
({ tree } = JSON.parse(xhr.responseText));
|
let paths;
|
||||||
|
({ tree, paths } = JSON.parse(xhr.responseText));
|
||||||
|
uploaded.push(...paths);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
failed += 1;
|
failed += 1;
|
||||||
}
|
}
|
||||||
@@ -989,6 +992,17 @@ export class GpxPanelControl {
|
|||||||
|
|
||||||
if (tree) this._renderTree(tree);
|
if (tree) this._renderTree(tree);
|
||||||
this._setStatus(failed > 0 ? `${failed} of ${files.length} uploads failed.` : "Uploaded.");
|
this._setStatus(failed > 0 ? `${failed} of ${files.length} uploads failed.` : "Uploaded.");
|
||||||
|
return uploaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Files shared to the installed app (share_import.js): uploaded like a
|
||||||
|
// drop onto the tree, then shown on the map straight away — whoever
|
||||||
|
// shared a track from OsmAnd/Locus wants to see it, not hunt for it.
|
||||||
|
async importFiles(files, folder) {
|
||||||
|
this._togglePanel(true);
|
||||||
|
const paths = await this._uploadFiles(files, folder);
|
||||||
|
await Promise.all(paths.map((path) => this.show(path)));
|
||||||
|
return paths;
|
||||||
}
|
}
|
||||||
|
|
||||||
async _deleteFile(path) {
|
async _deleteFile(path) {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ 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 { DebugControl } from "/js/debug.js";
|
||||||
|
import { offerSharedFiles } from "/js/share_import.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";
|
||||||
@@ -570,6 +571,7 @@ const gpxPanel = new GpxPanelControl(map, profilePanel);
|
|||||||
gpxPanel.mount(sidebar);
|
gpxPanel.mount(sidebar);
|
||||||
const overlaysControl = new OverlaysControl(map);
|
const overlaysControl = new OverlaysControl(map);
|
||||||
overlaysControl.mount(sidebar);
|
overlaysControl.mount(sidebar);
|
||||||
|
offerSharedFiles(gpxPanel);
|
||||||
searchControl.setLayerOpeners({
|
searchControl.setLayerOpeners({
|
||||||
layers: (path, result) => gpxPanel.showFeature(path, result.bbox.slice(0, 2)),
|
layers: (path, result) => gpxPanel.showFeature(path, result.bbox.slice(0, 2)),
|
||||||
hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code),
|
hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code),
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { isLoggedIn } from "/js/auth.js";
|
||||||
|
import { escapeHtml } from "/js/gpx.js";
|
||||||
|
|
||||||
|
// Files shared to the installed app from Android's share sheet (OsmAnd,
|
||||||
|
// Locus, mapy.com, a file manager, ...): public/sw.js parks them in this
|
||||||
|
// cache and opens the app; this offers to import them into a folder of
|
||||||
|
// Tracks & Points. Checked on every page load, not just right after a
|
||||||
|
// share, so a share made while logged out is still waiting after login.
|
||||||
|
const SHARED_CACHE = "shared-files";
|
||||||
|
const KNOWN_EXTENSION = /\.(gpx|fit|geojson|zip)$/i;
|
||||||
|
// Some apps share a bare name ("Track 12") — the upload only accepts
|
||||||
|
// these extensions, so one is added from the file's type.
|
||||||
|
const EXTENSION_BY_TYPE = {
|
||||||
|
"application/gpx+xml": ".gpx",
|
||||||
|
"application/xml": ".gpx",
|
||||||
|
"text/xml": ".gpx",
|
||||||
|
"application/geo+json": ".geojson",
|
||||||
|
"application/json": ".geojson",
|
||||||
|
"application/zip": ".zip",
|
||||||
|
"application/vnd.ant.fit": ".fit",
|
||||||
|
};
|
||||||
|
const DEFAULT_FOLDER = "Shared";
|
||||||
|
|
||||||
|
export async function offerSharedFiles(gpxPanel) {
|
||||||
|
if (new URLSearchParams(window.location.search).has("shared")) window.history.replaceState(null, "", "/");
|
||||||
|
if (!("caches" in window)) return;
|
||||||
|
|
||||||
|
let cache;
|
||||||
|
let requests;
|
||||||
|
try {
|
||||||
|
cache = await caches.open(SHARED_CACHE);
|
||||||
|
requests = await cache.keys();
|
||||||
|
} catch {
|
||||||
|
return; // storage blocked — nothing to offer
|
||||||
|
}
|
||||||
|
if (requests.length === 0) return;
|
||||||
|
|
||||||
|
const files = await Promise.all(
|
||||||
|
requests.map(async (request) => {
|
||||||
|
const response = await cache.match(request);
|
||||||
|
const blob = await response.blob();
|
||||||
|
return new File([blob], withExtension(decodeURIComponent(response.headers.get("x-filename") || "shared"), blob.type), {
|
||||||
|
type: blob.type,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const discard = () => Promise.all(requests.map((request) => cache.delete(request)));
|
||||||
|
|
||||||
|
const card = document.createElement("div");
|
||||||
|
card.className = "share-import";
|
||||||
|
card.innerHTML = `
|
||||||
|
<strong>Shared to MapTool</strong>
|
||||||
|
<ul class="share-import__files">${files.map((file) => `<li>${escapeHtml(file.name)}</li>`).join("")}</ul>
|
||||||
|
${
|
||||||
|
isLoggedIn()
|
||||||
|
? `<label class="share-import__folder">Folder
|
||||||
|
<input type="text" value="${DEFAULT_FOLDER}" list="share-import-folders">
|
||||||
|
<datalist id="share-import-folders"></datalist>
|
||||||
|
</label>
|
||||||
|
<div class="share-import__actions">
|
||||||
|
<button type="button" data-action="import">Import</button>
|
||||||
|
<button type="button" data-action="discard">Discard</button>
|
||||||
|
</div>`
|
||||||
|
: `<p>Log in to import — they'll wait here until then.</p>
|
||||||
|
<div class="share-import__actions">
|
||||||
|
<a href="/login">Log in</a>
|
||||||
|
<button type="button" data-action="discard">Discard</button>
|
||||||
|
</div>`
|
||||||
|
}
|
||||||
|
<p class="share-import__status" hidden></p>
|
||||||
|
`;
|
||||||
|
document.body.appendChild(card);
|
||||||
|
|
||||||
|
card.querySelector('[data-action="discard"]').addEventListener("click", async () => {
|
||||||
|
await discard();
|
||||||
|
card.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
const importButton = card.querySelector('[data-action="import"]');
|
||||||
|
if (!importButton) return;
|
||||||
|
|
||||||
|
fillFolderSuggestions(card.querySelector("datalist"));
|
||||||
|
importButton.addEventListener("click", async () => {
|
||||||
|
const folder = card.querySelector(".share-import__folder input").value.trim();
|
||||||
|
card.querySelectorAll("button").forEach((button) => (button.disabled = true));
|
||||||
|
const paths = await gpxPanel.importFiles(files, folder);
|
||||||
|
if (paths.length > 0) {
|
||||||
|
await discard();
|
||||||
|
card.remove();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Nothing made it in (wrong file type, server error) — keep them
|
||||||
|
// parked so another try or a discard is still possible.
|
||||||
|
const status = card.querySelector(".share-import__status");
|
||||||
|
status.hidden = false;
|
||||||
|
status.textContent = "Import failed — only GPX, FIT, GeoJSON and ZIP files can be imported.";
|
||||||
|
card.querySelectorAll("button").forEach((button) => (button.disabled = false));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function withExtension(name, type) {
|
||||||
|
return KNOWN_EXTENSION.test(name) ? name : `${name}${EXTENSION_BY_TYPE[type] || ".gpx"}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fillFolderSuggestions(datalist) {
|
||||||
|
try {
|
||||||
|
const tree = await (await fetch("/api/gpx/tree")).json();
|
||||||
|
const folders = [];
|
||||||
|
const walk = (node) =>
|
||||||
|
(node.children || []).forEach((child) => {
|
||||||
|
if (child.type !== "folder") return;
|
||||||
|
folders.push(child.path);
|
||||||
|
walk(child);
|
||||||
|
});
|
||||||
|
walk(tree);
|
||||||
|
datalist.innerHTML = folders.map((path) => `<option value="${escapeHtml(path)}">`).join("");
|
||||||
|
} catch {
|
||||||
|
// suggestions only — typing a folder name still works
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "MapTool",
|
||||||
|
"short_name": "MapTool",
|
||||||
|
"description": "Offline maps, tracks and points for the van",
|
||||||
|
"start_url": "/",
|
||||||
|
"scope": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#1a1a1a",
|
||||||
|
"theme_color": "#1a1a1a",
|
||||||
|
"icons": [
|
||||||
|
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||||
|
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
|
||||||
|
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
|
||||||
|
],
|
||||||
|
"share_target": {
|
||||||
|
"action": "/share-target",
|
||||||
|
"method": "POST",
|
||||||
|
"enctype": "multipart/form-data",
|
||||||
|
"params": {
|
||||||
|
"files": [
|
||||||
|
{
|
||||||
|
"name": "file",
|
||||||
|
"accept": [
|
||||||
|
"application/gpx+xml", ".gpx",
|
||||||
|
"application/geo+json", "application/json", ".geojson",
|
||||||
|
"application/zip", ".zip",
|
||||||
|
".fit", "application/vnd.ant.fit",
|
||||||
|
"application/xml", "text/xml",
|
||||||
|
"application/octet-stream"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
-2
@@ -1,11 +1,16 @@
|
|||||||
// Caches RainViewer radar tile images so the last-seen frames stay visible
|
// Caches RainViewer radar tile images so the last-seen frames stay visible
|
||||||
// once the network is actually gone — nothing else here. No app-shell
|
// once the network is actually gone, and receives files shared to the
|
||||||
|
// installed app (manifest.webmanifest's share_target, below). No app-shell
|
||||||
// precaching: the app itself is served by the same local server that's
|
// precaching: the app itself is served by the same local server that's
|
||||||
// already the offline resource in the van, so there's no "app unreachable
|
// already the offline resource in the van, so there's no "app unreachable
|
||||||
// but should still work" scenario to solve, unlike the radar tiles (a
|
// but should still work" scenario to solve, unlike the radar tiles (a
|
||||||
// third-party CDN).
|
// third-party CDN).
|
||||||
const CACHE_VERSION = "v1";
|
const CACHE_VERSION = "v1";
|
||||||
const RADAR_CACHE = `radar-tiles-${CACHE_VERSION}`;
|
const RADAR_CACHE = `radar-tiles-${CACHE_VERSION}`;
|
||||||
|
// Files shared to the app wait here until the page imports them (see
|
||||||
|
// public/js/share_import.js) — not versioned, so a SW update can't drop a
|
||||||
|
// file someone shared but hasn't imported yet.
|
||||||
|
const SHARED_CACHE = "shared-files";
|
||||||
|
|
||||||
// ponytail: a rough cap, not real LRU/expiry — trims oldest-by-insertion via
|
// ponytail: a rough cap, not real LRU/expiry — trims oldest-by-insertion via
|
||||||
// Cache API iteration order (stable in practice, not spec-guaranteed).
|
// Cache API iteration order (stable in practice, not spec-guaranteed).
|
||||||
@@ -25,13 +30,17 @@ self.addEventListener("activate", (event) => {
|
|||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches
|
caches
|
||||||
.keys()
|
.keys()
|
||||||
.then((keys) => Promise.all(keys.filter((key) => key !== RADAR_CACHE).map((key) => caches.delete(key))))
|
.then((keys) => Promise.all(keys.filter((key) => key !== RADAR_CACHE && key !== SHARED_CACHE).map((key) => caches.delete(key))))
|
||||||
.then(() => self.clients.claim()),
|
.then(() => self.clients.claim()),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
self.addEventListener("fetch", (event) => {
|
self.addEventListener("fetch", (event) => {
|
||||||
const url = new URL(event.request.url);
|
const url = new URL(event.request.url);
|
||||||
|
if (event.request.method === "POST" && url.origin === self.location.origin && url.pathname === "/share-target") {
|
||||||
|
event.respondWith(receiveSharedFiles(event.request));
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!isRadarTile(url)) return;
|
if (!isRadarTile(url)) return;
|
||||||
|
|
||||||
event.respondWith(networkFallingBackToCache(event.request));
|
event.respondWith(networkFallingBackToCache(event.request));
|
||||||
@@ -61,3 +70,32 @@ async function trimRadarCache(cache) {
|
|||||||
if (keys.length <= MAX_RADAR_TILES) return;
|
if (keys.length <= MAX_RADAR_TILES) return;
|
||||||
await Promise.all(keys.slice(0, keys.length - MAX_RADAR_TILES).map((key) => cache.delete(key)));
|
await Promise.all(keys.slice(0, keys.length - MAX_RADAR_TILES).map((key) => cache.delete(key)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Android's share sheet (OsmAnd, Locus, mapy.com, a file manager, ...)
|
||||||
|
// POSTs the files here. They're parked in SHARED_CACHE rather than
|
||||||
|
// uploaded straight away: the page does that with a normal same-origin
|
||||||
|
// request (session cookie, login redirect, folder choice) — see
|
||||||
|
// share_import.js.
|
||||||
|
async function receiveSharedFiles(request) {
|
||||||
|
try {
|
||||||
|
const form = await request.formData();
|
||||||
|
const cache = await caches.open(SHARED_CACHE);
|
||||||
|
const stamp = Date.now();
|
||||||
|
await Promise.all(
|
||||||
|
form
|
||||||
|
.getAll("file")
|
||||||
|
.filter((file) => file instanceof File)
|
||||||
|
.map((file, i) =>
|
||||||
|
cache.put(
|
||||||
|
`/shared-files/${stamp}-${i}`,
|
||||||
|
new Response(file, {
|
||||||
|
headers: { "content-type": file.type || "application/octet-stream", "x-filename": encodeURIComponent(file.name || "shared") },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// fall through to the app anyway — nothing parked just means nothing to offer
|
||||||
|
}
|
||||||
|
return Response.redirect("/?shared=1", 303);
|
||||||
|
}
|
||||||
@@ -212,6 +212,19 @@ class AppTest < Minitest::Test
|
|||||||
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original)
|
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_pwa_manifest_is_served_as_a_manifest_and_declares_the_share_target
|
||||||
|
response = request.get("/manifest.webmanifest")
|
||||||
|
assert_equal 200, response.status
|
||||||
|
assert_equal "application/manifest+json", response.content_type
|
||||||
|
assert_equal "/share-target", JSON.parse(response.body).dig("share_target", "action")
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_share_target_without_a_service_worker_goes_back_to_the_map
|
||||||
|
response = request.post("/share-target")
|
||||||
|
assert_equal 303, response.status
|
||||||
|
assert_equal "/", URI(response.location).path
|
||||||
|
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
|
||||||
|
|||||||
+4
-1
@@ -20,6 +20,9 @@ class PlacesTest < Minitest::Test
|
|||||||
feature("Point", [18.0, 48.0], "highway" => "crossing"), # no name -> skipped
|
feature("Point", [18.0, 48.0], "highway" => "crossing"), # no name -> skipped
|
||||||
feature("Polygon", [[[17.0, 48.0], [17.01, 48.0], [17.01, 48.01], [17.0, 48.0]]], "name" => "Bytovka Lidl", "building" => "yes"),
|
feature("Polygon", [[[17.0, 48.0], [17.01, 48.0], [17.01, 48.01], [17.0, 48.0]]], "name" => "Bytovka Lidl", "building" => "yes"),
|
||||||
feature("Polygon", [[[17.0, 48.0], [17.01, 48.0], [17.01, 48.01], [17.0, 48.0]]], "name" => "Družstvo", "landuse" => "farmland"),
|
feature("Polygon", [[[17.0, 48.0], [17.01, 48.0], [17.01, 48.01], [17.0, 48.0]]], "name" => "Družstvo", "landuse" => "farmland"),
|
||||||
|
feature("Point", [17.3, 48.3], "name" => "Pod Družstvom", "place" => "locality"),
|
||||||
|
feature("Point", [17.3, 48.31], "name" => "Samota Družstevná", "place" => "isolated_dwelling"),
|
||||||
|
feature("LineString", [[17.0, 48.0], [17.5, 48.5]], "name" => "Bus 31 Družstvo", "type" => "route"),
|
||||||
feature("Polygon", [[[17.2, 48.1], [17.21, 48.1], [17.21, 48.11], [17.2, 48.1]]],
|
feature("Polygon", [[[17.2, 48.1], [17.21, 48.1], [17.21, 48.11], [17.2, 48.1]]],
|
||||||
"name" => "Lidl Petržalka", "brand" => "Lidl", "shop" => "supermarket", "building" => "retail"),
|
"name" => "Lidl Petržalka", "brand" => "Lidl", "shop" => "supermarket", "building" => "retail"),
|
||||||
feature("Point", [17.15, 48.15], "name" => "McDonald's", "amenity" => "fast_food", "brand" => "McDonald's"),
|
feature("Point", [17.15, 48.15], "name" => "McDonald's", "amenity" => "fast_food", "brand" => "McDonald's"),
|
||||||
@@ -63,7 +66,7 @@ class PlacesTest < Minitest::Test
|
|||||||
|
|
||||||
def test_buildings_and_land_use_are_dropped_but_a_shop_in_a_building_is_kept
|
def test_buildings_and_land_use_are_dropped_but_a_shop_in_a_building_is_kept
|
||||||
assert_empty search("bytovka")
|
assert_empty search("bytovka")
|
||||||
assert_empty search("druzstvo")
|
assert_empty search("druzstv") # landuse, locality, isolated dwelling, no kind at all
|
||||||
assert_equal [["Lidl Petržalka", "supermarket"]], search("lidl").map { |r| r.values_at(:name, :kind) }
|
assert_equal [["Lidl Petržalka", "supermarket"]], search("lidl").map { |r| r.values_at(:name, :kind) }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,12 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>MapTool</title>
|
<title>MapTool</title>
|
||||||
|
<%# Installable as an app (PWA) — mainly so Android's share sheet offers
|
||||||
|
MapTool as a target for GPX/FIT files, see public/sw.js. %>
|
||||||
|
<link rel="manifest" href="/manifest.webmanifest">
|
||||||
|
<meta name="theme-color" content="#1a1a1a">
|
||||||
|
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
|
||||||
|
<link rel="apple-touch-icon" href="/icons/icon-192.png">
|
||||||
<link rel="stylesheet" href="/vendor/maplibre-gl/maplibre-gl.css">
|
<link rel="stylesheet" href="/vendor/maplibre-gl/maplibre-gl.css">
|
||||||
<link rel="stylesheet" href="/css/style.css?v=<%= ASSET_VERSION %>">
|
<link rel="stylesheet" href="/css/style.css?v=<%= ASSET_VERSION %>">
|
||||||
</head>
|
</head>
|
||||||
@@ -47,6 +53,7 @@
|
|||||||
"/js/panels.js": "/js/panels.js?v=<%= ASSET_VERSION %>",
|
"/js/panels.js": "/js/panels.js?v=<%= ASSET_VERSION %>",
|
||||||
"/js/plugins.js": "/js/plugins.js?v=<%= ASSET_VERSION %>",
|
"/js/plugins.js": "/js/plugins.js?v=<%= ASSET_VERSION %>",
|
||||||
"/js/radar.js": "/js/radar.js?v=<%= ASSET_VERSION %>",
|
"/js/radar.js": "/js/radar.js?v=<%= ASSET_VERSION %>",
|
||||||
|
"/js/share_import.js": "/js/share_import.js?v=<%= ASSET_VERSION %>",
|
||||||
"/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>",
|
"/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>",
|
||||||
"/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>",
|
"/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>",
|
||||||
"/js/sun.js": "/js/sun.js?v=<%= ASSET_VERSION %>",
|
"/js/sun.js": "/js/sun.js?v=<%= ASSET_VERSION %>",
|
||||||
|
|||||||
Reference in new issue
Block a user