import { Popup, LngLatBounds, Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { PointStyleFields, formatToolbar } from "/js/notes.js";
import {
GPX_ICON,
NEW_FOLDER_ICON,
UPLOAD_ICON,
DOWNLOAD_ICON,
SYNC_ICON,
MAP_MARKER_ICON,
POI_ICONS,
PARK4NIGHT_TAGS,
} from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged, addRoutePoint, editRoute } from "/js/panels.js";
import { formatActivityType } from "/js/track_profile.js";
import { isLoggedIn } from "/js/auth.js";
const TREE_URL = "/api/library/tree";
const UPLOAD_URL = "/api/library/import";
const FOLDER_URL = "/api/library/folder";
const MOVE_URL = "/api/library/move";
const TRACK_COLOR = "#e63946";
const TRACK_CASING = "#1d2a1f";
const ARROW_IMAGE = "track-arrow";
// Tracks without a color of their own get one of these, fixed per file,
// so several shown together are told apart.
const TRACK_PALETTE = ["#5a55e0", "#7cc957", "#e0a32e", "#9058d6", "#e63946", "#2aa7a0"];
const POI_ICON_KEYS = Object.keys(POI_ICONS);
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
const POI_ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
const MAP_MARKER_SIZE = 0.55;
// The clusters as the same rounded-square badge, light -> dark by count
// (16 / 20 / 26 px "radius" before, now that half the side).
const CLUSTER_COLORS = ["#a8c8ea", "#5b9bd5", "#2e6da4"];
const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge color actually seen, see _registerBadgeColors
// Custom drag payload MIME type for moving an already-uploaded file between
// folders, as opposed to an OS file drag (type "Files") for uploading a new
// one — both land on the same drop targets, told apart by this.
const MOVE_MIME = "application/x-gpx-path";
const GPX_VISIBLE_KEY = "gpxVisible";
// The kinds the Library filters by: chip label, a row's word for one, glyph and colour.
const KINDS = {
waypoint: { label: "Points", one: "points", glyph: "●", color: "#12bedf" },
track: { label: "Tracks", one: "track", glyph: "〰", color: "#c2410c" },
route: { label: "Routes", one: "route", glyph: "↝", color: "#1d6fdc" },
layer: { label: "Layers", one: "layer", glyph: "▤", color: "#6b6b66" },
};
const FOLDER_DRAG_PREFIX = "folder:";
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; // a dragged folder's MOVE_MIME payload, vs. a node key
// A sidebar icon that opens a side panel for uploading GPX files (via
// drag & drop, stored server-side in a folder hierarchy the user can add to
// and reorganize by dragging), and toggling their tracks/waypoints on and
// off the map.
export class GpxPanelControl {
constructor(map, profilePanel) {
this._map = map;
this._profilePanel = profilePanel;
this._visible = new Set(); // file paths currently shown on the map
this._interactiveLayers = new Set(); // point layer ids with click/hover wired up
this._pointsByPath = new Map(); // path -> its waypoints FeatureCollection, for the category legend
this._linesByPath = new Map(); // path -> its lines/polygons FeatureCollection, same reason (a polygon/line note also carries a category)
this._hiddenCategories = new Set(); // category names toggled off in the legend
this._openDownloadMenu = null; // the one gpx-tree__download-menu currently open, if any
// setStyle() (switching the Online/Offline base map) tears down all
// custom sources/layers/images — _addLayers re-registers the glyph and
// badge images a file needs before putting its layers back.
map.on("style.load", () => this._visible.forEach((path) => this._addLayers(path)));
// notes.js writes directly into the same GPX store (a hand-drawn note
// saved into a .geojson layer) — refresh so a newly created/grown file
// shows up in the tree without a manual reopen, and auto-show it (check
// + render) since a note the user just placed being invisible until
// they find and check its layer by hand defeats the point of dropping
// a pin right there on the map.
onGpxStoreChanged((path) => {
if (path) {
this._visible.add(path);
this._reloadFile(path);
}
this._loadTree();
});
}
// Registered on first use, always white, as plain (non-SDF) images: these used to
// be SDF images tinted white via icon-color, but MapLibre's SDF rendering
// assumes the source encodes an actual distance field (a smooth multi-pixel
// gradient at each edge) — feeding it a normally-antialiased raster (a
// sharp 1px edge transition) instead made every glyph noticeably softer
// than the base map's own icons, especially shrunk down to icon-size 0.3.
// Since the glyph color never varies (always white, unlike the badge
// below), there's no need for SDF's runtime-tintable alpha mask at all —
// baking the color into the raster and skipping SDF renders as sharp as
// any ordinary sprite.
// Only the icons a file actually uses: there are ~330 to choose from.
async _registerCategoryGlyphs(keys) {
await Promise.all(
[...keys].filter((key) => POI_ICONS[key]).map(async (key) => {
if (this._map.hasImage(key)) return;
const whiteSvg = POI_ICONS[key].replace(/currentColor/g, "#fff");
const imageData = await svgToImageData(whiteSvg, POI_ICON_IMAGE_SIZE);
if (!this._map.hasImage(key)) this._map.addImage(key, imageData);
}),
);
}
// The badge's color is per-category data (arbitrary hex from a GPX file),
// so unlike the glyphs it can't be a single fixed-color image — but a real
// POI export only ever has a handful of distinct category colors, so it's
// cheap to rasterize one sharp, non-SDF image per color actually seen
// (rather than one shared image SDF-tinted at render time, which is what
// made these blurry — see _registerCategoryGlyphs above) and cache them by
// color for reuse across files.
async _registerBadgeColors(colors) {
await Promise.all(
[...colors].map(async (color) => {
const id = badgeImageId(color);
if (this._map.hasImage(id)) return;
const coloredSvg = MAP_MARKER_ICON.replace(/currentColor/g, color);
const imageData = await svgToImageData(coloredSvg, POI_ICON_IMAGE_SIZE);
if (!this._map.hasImage(id)) this._map.addImage(id, imageData);
}),
);
}
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item";
this._container.innerHTML = ``;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("gpx-panel");
this._treeContainer = this._panel.querySelector(".gpx-tree");
this._legendContainer = this._panel.querySelector(".gpx-legend");
this._uploadStatus = this._panel.querySelector(".gpx-upload__status");
this._panel.querySelector('[data-action="new-folder"]').innerHTML = NEW_FOLDER_ICON;
this._panel.querySelector('[data-action="upload"]').innerHTML = UPLOAD_ICON;
if (!isLoggedIn()) {
this._panel.querySelector('[data-action="new-folder"]').hidden = true;
this._panel.querySelector('[data-action="upload"]').hidden = true;
} else {
// The top level's own items have no folder row with a menu of its own.
const close = this._panel.querySelector(".gpx-panel__close");
close.before(this._menuButton(DOWNLOAD_ICON, "Export the top level", this._exportEntries("", "MapTool")));
// A sync client (the car's server) syncs with the main one on demand.
if ("syncClient" in this._panel.dataset) {
const sync = document.createElement("button");
sync.type = "button";
sync.className = "gpx-panel__action";
sync.title = "Sync with the main server";
sync.setAttribute("aria-label", sync.title);
sync.innerHTML = SYNC_ICON;
sync.addEventListener("click", () => this._sync(sync));
close.before(sync);
}
}
this._panel
.querySelector(".gpx-panel__close")
.addEventListener("click", () => this._togglePanel(false));
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
// Closes whichever per-file download menu is open on any click that
// isn't the toggle button that opened it (that one calls
// stopPropagation so this never fights it) — same "outside click
// closes it" behavior sidebar-flyout dropdowns already have, just not
// wired through onlyOneSidePanelOpen since these aren't full side
// panels.
document.addEventListener("click", () => this._closeDownloadMenu());
this._setupFind();
this._setupToolbarActions();
this._setupRootDropTarget();
this._setupMapDropTarget();
this._loadTree();
sidebar.appendChild(this._container);
}
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
this._icon.classList.toggle("active", open);
if (open) notifySidePanelOpen(this._panel);
}
// Both toolbar actions are icon buttons now (matching OsmAnd's tracks
// panel) rather than an always-visible dropzone/form: upload triggers the
// native file picker, new folder prompts for a path.
_setupToolbarActions() {
const fileInput = this._panel.querySelector(".gpx-file-input");
fileInput.addEventListener("change", () => {
this._uploadFiles(fileInput.files, this._cwd);
fileInput.value = "";
});
this._panel.querySelector('[data-action="upload"]').addEventListener("click", () => fileInput.click());
this._panel.querySelector('[data-action="new-folder"]').addEventListener("click", async () => {
const path = window.prompt("New folder name (e.g. Hiking/2026):", this._cwd ? `${this._cwd}/` : "");
if (!path || !path.trim()) return;
const response = await fetch(FOLDER_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `path=${encodeURIComponent(path.trim())}`,
});
if (redirectIfUnauthorized(response)) return;
if (response.ok) {
const { tree } = await response.json();
this._renderTree(tree);
}
});
}
// The tree itself is the drop target for both an OS file drag (upload to
// the top level) and, for anywhere that isn't a folder (blank space, or
// onto another file — folder drop targets call stopPropagation() so this
// only fires then), an internal file drag (move back to the top level).
_setupRootDropTarget() {
this._treeContainer.addEventListener("dragover", (event) => {
if (!event.dataTransfer.types.includes("Files") && !event.dataTransfer.types.includes(MOVE_MIME)) return;
event.preventDefault();
this._treeContainer.classList.add("gpx-drop-hover");
});
this._treeContainer.addEventListener("dragleave", (event) => {
if (event.target === this._treeContainer) this._treeContainer.classList.remove("gpx-drop-hover");
});
this._treeContainer.addEventListener("drop", (event) => {
event.preventDefault();
this._treeContainer.classList.remove("gpx-drop-hover");
if (event.dataTransfer.files?.length > 0) {
this._uploadFiles(event.dataTransfer.files, this._cwd);
return;
}
const from = event.dataTransfer.getData(MOVE_MIME);
if (from) this._moveFile(from, this._cwd);
});
}
// Dropping a GPX file straight onto the map (not just the panel) uploads
// it to the top level too.
_setupMapDropTarget() {
const mapContainer = this._map.getContainer();
mapContainer.addEventListener("dragover", (event) => {
if (!event.dataTransfer.types.includes("Files")) return;
event.preventDefault();
mapContainer.classList.add("gpx-drop-hover");
});
mapContainer.addEventListener("dragleave", (event) => {
if (event.target === mapContainer) mapContainer.classList.remove("gpx-drop-hover");
});
mapContainer.addEventListener("drop", (event) => {
mapContainer.classList.remove("gpx-drop-hover");
if (event.dataTransfer.files?.length > 0) {
event.preventDefault();
this._uploadFiles(event.dataTransfer.files, "");
}
});
}
async _loadTree() {
const response = await fetch(TREE_URL);
const tree = await response.json();
this._renderTree(tree);
}
// The Design canvas' Library (after Locus Map): find on top — the text,
// what kinds, only the shown ones — then one folder level at a time (← up,
// the path), or, while searching or in List view, every match flat with
// the folder it lives in. An eye per row: ● shown, ◐ some (a folder), ○ not.
_renderTree(node) {
this._root = node;
this._files = new Map();
this._folders = new Map([["", node]]);
const index = (n) => (n.children || []).forEach((c) => {
if (c.type === "folder") {
this._folders.set(c.path, c);
index(c);
} else {
c.folder = n.path;
this._files.set(c.path, c);
}
});
index(node);
if (!this._folders.has(this._cwd ?? "")) this._cwd = "";
if (this._openTrack && !this._files.has(this._openTrack)) this._openTrack = null;
this._renderView();
}
_setupFind() {
this._cwd = "";
this._query = "";
this._mode = "folders";
this._kindsOn = new Set(Object.keys(KINDS));
this._shownOnly = false;
const find = this._panel.querySelector(".lib-find");
const input = find.querySelector(".lib-find__input");
input.addEventListener("input", () => {
this._query = input.value.trim().toLowerCase();
this._renderView();
});
find.querySelector(".lib-find__kinds").addEventListener("click", (event) => {
const chip = event.target.closest("[data-kind]");
if (!chip) return;
const kind = chip.dataset.kind;
if (this._kindsOn.has(kind) && this._kindsOn.size > 1) this._kindsOn.delete(kind);
else this._kindsOn.add(kind);
this._renderView();
});
find.querySelector('[data-find="shown"]').addEventListener("click", () => {
this._shownOnly = !this._shownOnly;
this._renderView();
});
find.querySelectorAll("[data-mode]").forEach((button) => button.addEventListener("click", () => {
this._mode = button.dataset.mode;
this._renderView();
}));
this._crumb = this._panel.querySelector(".lib-crumb");
this._footer = this._panel.querySelector(".lib-foot__text");
this._panel.querySelector('[data-action="hide-all"]').addEventListener("click", () => {
[...this._visible].forEach((path) => this._toggleFileOnly(path, false));
this._saveVisible();
this._renderView();
});
}
_kindOf(file) {
if (file.layer) return "layer";
if (file.kinds?.includes("route")) return "route";
if (file.kinds?.includes("track")) return "track";
return "waypoint";
}
_matches(file) {
if (!this._kindsOn.has(this._kindOf(file))) return false;
if (this._shownOnly && !this._visible.has(file.path)) return false;
return !this._query || `${file.folder} ${file.name}`.toLowerCase().includes(this._query);
}
// Every file under a folder (all levels).
_filesUnder(path) {
return [...this._files.values()].filter((f) => f.folder === path || f.folder.startsWith(`${path}/`) || path === "");
}
_renderView() {
if (!this._root) return;
const find = this._panel.querySelector(".lib-find");
const counts = {};
this._files.forEach((f) => (counts[this._kindOf(f)] = (counts[this._kindOf(f)] || 0) + 1));
find.querySelector(".lib-find__kinds").innerHTML = Object.entries(KINDS)
.map(([kind, { label, color }]) => ``)
.join("");
find.querySelector('[data-find="shown"]').setAttribute("aria-pressed", this._shownOnly);
const flat = this._mode === "list" || this._query;
find.querySelectorAll("[data-mode]").forEach((button) => button.setAttribute("aria-pressed", (button.dataset.mode === "list") === Boolean(flat)));
const ul = document.createElement("ul");
ul.className = "lib-list";
if (flat) {
this._crumb.hidden = true;
if (this._query) {
[...this._folders.values()]
.filter((f) => f.path && f.name.toLowerCase().includes(this._query))
.forEach((f) => ul.appendChild(this._folderRow(f, true)));
}
[...this._files.values()].filter((f) => this._matches(f)).forEach((f) => ul.appendChild(this._fileRow(f, true)));
} else if (this._openTrack) {
const track = this._files.get(this._openTrack);
this._renderCrumb(track.folder, track.name, plural(track.points.length, "point"), () => (this._openTrack = null));
track.points.forEach((point) => ul.appendChild(this._pointRow(track, point)));
} else {
const folder = this._folders.get(this._cwd);
const subfolders = folder.children.filter((c) => c.type === "folder");
const files = folder.children.filter((c) => c.type !== "folder" && this._matches(c));
if (this._cwd) {
const parent = this._cwd.includes("/") ? this._cwd.slice(0, this._cwd.lastIndexOf("/")) : "";
this._renderCrumb(parent, folder.name, `${plural(subfolders.length, "folder")} · ${plural(files.length, "item")}`, () => (this._cwd = parent), parent);
} else {
this._crumb.hidden = true;
}
subfolders.forEach((f) => ul.appendChild(this._folderRow(f)));
files.forEach((f) => ul.appendChild(this._fileRow(f)));
}
if (!ul.children.length) {
ul.innerHTML = `
${this._query ? "Nothing found" : "Nothing here yet"}
`;
}
this._treeContainer.innerHTML = "";
this._treeContainer.appendChild(ul);
this._footer.textContent = `${plural(this._folders.size - 1, "folder")} · ${plural(this._files.size, "item")} · ${this._visible.size} shown`;
}
// ← up, the path to here and its name; `dropTo` (the parent) also takes a
// dragged item, to move it a level up.
_renderCrumb(path, name, meta, up, dropTo) {
this._crumb.hidden = false;
this._crumb.innerHTML = "";
const back = Object.assign(document.createElement("button"), { type: "button", className: "lib-crumb__up", textContent: "←", title: "Up" });
back.addEventListener("click", () => {
up();
this._renderView();
});
if (dropTo !== undefined && isLoggedIn()) this._wireFolderDropTarget(back, dropTo);
const where = Object.assign(document.createElement("span"), { className: "lib-crumb__path", textContent: path ? `${path.replaceAll("/", " › ")} › ` : "" });
this._crumb.append(back, where, Object.assign(document.createElement("b"), { textContent: name }), Object.assign(document.createElement("small"), { textContent: meta }));
}
_row({ icon, color, name, meta, aside, eye, onOpen, onEye, bold }) {
const li = document.createElement("li");
li.className = "lib-row";
li.innerHTML = ``;
const iconEl = li.querySelector(".lib-row__icon");
iconEl.textContent = icon;
iconEl.style.color = color || "";
li.querySelector(".lib-row__name").textContent = name;
li.querySelector(".lib-row__name").classList.toggle("lib-row__name--folder", Boolean(bold));
li.querySelector(".lib-row__meta").textContent = meta || "";
li.querySelector(".lib-row__aside").textContent = aside || "";
li.querySelector(".lib-row__text").addEventListener("click", onOpen);
if (eye) {
const button = Object.assign(document.createElement("button"), { type: "button", className: `lib-eye lib-eye--${eye}`, textContent: { all: "●", some: "◐", none: "○" }[eye] });
button.title = eye === "none" ? "Show on the map" : "Hide from the map";
button.setAttribute("aria-label", button.title);
button.setAttribute("aria-pressed", eye !== "none");
button.addEventListener("click", onEye);
li.appendChild(button);
}
return li;
}
_folderRow(folder, withPath = false) {
const files = this._filesUnder(folder.path);
const shown = files.filter((f) => this._visible.has(f.path)).length;
const subfolders = folder.children.filter((c) => c.type === "folder").length;
const items = folder.children.length - subfolders;
const parent = folder.path.includes("/") ? folder.path.slice(0, folder.path.lastIndexOf("/")).replaceAll("/", " › ") : "";
const li = this._row({
icon: "▣",
name: folder.name,
bold: true,
meta: [withPath && parent, subfolders && plural(subfolders, "folder"), plural(items, "item")].filter(Boolean).join(" · "),
aside: "›",
eye: files.length ? (shown === 0 ? "none" : shown === files.length ? "all" : "some") : null,
onOpen: () => {
this._cwd = folder.path;
this._openTrack = null;
this._query = "";
this._mode = "folders";
this._panel.querySelector(".lib-find__input").value = "";
this._renderView();
},
onEye: async () => {
const show = shown === 0;
await Promise.all(files.map((f) => this._toggleFileOnly(f.path, show)));
this._saveVisible();
this._renderView();
},
});
if (isLoggedIn()) {
li.appendChild(this._menuButton("⋯", "Actions", [
{ label: "Rename…", run: () => this._renameFolder(folder) },
...this._exportEntries(folder.path, folder.name),
{ label: "Delete…", run: () => this._deleteFolder(folder.path) },
]));
li.draggable = true;
li.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
event.dataTransfer.effectAllowed = "move";
});
this._wireFolderDropTarget(li, folder.path);
}
return li;
}
_fileRow(file, withPath = false) {
const kind = this._kindOf(file);
const visible = this._visible.has(file.path);
const li = this._row({
icon: KINDS[kind].glyph,
color: file.color || KINDS[kind].color,
name: file.name,
meta: [withPath && (file.folder ? file.folder.replaceAll("/", " › ") : "Top level"), KINDS[kind].one, file.points && plural(file.points.length, "point")].filter(Boolean).join(" · "),
aside: file.points ? "›" : "",
eye: visible ? "all" : "none",
// the name zooms to it, shown first if needed; a track's points open
// from its ›
onOpen: async (event) => {
if (file.points && event.target.closest(".lib-row__aside, .lib-row__meta")) {
this._openTrack = file.path;
return this._renderView();
}
if (!this._visible.has(file.path)) await this._toggleFile(file.path, true);
if (this._visible.has(file.path)) this._zoomTo(file.path);
this._renderView();
},
onEye: async () => {
await this._toggleFile(file.path, !visible);
this._renderView();
},
});
if (file.points) {
li.querySelector(".lib-row__aside").addEventListener("click", () => {
this._openTrack = file.path;
this._renderView();
});
}
li.draggable = true;
li.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, file.path);
event.dataTransfer.effectAllowed = "move";
});
// Every action behind one ⋯ menu (as OsmAnd does), shown only once
// logged in: they all require login (app.rb).
if (isLoggedIn()) li.appendChild(this._fileMenu(file));
return li;
}
_pointRow(track, point) {
const li = this._row({
icon: "●",
color: KINDS.waypoint.color,
name: point.name,
meta: "point",
onOpen: () => this._goToPoint(track.path, point),
});
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(track, point)));
return li;
}
async _goToPoint(path, point) {
await this.show(path);
this._map.flyTo({ center: point.coordinates, zoom: Math.max(this._map.getZoom(), 15) });
const feature = this._pointsByPath.get(path)?.features.find((f) => f.properties.id === point.id);
if (feature) this._openPointPopup(path, feature, point.coordinates);
}
async _removePoint(file, point) {
if (!window.confirm(`Remove "${point.name}" from "${file.name}"?`)) return;
const response = await fetch(`/api/library/notes?${new URLSearchParams({ path: file.path, id: point.id })}`, { method: "DELETE" });
if (!response.ok) return window.alert("Could not remove the point.");
await this._loadTree();
if (this._visible.has(file.path)) await this._reloadFile(file.path);
}
// A copy of the point into a shown track/route, which keeps it from
// then on (exported with it, a course point in its FIT course).
async _addPointTo(target, feature) {
const { id, ...properties } = feature.properties;
const body = new URLSearchParams({ feature: JSON.stringify({ type: "Feature", geometry: { type: "Point", coordinates: feature.geometry.coordinates }, properties }) });
const response = await fetch(`${gpxFileUrl(target)}/points`, { method: "POST", body });
if (!response.ok) return window.alert("Could not add the point.");
this._renderTree((await response.json()).tree);
await this._reloadFile(target);
}
_fileMenu(file) {
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
// A folder's "Points (N)" node has no name or color of its own.
const item = file.path.startsWith("item:");
return this._menuButton("⋯", "Actions", [
item && { label: "Rename…", run: () => this._renameFile(file) },
item && { label: "Color…", run: () => this._pickColor(file) },
item && file.color && { label: "Default color", run: () => this._patchNode(file.path, { color: "" }) },
item && file.layer && { label: "Split into items", run: () => this._splitLayer(file) },
item && (file.kinds || []).includes("route") && { label: "Edit route", run: () => this._editRoute(file) },
// A folder's loose points have no single file they came from.
file.original && { label: "Download original file", run: () => this._download(`${gpxFileUrl(file.path)}?download=original`, file.name) },
{ label: "Download GeoJSON", run: () => this._download(geojsonUrl, `${file.name}.geojson`) },
// A course for a Garmin/Wahoo device to follow.
file.kinds?.some((kind) => kind === "track" || kind === "route") && {
label: "Download FIT course (Garmin, Wahoo)",
run: () => this._download(`${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "fit", name: file.name })}`, `${file.name}.fit`),
},
{ label: "Delete…", run: () => this._deleteFile(file) },
]);
}
// A button opening a small menu of `entries` ({ label, run }, falsy ones
// skipped).
_menuButton(content, title, entries) {
const wrapper = document.createElement("span");
wrapper.className = "gpx-tree__download-wrapper";
const button = document.createElement("button");
button.type = "button";
button.className = "gpx-tree__download";
button.title = title;
button.setAttribute("aria-label", title);
button.innerHTML = content;
const menu = document.createElement("div");
menu.className = "gpx-tree__download-menu";
menu.hidden = true;
entries.filter(Boolean).forEach(({ label, run }) => {
const item = document.createElement("button");
item.type = "button";
item.className = "gpx-tree__download-menu-item";
item.textContent = label;
item.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this._closeDownloadMenu();
run();
});
menu.appendChild(item);
});
// stopPropagation so this click doesn't immediately reach the
// document-level listener (mount()) that closes whichever menu is
// open on an outside click, nor toggle a folder's .
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this._toggleDownloadMenu(menu);
});
wrapper.appendChild(button);
wrapper.appendChild(menu);
return wrapper;
}
// Only one menu open at a time — opening a second one closes whichever
// was already open, same as onlyOneSidePanelOpen does for the sidebar's
// own panels (panels.js), just scoped to this one control instead of
// shared across the page.
_toggleDownloadMenu(menu) {
if (this._openDownloadMenu === menu) {
this._closeDownloadMenu();
return;
}
this._closeDownloadMenu();
menu.hidden = false;
this._openDownloadMenu = menu;
}
_closeDownloadMenu() {
if (this._openDownloadMenu) this._openDownloadMenu.hidden = true;
this._openDownloadMenu = null;
}
// fetch-based rather than a plain navigation so a 401 (not logged in —
// both download kinds require login now, see app.rb) redirects to
// /login like every other write action in this file
// (redirectIfUnauthorized), instead of navigating to a raw JSON error
// page. The filename is already known client-side, so there's no need
// to parse it back out of a Content-Disposition header.
async _download(url, filename) {
const response = await fetch(url);
if (redirectIfUnauthorized(response)) return;
if (!response.ok) {
window.alert("Could not download the file.");
return;
}
const blobUrl = URL.createObjectURL(await response.blob());
const link = document.createElement("a");
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(blobUrl);
}
_deleteButton(onClick) {
const button = document.createElement("button");
button.type = "button";
button.className = "gpx-tree__delete";
button.title = "Delete";
button.textContent = "×";
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
onClick();
});
return button;
}
// A folder accepts both an OS file drag (upload straight into it) and an
// internal file drag (move into it).
_wireFolderDropTarget(summary, folderPath) {
summary.addEventListener("dragover", (event) => {
if (!event.dataTransfer.types.includes("Files") && !event.dataTransfer.types.includes(MOVE_MIME)) return;
event.preventDefault();
summary.classList.add("gpx-drop-hover");
});
summary.addEventListener("dragleave", () => summary.classList.remove("gpx-drop-hover"));
summary.addEventListener("drop", (event) => {
event.preventDefault();
event.stopPropagation();
summary.classList.remove("gpx-drop-hover");
if (event.dataTransfer.files?.length > 0) {
this._uploadFiles(event.dataTransfer.files, folderPath);
return;
}
const from = event.dataTransfer.getData(MOVE_MIME);
if (from) this._moveFile(from, folderPath);
});
}
// 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.
async show(path) {
if (this._visible.has(path)) return;
await this._toggleFile(path, true);
this._renderView();
}
// For the driving grid's Points (driving.js): the tree as indexed by
// _renderTree, whether a node is shown, and showing / hiding nodes.
libraryTree() {
return { folders: this._folders || new Map(), files: this._files || new Map(), filesUnder: (path) => this._filesUnder(path) };
}
isShown(path) {
return this._visible.has(path);
}
async setShown(paths, visible) {
await Promise.all(paths.map((path) => this._toggleFileOnly(path, visible)));
this._saveVisible();
this._renderView();
}
zoomTo(path) {
return this._zoomTo(path);
}
// Search result picked: show its file, then open the matching point's
// popup as if it had been clicked on the map. Matched by exact
// coordinates (the search index reads the same GeoJSON); a track/line
// result has no popup to open, so it just shows the file.
async showFeature(path, [lng, lat]) {
await this.show(path);
const feature = this._pointsByPath
.get(path)
?.features.find((f) => f.geometry.coordinates[0] === lng && f.geometry.coordinates[1] === lat);
if (feature) this._openPointPopup(path, feature, [lng, lat]);
}
// The shown files, per device (localStorage) — back after a reload by restore().
_saveVisible() {
try { localStorage.setItem(GPX_VISIBLE_KEY, JSON.stringify([...this._visible])); } catch { /* private window: not kept */ }
}
async restore() {
let paths = [];
try { paths = JSON.parse(localStorage.getItem(GPX_VISIBLE_KEY)) || []; } catch { /* nothing kept */ }
await Promise.all(paths.map((path) => this.show(path)));
}
async _toggleFile(path, visible, checkbox) {
await this._toggleFileOnly(path, visible, checkbox);
this._saveVisible();
}
async _toggleFileOnly(path, visible, checkbox) {
if (visible) {
this._visible.add(path);
const ok = await this._addLayers(path);
if (!ok) {
// Loading failed (see _addLayers) — don't leave the box checked
// for a file that isn't actually showing anything.
this._visible.delete(path);
if (checkbox) checkbox.checked = false;
}
} else {
this._visible.delete(path);
this._removeLayers(path);
}
}
async _zoomTo(path) {
const sources = [linesSourceId(path), pointsSourceId(path)].map((id) => this._map.getSource(id)).filter(Boolean);
const bounds = new LngLatBounds();
const extend = (c) => (typeof c[0] === "number" ? bounds.extend([c[0], c[1]]) : c.forEach(extend));
for (const source of sources) (await source.getData()).features.forEach((f) => f.geometry && extend(f.geometry.coordinates));
if (!bounds.isEmpty()) this._map.fitBounds(bounds, { padding: 60, maxZoom: 15 });
}
// Fetches the file's GeoJSON itself (rather than handing maplibre a URL
// to fetch internally) so a parse failure — a real GPX a device/app
// wrote in some way REXML doesn't like, say — surfaces as an alert
// instead of the layer just silently never appearing. Returns whether it
// succeeded.
async _addLayers(path) {
const linesId = linesSourceId(path);
const pointsId = pointsSourceId(path);
if (this._map.getSource(linesId) || this._map.getSource(pointsId)) return true;
let geojson;
try {
const response = await fetch(gpxFileUrl(path));
if (!response.ok) {
const { error } = await response.json().catch(() => ({}));
window.alert(error || `Could not load "${path}".`);
return false;
}
geojson = await response.json();
} catch (err) {
window.alert(`Could not load "${path}": ${err.message}`);
return false;
}
if (this._map.getSource(linesId) || this._map.getSource(pointsId)) return true; // added concurrently (e.g. a style.load race) while this was fetching
// Split into two sources: MapLibre's clustering only understands a
// source made entirely of Point/MultiPoint features, and a file can mix
// a track/route line with waypoints (or, like a park4night POI export,
// be thousands of waypoints and nothing else).
const lines = { type: "FeatureCollection", features: [] };
const points = { type: "FeatureCollection", features: [] };
for (const feature of geojson.features) {
(feature.geometry.type === "Point" ? points : lines).features.push(feature);
}
// Normalized here (rather than a ["coalesce", ...] in the layer's
// icon-image expression) so every point's badge color is known upfront,
// before registering the per-color badge images below.
for (const feature of points.features) {
feature.properties.color ||= TRACK_COLOR;
}
this._map.addSource(linesId, { type: "geojson", data: lines });
// Excludes category:"Note" — a saved Measure-tool distance line gets
// its own layer below (popup-on-click, not this hover-summary/profile-
// panel track behavior), not this one.
// Tracks: a dark casing under the colored line, direction arrows along
// it and a dot at each end.
const trackFilter = ["all", ["!=", ["get", "category"], "Note"], ["!=", ["geometry-type"], "Polygon"]]; // also true without a category (null)
this._map.addLayer({
id: `${linesId}-casing`,
type: "line",
source: linesId,
filter: trackFilter,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": TRACK_CASING, "line-width": ["interpolate", ["linear"], ["zoom"], 8, 4, 14, 8] },
});
this._map.addLayer({
id: `${linesId}-line`,
type: "line",
source: linesId,
filter: trackFilter,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": ["coalesce", ["get", "color"], defaultTrackColor(path)], "line-width": ["interpolate", ["linear"], ["zoom"], 8, 2, 14, 5] },
});
this._registerLineInteractivity(`${linesId}-line`);
if (!this._map.hasImage(ARROW_IMAGE)) this._map.addImage(ARROW_IMAGE, arrowImage(), { pixelRatio: 2 });
this._map.addLayer({
id: `${linesId}-arrows`,
type: "symbol",
source: linesId,
filter: trackFilter,
minzoom: 10,
layout: { "symbol-placement": "line", "symbol-spacing": 160, "icon-image": ARROW_IMAGE, "icon-rotation-alignment": "map", "icon-allow-overlap": true, "icon-ignore-placement": true },
});
this._map.addSource(`${linesId}-ends`, { type: "geojson", data: lineEnds(lines) });
this._map.addLayer({
id: `${linesId}-ends`,
type: "circle",
source: `${linesId}-ends`,
paint: { "circle-radius": ["interpolate", ["linear"], ["zoom"], 8, 4, 14, 7], "circle-color": TRACK_CASING, "circle-stroke-color": "#fff", "circle-stroke-width": 2 },
});
// Polygon/line notes (see notes.js and measure.js's "Save as note") —
// the same "lines" source already only renders LineString geometry
// through the line layer above, and Polygon geometry isn't drawn by a
// "line"-type layer at all (MapLibre only draws LineString for that
// type), so these are just more layers reading the same source, not a
// new bucket. Popup-on-click like a waypoint (_registerPointInteractivity),
// not the track line's hover-summary/profile-panel behavior — a note
// has no elevation profile to open.
this._map.addLayer({
id: `${linesId}-polygon-fill`,
type: "fill",
source: linesId,
filter: ["==", ["geometry-type"], "Polygon"],
paint: { "fill-color": TRACK_COLOR, "fill-opacity": 0.2 },
});
this._map.addLayer({
id: `${linesId}-polygon-outline`,
type: "line",
source: linesId,
filter: ["==", ["geometry-type"], "Polygon"],
paint: { "line-color": TRACK_COLOR, "line-width": 2 },
});
this._registerPointInteractivity(`${linesId}-polygon-fill`, path);
this._map.addLayer({
id: `${linesId}-note-line`,
type: "line",
source: linesId,
filter: ["all", ["==", ["geometry-type"], "LineString"], ["==", ["get", "category"], "Note"]],
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": TRACK_COLOR, "line-width": 3, "line-dasharray": [2, 1] },
});
this._registerPointInteractivity(`${linesId}-note-line`, path);
// clusterRadius/clusterMaxZoom are harmless when there's nothing dense
// enough to cluster (a handful of waypoints just render individually).
this._map.addSource(pointsId, { type: "geojson", data: points, cluster: true, clusterRadius: 50, clusterMaxZoom: 14 });
const badgeColors = new Set([...points.features.map((f) => f.properties.color), ...CLUSTER_COLORS]);
await Promise.all([this._registerCategoryGlyphs(new Set(points.features.map((f) => f.properties.icon))), this._registerBadgeColors(badgeColors)]);
if (!this._map.getSource(pointsId)) return true; // a style.load (basemap switch) tore it down while icons were loading
this._addClusterLayers(pointsId, path);
if (points.features.length > 0) this._pointsByPath.set(path, points);
if (lines.features.length > 0) this._linesByPath.set(path, lines);
this._updateLegend();
this._applyCategoryFilter();
return true;
}
// A single-hue, light->dark ramp keyed on point_count (magnitude, not
// category) for the cluster badges; individual points below that use
// each waypoint's own category color (see Maptool::Gpx#waypoint_color),
// falling back to the plain track color for waypoints with no category
// (e.g. a hand-placed GNSS pin, not from a POI export).
_addClusterLayers(pointsId, path) {
this._map.addLayer({
id: `${pointsId}-clusters`,
type: "symbol",
source: pointsId,
filter: ["has", "point_count"],
layout: {
"icon-image": ["step", ["get", "point_count"], badgeImageId(CLUSTER_COLORS[0]), 25, badgeImageId(CLUSTER_COLORS[1]), 100, badgeImageId(CLUSTER_COLORS[2])],
"icon-size": ["step", ["get", "point_count"], 32 / POI_ICON_IMAGE_SIZE, 25, 40 / POI_ICON_IMAGE_SIZE, 100, 52 / POI_ICON_IMAGE_SIZE],
"icon-allow-overlap": true,
"icon-ignore-placement": true,
},
});
this._map.addLayer({
id: `${pointsId}-cluster-count`,
type: "symbol",
source: pointsId,
filter: ["has", "point_count"],
layout: { "text-field": ["get", "point_count_abbreviated"], "text-font": ["Noto Sans Regular"], "text-size": 11 },
paint: { "text-color": "#fff" },
});
// A rounded-square badge (icons.js's MAP_MARKER_ICON), not a plain
// circle: a flat colored dot looked too much like a base map style's
// own small circular POI icons, so individual waypoints blended in
// instead of standing out as "your data". A rounded square rather than
// a pin/teardrop specifically to match how the NPS itself frames these
// exact category symbols (POI_ICONS below) on its own maps. Centered on
// the coordinate — a square has no natural "tip" the way a pin does, so
// default center anchoring is simplest and also means the glyph layer
// below needs no offset, just the same center anchor.
// A point with no NPS symbol (a Google saved place, a bare GPX
// waypoint) is a small badge instead, about half the size — a full-size
// empty badge read as a big red square.
const single = ["!", ["has", "point_count"]];
const hasSymbol = ["in", ["get", "icon"], ["literal", POI_ICON_KEYS]];
this._map.addLayer({
id: `${pointsId}-dot`,
type: "symbol",
source: pointsId,
filter: ["all", single, ["!", hasSymbol]],
layout: {
"icon-image": ["concat", BADGE_IMAGE_PREFIX, ["get", "color"]],
"icon-size": ["interpolate", ["linear"], ["zoom"], 6, 8 / POI_ICON_IMAGE_SIZE, 14, 13 / POI_ICON_IMAGE_SIZE],
"icon-allow-overlap": true,
"icon-ignore-placement": true,
},
});
this._map.addLayer({
id: `${pointsId}-unclustered`,
type: "symbol",
source: pointsId,
filter: ["all", single, hasSymbol],
layout: {
"icon-image": ["concat", BADGE_IMAGE_PREFIX, ["get", "color"]],
"icon-size": MAP_MARKER_SIZE,
"icon-allow-overlap": true,
"icon-ignore-placement": true,
},
});
// Only for the curated POI_ICON_KEYS (see icons.js) — anything else
// (a plain hand-placed waypoint, or a category p4n2gpx/OsmAnd hasn't
// been taught here) just keeps the plain badge above with no glyph.
this._map.addLayer({
id: `${pointsId}-unclustered-icon`,
type: "symbol",
source: pointsId,
filter: ["all", single, hasSymbol],
layout: {
"icon-image": ["get", "icon"],
"icon-size": POI_ICON_SIZE,
"icon-allow-overlap": true,
"icon-ignore-placement": true,
},
});
// Its name beside each point from zoom 10, NPS-map style: dark text
// on a white halo, right of the dot/badge, dropped where it collides.
this._map.addLayer({
id: `${pointsId}-label`,
type: "symbol",
source: pointsId,
filter: single,
minzoom: 10,
layout: {
"text-field": ["get", "name"],
"text-font": ["Noto Sans Regular"],
"text-size": 12,
"text-anchor": "left",
"text-offset": ["case", hasSymbol, ["literal", [1.4, 0]], ["literal", [0.8, 0]]],
"text-max-width": 10,
},
paint: { "text-color": "#2b2b2b", "text-halo-color": "#fff", "text-halo-width": 1.5 },
});
this._registerClusterInteractivity(pointsId);
this._registerPointInteractivity(`${pointsId}-unclustered`, path);
this._registerPointInteractivity(`${pointsId}-dot`, path);
}
// Clicking a cluster zooms in just far enough to break it apart, the
// standard MapLibre cluster-expansion pattern.
_registerClusterInteractivity(pointsId) {
const clusterId = `${pointsId}-clusters`;
if (this._interactiveLayers.has(clusterId)) return;
this._interactiveLayers.add(clusterId);
this._map.on("click", clusterId, async (event) => {
const feature = this._map.queryRenderedFeatures(event.point, { layers: [clusterId] })[0];
if (!feature) return;
const zoom = await this._map.getSource(pointsId).getClusterExpansionZoom(feature.properties.cluster_id);
this._map.easeTo({ center: feature.geometry.coordinates, zoom });
});
this._map.on("mouseenter", clusterId, () => {
this._map.getCanvas().style.cursor = "pointer";
});
this._map.on("mouseleave", clusterId, () => {
this._map.getCanvas().style.cursor = "";
});
}
// Registered once per layer id, ever — map.on(type, layerId, fn) is a
// delegated listener that lives on the map itself and keeps matching
// that layer id after setStyle() removes and (via _addLayers) re-adds
// it, so re-registering on every re-add would stack duplicate popups.
// `path` (which file this layer's features came from) is only used for
// a "Note" feature's Edit/Delete actions — plain GPX/FIT/park4night
// waypoints don't get those, so it's otherwise unused.
_registerPointInteractivity(layerId, path) {
if (this._interactiveLayers.has(layerId)) return;
this._interactiveLayers.add(layerId);
this._map.on("click", layerId, (event) => {
const feature = event.features[0];
if (feature) this._openPointPopup(path, feature, event.lngLat);
});
this._map.on("mouseenter", layerId, () => {
this._map.getCanvas().style.cursor = "pointer";
});
this._map.on("mouseleave", layerId, () => {
this._map.getCanvas().style.cursor = "";
});
}
_openPointPopup(path, feature, lngLat) {
// properties.id is what update/delete target by — a note saved before
// that existed (see `rake gpx:backfill_note_ids`) doesn't have one
// yet, and offering Edit/Delete for it would just 404.
// Any point or note kept in the library (it has an id) can be edited;
// a waypoint inside an old uploaded file without one can't.
const editable = !!feature.properties.id && isLoggedIn();
const popup = new Popup({ closeButton: true, maxWidth: "260px" })
.setLngLat(lngLat)
.setHTML(popupHtml(feature.properties, { editable, movable: feature.geometry.type === "Point" }))
.addTo(this._map);
if (editable) this._wireNoteActions(popup, path, feature);
if (feature.geometry.type === "Point") {
const button = document.createElement("button");
button.type = "button";
button.className = "gpx-popup__route";
button.textContent = "Add to route";
button.addEventListener("click", () => {
addRoutePoint(feature.geometry.coordinates, feature.properties.name);
popup.remove();
});
const content = popup.getElement().querySelector(".maplibregl-popup-content");
content.appendChild(button);
if (isLoggedIn()) {
// Into any track/route shown right now, or out of the one holding it.
const holder = this._files?.get(path)?.points?.some((p) => p.id === feature.properties.id) && this._files.get(path);
const targets = [...this._visible].filter((p) => p !== path && p.startsWith("item:") && this._files?.get(p)?.kinds?.some((k) => k === "track" || k === "route") && !this._files.get(p).layer);
targets.forEach((target) => {
content.appendChild(this._popupButton(`Add to "${this._files.get(target).name}"`, async () => {
popup.remove();
await this._addPointTo(target, feature);
}));
});
if (holder) {
content.appendChild(this._popupButton(`Remove from "${holder.name}"`, async () => {
popup.remove();
await this._removePoint(holder, { id: feature.properties.id, name: feature.properties.name || "Point" });
}));
}
}
}
}
_popupButton(label, onClick) {
const button = document.createElement("button");
button.type = "button";
button.className = "gpx-popup__route";
button.textContent = label;
button.addEventListener("click", onClick);
return button;
}
// Edit swaps the popup's content for a plain textarea + Save/Cancel (the
// note's location doesn't change, just its text, so there's no need for
// NoteSaveForm's fuller target-file picker here). Delete just confirms
// and removes. Both end by reloading the file's layers from the server —
// simplest way to keep the map, the category legend, and this popup's
// own feature data all in sync with what the edit/delete actually wrote,
// rather than hand-patching three different client-side copies of it.
_wireNoteActions(popup, path, feature) {
const element = popup.getElement();
const id = feature.properties.id;
element.querySelector(".gpx-popup__delete")?.addEventListener("click", async () => {
if (!window.confirm("Delete this note?")) return;
try {
const response = await fetch(`/api/library/notes?${new URLSearchParams({ path, id })}`, { method: "DELETE" });
if (!response.ok) throw new Error(`delete failed: ${response.status}`);
popup.remove();
notifyGpxStoreChanged();
await this._reloadFile(path);
} catch (err) {
window.alert("Could not delete the note — check your connection and try again.");
}
});
element.querySelector(".gpx-popup__edit")?.addEventListener("click", () => {
const content = popup.getElement().querySelector(".maplibregl-popup-content");
content.innerHTML = `
`;
const titleInput = content.querySelector(".gpx-popup__edit-title");
const bodyInput = content.querySelector(".gpx-popup__edit-body");
bodyInput.before(formatToolbar(bodyInput));
const style = new PointStyleFields(content.querySelector(".gpx-popup__edit-style"));
style.set(feature.properties.icon || "", feature.properties.color === TRACK_COLOR ? "" : feature.properties.color || "");
style.iconsVisible = feature.geometry.type === "Point";
titleInput.focus();
content.querySelector(".gpx-popup__edit-cancel").addEventListener("click", () => {
content.innerHTML = popupHtml(feature.properties, { editable: true, movable: feature.geometry.type === "Point" });
this._wireNoteActions(popup, path, feature);
});
content.querySelector(".gpx-popup__edit-save").addEventListener("click", async () => {
const title = titleInput.value.trim();
if (!title) return;
const details = bodyInput.value.trim();
const properties = style.applyTo({ ...feature.properties, name: title });
if (details) properties.description = details;
else delete properties.description;
if (await this._saveNote(path, { ...feature, properties })) popup.remove();
});
});
// Move: a draggable marker at the point — drag it, or tap the new spot —
// with Save/Cancel in a popup that follows it.
element.querySelector(".gpx-popup__move")?.addEventListener("click", () => {
popup.remove();
this._moveNote(path, feature);
});
}
_moveNote(path, feature) {
this._cancelMove?.();
const markerEl = document.createElement("div");
markerEl.className = "route-marker note-move-marker";
const marker = new Marker({ element: markerEl, draggable: true }).setLngLat(feature.geometry.coordinates).addTo(this._map);
const bar = document.createElement("div");
bar.className = "gpx-popup__move-bar";
bar.innerHTML = `
Drag the point or tap its new spot
`;
const barPopup = new Popup({ closeButton: false, closeOnClick: false, offset: 22, maxWidth: "240px" }).setDOMContent(bar);
marker.setPopup(barPopup).togglePopup();
const onMapClick = (event) => {
marker.setLngLat(event.lngLat);
if (!barPopup.isOpen()) marker.togglePopup();
};
this._map.on("click", onMapClick);
const end = () => {
this._map.off("click", onMapClick);
marker.remove();
this._cancelMove = null;
};
this._cancelMove = end;
bar.querySelector(".gpx-popup__edit-cancel").addEventListener("click", end);
bar.querySelector(".gpx-popup__edit-save").addEventListener("click", async () => {
const { lng, lat } = marker.getLngLat();
if (await this._saveNote(path, { ...feature, geometry: { ...feature.geometry, coordinates: [lng, lat] } })) end();
});
}
// PUTs the edited note and reloads its file's layers; false on failure.
async _saveNote(path, updated) {
try {
const body = new URLSearchParams({ path, id: updated.properties.id, feature: JSON.stringify(updated) });
const response = await fetch("/api/library/notes", { method: "PUT", body });
if (!response.ok) throw new Error(`save failed: ${response.status}`);
notifyGpxStoreChanged();
await this._reloadFile(path);
return true;
} catch (err) {
window.alert("Could not save the note — check your connection and try again.");
return false;
}
}
async _reloadFile(path) {
this._removeLayers(path);
await this._addLayers(path);
}
// Hover shows a quick summary (unlike a waypoint popup, which is
// click-triggered — a track's summary describes the whole line, not
// whatever point along it happens to get hovered, so there's no single
// right anchor point worth waiting for a click on). Click opens the full
// profile panel, which does need the click gesture to avoid flashing
// open on every casual hover.
_registerLineInteractivity(layerId) {
if (this._interactiveLayers.has(layerId)) return;
this._interactiveLayers.add(layerId);
let popup = null;
this._map.on("mouseenter", layerId, (event) => {
this._map.getCanvas().style.cursor = "pointer";
const feature = event.features[0];
if (!feature) return;
popup = new Popup({ closeButton: false, closeOnClick: false, maxWidth: "260px" })
.setLngLat(event.lngLat)
.setHTML(trackPopupHtml(feature.properties))
.addTo(this._map);
});
this._map.on("mouseleave", layerId, () => {
this._map.getCanvas().style.cursor = "";
popup?.remove();
popup = null;
});
this._map.on("click", layerId, (event) => {
const feature = event.features[0];
if (feature) this._profilePanel?.show(feature.properties);
});
}
_removeLayers(path) {
const linesId = linesSourceId(path);
const pointsId = pointsSourceId(path);
[
`${linesId}-casing`,
`${linesId}-line`,
`${linesId}-arrows`,
`${linesId}-ends`,
`${linesId}-polygon-fill`,
`${linesId}-polygon-outline`,
`${linesId}-note-line`,
`${pointsId}-clusters`,
`${pointsId}-cluster-count`,
`${pointsId}-dot`,
`${pointsId}-unclustered`,
`${pointsId}-unclustered-icon`,
`${pointsId}-label`,
].forEach((layerId) => {
if (this._map.getLayer(layerId)) this._map.removeLayer(layerId);
});
if (this._map.getSource(linesId)) this._map.removeSource(linesId);
if (this._map.getSource(`${linesId}-ends`)) this._map.removeSource(`${linesId}-ends`);
if (this._map.getSource(pointsId)) this._map.removeSource(pointsId);
this._pointsByPath.delete(path);
this._linesByPath.delete(path);
this._updateLegend();
}
// Rebuilt from whichever visible files actually carry categorized
// waypoints (a park4night/OsmAnd POI export) — a plain GPS track has none
// and the legend just stays hidden. Doubles as a filter: each item is a
// toggle button (Unigrid-style icon grid) that hides/shows that category
// on the map, not just a read-only color key.
_updateLegend() {
const categories = new Map(); // category name -> { color, icon }
for (const collection of [...this._pointsByPath.values(), ...this._linesByPath.values()]) {
for (const feature of collection.features) {
const category = feature.properties.category;
if (category && !categories.has(category)) {
categories.set(category, { color: feature.properties.color || TRACK_COLOR, icon: feature.properties.icon });
}
}
}
this._legendContainer.innerHTML = "";
this._legendContainer.hidden = categories.size === 0;
[...categories].sort(([a], [b]) => a.localeCompare(b)).forEach(([category, { color, icon }]) => {
const item = document.createElement("button");
item.type = "button";
item.className = "gpx-legend__item";
item.classList.toggle("gpx-legend__item--hidden", this._hiddenCategories.has(category));
item.title = category;
item.setAttribute("aria-pressed", String(!this._hiddenCategories.has(category)));
const glyph = document.createElement("span");
if (icon && POI_ICONS[icon]) {
glyph.className = "gpx-legend__icon";
glyph.innerHTML = POI_ICONS[icon];
} else {
glyph.className = "gpx-legend__swatch";
glyph.style.background = color; // a malformed/malicious value from an uploaded file is simply ignored by the CSSOM, never parsed as markup
}
const label = document.createElement("span");
label.className = "gpx-legend__label";
label.textContent = category;
item.appendChild(glyph);
item.appendChild(label);
item.addEventListener("click", () => {
if (!this._hiddenCategories.delete(category)) this._hiddenCategories.add(category);
this._updateLegend();
this._applyCategoryFilter();
});
this._legendContainer.appendChild(item);
});
}
// Re-clusters each visible file's points around only the categories still
// toggled on — a plain layer `filter` can't do this: MapLibre clusters a
// GeoJSON source's *entire* data set regardless of what a layer filter
// hides, so a cluster's count/expansion would stay wrong. Cheap to redo
// in full: _pointsByPath already holds each file's complete features in
// memory, this is just re-slicing it, no re-parsing or network involved.
_applyCategoryFilter() {
for (const [path, points] of this._pointsByPath) {
const source = this._map.getSource(pointsSourceId(path));
if (!source) continue;
const visible = points.features.filter((f) => !this._hiddenCategories.has(f.properties.category));
source.setData({ type: "FeatureCollection", features: visible });
}
// Same re-slicing for polygon/line notes sharing the "lines" source with
// plain tracks/routes — those have no `category` of their own, so
// `_hiddenCategories.has(undefined)` is always false and they're never
// affected by this, only a hidden Note (or other categorized) shape is.
for (const [path, lines] of this._linesByPath) {
const source = this._map.getSource(linesSourceId(path));
if (!source) continue;
const visible = lines.features.filter((f) => !this._hiddenCategories.has(f.properties.category));
source.setData({ type: "FeatureCollection", features: visible });
}
}
async _uploadFiles(fileList, folder) {
// .zip: Garmin's bulk/FIT export format — the server expands it into
// its .gpx/.fit/.geojson entries, so it's accepted here even though the
// tree never shows a .zip itself. .geojson: e.g. a node's GeoJSON
// download, re-imported.
const files = [...fileList].filter((file) => /\.(gpx|fit|tcx|geojson|zip)$/i.test(file.name));
if (files.length === 0) return [];
let tree = null;
let failed = 0;
const uploaded = [];
for (const [index, file] of files.entries()) {
this._setStatus(files.length === 1 ? "Uploading…" : `Uploading ${index + 1} of ${files.length}…`);
const formData = new FormData();
formData.append("file", file);
formData.append("folder", folder);
try {
// fetch() has no cross-browser upload progress event, so this one
// upload uses XMLHttpRequest instead — its upload.progress firing
// with loaded === total is the only client-observable signal that
// the server has (or is about to start) converting rather than
// still receiving bytes, worth surfacing now that a several-
// thousand-waypoint POI export's conversion can itself take
// several more seconds on top of the transfer (GpxStore#save).
const xhr = await uploadFile(formData, () => this._setStatus("Converting…"));
if (xhr.status === 401) {
window.location.href = "/login";
return uploaded;
}
if (xhr.status < 200 || xhr.status >= 300) throw new Error("upload failed");
let paths;
({ tree, paths } = JSON.parse(xhr.responseText));
uploaded.push(...paths);
} catch (err) {
failed += 1;
}
}
if (tree) this._renderTree(tree);
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, name }) {
if (!window.confirm(`Delete "${name}"?`)) return;
const response = await fetch(gpxFileUrl(path), { method: "DELETE" });
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
if (this._visible.has(path)) {
this._visible.delete(path);
this._removeLayers(path);
}
const { tree } = await response.json();
this._renderTree(tree);
}
async _deleteFolder(path) {
if (!window.confirm(`Delete "${path}" and everything in it?`)) return;
const response = await fetch(`/api/library/folder/${path.split("/").map(encodeURIComponent).join("/")}`, {
method: "DELETE",
});
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
// Node keys don't carry their folder's path — whatever's no longer in
// the tree was in the deleted folder.
const { tree } = await response.json();
const remaining = new Set(nodeKeys(tree));
[...this._visible].forEach((key) => {
if (remaining.has(key)) return;
this._visible.delete(key);
this._removeLayers(key);
});
this._renderTree(tree);
}
async _moveFile(from, toFolder) {
if (from.startsWith(FOLDER_DRAG_PREFIX)) {
await this._patchFolder(from.slice(FOLDER_DRAG_PREFIX.length), { to_folder: toFolder });
return;
}
const response = await fetch(MOVE_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `key=${encodeURIComponent(from)}&to_folder=${encodeURIComponent(toFolder)}`,
});
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
const { path: newPath, tree } = await response.json();
if (this._visible.has(from) && newPath !== from) {
this._visible.delete(from);
this._removeLayers(from);
this._visible.add(newPath);
this._addLayers(newPath);
}
this._renderTree(tree);
}
// A folder (or "" for the top level) as files for the phone apps.
_exportEntries(path, name) {
const url = (flavor) => `/api/library/export?${new URLSearchParams({ folder: path, flavor })}`;
return [
{ label: "Export for Locus (GPX)", run: () => this._download(url("locus"), `${name}.gpx`) },
{ label: "Export for OsmAnd (zip)", run: () => this._download(url("osmand"), `${name}-osmand.zip`) },
];
}
async _renameFolder(folder) {
const name = window.prompt("Rename folder:", folder.name);
if (name && name.trim() && name.trim() !== folder.name) await this._patchFolder(folder.path, { name: name.trim() });
}
// Node keys are ids, so nothing shown on the map changes with its folder.
async _patchFolder(path, fields) {
const response = await fetch(`${FOLDER_URL}/${path.split("/").map(encodeURIComponent).join("/")}`, {
method: "PATCH",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(fields),
});
if (redirectIfUnauthorized(response)) return;
if (response.status === 409) window.alert("A folder with that name already exists there.");
if (!response.ok) return;
this._renderTree((await response.json()).tree);
}
async _renameFile(file) {
const name = window.prompt("Rename:", file.name);
if (name && name.trim() && name.trim() !== file.name) await this._patchNode(file.path, { name: name.trim() });
}
// The native color picker; one hidden input reused for every node.
_pickColor(file) {
if (!this._colorInput) {
this._colorInput = document.createElement("input");
this._colorInput.type = "color";
this._colorInput.hidden = true;
this._panel.appendChild(this._colorInput);
this._colorInput.addEventListener("change", () => this._patchNode(this._colorInput.dataset.path, { color: this._colorInput.value }));
}
this._colorInput.dataset.path = file.path;
this._colorInput.value = file.color || defaultTrackColor(file.path);
this._colorInput.click();
}
async _patchNode(path, fields) {
const response = await fetch(gpxFileUrl(path), {
method: "PATCH",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(fields),
});
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
this._renderTree((await response.json()).tree);
if (this._visible.has(path)) {
this._removeLayers(path);
await this._addLayers(path);
}
}
// A route saved from the route panel keeps its points (properties.via);
// one without them (an imported GPX route) can't be re-routed.
async _editRoute(file) {
const { features } = await (await fetch(gpxFileUrl(file.path))).json();
const route = features.find((f) => f.geometry.type === "LineString" && Array.isArray(f.properties.via));
if (!route) {
window.alert("This route has no saved route points, so it can't be edited.");
return;
}
editRoute(file.path, route);
}
async _splitLayer(file) {
if (!window.confirm(`Split "${file.name}" into separate points and tracks? This can't be undone.`)) return;
this._setStatus("Splitting…");
const response = await fetch(`${gpxFileUrl(file.path)}/split`, { method: "POST" });
if (redirectIfUnauthorized(response)) return;
if (!response.ok) {
this._setStatus("Split failed.");
return;
}
const { paths, tree } = await response.json();
this._renderTree(tree);
this._setStatus("Split.");
if (this._visible.has(file.path)) {
this._visible.delete(file.path);
this._removeLayers(file.path);
await Promise.all(paths.map((path) => this.show(path)));
}
}
async _sync(button) {
button.disabled = true;
this._setStatus("Syncing…");
try {
const response = await fetch("/api/sync/run", { method: "POST" });
if (redirectIfUnauthorized(response)) return;
const body = await response.json();
if (!response.ok) return this._setStatus(body.error || "Sync failed.");
this._setStatus(`Synced: ${body.pulled} from the server, ${body.pushed} sent.`);
await this._loadTree();
await Promise.all([...this._visible].map((path) => this._reloadFile(path)));
} catch {
this._setStatus("Sync failed: the server is unreachable.");
} finally {
button.disabled = false;
}
}
_setStatus(text) {
this._uploadStatus.hidden = false;
this._uploadStatus.textContent = text;
}
}
// Write endpoints require login (see app.rb); a 401 means the session
// expired or was never established — send the user to log in rather than
// silently failing.
function redirectIfUnauthorized(response) {
if (response.status !== 401) return false;
window.location.href = "/login";
return true;
}
// XMLHttpRequest rather than fetch() — only so onUploadComplete (the
// upload.progress event) is available at all; every other write action in
// this file stays on fetch()/redirectIfUnauthorized. Resolves with the xhr
// itself (not just responseText) so the caller can still read .status the
// same way a fetch Response would let it.
function uploadFile(formData, onUploadComplete) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", UPLOAD_URL);
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable && event.loaded === event.total) onUploadComplete();
});
xhr.addEventListener("load", () => resolve(xhr));
xhr.addEventListener("error", () => reject(new Error("network error")));
xhr.send(formData);
});
}
function defaultTrackColor(path) {
let hash = 0;
for (const ch of String(path)) hash = (hash * 31 + ch.charCodeAt(0)) | 0;
return TRACK_PALETTE[Math.abs(hash) % TRACK_PALETTE.length];
}
// Start and end of every track/route line, for the end dots.
function lineEnds(lines) {
const features = [];
for (const f of lines.features) {
if (f.properties?.category === "Note") continue;
const parts = f.geometry.type === "LineString" ? [f.geometry.coordinates] : f.geometry.type === "MultiLineString" ? f.geometry.coordinates : [];
const coords = parts.flat();
if (coords.length < 2) continue;
for (const c of [coords[0], coords.at(-1)]) features.push({ type: "Feature", geometry: { type: "Point", coordinates: c.slice(0, 2) }, properties: {} });
}
return { type: "FeatureCollection", features };
}
// A white pill with a chevron pointing along the line (drawn at 2x).
function arrowImage() {
const [w, h] = [36, 22];
const ctx = Object.assign(document.createElement("canvas"), { width: w, height: h }).getContext("2d");
ctx.beginPath();
ctx.roundRect(1.5, 1.5, w - 3, h - 3, (h - 3) / 2);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.lineWidth = 2.5;
ctx.strokeStyle = TRACK_CASING;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(12, 11);
ctx.lineTo(24, 11);
ctx.moveTo(19, 6);
ctx.lineTo(24, 11);
ctx.lineTo(19, 16);
ctx.lineCap = ctx.lineJoin = "round";
ctx.lineWidth = 2.5;
ctx.stroke();
return ctx.getImageData(0, 0, w, h);
}
// Rasterizes a hand-authored SVG icon to ImageData for map.addImage(), at a
// fixed square size (the source SVGs have no explicit width/height, just a
// viewBox, so one is injected — otherwise an falls back to the CSS
// default replaced-element size instead of the viewBox's aspect).
// Exported: overlays.js's own live layers (Wikipedia, more to come per its
// own doc comment) need the same SVG-to-map-image/badge-id/escaping
// helpers this file already has, and reimplementing them there would just
// be the same three functions typed twice.
export async function svgToImageData(svgMarkup, size) {
// xmlns is required here even though the other hand-drawn icons in this
// app get away without it — those are inlined via innerHTML, where the
// HTML parser assigns the SVG namespace from context, but a standalone
// loads it as its own XML document, which needs an
// explicit namespace or every browser refuses to decode it.
const sized = svgMarkup.replace("