Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(geomap): image map reloads, saved views and GPX pins
Elian Doran76842253531a
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.ts b/apps/client/src/widgets/collections/geomap/ContextMenus.tsindex 1b359e382b..1342b0a0f0 100644--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts@@ -11,10 +11,9 @@ import froca from "../../../services/froca.js";import { t } from "../../../services/i18n.js";import link from "../../../services/link.js";import { removeFromMap } from "./api.js";-import { GPX_MIME } from "./GpxTrack.js";import { type GeoMouseEvent, ParentMap, toGeoMouseEvent } from "./map.js";import { featureAt } from "./ShapeLayer.js";-import { isShapeNote, type MapSpace, MapSpaceContext } from "./space.js";+import { isShapeNote, isTrackNote, type MapSpace, MapSpaceContext } from "./space.js";interface ContextMenusProps {/** The map's own note, which is how the tree is told what the map holds a note by. */@@ -91,7 +90,7 @@ export function openContextMenu(noteId: string, e: GeoMouseEvent, { isEditable,// A track is named for what removing it does, which is delete the note: its line is// drawn from the note's own file rather than from a location written on it, so there// is no taking it off the map and keeping it (see removeFromMap).- title: t(note?.mime === GPX_MIME ? "geo-map-context.delete-note" : "geo-map-context.remove-from-map"),+ title: t(note && isTrackNote(note, space) ? "geo-map-context.delete-note" : "geo-map-context.remove-from-map"),// Called rather than commanded: what was a broadcast command every open map heard// would now put a dialog up on each of them in turn.handler: () => note && void removeFromMap(space, note, parentNote),@@ -157,7 +156,7 @@ export function openMapContextMenu(e: GeoMouseEvent, isEditable: boolean, onCrea*/function buildRelocateItem(noteId: string, onRelocate: (noteId: string) => void, space: MapSpace): MenuItem<keyof CommandMappings>[] {const note = froca.getNoteFromCache(noteId);- if (!note || note.mime === GPX_MIME || isShapeNote(note, space)) {+ if (!note || isTrackNote(note, space) || isShapeNote(note, space)) {return [];}diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxindex 47f1384fd8..a70a840cfd 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -16,11 +16,11 @@ import ActionButton from "../../react/ActionButton";import { useNoteLabelByName, useStaticTooltip } from "../../react/hooks";import { removeFromMap } from "./api";import { type Bounds, boundsOf } from "./coordinates";-import { GPX_MIME, trackSourceId } from "./GpxTrack";+import { trackSourceId } from "./GpxTrack";import { ParentMap } from "./map";import { featureAt } from "./ShapeLayer";import { geoShapeBounds } from "./shapes";-import { isShapeNote, locationOf, type MapSpace, MapSpaceContext } from "./space";+import { isShapeNote, isTrackNote, locationOf, type MapSpace, MapSpaceContext } from "./space";/*** Which marker the pane stands for, and why it came to be selected.@@ -198,7 +198,7 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, selreturn;}- if (note.mime === GPX_MIME) {+ if (isTrackNote(note, space)) {const focus = selection?.focus;// A clicked flag is a place the reader chose: stood clear of the pane at the zoom they@@ -350,7 +350,7 @@ const FIT_MAX_ZOOM = 16;* coming from the note's own file rather than from a label. An image map draws no tracks.*/function standsOnMap(note: FNote, space: MapSpace) {- return (space.kind === "geo" && note.mime === GPX_MIME)+ return isTrackNote(note, space)|| !!locationOf(note, space)|| isShapeNote(note, space);}@@ -503,7 +503,7 @@ function MarkerActions({ note, parentNote, isReadOnly, onRelocate }: { note: FNo{/* Not offered for a track or a drawn shape: neither has a location label torewrite, and moving one means drawing it again. ContextMenus leaves it out forthe same reason. */}- {note.mime !== GPX_MIME && !isShape && <ActionButton+ {!isTrackNote(note, space) && !isShape && <ActionButtonclassName="geo-detail-pane-move"icon="bx bx-move"text={t("geo-map-context.move-marker")}@@ -519,7 +519,7 @@ function MarkerActions({ note, parentNote, isReadOnly, onRelocate }: { note: FNo// Named for what it does to a track, which is delete the note: a track's line is// drawn from the note's own file, so there is no taking it off the map and// keeping it (see removeFromMap). The right-click menu names it the same way.- text={t(note.mime === GPX_MIME ? "geo-map-context.delete-note" : "geo-map-context.remove-from-map")}+ text={t(isTrackNote(note, space) ? "geo-map-context.delete-note" : "geo-map-context.remove-from-map")}// Whether the note goes with its marker is asked before anything happens, the// two being different wishes. Nothing closes the pane afterwards because the// effect above already stands it down, either way round.diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsxindex 0d5ce079c5..49363de038 100644--- a/apps/client/src/widgets/collections/geomap/Markers.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -497,8 +497,6 @@ export function FitToNotes({ notes, enabled, bounds: fixedBounds }: { notes: FNo//// Not animated: this is where the map opens, not somewhere it is taken. Flying would show// the stock view first and swoop off it every time a map is opened for the first time.- // No `maxZoom` key at all for fixed bounds: MapLibre merges an `undefined` over its own- // default, and the fit then comes out NaN.map.fitBounds(bounds, {padding: FIT_PADDING,animate: false,diff --git a/apps/client/src/widgets/collections/geomap/api.spec.ts b/apps/client/src/widgets/collections/geomap/api.spec.tsindex 24901fa5ba..ef1d172c4d 100644--- a/apps/client/src/widgets/collections/geomap/api.spec.ts+++ b/apps/client/src/widgets/collections/geomap/api.spec.ts@@ -14,7 +14,7 @@ import { buildNote } from "../../../test/easy-froca";import {createNewNote, createNoteForPlace, createShapeNote, importGpxTrack, moveMarker, removeFromMap} from "./api";-import { geoSpace } from "./space";+import { geoSpace, imageSpace } from "./space";vi.mock("../../../services/note_create", () => ({default: { createNote: vi.fn(async () => ({ note: { noteId: "created" }, branch: null })) }@@ -185,6 +185,19 @@ describe("geo map api", () => {expect(setLabel).toHaveBeenLastCalledWith(note.noteId, "geolocation", "");});+ it("insists on deleting a track on a world map, but lets a GPX pin on an image map go", async () => {+ const map = buildNote({ title: "The map" });+ const track = buildNote({ title: "Sunday ride", type: "file", mime: "application/gpx+xml" });+ confirmDelete.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });++ await removeFromMap(geoSpace, track, map);+ expect(confirmDelete).toHaveBeenLastCalledWith(track.title, expect.anything(), expect.objectContaining({ mustDeleteNote: true }));++ await removeFromMap(imageSpace({ width: 100, height: 100 }), track, map);+ expect(confirmDelete).toHaveBeenLastCalledWith(track.title, expect.anything(), expect.objectContaining({ mustDeleteNote: false }));+ expect(setLabel).toHaveBeenLastCalledWith(track.noteId, "imagePosition", "");+ });+it("leaves the marker alone where the reader changed their mind", async () => {const map = buildNote({ title: "The map" });const note = buildNote({ title: "A place" });diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.tsindex fe8f7df86e..3c7ded7906 100644--- a/apps/client/src/widgets/collections/geomap/api.ts+++ b/apps/client/src/widgets/collections/geomap/api.ts@@ -6,10 +6,9 @@ import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import note_create from "../../../services/note_create";import { deleteNoteOrBranch } from "../../../services/note_deletion";-import { GPX_MIME } from "./GpxTrack";import type { GeoMouseEvent } from "./map";import type { GeoShape } from "./shapes";-import { geoSpace, type MapSpace } from "./space";+import { geoSpace, isTrackNote, type MapSpace } from "./space";/** The type a note put on the map is created as, and so what a template handed to it must match. */export const MARKER_NOTE_TYPE: NoteType = "text";@@ -33,7 +32,7 @@ export async function moveMarker(space: MapSpace, noteId: string, latLng: { lat:* the note is the track. That is also why it is not offered under the same name (see ContextMenus).*/export async function removeFromMap(space: MapSpace, note: FNote, mapNote: FNote) {- const isTrack = note.mime === GPX_MIME;+ const isTrack = isTrackNote(note, space);// The map's own branch for the note, which is how a note the map merely shows — cloned in from// elsewhere, and clone-able out again — is told from one that lives here and nowhere else.const branchId = note.parentToBranch[mapNote.noteId] ?? null;diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex 5bdcd9fa85..be5d585ea7 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -12,7 +12,7 @@ import toast from "../../../services/toast";import { fileAccept } from "../../../services/utils";import { logError } from "../../../services/ws";import CollectionProperties from "../../note_bars/CollectionProperties";-import { useCollectionTreeDrag, useColorScheme, useEffectiveReadOnly, useNoteBlob, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelByName, useNoteProperty, useNoteRelation, useSpacedUpdate } from "../../react/hooks";+import { useCollectionTreeDrag, useColorScheme, useEffectiveReadOnly, useNoteBlob, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelByName, useNoteProperty, useNoteRelation, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";import NoItems from "../../react/NoItems";import { ViewModeProps } from "../interface";import { createNewNote, createNoteForPlace, createShapeNote, importGpxTrack, moveMarker } from "./api";@@ -65,10 +65,15 @@ const PLACEMENT_TOAST_ID = "geo-placement";const OUTLINE_DELAY_MS = 250;interface MapData {- view?: {- center?: { lat: number; lng: number } | [number, number];- zoom?: number;- };+ view?: SavedView;+ /** The view of the same map drawn over its image (`~map:image`), whose positions say nothing+ * about the world map's, so that switching between the two restores each. */+ imageView?: SavedView;+}++interface SavedView {+ center?: { lat: number; lng: number } | [number, number];+ zoom?: number;}/**@@ -114,8 +119,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM// Whether that pane has been grown over the map. Held here for the reason the selection is: what// the map places around the pane has to know of it too (see the maximized pane in DetailPane).const [ paneMaximized, setPaneMaximized ] = useState(false);- const [ coordinates, setCoordinates ] = useState(viewConfig?.view?.center);- const [ zoom, setZoom ] = useState(viewConfig?.view?.zoom);+ const [ coordinates, setCoordinates ] = useState<SavedView["center"]>();+ const [ zoom, setZoom ] = useState<number>();const [ hasScale ] = useNoteLabelBoolean(note, "map:scale");const [ hideLabels ] = useNoteLabelBoolean(note, "map:hideLabels");const [ clustered ] = useNoteLabelBoolean(note, "map:cluster");@@ -126,6 +131,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMconst image = imageMap.status === "image" ? imageMap : undefined;const space = image?.space ?? geoSpace;const isGeo = space.kind === "geo";+ const viewKey = isGeo ? "view" : "imageView";+ const savedView = viewConfig?.[viewKey];const layerData = useLayerData(note, image);const spacedUpdate = useSpacedUpdate(() => {if (viewConfig) {@@ -139,9 +146,9 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMif (!note) return;// An image map with no saved view is fitted to its image as soon as it is drawn (see// FitToNotes), so where it starts out matters only for the frame before that.- setCoordinates(viewConfig?.view?.center ?? (image ? imageCenter(image.space) : DEFAULT_COORDINATES));- setZoom(viewConfig?.view?.zoom ?? DEFAULT_ZOOM);- }, [ note, viewConfig, image ]);+ setCoordinates(savedView?.center ?? (image ? imageCenter(image.space) : DEFAULT_COORDINATES));+ setZoom(savedView?.zoom ?? DEFAULT_ZOOM);+ }, [ note, savedView, image ]);// Note creation and marker relocation. Both are scoped to this map instance via local callbacks// rather than global commands: embedded maps share no note context (no distinct ntxId), so a@@ -427,7 +434,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMlayerData={layerData}viewportChanged={(coordinates, zoom) => {if (!viewConfig) viewConfig = {};- viewConfig.view = { center: coordinates, zoom };+ viewConfig[viewKey] = { center: coordinates, zoom };spacedUpdate.scheduleUpdate();}}onClick={onClick}@@ -497,7 +504,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM{notes.map(note => <NoteShapeWrapper key={note.noteId} note={note} />)}{/* One binding for every shape's layers, rather than one per shape (see ShapeNames). */}<ShapeNames />- <FitToNotes notes={notes} enabled={!viewConfig?.view} bounds={image?.space.bounds} />+ <FitToNotes notes={notes} enabled={!savedView} bounds={image?.space.bounds} /></Map></MapSpaceContext.Provider>}</div>);@@ -549,6 +556,15 @@ function useImageMap(note: FNote): ImageMapState {const [ imageNoteId ] = useNoteRelation(note, "map:image");const [ boundsValue ] = useNoteLabel(note, "map:imageBounds");const [ image, setImage ] = useState<LoadedImage>(imageNoteId ? { status: "loading" } : { status: "geo" });+ // Bumped when the image note's content or title changes, which loads the picture again under a+ // URL of its own, so neither the browser's cache nor MapLibre's keeps the old one.+ const [ version, setVersion ] = useState(0);++ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ if (imageNoteId && (loadResults.isNoteContentReloaded(imageNoteId) || loadResults.isNoteReloaded(imageNoteId))) {+ setVersion((current) => current + 1);+ }+ });useEffect(() => {if (!imageNoteId) {@@ -559,31 +575,36 @@ function useImageMap(note: FNote): ImageMapState {let cancelled = false;setImage({ status: "loading" });+ const fail = (reason: "unloadable" | "svg", detail?: unknown) => {+ if (cancelled) return;+ if (reason === "unloadable") {+ logError(`The image ${imageNoteId} of map ${note.noteId} could not be loaded${detail ? `: ${detail}` : "."}`);+ }+ setImage({ status: "error", reason });+ };+(async () => {const imageNote = await froca.getNote(imageNoteId, true);// MapLibre decodes an image source with `createImageBitmap`, which refuses SVG, and// would leave the map blank with only a console warning to show for it.if (imageNote?.mime === "image/svg+xml") {- if (!cancelled) setImage({ status: "error", reason: "svg" });+ fail("svg");return;}// Absolute, as MapLibre resolves a source's URL against its worker rather than the page.const url = imageNote && new URL(- `api/images/${imageNote.noteId}/${encodeURIComponent(imageNote.title)}`, document.baseURI).href;+ `api/images/${imageNote.noteId}/${encodeURIComponent(imageNote.title)}?v=${version}`, document.baseURI).href;const size = url ? await measureImage(url) : null;- if (cancelled) return;-if (!url || !size) {- logError(`The image ${imageNoteId} of map ${note.noteId} could not be loaded.`);- setImage({ status: "error", reason: "unloadable" });+ fail("unloadable");return;}- setImage({ status: "image", url, size });- })();+ if (!cancelled) setImage({ status: "image", url, size });+ })().catch((e: unknown) => fail("unloadable", e));return () => { cancelled = true; };- }, [ note.noteId, imageNoteId ]);+ }, [ note.noteId, imageNoteId, version ]);// Built apart from the loading, so naming the corners anew does not fetch the image again.// A value that names no corners is read as none, which leaves the image's own pixels.diff --git a/apps/client/src/widgets/collections/geomap/space.ts b/apps/client/src/widgets/collections/geomap/space.tsindex 7656092532..c774106785 100644--- a/apps/client/src/widgets/collections/geomap/space.ts+++ b/apps/client/src/widgets/collections/geomap/space.ts@@ -12,6 +12,8 @@ import { GEO_LOCATION_ATTRIBUTE, GEO_SHAPE_ATTRIBUTE, IMAGE_POSITION_ATTRIBUTE,import { MercatorCoordinate } from "maplibre-gl";import { createContext } from "preact";+import { GPX_MIME } from "../../../services/gpx";+import type { Bounds } from "./coordinates";import { CIRCLE_SEGMENTS, type GeoShape, parseGeoShape, readShape, serializeGeoShape, shapeRing, writeShape } from "./shapes";@@ -71,6 +73,14 @@ export function isShapeNote(note: LabelSource, space: MapSpace): boolean {return !!shapeOf(note, space);}+/**+ * Whether the note is drawn as a GPX track, which only a geo map does. On an image map a GPX note is+ * a marker like any other, placed and removed through its position label.+ */+export function isTrackNote(note: { mime: string }, space: MapSpace): boolean {+ return space.kind === "geo" && note.mime === GPX_MIME;+}+/** `lat,lng` as the label stores it, as the `[lng, lat]` GeoJSON wants, or `null` if unreadable. */export function parseLocation(location: string | null | undefined): [number, number] | null {if (!location) return null;