Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): bring a GPS track onto the map from a GPX file

Elian Doran1a61e689c11a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f4b0b8a537..ebe76ba37b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2742,6 +2742,7 @@
"create-child-note-cancel": "Cancel adding the note",
"create-child-note-instruction": "Click on the map to create a new note at that location or press Escape to dismiss.",
"create-child-note-toast-title": "New note",
+ "add-gpx-track": "Add a GPS track from a GPX file",
"move-marker-instruction": "Click on the map to move the marker to that location or press Escape to dismiss.",
"move-marker-toast-title": "Move marker",
"unable-to-load-map": "Unable to load map.",
diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx
index 2b20c9e968..1fdd58415e 100644
--- a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx
@@ -13,19 +13,25 @@ import { ParentMap } from "./map";
/** Builds the bar over a map, which it asks nothing more of than being there at all. */
function renderBar({ map = {} as never, isReadOnly = false, placing = false } = {}) {
const onTogglePlacement = vi.fn();
+ const onAddGpxTrack = vi.fn();
let container: HTMLElement | undefined;
act(() => {
container = renderInto(
<ParentMap.Provider value={map}>
- <EditToolbar isReadOnly={isReadOnly} placing={placing} onTogglePlacement={onTogglePlacement} />
+ <EditToolbar isReadOnly={isReadOnly} placing={placing} onTogglePlacement={onTogglePlacement} onAddGpxTrack={onAddGpxTrack} />
</ParentMap.Provider>
);
});
if (!container) throw new Error("the toolbar was not rendered");
+ const all = () => [ ...container?.querySelectorAll<HTMLButtonElement>(".geo-edit-toolbar button") ?? [] ];
return {
onTogglePlacement,
- button: () => container?.querySelector<HTMLButtonElement>(".geo-edit-toolbar button") ?? null
+ onAddGpxTrack,
+ buttons: all,
+ /** The first button, which is the +. */
+ button: () => all()[0] ?? null,
+ gpxButton: () => all()[1] ?? null
};
}
@@ -49,15 +55,26 @@ describe("geo map EditToolbar", () => {
expect(onTogglePlacement).toHaveBeenCalledTimes(1);
});
- it("refuses on a map that may not be edited", () => {
- const { button } = renderBar({ isReadOnly: true });
+ it("offers to bring in a GPX track, and hands the asking to the map view", () => {
+ const { gpxButton, onAddGpxTrack } = renderBar();
- expect(button()?.disabled).toBe(true);
+ expect(gpxButton()?.className).toContain("bx-trip");
+
+ act(() => gpxButton()?.click());
+ expect(onAddGpxTrack).toHaveBeenCalledTimes(1);
+ });
+
+ it("refuses every button on a map that may not be edited", () => {
+ const { buttons } = renderBar({ isReadOnly: true });
+
+ for (const button of buttons()) {
+ expect(button.disabled).toBe(true);
+ }
});
it("stands aside where there is no map at all", () => {
- const { button } = renderBar({ map: null as never });
+ const { buttons } = renderBar({ map: null as never });
- expect(button()).toBeNull();
+ expect(buttons()).toHaveLength(0);
});
});
diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
index 0f5239ac4e..2887ab4f3a 100644
--- a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
@@ -15,6 +15,8 @@ interface EditToolbarProps {
/** Arms the map for a note to be placed, or stands it down again — the visible counterpart of
* the Escape the instruction toast offers (see index.tsx). */
onTogglePlacement: () => void;
+ /** Asks for a GPX file and brings it onto the map (see `addGpxTrack` in index.tsx). */
+ onAddGpxTrack: () => void;
}
/**
@@ -30,7 +32,7 @@ interface EditToolbarProps {
* goes fullscreen (see MapToolbar): the collection bar stays behind, and while the button lived
* there, a fullscreen map could only be added to through its right-click menu.
*/
-export default function EditToolbar({ isReadOnly, placing, onTogglePlacement }: EditToolbarProps) {
+export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, onAddGpxTrack }: EditToolbarProps) {
const map = useContext(ParentMap);
// No bar over a map that could not be drawn (see the WebGL fallback in map.tsx).
@@ -46,6 +48,13 @@ export default function EditToolbar({ isReadOnly, placing, onTogglePlacement }:
disabled={isReadOnly}
onClick={onTogglePlacement}
/>
+
+ <OverlayToolbarButton
+ icon="bx bx-trip"
+ text={t("geo-map.add-gpx-track")}
+ disabled={isReadOnly}
+ onClick={onAddGpxTrack}
+ />
</OverlayToolbar>
);
}
diff --git a/apps/client/src/widgets/collections/geomap/api.spec.ts b/apps/client/src/widgets/collections/geomap/api.spec.ts
new file mode 100644
index 0000000000..820a0dea65
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/api.spec.ts
@@ -0,0 +1,59 @@
+/**
+ * What the geo map writes when something is put on it (see api.ts): the note a placement click
+ * creates, and the note a GPX file is brought in as. Both go through the ordinary note-creation
+ * service; what is checked here is what they ask it for.
+ */
+import { describe, expect, it, vi } from "vitest";
+
+import note_create from "../../../services/note_create";
+import { buildNote } from "../../../test/easy-froca";
+import { createNewNote, importGpxTrack } from "./api";
+
+vi.mock("../../../services/note_create", () => ({
+ default: { createNote: vi.fn(async () => ({ note: { noteId: "created" }, branch: null })) }
+}));
+
+const createNote = vi.mocked(note_create.createNote);
+
+describe("geo map api", () => {
+ it("creates a placed note under the stock name, located where the click landed", async () => {
+ const parent = buildNote({ title: "The map" });
+
+ const created = await createNewNote(parent, {
+ latlng: { lat: 48.85, lng: 2.36 },
+ originalEvent: new MouseEvent("click"),
+ point: { x: 0, y: 0 } as never
+ });
+
+ // Handed back for the pane to open on (see createNoteAt in index.tsx).
+ expect(created).toEqual({ noteId: "created" });
+ expect(createNote).toHaveBeenCalledWith(parent.noteId, expect.objectContaining({
+ type: "text",
+ // Nothing is asked first — the name is typed over in the pane, not answered in a modal.
+ activate: false,
+ attributes: expect.arrayContaining([
+ { type: "label", name: "geolocation", value: "48.85,2.36" },
+ { type: "label", name: "iconClass", value: "bx bx-pin" }
+ ])
+ }));
+ });
+
+ it("brings a GPX file in as a file note the map draws tracks by", async () => {
+ const parent = buildNote({ title: "The map" });
+ const file = new File([ "<gpx><trk/></gpx>" ], "sunday-ride.gpx");
+
+ const created = await importGpxTrack(parent, file);
+
+ expect(created).toEqual({ noteId: "created" });
+ expect(createNote).toHaveBeenCalledWith(parent.noteId, expect.objectContaining({
+ title: "sunday-ride.gpx",
+ content: "<gpx><trk/></gpx>",
+ type: "file",
+ // Pinned rather than read off the file: a browser reports no type for a .gpx, and this
+ // is the one mime the map recognises a track by (see NoteGpxTrackWrapper).
+ mime: "application/gpx+xml",
+ activate: false,
+ attributes: [ { type: "label", name: "originalFileName", value: "sunday-ride.gpx" } ]
+ }));
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.ts
index 7c3ed19806..3fde07aa83 100644
--- a/apps/client/src/widgets/collections/geomap/api.ts
+++ b/apps/client/src/widgets/collections/geomap/api.ts
@@ -21,6 +21,35 @@ export async function moveMarker(noteId: string, latLng: { lat: number; lng: num
* under the stock name instead, and the caller opens the pane on it with that name selected — naming
* the place is typing over it (see index.tsx).
*/
+/**
+ * Brings a GPX file onto the map as a child note, and hands the note back.
+ *
+ * Created directly rather than sent through the import pipeline: an import's success is announced
+ * app-wide and navigates the active tab to what it made, which here would carry the user off the
+ * very map the track was added to. The note a track lives in is simple enough to make in place — a
+ * file note whose content is the file's text.
+ *
+ * The mime is pinned to what the map draws tracks by (see NoteGpxTrackWrapper in index.tsx) rather
+ * than read off the file: a browser reports no type at all for a `.gpx`, and an import that guessed
+ * wrong left the user hunting the File-type field for why their track never appeared — the user
+ * guide has a step for exactly that.
+ */
+export async function importGpxTrack(parentNote: FNote, file: File) {
+ const { note } = await note_create.createNote(parentNote.noteId, {
+ title: file.name,
+ content: await file.text(),
+ type: "file",
+ mime: "application/gpx+xml",
+ activate: false,
+ isProtected: parentNote.isProtected,
+ attributes: [
+ { type: "label", name: "originalFileName", value: file.name }
+ ]
+ });
+
+ return note;
+}
+
export async function createNewNote(parentNote: FNote, e: GeoMouseEvent) {
const { note } = await note_create.createNote(parentNote.noteId, {
title: t("relation_map.default_new_note_title"),
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index b4834ef558..22d898bd1a 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -16,7 +16,7 @@ import CollectionProperties from "../../note_bars/CollectionProperties";
import ActionButton from "../../react/ActionButton";
import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";
import { ViewModeProps } from "../interface";
-import { createNewNote, moveMarker } from "./api";
+import { createNewNote, importGpxTrack, moveMarker } from "./api";
import ContextMenus from "./ContextMenus";
import DetailPane, { PaneSelection } from "./DetailPane";
import EditToolbar from "./EditToolbar";
@@ -120,6 +120,22 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
setSelection({ noteId: created.noteId, isNew: true });
}, [ note ]);
+ /**
+ * Asks for a GPX file and brings it onto the map as a child note (see importGpxTrack). The
+ * note is put among the map's own straight away, as a created note is, so the track is drawn
+ * the moment the file is read rather than after the collection reloads around it. No pane
+ * opens: a track is not a marker, and the file's name already names it.
+ */
+ const addGpxTrack = useCallback(async () => {
+ const file = await pickGpxFile();
+ if (!file) return;
+
+ const created = await importGpxTrack(note, file);
+ if (!created) return;
+
+ setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);
+ }, [ note ]);
+
// Placement mode is armed by the button or by the context menu. Tying the instruction toast and
// the global Escape-to-cancel listener to the state (rather than the handler that armed it)
// guarantees both are torn down on cancel, on completion (map click) and on unmount — otherwise
@@ -233,6 +249,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
isReadOnly={isReadOnly}
placing={placement?.mode === "new"}
onTogglePlacement={toggleNotePlacement}
+ onAddGpxTrack={addGpxTrack}
/>
<Tooltips />
{/* The preview under the pointer while a click is armed to mean a place — the note
@@ -251,6 +268,26 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
);
}
+/**
+ * Asks the user for a GPX file, resolving to none where the dialog is dismissed.
+ *
+ * A detached input rather than one rendered somewhere: the browser only wants an input to open its
+ * file dialog through, and a rendered one would be a piece of DOM standing around for the one
+ * moment a button is pressed. The `cancel` event is how a file input reports the dialog closed
+ * empty-handed; a browser old enough not to fire it leaves an already-forgotten promise unsettled,
+ * which is the same nothing the caller does on null.
+ */
+function pickGpxFile(): Promise<File | null> {
+ return new Promise((resolve) => {
+ const input = document.createElement("input");
+ input.type = "file";
+ input.accept = ".gpx,application/gpx+xml";
+ input.addEventListener("change", () => resolve(input.files?.[0] ?? null));
+ input.addEventListener("cancel", () => resolve(null));
+ input.click();
+ });
+}
+
function useLayerData(note: FNote) {
const [ layerName ] = useNoteLabel(note, "map:style");
// Whether the style is a dark one, which decides how a marker's title is drawn over it (see