Files
maptool/public/js/notes.js
T

391 lines
16 KiB
JavaScript

import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { NOTE_PIN_ICON, NPS_SYMBOLS, POI_ICONS } from "/js/icons.js";
import { notifyGpxStoreChanged } from "/js/panels.js";
// Human labels for the icon picker's title attribute — POI_ICONS' own keys
// are internal (OSM-tag-shaped) ids, not display text.
const ICON_LABELS = {
amenity_parking: "Parking",
tourism_camp_site: "Camp site",
leisure_picnic_table: "Picnic table",
amenity_fuel: "Fuel",
tourism_hotel: "Lodging",
forest: "Forest",
sport_cycling: "Cycling",
amenity_drinking_water: "Drinking water",
amenity_sanitary_dump_station: "Dump station",
amenity_toilets: "Toilets",
shop_gas: "Gas/LPG refill",
amenity_electricity: "Electricity",
shop_laundry: "Laundry",
leisure_playground: "Playground",
tourism_viewpoint: "Viewpoint",
leisure_swimming: "Swimming",
leisure_fishing: "Fishing",
sport_climbing: "Climbing",
route_hiking: "Hiking",
shop_supermarket: "Supermarket",
shop_convenience: "Convenience store",
};
// The picker: the labelled everyday ones first, then every other NPS symbol
// (named after its file, "drinking-water" → "drinking water").
const CURATED = Object.keys(ICON_LABELS);
const PICKER_ICONS = [
...CURATED.map((key) => [key, ICON_LABELS[key]]),
...Object.keys(NPS_SYMBOLS)
.filter((name) => !CURATED.some((key) => POI_ICONS[key] === NPS_SYMBOLS[name]))
.map((name) => [name, name.replace(/-/g, " ")]),
];
// Badge colors a point can take: the track palette plus NPS olive, brown and
// black. "" = no color of its own (the layer's default badge color).
const POINT_COLORS = ["#e63946", "#e0a32e", "#7cc957", "#2aa7a0", "#5a55e0", "#9058d6", "#546619", "#5e4b3c", "#1a1a1a"];
// Icon + color for a point — shared by the new-note form and the Edit form
// in a point's popup (gpx.js), so both offer the same choices.
export class PointStyleFields {
constructor(container, { onIconChange } = {}) {
this._onIconChange = onIconChange;
this.el = document.createElement("div");
this.el.className = "notes-panel__style";
this.el.innerHTML = `
<div class="notes-panel__colors" role="radiogroup" aria-label="Color">
<button type="button" class="notes-panel__color" data-color="" title="Default color" aria-label="Default color"></button>
${POINT_COLORS.map((c) => `<button type="button" class="notes-panel__color" data-color="${c}" style="--swatch:${c}" title="${c}" aria-label="${c}"></button>`).join("")}
</div>
<div class="notes-panel__icon-picker">
<input type="search" class="notes-panel__icon-filter" placeholder="Find an icon (${PICKER_ICONS.length})">
<div class="notes-panel__icons">
<button type="button" class="notes-panel__icon-option" data-icon="" title="No icon">${NOTE_PIN_ICON}</button>
${PICKER_ICONS.map(
([key, label]) =>
`<button type="button" class="notes-panel__icon-option" data-icon="${key}" title="${escapeAttr(label)}">${POI_ICONS[key]}</button>`,
).join("")}
</div>
</div>
`;
container.appendChild(this.el);
this._filter = this.el.querySelector(".notes-panel__icon-filter");
this._filter.addEventListener("input", () => {
const query = this._filter.value.trim().toLowerCase();
this.el.querySelectorAll(".notes-panel__icon-option").forEach((b) => {
b.hidden = query !== "" && !`${b.title} ${b.dataset.icon}`.toLowerCase().includes(query);
});
});
this.el.querySelectorAll(".notes-panel__icon-option").forEach((button) =>
button.addEventListener("click", () => {
this._setIcon(button.dataset.icon);
this._onIconChange?.(this.icon);
}),
);
this.el.querySelectorAll(".notes-panel__color").forEach((button) => button.addEventListener("click", () => this._setColor(button.dataset.color)));
this.set();
}
// Resets the filter too; an unknown color/icon just leaves none selected.
set(icon = "", color = "") {
this._filter.value = "";
this.el.querySelectorAll(".notes-panel__icon-option").forEach((b) => (b.hidden = false));
this._setIcon(icon);
this._setColor(color);
}
// An icon only makes sense on a single point (not a measured line/area).
set iconsVisible(visible) {
this.el.querySelector(".notes-panel__icon-picker").hidden = !visible;
}
_setIcon(icon) {
this.icon = icon;
this.el.querySelectorAll(".notes-panel__icon-option").forEach((b) => b.classList.toggle("active", b.dataset.icon === icon));
}
_setColor(color) {
this.color = color;
this.el.querySelectorAll(".notes-panel__color").forEach((b) => b.classList.toggle("active", b.dataset.color === color));
}
// Writes icon/color into a feature's properties (removing the ones unset).
applyTo(properties) {
for (const [key, value] of [["icon", this.icon], ["color", this.color]]) {
if (value) properties[key] = value;
else delete properties[key];
}
return properties;
}
}
// B / I buttons above a note's textarea: wrap the selection in the light
// markdown formatNoteBody renders (**bold**, *italic*), or insert an empty
// pair with the cursor in between.
export function formatToolbar(textarea) {
const bar = document.createElement("div");
bar.className = "notes-panel__format";
bar.innerHTML = `<button type="button" data-mark="**" title="Bold" aria-label="Bold"><b>B</b></button><button type="button" data-mark="*" title="Italic" aria-label="Italic"><i>I</i></button>`;
bar.addEventListener("click", (event) => {
const mark = event.target.closest("button")?.dataset.mark;
if (!mark) return;
const { selectionStart: start, selectionEnd: end, value } = textarea;
textarea.value = value.slice(0, start) + mark + value.slice(start, end) + mark + value.slice(end);
textarea.focus();
textarea.setSelectionRange(start + mark.length, end + mark.length);
});
return bar;
}
const NEW_FOLDER_VALUE = "__new__";
// Every hand-drawn note (from here or measure.js's "Save as note") gets one
// of these — the only stable way to find a specific feature again for
// editing/deleting later (see GpxStore#update_feature/#delete_feature):
// array position shifts as other notes are added/removed, and the note's
// own text is exactly the thing an edit changes.
export function generateNoteId() {
return typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
// The "note text + which .geojson layer" form, shared by NotesControl (a
// single click) and measure.js's "Save as note" button (its current
// distance/area shape) — extracted here rather than duplicated in both,
// since the two differ only in *what* the note attaches a location to,
// not in how it's captured or where it's saved. Renders into whatever
// container it's given (each caller owns where that sits in its own panel);
// hidden until open() is called.
export class NoteSaveForm {
constructor(container, { onSaved, onCancel, onIconChange } = {}) {
this._onSaved = onSaved;
this._onCancel = onCancel;
this._onIconChange = onIconChange;
this._el = document.createElement("div");
this._el.className = "notes-panel__form";
this._el.hidden = true;
this._el.innerHTML = `
<input type="text" class="notes-panel__title" placeholder="Title">
<div class="notes-panel__style-slot"></div>
<textarea class="notes-panel__body" rows="3" placeholder="Details (optional) — **bold**, *italic*, links"></textarea>
<select class="notes-panel__target"></select>
<input type="text" class="notes-panel__new-name" placeholder="Folder name" hidden>
<div class="notes-panel__actions">
<button type="button" class="notes-panel__save">Save</button>
<button type="button" class="notes-panel__cancel">Cancel</button>
</div>
`;
container.appendChild(this._el);
this._title = this._el.querySelector(".notes-panel__title");
this._style = new PointStyleFields(this._el.querySelector(".notes-panel__style-slot"), { onIconChange: (icon) => this._onIconChange?.(icon) });
this._body = this._el.querySelector(".notes-panel__body");
this._body.before(formatToolbar(this._body));
this._target = this._el.querySelector(".notes-panel__target");
this._newName = this._el.querySelector(".notes-panel__new-name");
this._saveButton = this._el.querySelector(".notes-panel__save");
this._target.addEventListener("change", () => {
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
if (!this._newName.hidden) this._newName.focus();
});
this._saveButton.addEventListener("click", () => this._save());
this._el.querySelector(".notes-panel__cancel").addEventListener("click", () => this.close(true));
}
get isOpen() {
return !this._el.hidden;
}
async open(geometry) {
this._geometry = geometry;
this._el.hidden = false;
this._title.value = "";
this._body.value = "";
this._style.set();
this._onIconChange?.("");
// An icon only makes sense on a single point — Measure's "Save as
// note" can hand this a LineString/Polygon, which has no one spot for
// a badge glyph to sit at.
this._style.iconsVisible = geometry.type === "Point";
this._title.focus();
await this._populateTargets();
}
close(viaCancel = false) {
this._geometry = null;
this._el.hidden = true;
this._newName.hidden = true;
this._newName.value = "";
if (viaCancel) this._onCancel?.();
}
async _populateTargets() {
const previousValue = this._target.value;
let folders = [];
let lines = [];
try {
const tree = await (await fetch("/api/library/tree")).json();
folders = folderPaths(tree);
lines = this._geometry?.type === "Point" ? trackNodes(tree) : [];
} catch (err) {
// Tree fetch failed — still usable with the top level or a new folder.
}
this._target.innerHTML =
`<option value="">Top level</option>` +
folders.map((path) => `<option value="${escapeAttr(path)}">${escapeText(path)}</option>`).join("") +
`<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>` +
// A point can go straight into a track/route (kept and exported with it).
(lines.length ? `<optgroup label="Into a track / route">${lines.map(([key, label]) => `<option value="${escapeAttr(key)}">${escapeText(label)}</option>`).join("")}</optgroup>` : "");
const values = [...this._target.options].map((o) => o.value);
this._target.value = values.includes(previousValue) ? previousValue : "";
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
}
async _save() {
const title = this._title.value.trim();
const details = this._body.value.trim();
if (!title || !this._geometry) return;
const isNewFolder = this._target.value === NEW_FOLDER_VALUE;
const folder = isNewFolder ? this._newName.value.trim() : this._target.value;
if (isNewFolder && !folder) {
this._newName.focus();
return;
}
const feature = {
type: "Feature",
properties: {
id: generateNoteId(),
name: title,
category: "Note",
time: new Date().toISOString(),
...(details ? { description: details } : {}),
},
geometry: this._geometry,
};
this._style.applyTo(feature.properties);
const intoLine = folder.startsWith("item:");
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), ...(intoLine ? {} : { folder }) });
this._saveButton.disabled = true;
try {
const url = intoLine ? `/api/library/node/${encodeURIComponent(folder)}/points` : "/api/library/notes";
const response = await fetch(url, { method: "POST", body: requestBody });
if (!response.ok) throw new Error(`save failed: ${response.status}`);
const { path } = await response.json();
notifyGpxStoreChanged(intoLine ? folder : path);
this.close();
this._onSaved?.();
} catch (err) {
window.alert("Could not save the note — check your connection and try again.");
} finally {
this._saveButton.disabled = false;
}
}
}
// A quick "pin it with a note" tool — click the map, write a short note,
// pick which folder it goes into (or start a new one). Point
// only: for a distance/area shape, draw it with the Measure tool and use
// its own "Save as note" button instead of duplicating that click-to-place
// UX here — see measure.js.
export class NotesControl {
constructor() {
this._active = false;
this._marker = null; // where the pending note will land — visible until saved/cancelled
}
onAdd(map) {
this._map = map;
this._container = document.createElement("div");
this._container.className = "maplibregl-ctrl maplibregl-ctrl-group notes-ctrl";
this._container.innerHTML = `
<button type="button" class="notes-ctrl__button" title="Add note" aria-label="Add note">${NOTE_PIN_ICON}</button>
<div class="notes-panel" hidden>
<p class="notes-panel__hint">Click the map to place a note.</p>
</div>
`;
this._button = this._container.querySelector(".notes-ctrl__button");
this._panel = this._container.querySelector(".notes-panel");
this._hint = this._container.querySelector(".notes-panel__hint");
this._form = new NoteSaveForm(this._panel, {
onSaved: () => {
this._hint.hidden = false;
this._removeMarker();
},
onCancel: () => {
this._hint.hidden = false;
this._removeMarker();
},
// Keeps the map preview in sync with the icon picker — it used to
// always show a plain red pin no matter which icon got picked.
onIconChange: (icon) => {
if (this._marker) this._marker.getElement().innerHTML = icon && POI_ICONS[icon] ? POI_ICONS[icon] : NOTE_PIN_ICON;
},
});
this._button.addEventListener("click", () => this._setActive(!this._active));
this._onClick = (event) => {
if (!this._active || this._form.isOpen) return;
this._hint.hidden = true;
const el = document.createElement("div");
el.className = "notes-panel__preview-marker";
el.innerHTML = NOTE_PIN_ICON;
this._marker = new Marker({ element: el }).setLngLat(event.lngLat).addTo(this._map);
this._form.open({ type: "Point", coordinates: [event.lngLat.lng, event.lngLat.lat] });
};
map.on("click", this._onClick);
return this._container;
}
_removeMarker() {
this._marker?.remove();
this._marker = null;
}
onRemove() {
this._map.off("click", this._onClick);
this._container.remove();
}
getDefaultPosition() {
return "top-left";
}
_setActive(active) {
this._active = active;
this._button.classList.toggle("active", active);
this._panel.hidden = !active;
this._map.getCanvas().style.cursor = active ? "crosshair" : "";
if (!active) {
this._form.close();
this._removeMarker();
}
}
}
function folderPaths(node) {
return (node.children || []).filter((child) => child.type === "folder").flatMap((child) => [child.path, ...folderPaths(child)]);
}
// Tracks/routes of the library as [key, "folder / name"].
function trackNodes(node, folder = "") {
return (node.children || []).flatMap((child) => {
if (child.type === "folder") return trackNodes(child, child.path);
const line = child.path.startsWith("item:") && !child.layer && child.kinds?.some((k) => k === "track" || k === "route");
return line ? [[child.path, [folder, child.name].filter(Boolean).join(" / ")]] : [];
});
}
function escapeAttr(value) {
return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
}
function escapeText(value) {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;");
}