feat(collections): own order, KML/KMZ import, copy options, position search, place names on the trip map

- A list keeps its own order: drag a place by its grip (desktop and phone) or
  move it with the arrow keys. Reordering is off while a search or filter hides
  places and the list says why. New PUT /collections/:id/places/reorder and the
  MCP tool reorder_collection_places; new places go to the end. Client and
  server now order ties the same way (sort_order, oldest first, id).
- Copying saved places into a trip no longer takes their notes and tags along
  unasked. The picker offers both; a tag taken along becomes a trip tag (a trip
  tag of the same name is reused), never someone's personal tag.
- The source trip and place a saved place names are only kept when the user can
  open that trip and the place belongs to it.
- A KML or KMZ map can be read into a list: the dialog lists every placemark to
  keep or leave out and says which entries were skipped and why
  (POST /collections/map/read writes nothing; the import does).
- A saved place without coordinates says so and can be looked up on the map
  from its edit form, on the phone too, where a missing position could not be
  added at all. A typed address without a pick says it will not be on the map.
- The trip map can show the place names beside the pins (desktop and phone,
  both renderers). Names that would cover another pin or a control give way,
  the selected place and the planned stops first.
This commit is contained in:
Maurice
2026-11-29 14:57:00 +01:00
parent 177a0febe2
commit 82165855c7
148 changed files with 4219 additions and 321 deletions
@@ -0,0 +1,25 @@
import { useCallback } from 'react';
import { useMap } from 'react-leaflet';
import { usePlaceNameLayout, usePlaceNamesSetting } from './usePlaceNameLayout';
/**
* The Leaflet map's wiring for the place names (#2796): its container, and a layout
* after every zoom or move ends. Renders nothing; it lives inside the MapContainer
* only to reach the map.
*/
export function LeafletPlaceNames() {
const map = useMap();
const enabled = usePlaceNamesSetting();
const getContainer = useCallback(() => map.getContainer(), [map]);
const listen = useCallback(
(run: () => void) => {
map.on('zoomend moveend', run);
return () => {
map.off('zoomend moveend', run);
};
},
[map]
);
usePlaceNameLayout(enabled, getContainer, listen);
return null;
}
+7 -17
View File
@@ -44,7 +44,9 @@ import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import { mapsApi } from '../../api/client'
import { AssistantMapLeaflet } from './AssistantMapLeaflet'
import PlaceHoverCard from './PlaceHoverCard'
import { ratingBadgeHtml } from './ratingBadge'
import { cornerBadgeHtml } from './ratingBadge'
import { tagPlaceName } from './placeNameLabels'
import { LeafletPlaceNames } from './LeafletPlaceNames'
import ReservationOverlay from './ReservationOverlay'
import { PluginMapMarkers } from './MapPluginMarkers'
import { PluginMapLayers } from './MapPluginLayers'
@@ -163,22 +165,7 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
// Number badges (bottom-right), or the rating where there are none: a numbered stop
// is one already planned into a day, and the rating answers the question asked before
// that. The two never want the same corner at the same time.
let badgeHtml = look.showRating ? ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg) : ''
if (orderNumbers && orderNumbers.length > 0) {
const label = orderNumbers.join(' · ')
badgeHtml = `<span style="
position:absolute;bottom:-4px;right:-4px;
min-width:18px;height:${orderNumbers.length > 1 ? 16 : 18}px;border-radius:${orderNumbers.length > 1 ? 8 : 9}px;
padding:0 ${orderNumbers.length > 1 ? 4 : 3}px;
background:rgba(255,255,255,0.94);
border:1.5px solid rgba(0,0,0,0.15);
box-shadow:0 1px 4px rgba(0,0,0,0.18);
display:flex;align-items:center;justify-content:center;
font-size:${orderNumbers.length > 1 ? 7.5 : 9}px;font-weight:800;color:#111827;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${label}</span>`
}
const badgeHtml = cornerBadgeHtml(orderNumbers, (place as { rating_avg?: number | null }).rating_avg, look.showRating, -4)
// Prefer base64 data URLs (no zoom lag); also accept same-origin proxy + uploaded
// custom images (#1136) as a fallback while the thumb is still being generated
@@ -552,6 +539,7 @@ const MemoMarker = memo(function MemoMarker({
// and it is rebuilt whenever the icon changes (selection, day number),
// so the wiring is redone on every add rather than once on mount.
add: (e: any) => {
tagPlaceName(e.target.getElement(), place.name, isSelected ? 2 : orderNumbers?.length ? 1 : 0)
cleanupRef.current?.()
cleanupRef.current = draggable ? wireDraggablePin(e.target.getElement() as HTMLElement, place.id, map) : null
},
@@ -573,6 +561,7 @@ function plannerWaypointPinCss(size: number, selected: boolean): string {
export const MapView = memo(function MapView({
places = [],
placeNames = false,
dayPlaces = [],
route = null,
// One colour pair per entry of `route`, or absent for the blue the route has always
@@ -946,6 +935,7 @@ export const MapView = memo(function MapView({
<MapClickHandler onClick={onMapClick} />
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
{placeNames && <LeafletPlaceNames />}
<ViewportController onViewportChange={onViewportChange} />
<PoiDropTarget onPoiDropOnRoute={onPoiDropOnRoute} />
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
+7 -17
View File
@@ -47,7 +47,7 @@ import { useDawarichTrailGL } from './useDawarichTrailGL'
import { bindDayBoundaryDrag } from './dayBoundaryDrag'
import NightPauseTooltip from './NightPauseTooltip'
import PlaceHoverCard from './PlaceHoverCard'
import { ratingBadgeHtml } from './ratingBadge'
import { cornerBadgeHtml } from './ratingBadge'
import type { Poi } from './poiCategories'
import { poiPinParts } from './poiMarker'
import { addGpxTrackLayers, GPX_HIT_LAYER_ID, hasGpxTrackLayers, selectGpxTrack, setGpxTracks } from './gpxTrackLayers'
@@ -58,6 +58,8 @@ import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefault
import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
import { onRealWorld } from '../../utils/worldCopy'
import { bindPoiDropTarget } from './poiDropTarget'
import { tagPlaceName } from './placeNameLabels'
import { useGlPlaceNames } from './usePlaceNameLayout'
import {
PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID, PLACE_CLUSTER_SOURCE_ID,
addPlaceClusterLayers, drawClusterBubbles, expandCluster,
@@ -144,22 +146,7 @@ function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?
// Same corner, same rule as the Leaflet map: numbers when the place is planned into a
// day, the rating when it is not.
let badgeHtml = look.showRating ? ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg) : ''
if (orderNumbers && orderNumbers.length > 0) {
const label = orderNumbers.join(' · ')
badgeHtml = `<span style="
position:absolute;bottom:-2px;right:-2px;
min-width:18px;height:${orderNumbers.length > 1 ? 16 : 18}px;border-radius:${orderNumbers.length > 1 ? 8 : 9}px;
padding:0 ${orderNumbers.length > 1 ? 4 : 3}px;
background:rgba(255,255,255,0.94);
border:1.5px solid rgba(0,0,0,0.15);
box-shadow:0 1px 4px rgba(0,0,0,0.18);
display:flex;align-items:center;justify-content:center;
font-size:${orderNumbers.length > 1 ? 7.5 : 9}px;font-weight:800;color:#111827;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${label}</span>`
}
const badgeHtml = cornerBadgeHtml(orderNumbers, (place as { rating_avg?: number | null }).rating_avg, look.showRating, -2)
const wrap = document.createElement('div')
// Do NOT set `position: relative` here — GL map libraries ship
@@ -368,6 +355,7 @@ function plannerWaypointPinCss(size: number, selected: boolean): string {
export function MapViewGL({
places = NO_PLACES,
placeNames = false,
dayPlaces = NO_PLACES,
tripId,
routeVias = NO_ROUTE_VIAS,
@@ -457,6 +445,7 @@ export function MapViewGL({
const enableMapbox3d = !isMapLibre && mapbox3d
const [mapReady, setMapReady] = useState(false)
const [readyMap, setReadyMap] = useState<FerrataGlMap | null>(null) // the ready map, read without touching mapRef
useGlPlaceNames(placeNames ? readyMap : null) // place names beside the pins (#2796)
// Hover tooltip — a cursor-following name/category/address card, matching the
// Leaflet map's overlay exactly (no anchored popup, no photo thumbnail).
const [hoverPlace, setHoverPlace] = useState<MapHoverInfo | null>(null)
@@ -1490,6 +1479,7 @@ export function MapViewGL({
const photoUrl = placePhotoUrl(place, photoUrls)
const selected = place.id === selectedPlaceId
const el = createMarkerElement(place as Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl, orderNumbers, selected)
tagPlaceName(el, place.name, selected ? 2 : orderNumbers?.length ? 1 : 0)
// Drag onto a day in the plan (#891). Markers are rebuilt from scratch
// on every reconcile, so the listeners go with the element and need no
// teardown of their own.
@@ -0,0 +1,29 @@
// FE-MAP-PLACENAMESPILL-001 to FE-MAP-PLACENAMESPILL-002
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { useSettingsStore } from '../../store/settingsStore';
import { PlaceNamesPill } from './PlaceNamesPill';
describe('PlaceNamesPill', () => {
it('FE-MAP-PLACENAMESPILL-001: switches the place names setting on and off', async () => {
const updateSetting = vi.fn(async (key: string, value: unknown) => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, [key]: value } }));
});
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: false }, updateSetting }));
render(<PlaceNamesPill />);
fireEvent.click(screen.getByRole('button', { name: 'Show place names' }));
expect(updateSetting).toHaveBeenCalledWith('map_place_labels', true);
expect(await screen.findByRole('button', { name: 'Hide place names' })).toHaveAttribute('aria-pressed', 'true');
});
it('FE-MAP-PLACENAMESPILL-002: a save that fails turns the switch back', async () => {
const updateSetting = vi.fn(async (key: string, value: unknown) => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, [key]: value } }));
throw new Error('Error saving setting');
});
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: false }, updateSetting }));
render(<PlaceNamesPill />);
fireEvent.click(screen.getByRole('button', { name: 'Show place names' }));
await waitFor(() => expect(useSettingsStore.getState().settings.map_place_labels).toBe(false));
expect(screen.getByRole('button', { name: 'Show place names' })).toHaveAttribute('aria-pressed', 'false');
});
});
@@ -0,0 +1,37 @@
import { Type } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useToast } from '../shared/Toast';
import { MapTogglePill } from './MapTogglePill';
import { usePlaceNamesSetting } from './usePlaceNameLayout';
/**
* Turns the place names beside the trip map's pins on and off (#2796). The choice is
* the reader's own setting, so it holds on every trip and on the other device too.
*/
export function PlaceNamesPill() {
const { t } = useTranslation();
const on = usePlaceNamesSetting();
const updateSetting = useSettingsStore((s) => s.updateSetting);
const toast = useToast();
// The switch flips at once; a save that fails turns it back and says so.
const toggle = async () => {
try {
await updateSetting('map_place_labels', !on);
} catch (err) {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: on } }));
toast.error(err instanceof Error ? err.message : t('common.error'));
}
};
return (
<MapTogglePill
active={on}
onToggle={() => {
void toggle();
}}
label={on ? t('map.placeNames.hide') : t('map.placeNames.show')}
testId="place-names-pill"
icon={<Type size={17} strokeWidth={2} />}
/>
);
}
@@ -42,6 +42,8 @@ export interface RouteSegment {
export interface MapViewProps {
places?: Place[];
/** The trip map offers place names beside the pins, shown while the reader's setting is on (#2796). */
placeNames?: boolean;
dayPlaces?: Place[];
// Enables the plugin map contributions (markers + layers). Absent on surfaces
// without a trip (CollectionMap), which naturally excludes them — same rule as
@@ -0,0 +1,131 @@
// FE-MAP-PLACENAMES-001 to FE-MAP-PLACENAMES-005: the place names beside the trip map's pins (#2796).
import { afterEach, describe, expect, it } from 'vitest';
import { controlBoxes, layoutPlaceNames, tagPlaceName } from './placeNameLabels';
type Rect = { left: number; top: number; width: number; height: number };
/** jsdom lays nothing out, so every element answers the box it was given. */
function place(el: Element, r: Rect): void {
el.getBoundingClientRect = () =>
({ ...r, right: r.left + r.width, bottom: r.top + r.height, x: r.left, y: r.top, toJSON: () => ({}) }) as DOMRect;
}
function mapWith(pins: { name: string; priority: 0 | 1 | 2; at: Rect; label: Rect }[]): HTMLElement {
const container = document.createElement('div');
place(container, { left: 0, top: 0, width: 800, height: 600 });
document.body.appendChild(container);
for (const pin of pins) {
const el = document.createElement('div');
place(el, pin.at);
tagPlaceName(el, pin.name, pin.priority);
container.appendChild(el);
// The label is made on the first layout; it gets its box the moment it is added.
const original = el.appendChild.bind(el);
el.appendChild = <T extends Node>(node: T): T => {
if (node instanceof HTMLElement) place(node, pin.label);
return original(node);
};
}
return container;
}
const labels = (c: HTMLElement) => Array.from(c.querySelectorAll<HTMLElement>('.trek-place-name'));
afterEach(() => {
document.body.innerHTML = '';
});
describe('place names on the map', () => {
it('FE-MAP-PLACENAMES-001: every tagged pin gets its name as text, nothing as markup', () => {
const c = mapWith([
{
name: '<b>Senso-ji</b>',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true);
expect(labels(c)).toHaveLength(1);
expect(labels(c)[0].textContent).toBe('<b>Senso-ji</b>');
expect(c.querySelector('b')).toBeNull();
});
it('FE-MAP-PLACENAMES-002: of two colliding names the selected one stays', () => {
const c = mapWith([
{
name: 'Plain',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
{
name: 'Picked',
priority: 2,
at: { left: 10, top: 60, width: 20, height: 20 },
label: { left: 40, top: 14, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true);
const [plain, picked] = labels(c);
expect(picked.hasAttribute('data-hidden')).toBe(false);
expect(plain.hasAttribute('data-hidden')).toBe(true);
});
it('FE-MAP-PLACENAMES-003: a name that would cover another pin, a control or run off the map is hidden', () => {
const c = mapWith([
{
name: 'Covers a pin',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
{
name: 'Neighbour',
priority: 0,
at: { left: 60, top: 8, width: 20, height: 20 },
label: { left: 300, top: 300, width: 40, height: 16 },
},
{
name: 'Edge',
priority: 0,
at: { left: 760, top: 200, width: 20, height: 20 },
label: { left: 786, top: 202, width: 80, height: 16 },
},
{
name: 'Under control',
priority: 0,
at: { left: 400, top: 500, width: 20, height: 20 },
label: { left: 426, top: 502, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true, [{ left: 450, top: 490, right: 520, bottom: 530 }]);
const hidden = labels(c).map((l) => l.hasAttribute('data-hidden'));
expect(hidden).toEqual([true, false, true, true]);
});
it('FE-MAP-PLACENAMES-004: switched off, the names go away again', () => {
const c = mapWith([
{
name: 'Senso-ji',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true);
layoutPlaceNames(c, false);
expect(labels(c)).toHaveLength(0);
layoutPlaceNames(null, true);
});
it('FE-MAP-PLACENAMES-005: control boxes are read off the elements the selector finds', () => {
const c = document.createElement('div');
const btn = document.createElement('button');
place(btn, { left: 5, top: 6, width: 30, height: 30 });
c.appendChild(btn);
expect(controlBoxes(c, 'button')).toEqual([{ left: 5, top: 6, right: 35, bottom: 36 }]);
expect(controlBoxes(null, 'button')).toEqual([]);
});
});
@@ -0,0 +1,105 @@
import './placeNames.css';
/**
* Place names beside the trip map's markers (#2796, discussion #1603).
*
* Both renderers draw a place as a DOM marker, so the name rides along as a child of
* that element and pans with it for free. The renderer only tags the element
* (`tagPlaceName`); `layoutPlaceNames` then adds or removes the labels and thins
* them out: a label that would cover a kept label, another place's marker or one of
* the map's controls is hidden, the selected place and the planned stops win first.
* A place folded into a cluster has no element, so it has no label either.
*/
export const PLACE_NAME_ATTR = 'data-place-name';
const PRIORITY_ATTR = 'data-place-name-priority';
const LABEL_CLASS = 'trek-place-name';
const HIDDEN_ATTR = 'data-hidden';
/** How strongly a label holds its spot when two collide: selected, then planned, then the rest. */
export type PlaceNamePriority = 0 | 1 | 2;
export function tagPlaceName(el: HTMLElement | null | undefined, name: string, priority: PlaceNamePriority): void {
if (!el) return;
el.setAttribute(PLACE_NAME_ATTR, name);
el.setAttribute(PRIORITY_ATTR, String(priority));
}
interface Box {
left: number;
top: number;
right: number;
bottom: number;
}
// Overlaps nothing: a marker that was not measured cannot push a label away.
const NO_BOX: Box = { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity };
const overlaps = (a: Box, b: Box, gap = 2): boolean =>
a.left < b.right + gap && b.left < a.right + gap && a.top < b.bottom + gap && b.top < a.bottom + gap;
function ensureLabel(marker: HTMLElement): HTMLElement {
const name = marker.getAttribute(PLACE_NAME_ATTR) ?? '';
let label = marker.querySelector<HTMLElement>(`:scope > .${LABEL_CLASS}`);
if (!label) {
label = document.createElement('span');
label.className = LABEL_CLASS;
label.setAttribute('aria-hidden', 'true');
marker.appendChild(label);
}
// textContent, never markup: the name is the user's own text.
if (label.textContent !== name) label.textContent = name;
return label;
}
/**
* Brings the labels inside `container` in line with `enabled` and hides the ones that
* collide. `avoid` is what no label may cover beyond the markers themselves: the map's
* controls, measured by the caller. Cheap enough to run after every move and zoom.
*/
export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean, avoid: readonly Box[] = []): void {
if (!container) return;
const markers = Array.from(container.querySelectorAll<HTMLElement>(`[${PLACE_NAME_ATTR}]`));
if (!enabled) {
container.querySelectorAll(`.${LABEL_CLASS}`).forEach((label) => label.remove());
return;
}
const frame = container.getBoundingClientRect();
const markerBoxes = new Map<HTMLElement, Box>();
for (const marker of markers) {
const r = marker.getBoundingClientRect();
markerBoxes.set(marker, { left: r.left, top: r.top, right: r.right, bottom: r.bottom });
}
const ordered = markers
.map((marker, index) => ({ marker, index, priority: Number(marker.getAttribute(PRIORITY_ATTR) ?? 0) }))
.sort((a, b) => b.priority - a.priority || a.index - b.index);
const kept: Box[] = [];
for (const { marker } of ordered) {
const label = ensureLabel(marker);
label.removeAttribute(HIDDEN_ATTR);
const r = label.getBoundingClientRect();
const box: Box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
const offFrame =
box.left < frame.left || box.right > frame.right || box.top < frame.top || box.bottom > frame.bottom;
const coversMarker = markers.some(
(other) => other !== marker && overlaps(box, markerBoxes.get(other) ?? NO_BOX, 0)
);
const collides =
offFrame || coversMarker || kept.some((k) => overlaps(box, k)) || avoid.some((a) => overlaps(box, a, 0));
if (collides) label.setAttribute(HIDDEN_ATTR, '');
else kept.push(box);
}
}
/** The boxes of the map controls inside `container` that a label must leave free. */
export function controlBoxes(container: HTMLElement | null, selector: string): Box[] {
if (!container) return [];
return Array.from(container.querySelectorAll<HTMLElement>(selector)).map((el) => {
const r = el.getBoundingClientRect();
return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
});
}
/** What no label may cover: the controls drawn over the map beside it. */
export const PLACE_NAMES_CONTROLS = '.leaflet-control, .mapboxgl-ctrl, .maplibregl-ctrl, button';
+28
View File
@@ -0,0 +1,28 @@
/* Place names beside the trip map's markers (#2796). The label hangs off the marker
element, so it pans with it; placeNameLabels.ts decides which ones stay visible. */
.trek-place-name {
position: absolute;
left: calc(100% + 6px); /* rtl-lint-disable: map geometry, the label sits beside the pin on screen */
top: 50%;
transform: translateY(-50%);
max-width: 13em;
padding: 2px 8px;
border-radius: 999px;
background: var(--sidebar-bg);
-webkit-backdrop-filter: blur(12px) saturate(180%);
backdrop-filter: blur(12px) saturate(180%);
box-shadow: var(--sidebar-shadow);
color: var(--text-primary);
font-family: var(--font-system);
font-size: calc(11.5px * var(--fs-scale-caption, 1));
font-weight: 600;
line-height: 1.35;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
pointer-events: none;
}
.trek-place-name[data-hidden] {
visibility: hidden;
}
+16 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { ratingBadgeHtml } from './ratingBadge'
import { cornerBadgeHtml, ratingBadgeHtml } from './ratingBadge'
describe('ratingBadgeHtml', () => {
it('FE-MAP-RATINGBADGE-001: shows a whole rating without a decimal', () => {
@@ -21,3 +21,18 @@ describe('ratingBadgeHtml', () => {
expect(ratingBadgeHtml(0)).toBe('')
})
})
describe('cornerBadgeHtml', () => {
it('FE-MAP-RATINGBADGE-101: day numbers win the corner over the rating', () => {
const html = cornerBadgeHtml([2, 5], 4.5, true, -4);
expect(html).toContain('2 · 5');
expect(html).toContain('bottom:-4px;right:-4px');
expect(html).not.toContain('#f59e0b');
});
it('FE-MAP-RATINGBADGE-102: without numbers the rating shows when asked for, else nothing', () => {
expect(cornerBadgeHtml(null, 4, true, -2)).toContain('#f59e0b');
expect(cornerBadgeHtml([], 4, false, -2)).toBe('');
expect(cornerBadgeHtml([3], null, true, -2)).toContain('height:18px');
});
});
+27
View File
@@ -25,3 +25,30 @@ export function ratingBadgeHtml(rating: number | null | undefined): string {
box-sizing:border-box;white-space:nowrap;
">${label}</span>`;
}
/**
* The marker's corner badge: the day numbers of a planned stop, or else its rating.
* Both maps draw the same badge; only how far it hangs off the pin differs, since the
* GL wrapper is the pin's full outer size and the Leaflet one is not.
*/
export function cornerBadgeHtml(
orderNumbers: readonly number[] | null | undefined,
rating: number | null | undefined,
showRating: boolean,
inset: number
): string {
if (!orderNumbers || orderNumbers.length === 0) return showRating ? ratingBadgeHtml(rating) : '';
const many = orderNumbers.length > 1;
return `<span style="
position:absolute;bottom:${inset}px;right:${inset}px;
min-width:18px;height:${many ? 16 : 18}px;border-radius:${many ? 8 : 9}px;
padding:0 ${many ? 4 : 3}px;
background:rgba(255,255,255,0.94);
border:1.5px solid rgba(0,0,0,0.15);
box-shadow:0 1px 4px rgba(0,0,0,0.18);
display:flex;align-items:center;justify-content:center;
font-size:${many ? 7.5 : 9}px;font-weight:800;color:#111827;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${orderNumbers.join(' · ')}</span>`;
}
@@ -0,0 +1,57 @@
// FE-MAP-PLACENAMESHOOK-001 to FE-MAP-PLACENAMESHOOK-002
import { renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useSettingsStore } from '../../store/settingsStore';
import { tagPlaceName } from './placeNameLabels';
import { useGlPlaceNames } from './usePlaceNameLayout';
beforeEach(() => {
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
cb(0);
return 1;
});
});
afterEach(() => {
vi.restoreAllMocks();
document.body.innerHTML = '';
});
function glMap() {
const container = document.createElement('div');
const pin = document.createElement('div');
tagPlaceName(pin, 'Senso-ji', 0);
container.appendChild(pin);
document.body.appendChild(container);
const handlers = new Set<() => void>();
return {
container,
map: {
getContainer: () => container,
on: vi.fn((_t: 'moveend', fn: () => void) => handlers.add(fn)),
off: vi.fn((_t: 'moveend', fn: () => void) => handlers.delete(fn)),
},
handlers,
};
}
describe('useGlPlaceNames', () => {
it('FE-MAP-PLACENAMESHOOK-001: with the setting on, names are laid out and follow every move', () => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: true } }));
const { container, map, handlers } = glMap();
const { unmount } = renderHook(() => useGlPlaceNames(map));
expect(container.querySelector('.trek-place-name')?.textContent).toBe('Senso-ji');
expect(map.on).toHaveBeenCalledWith('moveend', expect.any(Function));
unmount();
expect(handlers.size).toBe(0);
});
it('FE-MAP-PLACENAMESHOOK-002: with the setting off, or no map yet, there are no names', () => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: false } }));
const { container, map } = glMap();
renderHook(() => useGlPlaceNames(map));
expect(container.querySelector('.trek-place-name')).toBeNull();
expect(map.on).not.toHaveBeenCalled();
renderHook(() => useGlPlaceNames(null));
});
});
@@ -0,0 +1,71 @@
import { useCallback, useEffect } from 'react';
import { useSettingsStore } from '../../store/settingsStore';
import { controlBoxes, layoutPlaceNames, PLACE_NAMES_CONTROLS } from './placeNameLabels';
/** Whether the trip map shows its place names, the reader's own setting (#2796). */
export function usePlaceNamesSetting(): boolean {
return useSettingsStore((s) => s.settings.map_place_labels) === true;
}
/**
* Keeps the place names of one map laid out: once after every change of the markers
* (a cluster opening, a day picked) and after every move or zoom the renderer reports
* through `listen`. Both renderers share it; only how they report a move differs.
*/
export function usePlaceNameLayout(
enabled: boolean,
/** The element the markers live in, or null while the map is not up yet. Keep it stable (useCallback). */
getContainer: () => HTMLElement | null,
/** Subscribes `run` to the renderer's move and zoom ends and returns the unsubscribe. Keep it stable too. */
listen: (run: () => void) => () => void
): void {
useEffect(() => {
const container = getContainer();
if (!container) return;
let frame = 0;
const run = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const scope = container.parentElement ?? container;
const controls = enabled ? controlBoxes(scope, PLACE_NAMES_CONTROLS).filter((b) => b.right > b.left) : [];
layoutPlaceNames(container, enabled, controls);
});
};
run();
if (!enabled) return () => cancelAnimationFrame(frame);
const stop = listen(run);
// A marker added or taken away (a cluster splitting, a selection rebuilding the pins).
const observer = new MutationObserver(run);
observer.observe(container, { childList: true, subtree: true });
return () => {
cancelAnimationFrame(frame);
stop();
observer.disconnect();
};
}, [enabled, getContainer, listen]);
}
/** The part of either GL map the names need. */
interface NamesGlMap {
getContainer: () => HTMLElement;
on: (type: 'moveend', listener: () => void) => unknown;
off: (type: 'moveend', listener: () => void) => unknown;
}
/** The GL map's wiring: its container, and a layout after every move or zoom ends. */
export function useGlPlaceNames(map: NamesGlMap | null): void {
const enabled = usePlaceNamesSetting();
const getContainer = useCallback(() => map?.getContainer() ?? null, [map]);
const listen = useCallback(
(run: () => void) => {
if (!map) return () => {};
map.on('moveend', run);
return () => {
map.off('moveend', run);
};
},
[map]
);
usePlaceNameLayout(enabled, getContainer, listen);
}