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
refactor(collections/map): extract markers into own component
Elian Doran7829957548aa
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.ts b/apps/client/src/widgets/collections/geomap/ContextMenus.tsindex d885037522..ba485a8461 100644--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts@@ -1,6 +1,7 @@import { useCallback, useContext, useEffect } from "preact/hooks";import appContext, { type CommandMappings } from "../../../components/app_context.js";+import FNote from "../../../entities/fnote.js";import contextMenu, { type MenuItem } from "../../../menus/context_menu.js";import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker.jsx";import linkContextMenu from "../../../menus/link_context_menu.js";@@ -9,7 +10,7 @@ import { t } from "../../../services/i18n.js";import link from "../../../services/link.js";import { createNewNote } from "./api.js";import { type GeoMouseEvent,ParentMap, toMapLibreEvent } from "./map.js";-import { MARKER_LAYER } from "./marker_data.js";+import { MARKER_LAYER } from "./Markers.js";export default function ContextMenus({ note, isReadOnly }: { note: FNote, isReadOnly }) {const map = useContext(ParentMap);diff --git a/apps/client/src/widgets/collections/geomap/marker_renderer.ts b/apps/client/src/widgets/collections/geomap/Markers.tsxsimilarity index 50%rename from apps/client/src/widgets/collections/geomap/marker_renderer.tsrename to apps/client/src/widgets/collections/geomap/Markers.tsxindex 21cc968ea6..4fd25ddd09 100644--- a/apps/client/src/widgets/collections/geomap/marker_renderer.ts+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -1,6 +1,95 @@+import { useContext, useEffect } from "preact/hooks";++import FNote from "../../../entities/fnote";+import { useChildNotes } from "../../react/hooks";+import { ParentMap } from "./map";++export const LOCATION_ATTRIBUTE = "geolocation";+export const MARKER_LAYER = "points-layer";+const DEFAULT_MARKER_COLOR = "#2A81CB";++// SVG marker pin shape (replaces the Leaflet marker PNG).+export const MARKER_SVG = "foo"; // TODO: Fix+const iconSvgCache = new Map<string, string>();const iconClassToBitmapCache = new Map<string, string | undefined>();-export async function buildMarkerIcon(color: string, iconClass: string, scale = window.devicePixelRatio || 1) {++export default function Markers({ note }: { note: FNote }) {+ const map = useContext(ParentMap);+ const childNotes = useChildNotes(note?.noteId);++ async function refresh() {+ if (!map) return;++ async function ensureIcon(color: string, iconClass: string) {+ const key = `marker-${color}-${iconClass}`;++ if (!iconSvgCache.has(key)) {+ const svg = await buildMarkerIcon(color, iconClass);+ iconSvgCache.set(key, svg);+ }++ return key;+ }++ const features: maplibregl.GeoJSONFeature[] = [];+ for (const childNote of childNotes) {+ const location = childNote.getLabelValue(LOCATION_ATTRIBUTE);+ const latLng = location?.split(",", 2).map((el) => parseFloat(el)) as [ number, number ] | undefined;+ if (!latLng) continue;+ latLng.reverse();++ const color = childNote.getLabelValue("color") ?? DEFAULT_MARKER_COLOR;+ features.push({+ type: "Feature",+ geometry: {+ type: "Point",+ coordinates: latLng+ },+ properties: {+ id: childNote.noteId,+ name: childNote.title,+ icon: await ensureIcon(color, childNote.getIcon())+ }+ });+ }++ // Build all the icons.+ await Promise.all(iconSvgCache.entries().map(async ([ key, svg ]) => {+ const image = await svgToImage(svg);+ map.addImage(key, image, {+ pixelRatio: window.devicePixelRatio+ });+ }));++ map.addSource("points", {+ type: "geojson",+ data: {+ type: "FeatureCollection",+ features+ }+ });+ map.addLayer({+ id: MARKER_LAYER,+ type: "symbol",+ source: "points",+ layout: {+ "icon-image": [ "get", "icon" ],+ "icon-size": 1,+ "icon-anchor": "bottom",+ "icon-allow-overlap": true+ }+ });+ }++ useEffect(() => {+ refresh();+ }, [ map, childNotes ]);+ return null;+}++//#region Renderer+async function buildMarkerIcon(color: string, iconClass: string, scale = window.devicePixelRatio || 1) {const iconUrl = iconClassToBitmapCache.get(iconClass) ?? await snapshotIcon(iconClass, 16 * scale);return `\<svg width="${25 * scale}" height="${41 * scale}" viewBox="0 0 25 41" xmlns="http://www.w3.org/2000/svg">@@ -95,7 +184,7 @@ function getGlyphFromClass(iconClass: string) {};}-export function svgToImage(svgString: string){+function svgToImage(svgString: string){return new Promise<HTMLImageElement>(resolve => {const svgBlob = new Blob([svgString], { type: "image/svg+xml" });const url = URL.createObjectURL(svgBlob);@@ -110,3 +199,4 @@ export function svgToImage(svgString: string){img.src = url;});}+//#endregiondiff --git a/apps/client/src/widgets/collections/geomap/Tooltips.tsx b/apps/client/src/widgets/collections/geomap/Tooltips.tsxindex 329a00f5bd..807e5c8946 100644--- a/apps/client/src/widgets/collections/geomap/Tooltips.tsx+++ b/apps/client/src/widgets/collections/geomap/Tooltips.tsx@@ -2,7 +2,7 @@ import { MapMouseEvent, Popup } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";import { ParentMap } from "./map";-import { MARKER_LAYER } from "./marker_data";+import { MARKER_LAYER } from "./Markers";export default function Tooltips() {const map = useContext(ParentMap);diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.tsindex e5c197fefd..8705f6e6da 100644--- a/apps/client/src/widgets/collections/geomap/api.ts+++ b/apps/client/src/widgets/collections/geomap/api.ts@@ -1,10 +1,11 @@-import type { GeoMouseEvent } from "./map";-import { LOCATION_ATTRIBUTE } from ".";+import { CreateChildrenResponse } from "@triliumnext/commons";+import attributes from "../../../services/attributes";import { prompt } from "../../../services/dialog";-import server from "../../../services/server";import { t } from "../../../services/i18n";-import { CreateChildrenResponse } from "@triliumnext/commons";+import server from "../../../services/server";+import type { GeoMouseEvent } from "./map";+import { LOCATION_ATTRIBUTE } from "./Markers";const CHILD_NOTE_ICON = "bx bx-pin";diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex ffa9d594dd..aee2959b1a 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -22,12 +22,11 @@ import ContextMenus from "./ContextMenus";import Map, { GeoMouseEvent } from "./map";import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";import Marker, { GpxTrack } from "./marker";-import { MARKER_SVG, useMarkerData } from "./marker_data";+import Markers, { LOCATION_ATTRIBUTE } from "./Markers";import Tooltips from "./Tooltips";const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];const DEFAULT_ZOOM = 2;-export const LOCATION_ATTRIBUTE = "geolocation";interface MapData {view?: {@@ -101,7 +100,6 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM// Draggingconst containerRef = useRef<HTMLDivElement>(null);const apiRef = useRef<maplibregl.Map | null>(null);- useMarkerData(note, apiRef);useNoteTreeDrag(containerRef, {dragEnabled: !isReadOnly,dragNotEnabledMessage: {@@ -161,6 +159,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM><Tooltips /><ContextMenus note={note} isReadOnly={isReadOnly} />+ <Markers note={note} /></Map>}<GeoMapTouchBar state={state} map={apiRef.current} /></div>diff --git a/apps/client/src/widgets/collections/geomap/marker_data.ts b/apps/client/src/widgets/collections/geomap/marker_data.tsdeleted file mode 100644index 6b38ebd17e..0000000000--- a/apps/client/src/widgets/collections/geomap/marker_data.ts+++ /dev/null@@ -1,88 +0,0 @@-import { MutableRef, useEffect } from "preact/hooks";--import FNote from "../../../entities/fnote";-import { useChildNotes } from "../../react/hooks";-import { LOCATION_ATTRIBUTE } from ".";-import { buildMarkerIcon, svgToImage } from "./marker_renderer";--const DEFAULT_MARKER_COLOR = "#2A81CB";--// SVG marker pin shape (replaces the Leaflet marker PNG).-export const MARKER_SVG = "foo"; // TODO: Fix-const iconSvgCache = new Map<string, string>();--export const MARKER_LAYER = "points-layer";--export function useMarkerData(note: FNote | null | undefined, apiRef: MutableRef<maplibregl.Map | null>) {- const childNotes = useChildNotes(note?.noteId);-- async function refresh() {- const map = apiRef.current as maplibregl.Map | undefined;- if (!map) return;--- async function ensureIcon(color: string, iconClass: string) {- const key = `marker-${color}-${iconClass}`;-- if (!iconSvgCache.has(key)) {- const svg = await buildMarkerIcon(color, iconClass);- iconSvgCache.set(key, svg);- }-- return key;- }-- const features: maplibregl.GeoJSONFeature[] = [];- for (const childNote of childNotes) {- const location = childNote.getLabelValue(LOCATION_ATTRIBUTE);- const latLng = location?.split(",", 2).map((el) => parseFloat(el)) as [ number, number ] | undefined;- if (!latLng) continue;- latLng.reverse();-- const color = childNote.getLabelValue("color") ?? DEFAULT_MARKER_COLOR;- features.push({- type: "Feature",- geometry: {- type: "Point",- coordinates: latLng- },- properties: {- id: childNote.noteId,- name: childNote.title,- icon: await ensureIcon(color, childNote.getIcon())- }- });- }-- // Build all the icons.- await Promise.all(iconSvgCache.entries().map(async ([ key, svg ]) => {- const image = await svgToImage(svg);- map.addImage(key, image, {- pixelRatio: window.devicePixelRatio- });- }));-- map.addSource("points", {- type: "geojson",- data: {- type: "FeatureCollection",- features- }- });- map.addLayer({- id: MARKER_LAYER,- type: "symbol",- source: "points",- layout: {- "icon-image": [ "get", "icon" ],- "icon-size": 1,- "icon-anchor": "bottom",- "icon-allow-overlap": true- }- });- }-- useEffect(() => {- refresh();- }, [ apiRef, childNotes ]);-}