mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
lint + prettier
This commit is contained in:
@@ -1,37 +1,84 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { Marker, useMap } from 'react-leaflet'
|
||||
import L from 'leaflet'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import type { Poi } from './poiCategories'
|
||||
import { clusterPois, poiClusterMarkup, poiClusterList, POI_CLUSTER_DETAIL_ZOOM } from './poiClusters'
|
||||
import L from 'leaflet';
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Marker, useMap } from 'react-leaflet';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import type { Poi } from './poiCategories';
|
||||
import { clusterPois, POI_CLUSTER_DETAIL_ZOOM, poiClusterList, poiClusterMarkup } from './poiClusters';
|
||||
|
||||
export default function ClusteredPois({ pois, enabled, onPoiClick, children }: {
|
||||
pois: Poi[]; enabled: boolean; onPoiClick?: (poi: Poi) => void; children: ReactNode[]
|
||||
export default function ClusteredPois({
|
||||
pois,
|
||||
enabled,
|
||||
onPoiClick,
|
||||
children,
|
||||
}: {
|
||||
pois: Poi[];
|
||||
enabled: boolean;
|
||||
onPoiClick?: (poi: Poi) => void;
|
||||
children: ReactNode[];
|
||||
}) {
|
||||
const map = useMap()
|
||||
const { t } = useTranslation()
|
||||
const [zoom, setZoom] = useState(() => map.getZoom())
|
||||
const popup = useRef<L.Popup | null>(null)
|
||||
useEffect(() => () => { popup.current?.remove() }, [pois, enabled, zoom])
|
||||
const map = useMap();
|
||||
const { t } = useTranslation();
|
||||
const [zoom, setZoom] = useState(() => map.getZoom());
|
||||
const popup = useRef<L.Popup | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
popup.current?.remove();
|
||||
},
|
||||
[pois, enabled, zoom]
|
||||
);
|
||||
useEffect(() => {
|
||||
const update = () => setZoom(map.getZoom())
|
||||
map.on('zoomend', update)
|
||||
return () => { map.off('zoomend', update) }
|
||||
}, [map])
|
||||
const groups = useMemo(() => enabled ? clusterPois(pois, poi => map.latLngToContainerPoint([poi.lat, poi.lng]), zoom) : [], [pois, enabled, map, zoom])
|
||||
const markers = new Map(pois.map((poi, index) => [poi.osm_id, children[index]]))
|
||||
if (!enabled) return <>{children}</>
|
||||
return <>{groups.map(group => {
|
||||
if (group.pois.length === 1) return markers.get(group.pois[0].osm_id)
|
||||
const label = t('roadtrip.poi.found', { count: group.pois.length })
|
||||
return <Marker key={`poi-cluster-${group.pois[0].osm_id}`} position={[group.lat, group.lng]} alt={label}
|
||||
icon={L.divIcon({ className: '', html: poiClusterMarkup(group.pois.length), iconSize: [38, 38], iconAnchor: [19, 19] })}
|
||||
zIndexOffset={600} eventHandlers={{ click: () => {
|
||||
if (map.getZoom() >= POI_CLUSTER_DETAIL_ZOOM) {
|
||||
popup.current?.remove()
|
||||
popup.current = L.popup({ className: 'map-tooltip', maxWidth: 300 }).setLatLng([group.lat, group.lng])
|
||||
.setContent(poiClusterList(group.pois, poi => { popup.current?.remove(); onPoiClick?.(poi) })).openOn(map)
|
||||
} else map.fitBounds(group.pois.map(poi => [poi.lat, poi.lng] as [number, number]), { padding: [70, 70], maxZoom: POI_CLUSTER_DETAIL_ZOOM })
|
||||
} }} />
|
||||
})}</>
|
||||
const update = () => setZoom(map.getZoom());
|
||||
map.on('zoomend', update);
|
||||
return () => {
|
||||
map.off('zoomend', update);
|
||||
};
|
||||
}, [map]);
|
||||
const groups = useMemo(
|
||||
() => (enabled ? clusterPois(pois, (poi) => map.latLngToContainerPoint([poi.lat, poi.lng]), zoom) : []),
|
||||
[pois, enabled, map, zoom]
|
||||
);
|
||||
const markers = new Map(pois.map((poi, index) => [poi.osm_id, children[index]]));
|
||||
if (!enabled) return <>{children}</>;
|
||||
return (
|
||||
<>
|
||||
{groups.map((group) => {
|
||||
if (group.pois.length === 1) return markers.get(group.pois[0].osm_id);
|
||||
const label = t('roadtrip.poi.found', { count: group.pois.length });
|
||||
return (
|
||||
<Marker
|
||||
key={`poi-cluster-${group.pois[0].osm_id}`}
|
||||
position={[group.lat, group.lng]}
|
||||
alt={label}
|
||||
icon={L.divIcon({
|
||||
className: '',
|
||||
html: poiClusterMarkup(group.pois.length),
|
||||
iconSize: [38, 38],
|
||||
iconAnchor: [19, 19],
|
||||
})}
|
||||
zIndexOffset={600}
|
||||
eventHandlers={{
|
||||
click: () => {
|
||||
if (map.getZoom() >= POI_CLUSTER_DETAIL_ZOOM) {
|
||||
popup.current?.remove();
|
||||
popup.current = L.popup({ className: 'map-tooltip', maxWidth: 300 })
|
||||
.setLatLng([group.lat, group.lng])
|
||||
.setContent(
|
||||
poiClusterList(group.pois, (poi) => {
|
||||
popup.current?.remove();
|
||||
onPoiClick?.(poi);
|
||||
})
|
||||
)
|
||||
.openOn(map);
|
||||
} else
|
||||
map.fitBounds(
|
||||
group.pois.map((poi) => [poi.lat, poi.lng] as [number, number]),
|
||||
{ padding: [70, 70], maxZoom: POI_CLUSTER_DETAIL_ZOOM }
|
||||
);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,11 +25,10 @@
|
||||
* what stops Leaflet from being handed zero-length polylines on every trip that
|
||||
* has no recording.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared'
|
||||
import { DAWARICH_DAY_COLORS, DAWARICH_TRAIL_CASING } from './dawarichTrail'
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { DAWARICH_DAY_COLORS, DAWARICH_TRAIL_CASING } from './dawarichTrail';
|
||||
|
||||
// Leaflet itself is irrelevant here. What is under test is which polylines are
|
||||
// asked for and with what options, so the mock reflects the props back as data
|
||||
@@ -41,10 +40,10 @@ vi.mock('react-leaflet', () => ({
|
||||
pane,
|
||||
interactive,
|
||||
}: {
|
||||
positions: Array<[number, number]>
|
||||
pathOptions?: Record<string, unknown>
|
||||
pane?: string
|
||||
interactive?: boolean
|
||||
positions: Array<[number, number]>;
|
||||
pathOptions?: Record<string, unknown>;
|
||||
pane?: string;
|
||||
interactive?: boolean;
|
||||
}) => (
|
||||
<div
|
||||
data-testid="polyline"
|
||||
@@ -57,9 +56,9 @@ vi.mock('react-leaflet', () => ({
|
||||
data-interactive={String(interactive)}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
}));
|
||||
|
||||
import DawarichTrailLayer from './DawarichTrailLayer'
|
||||
import DawarichTrailLayer from './DawarichTrailLayer';
|
||||
|
||||
function day(date: string, ...segments: Array<Array<[number, number]>>): DawarichTrackDay {
|
||||
return {
|
||||
@@ -71,7 +70,7 @@ function day(date: string, ...segments: Array<Array<[number, number]>>): Dawaric
|
||||
endedAt: date + 'T09:0' + i + ':00.000Z',
|
||||
distanceMeters: 1200,
|
||||
})),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function track(days: DawarichTrackDay[]): DawarichTrack {
|
||||
@@ -81,89 +80,114 @@ function track(days: DawarichTrackDay[]): DawarichTrack {
|
||||
fetchedAt: '2026-05-03T10:00:00.000Z',
|
||||
pointCount: days.reduce((sum, d) => sum + d.segments.reduce((n, s) => n + s.points.length, 0), 0),
|
||||
truncated: false,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const DAY_ONE = day('2026-05-01', [[48.2, 16.37], [48.21, 16.38]])
|
||||
const DAY_TWO = day('2026-05-02', [[45.46, 9.18], [45.47, 9.19]], [[45.5, 9.2], [45.51, 9.21]])
|
||||
const DAY_ONE = day('2026-05-01', [
|
||||
[48.2, 16.37],
|
||||
[48.21, 16.38],
|
||||
]);
|
||||
const DAY_TWO = day(
|
||||
'2026-05-02',
|
||||
[
|
||||
[45.46, 9.18],
|
||||
[45.47, 9.19],
|
||||
],
|
||||
[
|
||||
[45.5, 9.2],
|
||||
[45.51, 9.21],
|
||||
]
|
||||
);
|
||||
|
||||
const lines = () => screen.queryAllByTestId('polyline')
|
||||
const lines = () => screen.queryAllByTestId('polyline');
|
||||
|
||||
describe('DawarichTrailLayer', () => {
|
||||
it('FE-DAWARICH-TRAILUI-010: draws nothing at all when there is no recording', () => {
|
||||
const { container } = render(<DawarichTrailLayer track={null} />)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
const { container } = render(<DawarichTrailLayer track={null} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-011: ignores a segment that is a single fix rather than a line', () => {
|
||||
// Dawarich reports a lone point for a day someone only opened the app on.
|
||||
// Leaflet would accept the one-point polyline and draw nothing visible, but
|
||||
// it would still be a layer, and every such day would add two of them.
|
||||
const { container } = render(<DawarichTrailLayer track={track([day('2026-05-01', [[48.2, 16.37]])])} />)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
const { container } = render(<DawarichTrailLayer track={track([day('2026-05-01', [[48.2, 16.37]])])} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-012: draws every casing first, then every coloured line on top', () => {
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} casingPane="trek-track-casing" />)
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} casingPane="trek-track-casing" />);
|
||||
|
||||
const drawn = lines()
|
||||
expect(drawn).toHaveLength(6) // three segments, casing + line each
|
||||
const drawn = lines();
|
||||
expect(drawn).toHaveLength(6); // three segments, casing + line each
|
||||
|
||||
// The first half is the casing pass. Reversing these two blocks would put
|
||||
// the white line over the coloured one and the overlay would go white.
|
||||
const casings = drawn.slice(0, 3)
|
||||
const coloured = drawn.slice(3)
|
||||
expect(casings.every(el => el.getAttribute('data-color') === DAWARICH_TRAIL_CASING)).toBe(true)
|
||||
expect(coloured.some(el => el.getAttribute('data-color') === DAWARICH_TRAIL_CASING)).toBe(false)
|
||||
})
|
||||
const casings = drawn.slice(0, 3);
|
||||
const coloured = drawn.slice(3);
|
||||
expect(casings.every((el) => el.getAttribute('data-color') === DAWARICH_TRAIL_CASING)).toBe(true);
|
||||
expect(coloured.some((el) => el.getAttribute('data-color') === DAWARICH_TRAIL_CASING)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-013: gives the casing the pane and the weight that make it a casing, and nothing catches clicks', () => {
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE])} casingPane="trek-track-casing" />)
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE])} casingPane="trek-track-casing" />);
|
||||
|
||||
const [casing, line] = lines()
|
||||
expect(casing.getAttribute('data-pane')).toBe('trek-track-casing')
|
||||
expect(casing.getAttribute('data-weight')).toBe('6')
|
||||
expect(casing.getAttribute('data-opacity')).toBe('0.55')
|
||||
const [casing, line] = lines();
|
||||
expect(casing.getAttribute('data-pane')).toBe('trek-track-casing');
|
||||
expect(casing.getAttribute('data-weight')).toBe('6');
|
||||
expect(casing.getAttribute('data-opacity')).toBe('0.55');
|
||||
|
||||
// Only the casing takes the pane; the coloured line is left in Leaflet's
|
||||
// default overlay pane. Pinned as the fact it is rather than as a rule:
|
||||
// that pane also holds the planned route, and the trail is mounted after
|
||||
// it, so the recorded line currently draws over the plan while the GL twin
|
||||
// puts both of its layers under it.
|
||||
expect(line.getAttribute('data-pane')).toBe('')
|
||||
expect(line.getAttribute('data-weight')).toBe('3')
|
||||
expect(line.getAttribute('data-dash')).toBe('6 5')
|
||||
expect(line.getAttribute('data-points')).toBe(JSON.stringify([[48.2, 16.37], [48.21, 16.38]]))
|
||||
expect(line.getAttribute('data-pane')).toBe('');
|
||||
expect(line.getAttribute('data-weight')).toBe('3');
|
||||
expect(line.getAttribute('data-dash')).toBe('6 5');
|
||||
expect(line.getAttribute('data-points')).toBe(
|
||||
JSON.stringify([
|
||||
[48.2, 16.37],
|
||||
[48.21, 16.38],
|
||||
])
|
||||
);
|
||||
|
||||
expect(lines().every(el => el.getAttribute('data-interactive') === 'false')).toBe(true)
|
||||
})
|
||||
expect(lines().every((el) => el.getAttribute('data-interactive') === 'false')).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-014: works without a casing pane on a renderer that has none', () => {
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE])} />)
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE])} />);
|
||||
|
||||
// An older Leaflet build, or the GL renderer's Leaflet fallback, has no
|
||||
// pane API and MapView passes undefined. Everything then lands in the
|
||||
// default overlay pane in insertion order, which still keeps the casing
|
||||
// under its own line, the one piece of the stacking that has to hold.
|
||||
expect(lines().every(el => el.getAttribute('data-pane') === '')).toBe(true)
|
||||
expect(lines()).toHaveLength(2)
|
||||
})
|
||||
expect(lines().every((el) => el.getAttribute('data-pane') === '')).toBe(true);
|
||||
expect(lines()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-015: scrubbing to one day keeps that day its own colour', () => {
|
||||
const { rerender } = render(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-02" />)
|
||||
const { rerender } = render(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-02" />);
|
||||
|
||||
// Two segments on the second day, so two casings and two lines, and the hue
|
||||
// is the SECOND of the palette even though it is now the only day drawn.
|
||||
expect(lines()).toHaveLength(4)
|
||||
expect(lines().slice(2).map(el => el.getAttribute('data-color')))
|
||||
.toEqual([DAWARICH_DAY_COLORS[1], DAWARICH_DAY_COLORS[1]])
|
||||
expect(lines()).toHaveLength(4);
|
||||
expect(
|
||||
lines()
|
||||
.slice(2)
|
||||
.map((el) => el.getAttribute('data-color'))
|
||||
).toEqual([DAWARICH_DAY_COLORS[1], DAWARICH_DAY_COLORS[1]]);
|
||||
|
||||
rerender(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-01" />)
|
||||
expect(lines().slice(1).map(el => el.getAttribute('data-color'))).toEqual([DAWARICH_DAY_COLORS[0]])
|
||||
rerender(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-01" />);
|
||||
expect(
|
||||
lines()
|
||||
.slice(1)
|
||||
.map((el) => el.getAttribute('data-color'))
|
||||
).toEqual([DAWARICH_DAY_COLORS[0]]);
|
||||
|
||||
// A day nobody recorded on falls back to the empty case rather than to the
|
||||
// whole trip, which would be the worst possible answer to "show me Sunday".
|
||||
rerender(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-09" />)
|
||||
expect(lines()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
rerender(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-09" />);
|
||||
expect(lines()).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Polyline } from 'react-leaflet'
|
||||
import type { DawarichTrack } from '@trek/shared'
|
||||
import {
|
||||
DAWARICH_TRAIL_CASING,
|
||||
trailSegments,
|
||||
type DawarichTrailSegment,
|
||||
} from './dawarichTrail'
|
||||
import type { DawarichTrack } from '@trek/shared';
|
||||
import { useMemo } from 'react';
|
||||
import { Polyline } from 'react-leaflet';
|
||||
import { DAWARICH_TRAIL_CASING, trailSegments, type DawarichTrailSegment } from './dawarichTrail';
|
||||
|
||||
/**
|
||||
* The recorded route on the Leaflet renderer.
|
||||
@@ -29,16 +25,16 @@ export default function DawarichTrailLayer({
|
||||
hiddenDates,
|
||||
casingPane,
|
||||
}: {
|
||||
track: DawarichTrack | null
|
||||
track: DawarichTrack | null;
|
||||
/** When set, only that local day is drawn. */
|
||||
selectedDate?: string | null
|
||||
selectedDate?: string | null;
|
||||
/** Local dates whose day is folded away in the day plan. */
|
||||
hiddenDates?: ReadonlySet<string> | null
|
||||
hiddenDates?: ReadonlySet<string> | null;
|
||||
/** The `trek-track-casing` pane, when the renderer supports panes. */
|
||||
casingPane?: string
|
||||
casingPane?: string;
|
||||
}) {
|
||||
const segments = useMemo(() => trailSegments(track, selectedDate, hiddenDates), [track, selectedDate, hiddenDates])
|
||||
if (segments.length === 0) return null
|
||||
const segments = useMemo(() => trailSegments(track, selectedDate, hiddenDates), [track, selectedDate, hiddenDates]);
|
||||
if (segments.length === 0) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -77,5 +73,5 @@ export default function DawarichTrailLayer({
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,133 +17,133 @@
|
||||
* dimmed logo on a switched-off control would read as broken rather than as
|
||||
* off.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { render, screen, fireEvent, act } from '../../../tests/helpers/render'
|
||||
import { DawarichTrailPill } from './DawarichTrailPill'
|
||||
import type { DawarichTrailStatus } from './useDawarichTrail'
|
||||
import React from 'react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { DawarichTrailPill } from './DawarichTrailPill';
|
||||
import type { DawarichTrailStatus } from './useDawarichTrail';
|
||||
|
||||
function pill(props: Partial<React.ComponentProps<typeof DawarichTrailPill>> = {}) {
|
||||
return render(
|
||||
<DawarichTrailPill active={false} status="idle" onToggle={vi.fn()} {...props} />,
|
||||
)
|
||||
return render(<DawarichTrailPill active={false} status="idle" onToggle={vi.fn()} {...props} />);
|
||||
}
|
||||
|
||||
const button = () => screen.getByTestId('dawarich-trail-pill')
|
||||
const label = () => button().getAttribute('aria-label')
|
||||
const button = () => screen.getByTestId('dawarich-trail-pill');
|
||||
const label = () => button().getAttribute('aria-label');
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('DawarichTrailPill', () => {
|
||||
it('FE-DAWARICH-TRAILUI-001: offers to show the route while the layer is off, whatever the last status was', () => {
|
||||
const { rerender } = pill()
|
||||
const { rerender } = pill();
|
||||
|
||||
expect(label()).toBe('Show recorded route')
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'false')
|
||||
expect(button().style.opacity).toBe('0.6')
|
||||
expect(label()).toBe('Show recorded route');
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(button().style.opacity).toBe('0.6');
|
||||
|
||||
// A stale failure from the last time the layer was on must not dim a
|
||||
// switched-off control: off already has its own resting opacity, and a
|
||||
// second, dimmer step would read as "this button is broken".
|
||||
rerender(<DawarichTrailPill active={false} status="unavailable" onToggle={vi.fn()} />)
|
||||
expect(label()).toBe('Show recorded route')
|
||||
expect(button().style.opacity).toBe('0.6')
|
||||
})
|
||||
rerender(<DawarichTrailPill active={false} status="unavailable" onToggle={vi.fn()} />);
|
||||
expect(label()).toBe('Show recorded route');
|
||||
expect(button().style.opacity).toBe('0.6');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-002: offers to hide the route once a line is on the map', () => {
|
||||
const { rerender } = pill({ active: true, status: 'ready' })
|
||||
const { rerender } = pill({ active: true, status: 'ready' });
|
||||
|
||||
expect(label()).toBe('Hide recorded route')
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(button().style.opacity).toBe('1')
|
||||
expect(label()).toBe('Hide recorded route');
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(button().style.opacity).toBe('1');
|
||||
|
||||
// `idle` is the state between the toggle flipping and the first fetch
|
||||
// starting. It falls through the same arm as `ready` on purpose: the button
|
||||
// has just been pressed and "hide" is the only honest thing it can offer.
|
||||
rerender(<DawarichTrailPill active status="idle" onToggle={vi.fn()} />)
|
||||
expect(label()).toBe('Hide recorded route')
|
||||
expect(button().style.opacity).toBe('1')
|
||||
})
|
||||
rerender(<DawarichTrailPill active status="idle" onToggle={vi.fn()} />);
|
||||
expect(label()).toBe('Hide recorded route');
|
||||
expect(button().style.opacity).toBe('1');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-003: says it is loading without dimming the mark', () => {
|
||||
pill({ active: true, status: 'loading' })
|
||||
pill({ active: true, status: 'loading' });
|
||||
|
||||
expect(label()).toMatch(/^Loading the recorded route/)
|
||||
expect(label()).toMatch(/^Loading the recorded route/);
|
||||
// Loading is not a problem, so the wordless "something is wrong" channel
|
||||
// stays off. Otherwise every refresh would blink the control.
|
||||
expect(button().style.opacity).toBe('1')
|
||||
})
|
||||
expect(button().style.opacity).toBe('1');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-004: names each reason there is no line and dims the mark for it', () => {
|
||||
const reasons: Array<[DawarichTrailStatus, string]> = [
|
||||
['empty', 'Nothing was recorded on these dates'],
|
||||
['offline', 'The recorded route needs a connection'],
|
||||
['unavailable', 'The recorded route could not be loaded'],
|
||||
]
|
||||
];
|
||||
|
||||
for (const [status, expected] of reasons) {
|
||||
const { unmount } = pill({ active: true, status })
|
||||
expect(label()).toBe(expected)
|
||||
expect(button().style.opacity).toBe('0.35')
|
||||
const { unmount } = pill({ active: true, status });
|
||||
expect(label()).toBe(expected);
|
||||
expect(button().style.opacity).toBe('0.35');
|
||||
// The pressed state survives the problem: the layer really is on, and
|
||||
// un-pressing it here would make the toggle disagree with the map.
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'true')
|
||||
unmount()
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'true');
|
||||
unmount();
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-005: reports a press once', () => {
|
||||
const onToggle = vi.fn()
|
||||
pill({ onToggle })
|
||||
const onToggle = vi.fn();
|
||||
pill({ onToggle });
|
||||
|
||||
fireEvent.click(button())
|
||||
expect(onToggle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
fireEvent.click(button());
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-006: lifts the mark under the pointer and puts it back', () => {
|
||||
pill({ active: true, status: 'ready' })
|
||||
pill({ active: true, status: 'ready' });
|
||||
|
||||
fireEvent.mouseEnter(button())
|
||||
expect(button().style.transform).toBe('scale(1.06)')
|
||||
fireEvent.mouseEnter(button());
|
||||
expect(button().style.transform).toBe('scale(1.06)');
|
||||
|
||||
fireEvent.mouseLeave(button())
|
||||
expect(button().style.transform).toBe('none')
|
||||
})
|
||||
fireEvent.mouseLeave(button());
|
||||
expect(button().style.transform).toBe('none');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-007: repeats the status in a readable tooltip rather than the native one', () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
pill({ active: true, status: 'empty' })
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
pill({ active: true, status: 'empty' });
|
||||
|
||||
fireEvent.mouseEnter(button())
|
||||
act(() => { vi.advanceTimersByTime(300) })
|
||||
fireEvent.mouseEnter(button());
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(300);
|
||||
});
|
||||
|
||||
// The whole reason this control carries TREK's own tooltip: the native one
|
||||
// never appears on a touch device, which is exactly where someone taps the
|
||||
// button to find out why the map is empty.
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Nothing was recorded on these dates')
|
||||
})
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Nothing was recorded on these dates');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-008: shows a spinning ring and a busy state while the route loads', () => {
|
||||
pill({ active: true, status: 'loading' })
|
||||
pill({ active: true, status: 'loading' });
|
||||
|
||||
// A first fetch from somebody's own server can take a while. With nothing on
|
||||
// the button it read as "done, no line", and the tester reloaded the page.
|
||||
expect(screen.getByTestId('dawarich-trail-loading')).toBeInTheDocument()
|
||||
expect(button()).toHaveAttribute('aria-busy', 'true')
|
||||
})
|
||||
expect(screen.getByTestId('dawarich-trail-loading')).toBeInTheDocument();
|
||||
expect(button()).toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-009: drops the ring once there is an answer, and never shows it while the layer is off', () => {
|
||||
const view = pill({ active: true, status: 'loading' })
|
||||
const view = pill({ active: true, status: 'loading' });
|
||||
|
||||
view.rerender(<DawarichTrailPill active status="ready" onToggle={vi.fn()} />)
|
||||
expect(screen.queryByTestId('dawarich-trail-loading')).not.toBeInTheDocument()
|
||||
expect(button()).toHaveAttribute('aria-busy', 'false')
|
||||
view.rerender(<DawarichTrailPill active status="ready" onToggle={vi.fn()} />);
|
||||
expect(screen.queryByTestId('dawarich-trail-loading')).not.toBeInTheDocument();
|
||||
expect(button()).toHaveAttribute('aria-busy', 'false');
|
||||
|
||||
// Switched off mid-load: the hook still reports its last status, the button
|
||||
// must not keep spinning for a layer nobody asked for any more.
|
||||
view.rerender(<DawarichTrailPill active={false} status="loading" onToggle={vi.fn()} />)
|
||||
expect(screen.queryByTestId('dawarich-trail-loading')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
view.rerender(<DawarichTrailPill active={false} status="loading" onToggle={vi.fn()} />);
|
||||
expect(screen.queryByTestId('dawarich-trail-loading')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
|
||||
import type { DawarichTrailStatus } from './useDawarichTrail'
|
||||
import { useTranslation } from '../../i18n';
|
||||
import DawarichIcon from '../shared/DawarichIcon';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow';
|
||||
import type { DawarichTrailStatus } from './useDawarichTrail';
|
||||
|
||||
/**
|
||||
* Toggle for the recorded-route overlay (#2279), in the same frosted shell as
|
||||
@@ -19,11 +19,11 @@ export function DawarichTrailPill({
|
||||
status,
|
||||
onToggle,
|
||||
}: {
|
||||
active: boolean
|
||||
status: DawarichTrailStatus
|
||||
onToggle: () => void
|
||||
active: boolean;
|
||||
status: DawarichTrailStatus;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { t } = useTranslation();
|
||||
|
||||
const label = !active
|
||||
? t('dawarich.trail.show')
|
||||
@@ -35,15 +35,15 @@ export function DawarichTrailPill({
|
||||
? t('dawarich.trail.offline')
|
||||
: status === 'unavailable'
|
||||
? t('dawarich.trail.unavailable')
|
||||
: t('dawarich.trail.hide')
|
||||
: t('dawarich.trail.hide');
|
||||
|
||||
// A problem worth seeing without reading the tooltip: the layer is on and
|
||||
// there is nothing to show.
|
||||
const muted = active && (status === 'empty' || status === 'offline' || status === 'unavailable')
|
||||
const muted = active && (status === 'empty' || status === 'offline' || status === 'unavailable');
|
||||
// Loading has to be visible too. A first fetch from somebody's own server can
|
||||
// take a while, and with nothing on the button it looked exactly like "done,
|
||||
// but no line", so testers reloaded the page to find out.
|
||||
const loading = active && status === 'loading'
|
||||
const loading = active && status === 'loading';
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -64,35 +64,39 @@ export function DawarichTrailPill({
|
||||
appears on a touch device, and this control's whole job is to explain
|
||||
why there is no line. */}
|
||||
<Tooltip label={label} placement="left">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
aria-label={label}
|
||||
aria-pressed={active}
|
||||
aria-busy={loading}
|
||||
data-testid="dawarich-trail-pill"
|
||||
style={{
|
||||
display: 'block',
|
||||
width: 34,
|
||||
height: 34,
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: 'transparent',
|
||||
padding: 0,
|
||||
// The mark fills the circle and is clipped by it, so the control reads
|
||||
// as the Dawarich button rather than as a frame with a logo in it.
|
||||
overflow: 'hidden',
|
||||
// Its own colours stay; on/off is carried by opacity, because a
|
||||
// recoloured logo is a different logo.
|
||||
opacity: muted ? 0.35 : active ? 1 : 0.6,
|
||||
transition: 'opacity 0.14s, transform 0.14s',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.06)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.transform = 'none' }}
|
||||
>
|
||||
<DawarichIcon fill />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
aria-label={label}
|
||||
aria-pressed={active}
|
||||
aria-busy={loading}
|
||||
data-testid="dawarich-trail-pill"
|
||||
style={{
|
||||
display: 'block',
|
||||
width: 34,
|
||||
height: 34,
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: 'transparent',
|
||||
padding: 0,
|
||||
// The mark fills the circle and is clipped by it, so the control reads
|
||||
// as the Dawarich button rather than as a frame with a logo in it.
|
||||
overflow: 'hidden',
|
||||
// Its own colours stay; on/off is carried by opacity, because a
|
||||
// recoloured logo is a different logo.
|
||||
opacity: muted ? 0.35 : active ? 1 : 0.6,
|
||||
transition: 'opacity 0.14s, transform 0.14s',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.transform = 'scale(1.06)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.transform = 'none';
|
||||
}}
|
||||
>
|
||||
<DawarichIcon fill />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{loading && (
|
||||
<span
|
||||
@@ -111,5 +115,5 @@ export function DawarichTrailPill({
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import { GeoJSON } from 'react-leaflet'
|
||||
import type { RoadtripHazard } from '@trek/shared'
|
||||
import L from 'leaflet'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import type { RoadtripHazard } from '@trek/shared';
|
||||
import L from 'leaflet';
|
||||
import { GeoJSON } from 'react-leaflet';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
|
||||
import { hazardPopup, hazardFeature } from './hazardPopup'
|
||||
import { hazardFeature, hazardPopup } from './hazardPopup';
|
||||
|
||||
export default function HazardLayers({ hazards }: { hazards: RoadtripHazard[] }) {
|
||||
const { t } = useTranslation()
|
||||
return <>{hazards.map(hazard => <GeoJSON key={`${hazard.id}-${hazard.updatedAt}`} data={hazardFeature(hazard)}
|
||||
style={{ color: 'var(--warning)', weight: 2, fillOpacity: 0.16 }}
|
||||
pointToLayer={(_, point) => L.circleMarker(point, { radius: 7, color: 'var(--warning)', fillOpacity: 0.65 })}
|
||||
onEachFeature={(_, layer) => layer.bindPopup(hazardPopup(hazard, t('roadtrip.hazards.note'), t('roadtrip.hazards.point')), { className: 'map-tooltip trek-hazard-popup', maxWidth: 320 })}
|
||||
/>)}</>
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{hazards.map((hazard) => (
|
||||
<GeoJSON
|
||||
key={`${hazard.id}-${hazard.updatedAt}`}
|
||||
data={hazardFeature(hazard)}
|
||||
style={{ color: 'var(--warning)', weight: 2, fillOpacity: 0.16 }}
|
||||
pointToLayer={(_, point) => L.circleMarker(point, { radius: 7, color: 'var(--warning)', fillOpacity: 0.65 })}
|
||||
onEachFeature={(_, layer) =>
|
||||
layer.bindPopup(hazardPopup(hazard, t('roadtrip.hazards.note'), t('roadtrip.hazards.point')), {
|
||||
className: 'map-tooltip trek-hazard-popup',
|
||||
maxWidth: 320,
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// FE-MAP-LOCBTN-001 to FE-MAP-LOCBTN-005
|
||||
import { render } from '@testing-library/react';
|
||||
import LocationButton from './LocationButton';
|
||||
import type { GeoWatchErrorCode } from '../../hooks/useGeolocation';
|
||||
import LocationButton from './LocationButton';
|
||||
|
||||
// useToast talks to the mounted ToastContainer through window.__addToast,
|
||||
// so a spy there observes exactly what the user would get shown. Outside a
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
|
||||
import { Navigation, LocateFixed, Locate } from 'lucide-react'
|
||||
import type { TrackingMode, GeoWatchErrorCode } from '../../hooks/useGeolocation'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { Locate, LocateFixed, Navigation } from 'lucide-react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { GeoWatchErrorCode, TrackingMode } from '../../hooks/useGeolocation';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow';
|
||||
|
||||
interface Props {
|
||||
mode: TrackingMode
|
||||
error: string | null
|
||||
errorCode: GeoWatchErrorCode | null
|
||||
onClick: () => void
|
||||
mode: TrackingMode;
|
||||
error: string | null;
|
||||
errorCode: GeoWatchErrorCode | null;
|
||||
onClick: () => void;
|
||||
// Offset from the bottom edge — callers push this up above the mobile
|
||||
// bottom nav. Defaults to 20px for desktop.
|
||||
bottomOffset?: number
|
||||
bottomOffset?: number;
|
||||
}
|
||||
|
||||
// The raw error string from the browser is unlocalized WebKit English, so the
|
||||
@@ -22,43 +22,43 @@ interface Props {
|
||||
// exactly this in all locales.
|
||||
const ERROR_KEYS: Record<GeoWatchErrorCode, string> = {
|
||||
'permission-denied': 'map.location.denied',
|
||||
'unavailable': 'map.location.unavailable',
|
||||
'timeout': 'map.location.timeout',
|
||||
'unsupported': 'map.location.unavailable',
|
||||
unavailable: 'map.location.unavailable',
|
||||
timeout: 'map.location.timeout',
|
||||
unsupported: 'map.location.unavailable',
|
||||
'insecure-context': 'journey.editor.locationInsecureContext',
|
||||
}
|
||||
};
|
||||
|
||||
// Three-state FAB. Matches the Apple/Google Maps pattern:
|
||||
// off → outline locate icon
|
||||
// show → filled locate (blue dot is visible on the map)
|
||||
// follow → filled navigation arrow (map follows + rotates with heading)
|
||||
export default function LocationButton({ mode, error, errorCode, onClick, bottomOffset = 20 }: Props) {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
// A title tooltip is invisible on touch, which is exactly where geolocation
|
||||
// errors happen (iOS PWA, see discussion #2095), so surface new errors as a
|
||||
// toast. The ref guards against re-fires: only the transition from no error
|
||||
// to an error announces itself.
|
||||
const prevCodeRef = useRef<GeoWatchErrorCode | null>(null)
|
||||
const prevCodeRef = useRef<GeoWatchErrorCode | null>(null);
|
||||
useEffect(() => {
|
||||
const prev = prevCodeRef.current
|
||||
prevCodeRef.current = errorCode
|
||||
const prev = prevCodeRef.current;
|
||||
prevCodeRef.current = errorCode;
|
||||
if (errorCode && prev === null) {
|
||||
// The denied message is long, so give the toast extra time to be read.
|
||||
toast.error(t(ERROR_KEYS[errorCode]), 6000)
|
||||
toast.error(t(ERROR_KEYS[errorCode]), 6000);
|
||||
}
|
||||
}, [errorCode, t, toast])
|
||||
}, [errorCode, t, toast]);
|
||||
|
||||
const Icon = mode === 'follow' ? Navigation : mode === 'show' ? LocateFixed : Locate
|
||||
const isActive = mode !== 'off'
|
||||
const errorText = errorCode ? t(ERROR_KEYS[errorCode]) : error
|
||||
const Icon = mode === 'follow' ? Navigation : mode === 'show' ? LocateFixed : Locate;
|
||||
const isActive = mode !== 'off';
|
||||
const errorText = errorCode ? t(ERROR_KEYS[errorCode]) : error;
|
||||
const title = errorText
|
||||
? errorText
|
||||
: mode === 'off'
|
||||
? 'Show my location'
|
||||
: mode === 'show'
|
||||
? 'Follow my location'
|
||||
: 'Stop following'
|
||||
: 'Stop following';
|
||||
|
||||
return (
|
||||
<button
|
||||
@@ -77,7 +77,7 @@ export default function LocationButton({ mode, error, errorCode, onClick, bottom
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: isActive ? '#3b82f6' : 'var(--bg-card, white)',
|
||||
color: isActive ? 'white' : (error ? '#ef4444' : 'var(--text-muted, #6b7280)'),
|
||||
color: isActive ? 'white' : error ? '#ef4444' : 'var(--text-muted, #6b7280)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
@@ -87,5 +87,5 @@ export default function LocationButton({ mode, error, errorCode, onClick, bottom
|
||||
>
|
||||
<Icon size={20} strokeWidth={mode === 'follow' ? 2.5 : 2} />
|
||||
</button>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,88 +1,91 @@
|
||||
// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-006
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent, act } from '../../../tests/helpers/render'
|
||||
import { MapCompassPill, type CompassMap } from './MapCompassPill'
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { MapCompassPill, type CompassMap } from './MapCompassPill';
|
||||
|
||||
function fakeCompassMap(initialBearing = 0) {
|
||||
const listeners: Array<() => void> = []
|
||||
let bearing = initialBearing
|
||||
const listeners: Array<() => void> = [];
|
||||
let bearing = initialBearing;
|
||||
const map = {
|
||||
getBearing: vi.fn(() => bearing),
|
||||
on: vi.fn((_type: 'rotate', fn: () => void) => { listeners.push(fn) }),
|
||||
on: vi.fn((_type: 'rotate', fn: () => void) => {
|
||||
listeners.push(fn);
|
||||
}),
|
||||
off: vi.fn((_type: 'rotate', fn: () => void) => {
|
||||
const i = listeners.indexOf(fn)
|
||||
if (i >= 0) listeners.splice(i, 1)
|
||||
const i = listeners.indexOf(fn);
|
||||
if (i >= 0) listeners.splice(i, 1);
|
||||
}),
|
||||
easeTo: vi.fn(),
|
||||
}
|
||||
};
|
||||
return {
|
||||
map: map as unknown as CompassMap,
|
||||
spies: map,
|
||||
listenerCount: () => listeners.length,
|
||||
rotateTo: (next: number) => {
|
||||
bearing = next
|
||||
act(() => { listeners.forEach(fn => fn()) })
|
||||
bearing = next;
|
||||
act(() => {
|
||||
listeners.forEach((fn) => fn());
|
||||
});
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const needle = () => screen.getByRole('button', { name: 'Reset north' }).querySelector('svg') as SVGElement
|
||||
const needle = () => screen.getByRole('button', { name: 'Reset north' }).querySelector('svg') as SVGElement;
|
||||
|
||||
describe('MapCompassPill', () => {
|
||||
it('FE-COMP-MAPCOMPASS-001: points the needle against the current map bearing', () => {
|
||||
const { map } = fakeCompassMap(45)
|
||||
render(<MapCompassPill map={map} />)
|
||||
const { map } = fakeCompassMap(45);
|
||||
render(<MapCompassPill map={map} />);
|
||||
// The map rotated 45° clockwise, so the needle turns 45° back to keep pointing north.
|
||||
expect(needle().style.transform).toBe('rotate(-45deg)')
|
||||
})
|
||||
expect(needle().style.transform).toBe('rotate(-45deg)');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-002: follows the map while it rotates', () => {
|
||||
const compass = fakeCompassMap(0)
|
||||
render(<MapCompassPill map={compass.map} />)
|
||||
expect(needle().style.transform).toBe('rotate(0deg)')
|
||||
const compass = fakeCompassMap(0);
|
||||
render(<MapCompassPill map={compass.map} />);
|
||||
expect(needle().style.transform).toBe('rotate(0deg)');
|
||||
|
||||
compass.rotateTo(120)
|
||||
expect(needle().style.transform).toBe('rotate(-120deg)')
|
||||
})
|
||||
compass.rotateTo(120);
|
||||
expect(needle().style.transform).toBe('rotate(-120deg)');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-003: snaps the camera back to north and flat on click', () => {
|
||||
const compass = fakeCompassMap(75)
|
||||
render(<MapCompassPill map={compass.map} />)
|
||||
const compass = fakeCompassMap(75);
|
||||
render(<MapCompassPill map={compass.map} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Reset north' }))
|
||||
expect(compass.spies.easeTo).toHaveBeenCalledWith({ bearing: 0, pitch: 0, duration: 300 })
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Reset north' }));
|
||||
expect(compass.spies.easeTo).toHaveBeenCalledWith({ bearing: 0, pitch: 0, duration: 300 });
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-004: unsubscribes from the rotate event on unmount', () => {
|
||||
const compass = fakeCompassMap(0)
|
||||
const { unmount } = render(<MapCompassPill map={compass.map} />)
|
||||
expect(compass.listenerCount()).toBe(1)
|
||||
const compass = fakeCompassMap(0);
|
||||
const { unmount } = render(<MapCompassPill map={compass.map} />);
|
||||
expect(compass.listenerCount()).toBe(1);
|
||||
|
||||
unmount()
|
||||
expect(compass.spies.off).toHaveBeenCalledWith('rotate', expect.any(Function))
|
||||
expect(compass.listenerCount()).toBe(0)
|
||||
})
|
||||
unmount();
|
||||
expect(compass.spies.off).toHaveBeenCalledWith('rotate', expect.any(Function));
|
||||
expect(compass.listenerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-005: resubscribes when the map instance is swapped (style rebuild)', () => {
|
||||
const first = fakeCompassMap(10)
|
||||
const second = fakeCompassMap(200)
|
||||
const { rerender } = render(<MapCompassPill map={first.map} />)
|
||||
const first = fakeCompassMap(10);
|
||||
const second = fakeCompassMap(200);
|
||||
const { rerender } = render(<MapCompassPill map={first.map} />);
|
||||
|
||||
rerender(<MapCompassPill map={second.map} />)
|
||||
expect(first.listenerCount()).toBe(0)
|
||||
expect(second.listenerCount()).toBe(1)
|
||||
expect(needle().style.transform).toBe('rotate(-200deg)')
|
||||
})
|
||||
rerender(<MapCompassPill map={second.map} />);
|
||||
expect(first.listenerCount()).toBe(0);
|
||||
expect(second.listenerCount()).toBe(1);
|
||||
expect(needle().style.transform).toBe('rotate(-200deg)');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-006: highlights the button on hover and clears it again', () => {
|
||||
const { map } = fakeCompassMap(0)
|
||||
render(<MapCompassPill map={map} />)
|
||||
const button = screen.getByRole('button', { name: 'Reset north' })
|
||||
const { map } = fakeCompassMap(0);
|
||||
render(<MapCompassPill map={map} />);
|
||||
const button = screen.getByRole('button', { name: 'Reset north' });
|
||||
|
||||
fireEvent.mouseEnter(button)
|
||||
expect(button.style.background).toBe('var(--bg-hover)')
|
||||
fireEvent.mouseLeave(button)
|
||||
expect(button.style.background).toBe('transparent')
|
||||
})
|
||||
})
|
||||
fireEvent.mouseEnter(button);
|
||||
expect(button.style.background).toBe('var(--bg-hover)');
|
||||
fireEvent.mouseLeave(button);
|
||||
expect(button.style.background).toBe('transparent');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Navigation } from 'lucide-react'
|
||||
import { Navigation } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export interface CompassMap {
|
||||
getBearing: () => number
|
||||
on: (type: 'rotate', listener: () => void) => unknown
|
||||
off: (type: 'rotate', listener: () => void) => unknown
|
||||
easeTo: (options: { bearing: number; pitch: number; duration: number }) => unknown
|
||||
getBearing: () => number;
|
||||
on: (type: 'rotate', listener: () => void) => unknown;
|
||||
off: (type: 'rotate', listener: () => void) => unknown;
|
||||
easeTo: (options: { bearing: number; pitch: number; duration: number }) => unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -16,39 +16,62 @@ export interface CompassMap {
|
||||
* so its height and transparency match the POI pill exactly.
|
||||
*/
|
||||
export function MapCompassPill({ map }: { map: CompassMap }) {
|
||||
const [bearing, setBearing] = useState(() => map.getBearing())
|
||||
const [bearing, setBearing] = useState(() => map.getBearing());
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => setBearing(map.getBearing())
|
||||
update()
|
||||
map.on('rotate', update)
|
||||
return () => { map.off('rotate', update) }
|
||||
}, [map])
|
||||
const update = () => setBearing(map.getBearing());
|
||||
update();
|
||||
map.on('rotate', update);
|
||||
return () => {
|
||||
map.off('rotate', update);
|
||||
};
|
||||
}, [map]);
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: 'var(--sidebar-shadow, 0 4px 16px rgba(0,0,0,0.14))',
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
padding: 4,
|
||||
borderRadius: 999,
|
||||
pointerEvents: 'auto',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: 'var(--sidebar-shadow, 0 4px 16px rgba(0,0,0,0.14))',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => map.easeTo({ bearing: 0, pitch: 0, duration: 300 })}
|
||||
aria-label="Reset north"
|
||||
className="text-content-muted"
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
|
||||
background: 'transparent', padding: 0,
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: 34,
|
||||
height: 34,
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: 'transparent',
|
||||
padding: 0,
|
||||
transition: 'background 0.14s, color 0.14s',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.background = 'var(--bg-hover)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'transparent';
|
||||
}}
|
||||
>
|
||||
<Navigation size={16} strokeWidth={2} style={{ transform: `rotate(${-bearing}deg)`, transition: 'transform 0.1s linear' }} />
|
||||
<Navigation
|
||||
size={16}
|
||||
strokeWidth={2}
|
||||
style={{ transform: `rotate(${-bearing}deg)`, transition: 'transform 0.1s linear' }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,57 +1,56 @@
|
||||
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-006
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import { MapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { MAP_ROUND_CONTROL_SIZE, MapLayerSwitcher } from './MapLayerSwitcher';
|
||||
|
||||
describe('MapLayerSwitcher', () => {
|
||||
it('FE-COMP-MAPLAYER-001: on the default layer, offers the switch to satellite', () => {
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />)
|
||||
const button = screen.getByRole('button', { name: 'Switch to satellite view' })
|
||||
expect(button.getAttribute('aria-pressed')).toBe('false')
|
||||
})
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />);
|
||||
const button = screen.getByRole('button', { name: 'Switch to satellite view' });
|
||||
expect(button.getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPLAYER-002: on the satellite layer, offers the switch back to the map', () => {
|
||||
render(<MapLayerSwitcher active="satellite" onToggle={() => {}} />)
|
||||
const button = screen.getByRole('button', { name: 'Switch to map view' })
|
||||
expect(button.getAttribute('aria-pressed')).toBe('true')
|
||||
})
|
||||
render(<MapLayerSwitcher active="satellite" onToggle={() => {}} />);
|
||||
const button = screen.getByRole('button', { name: 'Switch to map view' });
|
||||
expect(button.getAttribute('aria-pressed')).toBe('true');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPLAYER-003: clicking fires the toggle', () => {
|
||||
const onToggle = vi.fn()
|
||||
render(<MapLayerSwitcher active="default" onToggle={onToggle} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Switch to satellite view' }))
|
||||
expect(onToggle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
const onToggle = vi.fn();
|
||||
render(<MapLayerSwitcher active="default" onToggle={onToggle} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Switch to satellite view' }));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPLAYER-004: swaps the icon with the active layer', () => {
|
||||
const { rerender } = render(<MapLayerSwitcher active="default" onToggle={() => {}} />)
|
||||
const { rerender } = render(<MapLayerSwitcher active="default" onToggle={() => {}} />);
|
||||
// Destination icon: on the map you can reach satellite, and vice-versa.
|
||||
const iconOnDefault = screen.getByRole('button').querySelector('svg')?.getAttribute('class')
|
||||
rerender(<MapLayerSwitcher active="satellite" onToggle={() => {}} />)
|
||||
const iconOnSatellite = screen.getByRole('button').querySelector('svg')?.getAttribute('class')
|
||||
expect(iconOnDefault).not.toBe(iconOnSatellite)
|
||||
})
|
||||
const iconOnDefault = screen.getByRole('button').querySelector('svg')?.getAttribute('class');
|
||||
rerender(<MapLayerSwitcher active="satellite" onToggle={() => {}} />);
|
||||
const iconOnSatellite = screen.getByRole('button').querySelector('svg')?.getAttribute('class');
|
||||
expect(iconOnDefault).not.toBe(iconOnSatellite);
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPLAYER-005: highlights the button on hover and clears it again', () => {
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />)
|
||||
const button = screen.getByRole('button')
|
||||
fireEvent.mouseEnter(button)
|
||||
expect(button.style.background).toBe('var(--bg-hover)')
|
||||
fireEvent.mouseLeave(button)
|
||||
expect(button.style.background).toBe('transparent')
|
||||
})
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />);
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.mouseEnter(button);
|
||||
expect(button.style.background).toBe('var(--bg-hover)');
|
||||
fireEvent.mouseLeave(button);
|
||||
expect(button.style.background).toBe('transparent');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPLAYER-006: the shell is as wide as the size its neighbours are placed off', () => {
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />)
|
||||
const button = screen.getByRole('button')
|
||||
const shell = button.parentElement as HTMLElement
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />);
|
||||
const button = screen.getByRole('button');
|
||||
const shell = button.parentElement as HTMLElement;
|
||||
|
||||
// The phone's compass stands beside the switcher at inset + size + gap. If the
|
||||
// markup grew without the constant, the compass would slide back under the shell.
|
||||
expect(shell.style.padding).toBe('4px')
|
||||
expect(button.style.width).toBe('34px')
|
||||
expect(button.style.height).toBe('34px')
|
||||
expect(parseFloat(button.style.width) + 2 * parseFloat(shell.style.padding)).toBe(MAP_ROUND_CONTROL_SIZE)
|
||||
})
|
||||
})
|
||||
expect(shell.style.padding).toBe('4px');
|
||||
expect(button.style.width).toBe('34px');
|
||||
expect(button.style.height).toBe('34px');
|
||||
expect(parseFloat(button.style.width) + 2 * parseFloat(shell.style.padding)).toBe(MAP_ROUND_CONTROL_SIZE);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,40 +1,46 @@
|
||||
import { Map as MapIcon, Satellite } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
|
||||
import { Map as MapIcon, Satellite } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow';
|
||||
|
||||
export type BaseLayer = 'default' | 'satellite'
|
||||
export type BaseLayer = 'default' | 'satellite';
|
||||
|
||||
// Where the switcher sits and how much room it takes, so a control placed beside it
|
||||
// (the phone's compass) is positioned off the same numbers instead of guessing them.
|
||||
// Both map engines place the switcher with the inset, so they cannot drift apart either.
|
||||
|
||||
/** Distance from the map's left edge (plus any side panel) to the switcher. */
|
||||
export const MAP_LAYER_SWITCHER_INSET = 20
|
||||
export const MAP_LAYER_SWITCHER_INSET = 20;
|
||||
/**
|
||||
* Outer size of the round shell: a 34px button in 4px of padding, the same shell as
|
||||
* MapCompassPill. The markup below keeps its literals, and FE-COMP-MAPLAYER-006 holds
|
||||
* them to this number.
|
||||
*/
|
||||
export const MAP_ROUND_CONTROL_SIZE = 42
|
||||
export const MAP_ROUND_CONTROL_SIZE = 42;
|
||||
|
||||
// Round base-layer switcher for both planner maps, Leaflet and GL (default street
|
||||
// tiles ↔ satellite). Same frosted shell as MapCompassPill so it lines up with the
|
||||
// other map controls; the icon shows the layer it switches to.
|
||||
export function MapLayerSwitcher({ active, onToggle }: { active: BaseLayer; onToggle: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const isSatellite = active === 'satellite'
|
||||
const Icon = isSatellite ? MapIcon : Satellite
|
||||
const label = isSatellite ? t('map.baseLayer.switchToDefault') : t('map.baseLayer.switchToSatellite')
|
||||
const { t } = useTranslation();
|
||||
const isSatellite = active === 'satellite';
|
||||
const Icon = isSatellite ? MapIcon : Satellite;
|
||||
const label = isSatellite ? t('map.baseLayer.switchToDefault') : t('map.baseLayer.switchToSatellite');
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
padding: 4,
|
||||
borderRadius: 999,
|
||||
pointerEvents: 'auto',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
}}
|
||||
>
|
||||
{/* Same tooltip as its neighbours on the map, for the same reasons — see
|
||||
TripRouteOverviewPill. To the right, though: this one sits at the
|
||||
bottom left of the map, where a tooltip to the left would land on the
|
||||
@@ -47,17 +53,28 @@ export function MapLayerSwitcher({ active, onToggle }: { active: BaseLayer; onTo
|
||||
aria-pressed={isSatellite}
|
||||
className="text-content-muted"
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
|
||||
background: 'transparent', padding: 0,
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: 34,
|
||||
height: 34,
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: 'transparent',
|
||||
padding: 0,
|
||||
transition: 'background 0.14s, color 0.14s',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.background = 'var(--bg-hover)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'transparent';
|
||||
}}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Lock, Unlock } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { MapTogglePill } from './MapTogglePill'
|
||||
import { Lock, Unlock } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { MapTogglePill } from './MapTogglePill';
|
||||
|
||||
/**
|
||||
* Locks the map view (#2010): picking days and places then leaves the camera where it is.
|
||||
* Sits on top of the base-layer switcher, the other control about the view itself.
|
||||
*/
|
||||
export function MapLockPill({ locked, onToggle }: { locked: boolean; onToggle: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<MapTogglePill
|
||||
active={locked}
|
||||
@@ -17,5 +17,5 @@ export function MapLockPill({ locked, onToggle }: { locked: boolean; onToggle: (
|
||||
tooltipPlacement="right"
|
||||
icon={locked ? <Lock size={16} strokeWidth={2} /> : <Unlock size={16} strokeWidth={2} />}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,152 +1,187 @@
|
||||
// FE-COMP-MAPPLUGINLAYERS-001 to FE-COMP-MAPPLUGINLAYERS-009
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import type { PluginMapLayer, PluginMapLayerFeature } from '../../api/client'
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import type { PluginMapLayer, PluginMapLayerFeature } from '../../api/client';
|
||||
|
||||
interface PathProps {
|
||||
positions?: [number, number][]
|
||||
center?: [number, number]
|
||||
radius?: number
|
||||
pathOptions?: Record<string, unknown>
|
||||
children?: React.ReactNode
|
||||
positions?: [number, number][];
|
||||
center?: [number, number];
|
||||
radius?: number;
|
||||
pathOptions?: Record<string, unknown>;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
// react-leaflet primitives are replaced by markers that surface exactly what the
|
||||
// component controls: geometry, the path options and the pane it draws into.
|
||||
const mapHolder = vi.hoisted(() => ({ current: {} as Record<string, unknown> }))
|
||||
const mapHolder = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));
|
||||
|
||||
vi.mock('react-leaflet', () => ({
|
||||
Polyline: ({ positions, pathOptions, children }: PathProps) => (
|
||||
<div data-testid="polyline" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>{children}</div>
|
||||
<div data-testid="polyline" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
Polygon: ({ positions, pathOptions, children }: PathProps) => (
|
||||
<div data-testid="polygon" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>{children}</div>
|
||||
<div data-testid="polygon" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
Circle: ({ center, radius, pathOptions, children }: PathProps) => (
|
||||
<div data-testid="circle" data-center={JSON.stringify(center)} data-radius={radius} data-path-options={JSON.stringify(pathOptions)}>{children}</div>
|
||||
<div
|
||||
data-testid="circle"
|
||||
data-center={JSON.stringify(center)}
|
||||
data-radius={radius}
|
||||
data-path-options={JSON.stringify(pathOptions)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
Tooltip: ({ children }: { children?: React.ReactNode }) => <span data-testid="tooltip">{children}</span>,
|
||||
useMap: () => mapHolder.current,
|
||||
}))
|
||||
}));
|
||||
|
||||
import { PluginMapLayers } from './MapPluginLayers'
|
||||
import { PluginMapLayers } from './MapPluginLayers';
|
||||
|
||||
function paneMap(preexisting = false) {
|
||||
const panes = new Map<string, HTMLElement>()
|
||||
if (preexisting) panes.set('trek-plugin-layers', document.createElement('div'))
|
||||
const panes = new Map<string, HTMLElement>();
|
||||
if (preexisting) panes.set('trek-plugin-layers', document.createElement('div'));
|
||||
return {
|
||||
panes,
|
||||
getPane: vi.fn((name: string) => panes.get(name)),
|
||||
createPane: vi.fn((name: string) => {
|
||||
const el = document.createElement('div')
|
||||
panes.set(name, el)
|
||||
return el
|
||||
const el = document.createElement('div');
|
||||
panes.set(name, el);
|
||||
return el;
|
||||
}),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function feature(overrides: Partial<PluginMapLayerFeature> = {}): PluginMapLayerFeature {
|
||||
return {
|
||||
type: 'polyline',
|
||||
points: [[48.85, 2.35], [48.86, 2.36]],
|
||||
points: [
|
||||
[48.85, 2.35],
|
||||
[48.86, 2.36],
|
||||
],
|
||||
tone: 'default',
|
||||
width: 3,
|
||||
dash: 'solid',
|
||||
opacity: 0.8,
|
||||
fill: false,
|
||||
...overrides,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function layer(features: PluginMapLayerFeature[], overrides: Partial<PluginMapLayer> = {}): PluginMapLayer {
|
||||
return { pluginId: 'ev-router', id: 'corridor', features, ...overrides }
|
||||
return { pluginId: 'ev-router', id: 'corridor', features, ...overrides };
|
||||
}
|
||||
|
||||
function serveLayers(layers: PluginMapLayer[]) {
|
||||
server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers })))
|
||||
server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers })));
|
||||
}
|
||||
|
||||
const optionsOf = (el: HTMLElement) => JSON.parse(el.getAttribute('data-path-options') || '{}') as Record<string, unknown>
|
||||
const optionsOf = (el: HTMLElement) =>
|
||||
JSON.parse(el.getAttribute('data-path-options') || '{}') as Record<string, unknown>;
|
||||
|
||||
beforeEach(() => {
|
||||
mapHolder.current = paneMap() as unknown as Record<string, unknown>
|
||||
})
|
||||
mapHolder.current = paneMap() as unknown as Record<string, unknown>;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('PluginMapLayers', () => {
|
||||
it('FE-COMP-MAPPLUGINLAYERS-001: renders nothing without a trip', async () => {
|
||||
let requests = 0
|
||||
server.use(http.get('/api/map-layers/:tripId', () => { requests += 1; return HttpResponse.json({ layers: [] }) }))
|
||||
let requests = 0;
|
||||
server.use(
|
||||
http.get('/api/map-layers/:tripId', () => {
|
||||
requests += 1;
|
||||
return HttpResponse.json({ layers: [] });
|
||||
})
|
||||
);
|
||||
|
||||
render(<PluginMapLayers />)
|
||||
await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull())
|
||||
expect(requests).toBe(0)
|
||||
})
|
||||
render(<PluginMapLayers />);
|
||||
await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull());
|
||||
expect(requests).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-002: creates the below-overlay pane and draws into it', async () => {
|
||||
const map = paneMap()
|
||||
mapHolder.current = map as unknown as Record<string, unknown>
|
||||
serveLayers([layer([feature()])])
|
||||
const map = paneMap();
|
||||
mapHolder.current = map as unknown as Record<string, unknown>;
|
||||
serveLayers([layer([feature()])]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
const line = await screen.findByTestId('polyline');
|
||||
|
||||
expect(map.createPane).toHaveBeenCalledWith('trek-plugin-layers')
|
||||
expect(map.createPane).toHaveBeenCalledWith('trek-plugin-layers');
|
||||
// Core geometry (overlayPane, 400) has to stay on top of plugin shapes.
|
||||
expect(map.panes.get('trek-plugin-layers')?.style.zIndex).toBe('399')
|
||||
expect(optionsOf(line).pane).toBe('trek-plugin-layers')
|
||||
})
|
||||
expect(map.panes.get('trek-plugin-layers')?.style.zIndex).toBe('399');
|
||||
expect(optionsOf(line).pane).toBe('trek-plugin-layers');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-003: reuses an existing pane instead of creating a second one', async () => {
|
||||
const map = paneMap(true)
|
||||
mapHolder.current = map as unknown as Record<string, unknown>
|
||||
serveLayers([layer([feature()])])
|
||||
const map = paneMap(true);
|
||||
mapHolder.current = map as unknown as Record<string, unknown>;
|
||||
serveLayers([layer([feature()])]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
await screen.findByTestId('polyline');
|
||||
|
||||
expect(map.createPane).not.toHaveBeenCalled()
|
||||
})
|
||||
expect(map.createPane).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-004: still draws on a map without the pane API, just without a pane', async () => {
|
||||
mapHolder.current = {}
|
||||
serveLayers([layer([feature()])])
|
||||
mapHolder.current = {};
|
||||
serveLayers([layer([feature()])]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
expect(optionsOf(line)).not.toHaveProperty('pane')
|
||||
})
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
const line = await screen.findByTestId('polyline');
|
||||
expect(optionsOf(line)).not.toHaveProperty('pane');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-005: draws polylines, polygons and metric circles', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ type: 'polyline' }),
|
||||
feature({ type: 'polygon', points: [[48, 2], [48, 3], [49, 3]] }),
|
||||
feature({ type: 'circle', points: undefined, center: [48.8, 2.3], radiusM: 750 }),
|
||||
])])
|
||||
serveLayers([
|
||||
layer([
|
||||
feature({ type: 'polyline' }),
|
||||
feature({
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[48, 2],
|
||||
[48, 3],
|
||||
[49, 3],
|
||||
],
|
||||
}),
|
||||
feature({ type: 'circle', points: undefined, center: [48.8, 2.3], radiusM: 750 }),
|
||||
]),
|
||||
]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
await screen.findByTestId('polyline');
|
||||
|
||||
expect(JSON.parse(screen.getByTestId('polygon').getAttribute('data-points') || '')).toEqual([[48, 2], [48, 3], [49, 3]])
|
||||
const circle = screen.getByTestId('circle')
|
||||
expect(JSON.parse(circle.getAttribute('data-center') || '')).toEqual([48.8, 2.3])
|
||||
expect(circle.getAttribute('data-radius')).toBe('750')
|
||||
})
|
||||
expect(JSON.parse(screen.getByTestId('polygon').getAttribute('data-points') || '')).toEqual([
|
||||
[48, 2],
|
||||
[48, 3],
|
||||
[49, 3],
|
||||
]);
|
||||
const circle = screen.getByTestId('circle');
|
||||
expect(JSON.parse(circle.getAttribute('data-center') || '')).toEqual([48.8, 2.3]);
|
||||
expect(circle.getAttribute('data-radius')).toBe('750');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-006: maps tone, width, dash and fill onto the leaflet path options', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ tone: 'danger', width: 6, dash: 'dash', opacity: 0.5 }),
|
||||
feature({ type: 'polygon', tone: 'success', dash: 'dot', opacity: 0.9, fill: true }),
|
||||
])])
|
||||
serveLayers([
|
||||
layer([
|
||||
feature({ tone: 'danger', width: 6, dash: 'dash', opacity: 0.5 }),
|
||||
feature({ type: 'polygon', tone: 'success', dash: 'dot', opacity: 0.9, fill: true }),
|
||||
]),
|
||||
]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
const line = await screen.findByTestId('polyline');
|
||||
|
||||
expect(optionsOf(line)).toMatchObject({
|
||||
color: '#ef4444',
|
||||
@@ -155,57 +190,56 @@ describe('PluginMapLayers', () => {
|
||||
dashArray: '8, 8',
|
||||
fill: false,
|
||||
fillOpacity: 0,
|
||||
})
|
||||
});
|
||||
// A filled shape is capped at 0.25 so it never hides the basemap underneath.
|
||||
expect(optionsOf(screen.getByTestId('polygon'))).toMatchObject({
|
||||
color: '#10b981',
|
||||
dashArray: '1, 7',
|
||||
fill: true,
|
||||
fillOpacity: 0.25,
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-007: only a labelled feature gets a tooltip and stays clickable', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ label: 'Charging corridor' }),
|
||||
feature({ type: 'polygon' }),
|
||||
])])
|
||||
serveLayers([layer([feature({ label: 'Charging corridor' }), feature({ type: 'polygon' })])]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
const line = await screen.findByTestId('polyline');
|
||||
|
||||
expect(screen.getByTestId('tooltip')).toHaveTextContent('Charging corridor')
|
||||
expect(optionsOf(line).interactive).toBe(true)
|
||||
expect(screen.getByTestId('tooltip')).toHaveTextContent('Charging corridor');
|
||||
expect(optionsOf(line).interactive).toBe(true);
|
||||
// Unlabelled shapes must never steal a map click.
|
||||
expect(optionsOf(screen.getByTestId('polygon')).interactive).toBe(false)
|
||||
expect(screen.getAllByTestId('tooltip')).toHaveLength(1)
|
||||
})
|
||||
expect(optionsOf(screen.getByTestId('polygon')).interactive).toBe(false);
|
||||
expect(screen.getAllByTestId('tooltip')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-008: skips features whose geometry is incomplete', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ type: 'polyline', points: undefined }),
|
||||
feature({ type: 'polygon', points: undefined }),
|
||||
feature({ type: 'circle', points: undefined, center: [48, 2] }),
|
||||
feature({ type: 'circle', points: undefined, radiusM: 500 }),
|
||||
feature({ label: 'kept' }),
|
||||
])])
|
||||
serveLayers([
|
||||
layer([
|
||||
feature({ type: 'polyline', points: undefined }),
|
||||
feature({ type: 'polygon', points: undefined }),
|
||||
feature({ type: 'circle', points: undefined, center: [48, 2] }),
|
||||
feature({ type: 'circle', points: undefined, radiusM: 500 }),
|
||||
feature({ label: 'kept' }),
|
||||
]),
|
||||
]);
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
render(<PluginMapLayers tripId={4} />);
|
||||
await screen.findByTestId('polyline');
|
||||
|
||||
expect(screen.getAllByTestId('polyline')).toHaveLength(1)
|
||||
expect(screen.queryByTestId('polygon')).toBeNull()
|
||||
expect(screen.queryByTestId('circle')).toBeNull()
|
||||
})
|
||||
expect(screen.getAllByTestId('polyline')).toHaveLength(1);
|
||||
expect(screen.queryByTestId('polygon')).toBeNull();
|
||||
expect(screen.queryByTestId('circle')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-009: a failing request leaves the map without plugin overlays', async () => {
|
||||
serveLayers([layer([feature()])])
|
||||
const { rerender } = render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
serveLayers([layer([feature()])]);
|
||||
const { rerender } = render(<PluginMapLayers tripId={4} />);
|
||||
await screen.findByTestId('polyline');
|
||||
|
||||
server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
|
||||
rerender(<PluginMapLayers tripId={9} />)
|
||||
server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
|
||||
rerender(<PluginMapLayers tripId={9} />);
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull())
|
||||
})
|
||||
})
|
||||
await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Circle, Polygon, Polyline, Tooltip, useMap } from 'react-leaflet'
|
||||
import { pluginsApi, type PluginMapLayer, type PluginMapLayerFeature } from '../../api/client'
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Circle, Polygon, Polyline, Tooltip, useMap } from 'react-leaflet';
|
||||
import { pluginsApi, type PluginMapLayer, type PluginMapLayerFeature } from '../../api/client';
|
||||
|
||||
/**
|
||||
* Host-rendered overlay for the `mapLayerProvider` plugin hook. A plugin returns
|
||||
@@ -18,18 +18,18 @@ const TONE_COLORS: Record<PluginMapLayerFeature['tone'], string> = {
|
||||
success: '#10b981',
|
||||
warn: '#f59e0b',
|
||||
danger: '#ef4444',
|
||||
}
|
||||
};
|
||||
|
||||
const PANE = 'trek-plugin-layers'
|
||||
const PANE = 'trek-plugin-layers';
|
||||
|
||||
const DASH_ARRAYS: Record<PluginMapLayerFeature['dash'], string | undefined> = {
|
||||
solid: undefined,
|
||||
dash: '8, 8',
|
||||
dot: '1, 7',
|
||||
}
|
||||
};
|
||||
|
||||
function pathOptions(f: PluginMapLayerFeature, pane: string | undefined) {
|
||||
const color = TONE_COLORS[f.tone] ?? TONE_COLORS.default
|
||||
const color = TONE_COLORS[f.tone] ?? TONE_COLORS.default;
|
||||
return {
|
||||
...(pane ? { pane } : {}),
|
||||
color,
|
||||
@@ -42,54 +42,78 @@ function pathOptions(f: PluginMapLayerFeature, pane: string | undefined) {
|
||||
fillColor: color,
|
||||
fillOpacity: f.fill ? Math.min(0.25, f.opacity) : 0,
|
||||
interactive: !!f.label,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function PluginMapLayers({ tripId }: { tripId?: number | string }) {
|
||||
const map = useMap()
|
||||
const [layers, setLayers] = useState<PluginMapLayer[]>([])
|
||||
const map = useMap();
|
||||
const [layers, setLayers] = useState<PluginMapLayer[]>([]);
|
||||
// Whether our dedicated below-overlay pane exists. Pane support is a Leaflet
|
||||
// optimization — if the map has no pane API (e.g. a minimal renderer), the
|
||||
// features still draw, just without the z-index separation, so we don't gate on it.
|
||||
const [hasPane, setHasPane] = useState(false)
|
||||
const [hasPane, setHasPane] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof map.getPane !== 'function' || typeof map.createPane !== 'function') return
|
||||
if (typeof map.getPane !== 'function' || typeof map.createPane !== 'function') return;
|
||||
if (!map.getPane(PANE)) {
|
||||
const pane = map.createPane(PANE)
|
||||
if (pane) pane.style.zIndex = '399' // under overlayPane (400): core routes/arcs win
|
||||
const pane = map.createPane(PANE);
|
||||
if (pane) pane.style.zIndex = '399'; // under overlayPane (400): core routes/arcs win
|
||||
}
|
||||
setHasPane(true)
|
||||
}, [map])
|
||||
setHasPane(true);
|
||||
}, [map]);
|
||||
|
||||
useEffect(() => {
|
||||
if (tripId == null) { setLayers([]); return }
|
||||
let alive = true
|
||||
pluginsApi.mapLayers(tripId)
|
||||
.then(r => { if (alive) setLayers(r.layers || []) })
|
||||
.catch(() => { if (alive) setLayers([]) }) // fail-safe: no extra layers
|
||||
return () => { alive = false }
|
||||
}, [tripId])
|
||||
if (tripId == null) {
|
||||
setLayers([]);
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
pluginsApi
|
||||
.mapLayers(tripId)
|
||||
.then((r) => {
|
||||
if (alive) setLayers(r.layers || []);
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setLayers([]);
|
||||
}); // fail-safe: no extra layers
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [tripId]);
|
||||
|
||||
if (layers.length === 0) return null
|
||||
const pane = hasPane ? PANE : undefined
|
||||
if (layers.length === 0) return null;
|
||||
const pane = hasPane ? PANE : undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
{layers.map(layer => layer.features.map((f, i) => {
|
||||
const key = `${layer.pluginId}:${layer.id}:${i}`
|
||||
const tooltip = f.label ? <Tooltip sticky>{f.label}</Tooltip> : null
|
||||
if (f.type === 'polyline' && f.points) {
|
||||
return <Polyline key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>{tooltip}</Polyline>
|
||||
}
|
||||
if (f.type === 'polygon' && f.points) {
|
||||
return <Polygon key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>{tooltip}</Polygon>
|
||||
}
|
||||
if (f.type === 'circle' && f.center && f.radiusM) {
|
||||
return <Circle key={key} center={f.center} radius={f.radiusM} pathOptions={pathOptions(f, pane)}>{tooltip}</Circle>
|
||||
}
|
||||
return null
|
||||
}))}
|
||||
{layers.map((layer) =>
|
||||
layer.features.map((f, i) => {
|
||||
const key = `${layer.pluginId}:${layer.id}:${i}`;
|
||||
const tooltip = f.label ? <Tooltip sticky>{f.label}</Tooltip> : null;
|
||||
if (f.type === 'polyline' && f.points) {
|
||||
return (
|
||||
<Polyline key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>
|
||||
{tooltip}
|
||||
</Polyline>
|
||||
);
|
||||
}
|
||||
if (f.type === 'polygon' && f.points) {
|
||||
return (
|
||||
<Polygon key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>
|
||||
{tooltip}
|
||||
</Polygon>
|
||||
);
|
||||
}
|
||||
if (f.type === 'circle' && f.center && f.radiusM) {
|
||||
return (
|
||||
<Circle key={key} center={f.center} radius={f.radiusM} pathOptions={pathOptions(f, pane)}>
|
||||
{tooltip}
|
||||
</Circle>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})
|
||||
)}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Marker, Popup } from 'react-leaflet'
|
||||
import L from 'leaflet'
|
||||
import { pluginsApi, type PluginMapMarker } from '../../api/client'
|
||||
import L from 'leaflet';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Marker, Popup } from 'react-leaflet';
|
||||
import { pluginsApi, type PluginMapMarker } from '../../api/client';
|
||||
|
||||
/**
|
||||
* Host-rendered overlay for the `mapMarkerProvider` plugin hook (#587). A plugin
|
||||
@@ -18,42 +18,52 @@ const TONE_COLORS: Record<PluginMapMarker['tone'], string> = {
|
||||
success: '#10b981',
|
||||
warn: '#f59e0b',
|
||||
danger: '#ef4444',
|
||||
}
|
||||
};
|
||||
|
||||
function markerIcon(tone: PluginMapMarker['tone']): L.DivIcon {
|
||||
const color = TONE_COLORS[tone] ?? TONE_COLORS.default
|
||||
const color = TONE_COLORS[tone] ?? TONE_COLORS.default;
|
||||
return L.divIcon({
|
||||
className: 'plugin-map-marker',
|
||||
html: `<span style="display:block;width:16px;height:16px;border-radius:50%;background:${color};border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,0.4)"></span>`,
|
||||
iconSize: [16, 16],
|
||||
iconAnchor: [8, 8],
|
||||
popupAnchor: [0, -8],
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function PluginMapMarkers({ tripId }: { tripId?: number | string }) {
|
||||
const [markers, setMarkers] = useState<PluginMapMarker[]>([])
|
||||
const [markers, setMarkers] = useState<PluginMapMarker[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (tripId == null) { setMarkers([]); return }
|
||||
let alive = true
|
||||
pluginsApi.mapMarkers(tripId)
|
||||
.then(r => { if (alive) setMarkers(r.markers || []) })
|
||||
.catch(() => { if (alive) setMarkers([]) }) // fail-safe: no extra markers
|
||||
return () => { alive = false }
|
||||
}, [tripId])
|
||||
if (tripId == null) {
|
||||
setMarkers([]);
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
pluginsApi
|
||||
.mapMarkers(tripId)
|
||||
.then((r) => {
|
||||
if (alive) setMarkers(r.markers || []);
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setMarkers([]);
|
||||
}); // fail-safe: no extra markers
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [tripId]);
|
||||
|
||||
const icons = useMemo(() => {
|
||||
const m = new Map<PluginMapMarker['tone'], L.DivIcon>()
|
||||
for (const tone of ['default', 'success', 'warn', 'danger'] as const) m.set(tone, markerIcon(tone))
|
||||
return m
|
||||
}, [])
|
||||
const m = new Map<PluginMapMarker['tone'], L.DivIcon>();
|
||||
for (const tone of ['default', 'success', 'warn', 'danger'] as const) m.set(tone, markerIcon(tone));
|
||||
return m;
|
||||
}, []);
|
||||
|
||||
if (markers.length === 0) return null
|
||||
if (markers.length === 0) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{markers.map(mk => (
|
||||
{markers.map((mk) => (
|
||||
<Marker key={`${mk.pluginId}:${mk.id}`} position={[mk.lat, mk.lng]} icon={icons.get(mk.tone)!}>
|
||||
{(mk.label || mk.popupText || mk.url) && (
|
||||
<Popup>
|
||||
@@ -61,7 +71,12 @@ export function PluginMapMarkers({ tripId }: { tripId?: number | string }) {
|
||||
{mk.label && <div style={{ fontWeight: 600, marginBottom: mk.popupText ? 4 : 0 }}>{mk.label}</div>}
|
||||
{mk.popupText && <div style={{ color: '#4b5563' }}>{mk.popupText}</div>}
|
||||
{mk.url && (
|
||||
<a href={mk.url} target="_blank" rel="noreferrer noopener" style={{ display: 'inline-block', marginTop: 6, color: TONE_COLORS.default }}>
|
||||
<a
|
||||
href={mk.url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
style={{ display: 'inline-block', marginTop: 6, color: TONE_COLORS.default }}
|
||||
>
|
||||
{mk.url}
|
||||
</a>
|
||||
)}
|
||||
@@ -71,5 +86,5 @@ export function PluginMapMarkers({ tripId }: { tripId?: number | string }) {
|
||||
</Marker>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,37 +1,52 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
|
||||
import type { ReactNode } from 'react';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { MAP_CONTROL_SHADOW } from './mapControlShadow';
|
||||
|
||||
/**
|
||||
* One round on/off control in the frosted shell every map control wears, so a new
|
||||
* one lines up with the compass, the layer switcher and the overview toggle.
|
||||
*/
|
||||
export function MapTogglePill({ active, onToggle, label, icon, testId, tooltipPlacement = 'left', badge = 0, opensDialog = false }: {
|
||||
active: boolean
|
||||
onToggle: () => void
|
||||
label: string
|
||||
icon: ReactNode
|
||||
testId?: string
|
||||
export function MapTogglePill({
|
||||
active,
|
||||
onToggle,
|
||||
label,
|
||||
icon,
|
||||
testId,
|
||||
tooltipPlacement = 'left',
|
||||
badge = 0,
|
||||
opensDialog = false,
|
||||
}: {
|
||||
active: boolean;
|
||||
onToggle: () => void;
|
||||
label: string;
|
||||
icon: ReactNode;
|
||||
testId?: string;
|
||||
/** Away from the edge the control hugs: left on the right edge, right on the left one. */
|
||||
tooltipPlacement?: 'left' | 'right'
|
||||
tooltipPlacement?: 'left' | 'right';
|
||||
/** A count pinned to the top right corner while above zero (how many filters are on, say). */
|
||||
badge?: number
|
||||
badge?: number;
|
||||
/**
|
||||
* The control opens a dialog instead of switching something on and off (the phone
|
||||
* map's places filter): it then announces the dialog, not a pressed state it
|
||||
* does not have. `active` still lights it.
|
||||
*/
|
||||
opensDialog?: boolean
|
||||
opensDialog?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div style={{
|
||||
position: 'relative',
|
||||
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
padding: 4,
|
||||
borderRadius: 999,
|
||||
pointerEvents: 'auto',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
}}
|
||||
>
|
||||
{/* TREK's own tooltip, not the browser's: the native one ignores the colour
|
||||
scheme, waits a second and a half, and cannot be read on a touch device. */}
|
||||
<Tooltip label={label} placement={tooltipPlacement}>
|
||||
@@ -44,13 +59,24 @@ export function MapTogglePill({ active, onToggle, label, icon, testId, tooltipPl
|
||||
data-testid={testId}
|
||||
className={active ? 'text-accent' : 'text-content-muted'}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
|
||||
background: 'transparent', padding: 0,
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: 34,
|
||||
height: 34,
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: 'transparent',
|
||||
padding: 0,
|
||||
transition: 'background 0.14s, color 0.14s',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.background = 'var(--bg-hover)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'transparent';
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</button>
|
||||
@@ -64,5 +90,5 @@ export function MapTogglePill({ active, onToggle, label, icon, testId, tooltipPl
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,16 +10,23 @@
|
||||
* The click itself has to keep taking Leaflet's route and the page's: it is what closes
|
||||
* an open popup on the map, and an open context menu beside it.
|
||||
*/
|
||||
import React, { useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'
|
||||
import { render, waitFor, act } from '../../../tests/helpers/render'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import { buildPlace } from '../../../tests/helpers/factories'
|
||||
import { useState } from 'react';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { buildPlace } from '../../../tests/helpers/factories';
|
||||
import { act, render, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
|
||||
vi.mock('../../hooks/useGeolocation', () => ({
|
||||
useGeolocation: () => ({ position: null, mode: 'off', error: null, errorCode: null, cycleMode: vi.fn(), setMode: vi.fn() }),
|
||||
}))
|
||||
useGeolocation: () => ({
|
||||
position: null,
|
||||
mode: 'off',
|
||||
error: null,
|
||||
errorCode: null,
|
||||
cycleMode: vi.fn(),
|
||||
setMode: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../../services/photoService', () => ({
|
||||
getCached: vi.fn(() => null),
|
||||
@@ -27,220 +34,254 @@ vi.mock('../../services/photoService', () => ({
|
||||
fetchPhoto: vi.fn(),
|
||||
onThumbReady: vi.fn(() => () => {}),
|
||||
getAllThumbs: vi.fn(() => ({})),
|
||||
}))
|
||||
}));
|
||||
|
||||
import L from 'leaflet'
|
||||
import { MapView } from './MapView'
|
||||
import { ContextMenu } from '../shared/ContextMenu'
|
||||
import L from 'leaflet';
|
||||
import { ContextMenu } from '../shared/ContextMenu';
|
||||
import { MapView } from './MapView';
|
||||
|
||||
// Every map this file builds, newest last, for the tests that reach past the component.
|
||||
const maps: L.Map[] = []
|
||||
L.Map.addInitHook(function (this: L.Map) { maps.push(this) })
|
||||
const maps: L.Map[] = [];
|
||||
L.Map.addInitHook(function (this: L.Map) {
|
||||
maps.push(this);
|
||||
});
|
||||
|
||||
// A raster template keeps the basemap a plain TileLayer: the vector default needs WebGL.
|
||||
const RASTER = 'https://tiles.example.test/{z}/{x}/{y}.png'
|
||||
const RASTER = 'https://tiles.example.test/{z}/{x}/{y}.png';
|
||||
|
||||
// Leaflet sizes the map from the container, which jsdom lays out at 0 x 0. The cluster
|
||||
// group only draws pins inside the visible bounds, so the map needs a real size.
|
||||
const sized = ['clientWidth', 'clientHeight'] as const
|
||||
const originals = new Map<string, PropertyDescriptor | undefined>()
|
||||
const sized = ['clientWidth', 'clientHeight'] as const;
|
||||
const originals = new Map<string, PropertyDescriptor | undefined>();
|
||||
beforeAll(() => {
|
||||
// The pans here are synthetic and instant. With inertia, Leaflet would carry them on in
|
||||
// animation frames that can land after a test has already unmounted its map.
|
||||
L.Map.mergeOptions({ inertia: false })
|
||||
L.Map.mergeOptions({ inertia: false });
|
||||
for (const key of sized) {
|
||||
originals.set(key, Object.getOwnPropertyDescriptor(HTMLElement.prototype, key))
|
||||
Object.defineProperty(HTMLElement.prototype, key, { configurable: true, get: () => (key === 'clientWidth' ? 1000 : 700) })
|
||||
originals.set(key, Object.getOwnPropertyDescriptor(HTMLElement.prototype, key));
|
||||
Object.defineProperty(HTMLElement.prototype, key, {
|
||||
configurable: true,
|
||||
get: () => (key === 'clientWidth' ? 1000 : 700),
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
afterAll(() => {
|
||||
L.Map.mergeOptions({ inertia: true })
|
||||
L.Map.mergeOptions({ inertia: true });
|
||||
for (const key of sized) {
|
||||
const original = originals.get(key)
|
||||
if (original) Object.defineProperty(HTMLElement.prototype, key, original)
|
||||
else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key]
|
||||
const original = originals.get(key);
|
||||
if (original) Object.defineProperty(HTMLElement.prototype, key, original);
|
||||
else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetAllStores()
|
||||
})
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
/** Leaflet only starts a pan for the primary button, which it reads off `which`. */
|
||||
function mouse(type: string, x: number, y: number): MouseEvent {
|
||||
const event = new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: y })
|
||||
Object.defineProperty(event, 'which', { value: 1 })
|
||||
return event
|
||||
const event = new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: y });
|
||||
Object.defineProperty(event, 'which', { value: 1 });
|
||||
return event;
|
||||
}
|
||||
|
||||
/** Drag the map by its background, the way a user pans it. */
|
||||
function panMap(container: Element) {
|
||||
act(() => {
|
||||
container.dispatchEvent(mouse('mousedown', 300, 300))
|
||||
container.dispatchEvent(mouse('mousemove', 340, 320))
|
||||
container.dispatchEvent(mouse('mousemove', 380, 340))
|
||||
container.dispatchEvent(mouse('mouseup', 380, 340))
|
||||
})
|
||||
container.dispatchEvent(mouse('mousedown', 300, 300));
|
||||
container.dispatchEvent(mouse('mousemove', 340, 320));
|
||||
container.dispatchEvent(mouse('mousemove', 380, 340));
|
||||
container.dispatchEvent(mouse('mouseup', 380, 340));
|
||||
});
|
||||
}
|
||||
|
||||
/** A plain click on an element: press, release, click, all on the same spot. */
|
||||
function clickOn(el: Element) {
|
||||
act(() => {
|
||||
el.dispatchEvent(mouse('mousedown', 500, 350))
|
||||
el.dispatchEvent(mouse('mouseup', 500, 350))
|
||||
el.dispatchEvent(mouse('click', 500, 350))
|
||||
})
|
||||
el.dispatchEvent(mouse('mousedown', 500, 350));
|
||||
el.dispatchEvent(mouse('mouseup', 500, 350));
|
||||
el.dispatchEvent(mouse('click', 500, 350));
|
||||
});
|
||||
}
|
||||
|
||||
// Two stops a few hundred metres apart in Nara: separate pins at this zoom, not a cluster.
|
||||
const places = [
|
||||
{ ...buildPlace({ id: 1, name: 'Todai-ji', lat: 34.689, lng: 135.8398 }), category_name: null, category_color: null, category_icon: null },
|
||||
{ ...buildPlace({ id: 2, name: 'Kasuga Taisha', lat: 34.6812, lng: 135.8484 }), category_name: null, category_color: null, category_icon: null },
|
||||
]
|
||||
{
|
||||
...buildPlace({ id: 1, name: 'Todai-ji', lat: 34.689, lng: 135.8398 }),
|
||||
category_name: null,
|
||||
category_color: null,
|
||||
category_icon: null,
|
||||
},
|
||||
{
|
||||
...buildPlace({ id: 2, name: 'Kasuga Taisha', lat: 34.6812, lng: 135.8484 }),
|
||||
category_name: null,
|
||||
category_color: null,
|
||||
category_icon: null,
|
||||
},
|
||||
];
|
||||
|
||||
async function renderMap() {
|
||||
const onMarkerClick = vi.fn()
|
||||
const onMapClick = vi.fn()
|
||||
const onMarkerClick = vi.fn();
|
||||
const onMapClick = vi.fn();
|
||||
const view = render(
|
||||
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} onMapClick={onMapClick} />,
|
||||
)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
<MapView
|
||||
places={places}
|
||||
center={[34.685, 135.844]}
|
||||
zoom={15}
|
||||
tileUrl={RASTER}
|
||||
onMarkerClick={onMarkerClick}
|
||||
onMapClick={onMapClick}
|
||||
/>
|
||||
);
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement;
|
||||
// The cluster group takes its markers in on a timer (chunkedLoading).
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
|
||||
const pins = [...container.querySelectorAll('.leaflet-marker-icon[draggable="true"]')] as HTMLElement[]
|
||||
return { container, pins, onMarkerClick, onMapClick }
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2));
|
||||
const pins = [...container.querySelectorAll('.leaflet-marker-icon[draggable="true"]')] as HTMLElement[];
|
||||
return { container, pins, onMarkerClick, onMapClick };
|
||||
}
|
||||
|
||||
describe('MapView on a real Leaflet map', () => {
|
||||
it('FE-MAPCLICK-001: a pin opens its place on a map nobody has dragged yet', async () => {
|
||||
const { pins, onMarkerClick, onMapClick } = await renderMap()
|
||||
clickOn(pins[0])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
const { pins, onMarkerClick, onMapClick } = await renderMap();
|
||||
clickOn(pins[0]);
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1);
|
||||
// Still the marker's click, not one on the empty map behind it.
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
expect(onMapClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MAPCLICK-002: a pin still opens its place after the map was dragged (#2504)', async () => {
|
||||
const { container, pins, onMarkerClick, onMapClick } = await renderMap()
|
||||
panMap(container)
|
||||
clickOn(pins[0])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
const { container, pins, onMarkerClick, onMapClick } = await renderMap();
|
||||
panMap(container);
|
||||
clickOn(pins[0]);
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1);
|
||||
// And again: the report was that every click after the pan went nowhere.
|
||||
clickOn(pins[1])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(2)
|
||||
expect(onMarkerClick.mock.calls.map(call => call[0]).sort()).toEqual([1, 2])
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
clickOn(pins[1]);
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(2);
|
||||
expect(onMarkerClick.mock.calls.map((call) => call[0]).sort()).toEqual([1, 2]);
|
||||
expect(onMapClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MAPCLICK-003: the click that ends a pan still counts for nothing', async () => {
|
||||
const { container, onMarkerClick, onMapClick } = await renderMap()
|
||||
panMap(container)
|
||||
const { container, onMarkerClick, onMapClick } = await renderMap();
|
||||
panMap(container);
|
||||
// The browser aims the click that closes a drag at the element both ends share,
|
||||
// which is the map rather than the pin the pointer happened to stop on. Leaflet
|
||||
// swallows it, and must go on doing so: it is not a click on the empty map either.
|
||||
act(() => { container.dispatchEvent(mouse('click', 380, 340)) })
|
||||
expect(onMarkerClick).not.toHaveBeenCalled()
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
act(() => {
|
||||
container.dispatchEvent(mouse('click', 380, 340));
|
||||
});
|
||||
expect(onMarkerClick).not.toHaveBeenCalled();
|
||||
expect(onMapClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("FE-MAPCLICK-004: a pin on a touch screen keeps Leaflet's own click and no drag wiring", async () => {
|
||||
const original = Object.getOwnPropertyDescriptor(window.navigator, 'maxTouchPoints')
|
||||
Object.defineProperty(window.navigator, 'maxTouchPoints', { configurable: true, value: 5 })
|
||||
const original = Object.getOwnPropertyDescriptor(window.navigator, 'maxTouchPoints');
|
||||
Object.defineProperty(window.navigator, 'maxTouchPoints', { configurable: true, value: 5 });
|
||||
try {
|
||||
const onMarkerClick = vi.fn()
|
||||
const view = render(<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon').length).toBe(2))
|
||||
const pin = container.querySelector('.leaflet-marker-icon') as HTMLElement
|
||||
expect(pin.getAttribute('draggable')).toBeNull()
|
||||
clickOn(pin)
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
const onMarkerClick = vi.fn();
|
||||
const view = render(
|
||||
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />
|
||||
);
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement;
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon').length).toBe(2));
|
||||
const pin = container.querySelector('.leaflet-marker-icon') as HTMLElement;
|
||||
expect(pin.getAttribute('draggable')).toBeNull();
|
||||
clickOn(pin);
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
if (original) Object.defineProperty(window.navigator, 'maxTouchPoints', original)
|
||||
else delete (window.navigator as unknown as Record<string, unknown>).maxTouchPoints
|
||||
if (original) Object.defineProperty(window.navigator, 'maxTouchPoints', original);
|
||||
else delete (window.navigator as unknown as Record<string, unknown>).maxTouchPoints;
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
it('FE-MAPCLICK-005: the place a pin opens stays open when the pin redraws mid-click', async () => {
|
||||
// The selection a pin makes redraws its icon, which replaces the element the click
|
||||
// landed on. Leaflet has to have found the pin before that happens: reading the target
|
||||
// afterwards, it finds it cut out of the map and takes the click for one on the empty
|
||||
// background, which would close the place again straight away.
|
||||
const onMapClick = vi.fn()
|
||||
const onMapClick = vi.fn();
|
||||
function Planner() {
|
||||
const [selected, setSelected] = useState<number | null>(null)
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
return (
|
||||
<>
|
||||
<output data-testid="selected">{selected ?? ''}</output>
|
||||
<MapView
|
||||
places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER}
|
||||
places={places}
|
||||
center={[34.685, 135.844]}
|
||||
zoom={15}
|
||||
tileUrl={RASTER}
|
||||
selectedPlaceId={selected}
|
||||
onMarkerClick={(id: number) => flushSync(() => setSelected(id))}
|
||||
onMapClick={() => { onMapClick(); setSelected(null) }}
|
||||
onMapClick={() => {
|
||||
onMapClick();
|
||||
setSelected(null);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
const view = render(<Planner />)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
|
||||
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement
|
||||
const view = render(<Planner />);
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement;
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2));
|
||||
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement;
|
||||
// The pointer lands on the photo inside the pin, which the redraw replaces.
|
||||
clickOn(pin.firstElementChild as HTMLElement)
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
expect(view.getByTestId('selected').textContent).not.toBe('')
|
||||
})
|
||||
clickOn(pin.firstElementChild as HTMLElement);
|
||||
expect(onMapClick).not.toHaveBeenCalled();
|
||||
expect(view.getByTestId('selected').textContent).not.toBe('');
|
||||
});
|
||||
|
||||
it('FE-MAPCLICK-006: a pin click after a pan still closes an open popup on the map', async () => {
|
||||
const { container, pins, onMarkerClick } = await renderMap()
|
||||
const map = maps[maps.length - 1]
|
||||
panMap(container)
|
||||
const { container, pins, onMarkerClick } = await renderMap();
|
||||
const map = maps[maps.length - 1];
|
||||
panMap(container);
|
||||
// A hazard or plugin popup, as the planner opens them. Leaflet closes those on the
|
||||
// "preclick" it sends ahead of every click it routes, a pin's included.
|
||||
const popup = L.popup({ autoPan: false }).setLatLng([34.685, 135.844]).setContent('Road closed')
|
||||
act(() => { popup.openOn(map) })
|
||||
expect(map.hasLayer(popup)).toBe(true)
|
||||
clickOn(pins[0])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
expect(map.hasLayer(popup)).toBe(false)
|
||||
})
|
||||
const popup = L.popup({ autoPan: false }).setLatLng([34.685, 135.844]).setContent('Road closed');
|
||||
act(() => {
|
||||
popup.openOn(map);
|
||||
});
|
||||
expect(map.hasLayer(popup)).toBe(true);
|
||||
clickOn(pins[0]);
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1);
|
||||
expect(map.hasLayer(popup)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MAPCLICK-007: a pin click after a pan still reaches the page and closes an open context menu', async () => {
|
||||
const onClose = vi.fn()
|
||||
const onMarkerClick = vi.fn()
|
||||
const onClose = vi.fn();
|
||||
const onMarkerClick = vi.fn();
|
||||
const view = render(
|
||||
<>
|
||||
{/* The menu the places list and the day plan open on a right click. It closes on
|
||||
any click that reaches the document. */}
|
||||
<ContextMenu menu={{ x: 20, y: 20, items: [{ label: 'Edit' }] }} onClose={onClose} />
|
||||
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />
|
||||
</>,
|
||||
)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
|
||||
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement
|
||||
panMap(container)
|
||||
clickOn(pin)
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
</>
|
||||
);
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement;
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2));
|
||||
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement;
|
||||
panMap(container);
|
||||
clickOn(pin);
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-MAPCLICK-008: pressing a pin after a pan still holds the map still for a drag onto a day', async () => {
|
||||
const { container, pins } = await renderMap()
|
||||
const map = maps[maps.length - 1]
|
||||
panMap(container)
|
||||
const before = map.getCenter()
|
||||
const { container, pins } = await renderMap();
|
||||
const map = maps[maps.length - 1];
|
||||
panMap(container);
|
||||
const before = map.getCenter();
|
||||
// Press on the pin and move off it, as the start of a drag towards the day plan.
|
||||
act(() => {
|
||||
pins[0].dispatchEvent(mouse('mousedown', 500, 350))
|
||||
document.dispatchEvent(mouse('mousemove', 560, 390))
|
||||
document.dispatchEvent(mouse('mousemove', 620, 430))
|
||||
document.dispatchEvent(mouse('mouseup', 620, 430))
|
||||
})
|
||||
expect(map.getCenter()).toEqual(before)
|
||||
pins[0].dispatchEvent(mouse('mousedown', 500, 350));
|
||||
document.dispatchEvent(mouse('mousemove', 560, 390));
|
||||
document.dispatchEvent(mouse('mousemove', 620, 430));
|
||||
document.dispatchEvent(mouse('mouseup', 620, 430));
|
||||
});
|
||||
expect(map.getCenter()).toEqual(before);
|
||||
// The pan handler is back on, and the background still pans the map.
|
||||
expect(map.dragging.enabled()).toBe(true)
|
||||
panMap(container)
|
||||
expect(map.getCenter()).not.toEqual(before)
|
||||
})
|
||||
})
|
||||
expect(map.dragging.enabled()).toBe(true);
|
||||
panMap(container);
|
||||
expect(map.getCenter()).not.toEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1050
-755
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,10 @@
|
||||
import { Suspense } from 'react'
|
||||
import { AlertTriangle, Clock, Info } from 'lucide-react'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { MapView } from './MapView'
|
||||
import ErrorBoundary from '../shared/ErrorBoundary'
|
||||
import { MapViewGLMapbox, MapViewGLMaplibre } from './glLazy'
|
||||
import { useRoadtripHazards } from './useRoadtripHazards'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { Suspense } from 'react';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import ErrorBoundary from '../shared/ErrorBoundary';
|
||||
import { MapViewGLMapbox, MapViewGLMaplibre } from './glLazy';
|
||||
import { MapView } from './MapView';
|
||||
import { useRoadtripHazards } from './useRoadtripHazards';
|
||||
|
||||
// Auto-selects the map renderer based on user settings. Keeps the existing
|
||||
// Leaflet MapView untouched so the Mapbox GL variant can mature iteratively
|
||||
@@ -18,22 +16,21 @@ import { useTranslation } from '../../i18n/TranslationContext'
|
||||
// them online (see the GL tile rules in vite.config.js), not prefetched.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function MapViewAuto(props: any) {
|
||||
const { t } = useTranslation()
|
||||
const hazards = useRoadtripHazards(props.tripId, !!props.clusterLoosely)
|
||||
const { t } = useTranslation();
|
||||
const hazards = useRoadtripHazards(props.tripId, !!props.clusterLoosely);
|
||||
// `dawarichTrack` arrives as a prop rather than being fetched here: the pill
|
||||
// that switches it on lives at page level and needs the load status, so the
|
||||
// fetch sits in useTripPlanner and both shells read the same one.
|
||||
const mapProps = { ...props, hazards: hazards.feed?.hazards }
|
||||
const provider = useSettingsStore(s => s.settings.map_provider)
|
||||
const token = useSettingsStore(s => s.settings.mapbox_access_token)
|
||||
const mapProps = { ...props, hazards: hazards.feed?.hazards };
|
||||
const provider = useSettingsStore((s) => s.settings.map_provider);
|
||||
const token = useSettingsStore((s) => s.settings.mapbox_access_token);
|
||||
// Fall back to Leaflet when Mapbox is selected but no token is set,
|
||||
// so trip planner never shows an empty map due to a missing token.
|
||||
const glProvider = provider === 'maplibre-gl' ? 'maplibre-gl'
|
||||
: provider === 'mapbox-gl' && token ? 'mapbox-gl'
|
||||
: null
|
||||
const glProvider =
|
||||
provider === 'maplibre-gl' ? 'maplibre-gl' : provider === 'mapbox-gl' && token ? 'mapbox-gl' : null;
|
||||
// One chunk per engine: picking the binding here is what keeps mapbox-gl and
|
||||
// maplibre-gl out of each other's downloads.
|
||||
const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox
|
||||
const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox;
|
||||
if (glProvider) {
|
||||
// Render the previous Leaflet map as the fallback so there's no blank flash
|
||||
// while the GL chunk loads on first use.
|
||||
@@ -48,7 +45,7 @@ export function MapViewAuto(props: any) {
|
||||
<MapViewGL {...mapProps} glProvider={glProvider} />
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
)
|
||||
);
|
||||
}
|
||||
return <MapView {...mapProps} />
|
||||
return <MapView {...mapProps} />;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1479
-1221
File diff suppressed because it is too large
Load Diff
@@ -1,27 +1,39 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useMap } from 'react-leaflet'
|
||||
import type L from 'leaflet'
|
||||
import type { RouteVia } from '../../types'
|
||||
import { bindDayBoundaryDrag, type DayBoundaryControls } from './dayBoundaryDrag'
|
||||
import type L from 'leaflet';
|
||||
import { useEffect } from 'react';
|
||||
import { useMap } from 'react-leaflet';
|
||||
import type { RouteVia } from '../../types';
|
||||
import { bindDayBoundaryDrag, type DayBoundaryControls } from './dayBoundaryDrag';
|
||||
|
||||
export function NightPauseDrag({ marker, via, controls }: { marker: L.Marker | null; via: RouteVia; controls?: DayBoundaryControls }) {
|
||||
const map = useMap()
|
||||
export function NightPauseDrag({
|
||||
marker,
|
||||
via,
|
||||
controls,
|
||||
}: {
|
||||
marker: L.Marker | null;
|
||||
via: RouteVia;
|
||||
controls?: DayBoundaryControls;
|
||||
}) {
|
||||
const map = useMap();
|
||||
useEffect(() => {
|
||||
const el = marker?.getElement()
|
||||
if (!marker || !el || !controls) return
|
||||
const el = marker?.getElement();
|
||||
if (!marker || !el || !controls) return;
|
||||
return bindDayBoundaryDrag(el, via, controls, {
|
||||
project: (lat, lng) => {
|
||||
const point = map.latLngToContainerPoint([lat, lng])
|
||||
const rect = map.getContainer().getBoundingClientRect()
|
||||
return { x: point.x + rect.left, y: point.y + rect.top }
|
||||
const point = map.latLngToContainerPoint([lat, lng]);
|
||||
const rect = map.getContainer().getBoundingClientRect();
|
||||
return { x: point.x + rect.left, y: point.y + rect.top };
|
||||
},
|
||||
setPosition: (lat, lng) => {
|
||||
marker.setLatLng([lat, lng]);
|
||||
},
|
||||
setPosition: (lat, lng) => { marker.setLatLng([lat, lng]) },
|
||||
lock: () => {
|
||||
const enabled = map.dragging.enabled()
|
||||
map.dragging.disable()
|
||||
return () => { if (enabled) map.dragging.enable() }
|
||||
const enabled = map.dragging.enabled();
|
||||
map.dragging.disable();
|
||||
return () => {
|
||||
if (enabled) map.dragging.enable();
|
||||
};
|
||||
},
|
||||
})
|
||||
}, [map, marker, via, controls])
|
||||
return null
|
||||
});
|
||||
}, [map, marker, via, controls]);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import NightPauseTooltip from './NightPauseTooltip'
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import NightPauseTooltip from './NightPauseTooltip';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('keeps the full pause description inside the viewport at its lower right edge', () => {
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ width: 240, height: 56 } as DOMRect)
|
||||
const label = 'Tagesende von Tag 12 um 18:00 Uhr'
|
||||
render(<NightPauseTooltip label={label} x={window.innerWidth - 5} y={window.innerHeight - 5} />)
|
||||
const tooltip = screen.getByRole('tooltip')
|
||||
expect(tooltip).toHaveTextContent(label)
|
||||
expect(parseFloat(tooltip.style.left) + 240).toBeLessThanOrEqual(window.innerWidth - 12)
|
||||
expect(parseFloat(tooltip.style.top) + 56).toBeLessThanOrEqual(window.innerHeight - 12)
|
||||
expect(tooltip.style.overflowWrap).toBe('anywhere')
|
||||
})
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ width: 240, height: 56 } as DOMRect);
|
||||
const label = 'Tagesende von Tag 12 um 18:00 Uhr';
|
||||
render(<NightPauseTooltip label={label} x={window.innerWidth - 5} y={window.innerHeight - 5} />);
|
||||
const tooltip = screen.getByRole('tooltip');
|
||||
expect(tooltip).toHaveTextContent(label);
|
||||
expect(parseFloat(tooltip.style.left) + 240).toBeLessThanOrEqual(window.innerWidth - 12);
|
||||
expect(parseFloat(tooltip.style.top) + 56).toBeLessThanOrEqual(window.innerHeight - 12);
|
||||
expect(tooltip.style.overflowWrap).toBe('anywhere');
|
||||
});
|
||||
|
||||
it('keeps descriptions visible at the upper left edge', () => {
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ width: 240, height: 56 } as DOMRect)
|
||||
render(<NightPauseTooltip label="End of day 1 at 18:00" x={-50} y={-50} />)
|
||||
expect(screen.getByRole('tooltip')).toHaveStyle({ left: '12px', top: '12px' })
|
||||
})
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ width: 240, height: 56 } as DOMRect);
|
||||
render(<NightPauseTooltip label="End of day 1 at 18:00" x={-50} y={-50} />);
|
||||
expect(screen.getByRole('tooltip')).toHaveStyle({ left: '12px', top: '12px' });
|
||||
});
|
||||
|
||||
@@ -1,24 +1,37 @@
|
||||
import { useLayoutEffect, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useLayoutEffect, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
export default function NightPauseTooltip({ label, x, y }: { label: string; x: number; y: number }) {
|
||||
const card = useRef<HTMLDivElement>(null)
|
||||
const card = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const place = () => {
|
||||
const node = card.current!
|
||||
const { width, height } = node.getBoundingClientRect()
|
||||
const left = x + 14 + width > window.innerWidth - 12 ? x - width - 14 : x + 14
|
||||
node.style.left = `${Math.max(12, Math.min(left, window.innerWidth - width - 12))}px`
|
||||
node.style.top = `${Math.max(12, Math.min(y - 10, window.innerHeight - height - 12))}px`
|
||||
}
|
||||
place()
|
||||
window.addEventListener('resize', place)
|
||||
return () => window.removeEventListener('resize', place)
|
||||
}, [label, x, y])
|
||||
const node = card.current!;
|
||||
const { width, height } = node.getBoundingClientRect();
|
||||
const left = x + 14 + width > window.innerWidth - 12 ? x - width - 14 : x + 14;
|
||||
node.style.left = `${Math.max(12, Math.min(left, window.innerWidth - width - 12))}px`;
|
||||
node.style.top = `${Math.max(12, Math.min(y - 10, window.innerHeight - height - 12))}px`;
|
||||
};
|
||||
place();
|
||||
window.addEventListener('resize', place);
|
||||
return () => window.removeEventListener('resize', place);
|
||||
}, [label, x, y]);
|
||||
return createPortal(
|
||||
<div ref={card} role="tooltip" data-testid="tooltip"
|
||||
<div
|
||||
ref={card}
|
||||
role="tooltip"
|
||||
data-testid="tooltip"
|
||||
className="pointer-events-none fixed z-[var(--z-toast)] rounded-lg border border-edge-faint bg-surface-card px-3 py-2 font-semibold leading-relaxed text-content shadow-popover"
|
||||
style={{ left: x + 14, top: y - 10, maxWidth: 'min(16rem, calc(100vw - 24px))', overflowWrap: 'anywhere', fontFamily: 'var(--font-system)', fontSize: 12 }}
|
||||
>{label}</div>, document.body,
|
||||
)
|
||||
style={{
|
||||
left: x + 14,
|
||||
top: y - 10,
|
||||
maxWidth: 'min(16rem, calc(100vw - 24px))',
|
||||
overflowWrap: 'anywhere',
|
||||
fontFamily: 'var(--font-system)',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,35 @@
|
||||
import React from 'react'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import PlaceHoverCard from './PlaceHoverCard'
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import PlaceHoverCard from './PlaceHoverCard';
|
||||
|
||||
describe('PlaceHoverCard', () => {
|
||||
it('FE-MAP-HOVERCARD-001: says what the place is, which a round photo cannot', () => {
|
||||
render(<PlaceHoverCard x={10} y={20} name="Museumsinsel" categoryName="Sights" categoryIcon="Landmark" address="Bodestraße 1" />)
|
||||
render(
|
||||
<PlaceHoverCard
|
||||
x={10}
|
||||
y={20}
|
||||
name="Museumsinsel"
|
||||
categoryName="Sights"
|
||||
categoryIcon="Landmark"
|
||||
address="Bodestraße 1"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Museumsinsel')).toBeInTheDocument()
|
||||
expect(screen.getByText('Sights')).toBeInTheDocument()
|
||||
expect(screen.getByText('Bodestraße 1')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText('Museumsinsel')).toBeInTheDocument();
|
||||
expect(screen.getByText('Sights')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bodestraße 1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MAP-HOVERCARD-002: shows a rating beside the name, and only when there is one', () => {
|
||||
const { rerender } = render(<PlaceHoverCard x={0} y={0} name="Museumsinsel" rating={4} />)
|
||||
expect(screen.getByText('4')).toBeInTheDocument()
|
||||
const { rerender } = render(<PlaceHoverCard x={0} y={0} name="Museumsinsel" rating={4} />);
|
||||
expect(screen.getByText('4')).toBeInTheDocument();
|
||||
|
||||
rerender(<PlaceHoverCard x={0} y={0} name="Museumsinsel" rating={null} />)
|
||||
expect(screen.queryByText('4')).toBeNull()
|
||||
})
|
||||
rerender(<PlaceHoverCard x={0} y={0} name="Museumsinsel" rating={null} />);
|
||||
expect(screen.queryByText('4')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MAP-HOVERCARD-003: never takes the pointer — it is a label, not a target', () => {
|
||||
render(<PlaceHoverCard x={0} y={0} name="Museumsinsel" />)
|
||||
expect(screen.getByTestId('tooltip')).toHaveStyle({ pointerEvents: 'none' })
|
||||
})
|
||||
})
|
||||
render(<PlaceHoverCard x={0} y={0} name="Museumsinsel" />);
|
||||
expect(screen.getByTestId('tooltip')).toHaveStyle({ pointerEvents: 'none' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React from 'react'
|
||||
import { MapPin, Star } from 'lucide-react'
|
||||
import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
import { tintOf } from '../Planner/planParts'
|
||||
import { MapPin, Star } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { tintOf } from '../Planner/planParts';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* What a place is, shown at the cursor while the pointer rests on its marker.
|
||||
@@ -17,50 +17,77 @@ import { tintOf } from '../Planner/planParts'
|
||||
* pointer: it is a label on the map, not something to aim at.
|
||||
*/
|
||||
export interface PlaceHoverCardProps {
|
||||
x: number
|
||||
y: number
|
||||
name: string | null | undefined
|
||||
categoryName?: string | null
|
||||
categoryIcon?: string | null
|
||||
categoryColor?: string | null
|
||||
address?: string | null
|
||||
x: number;
|
||||
y: number;
|
||||
name: string | null | undefined;
|
||||
categoryName?: string | null;
|
||||
categoryIcon?: string | null;
|
||||
categoryColor?: string | null;
|
||||
address?: string | null;
|
||||
/** Average across everyone who rated it, when the surface tracks ratings. */
|
||||
rating?: number | null
|
||||
rating?: number | null;
|
||||
/** The picture its marker wears; the card shows it in place of the category tile. */
|
||||
photo?: string | null
|
||||
photo?: string | null;
|
||||
}
|
||||
|
||||
export default function PlaceHoverCard({ x, y, name, categoryName, categoryIcon, categoryColor, address, rating, photo }: PlaceHoverCardProps): React.ReactElement {
|
||||
export default function PlaceHoverCard({
|
||||
x,
|
||||
y,
|
||||
name,
|
||||
categoryName,
|
||||
categoryIcon,
|
||||
categoryColor,
|
||||
address,
|
||||
rating,
|
||||
photo,
|
||||
}: PlaceHoverCardProps): React.ReactElement {
|
||||
// The tile wears the category the way the planner's rows do; without one it is a quiet pin.
|
||||
const CatIcon = categoryName ? getCategoryIcon(categoryIcon) : MapPin
|
||||
const tone = categoryName ? categoryColor || 'var(--text-muted)' : null
|
||||
const CatIcon = categoryName ? getCategoryIcon(categoryIcon) : MapPin;
|
||||
const tone = categoryName ? categoryColor || 'var(--text-muted)' : null;
|
||||
return (
|
||||
<div data-testid="tooltip"
|
||||
className="flex max-w-[300px] items-center gap-3 rounded-[18px] border border-edge-faint bg-surface-card p-1.5 pr-4 font-system shadow-popover"
|
||||
style={{ position: 'fixed', left: x + 14, top: y - 10, zIndex: 9999, pointerEvents: 'none' }}>
|
||||
<div
|
||||
data-testid="tooltip"
|
||||
className="font-system flex max-w-[300px] items-center gap-3 rounded-[18px] border border-edge-faint bg-surface-card p-1.5 pr-4 shadow-popover"
|
||||
style={{ position: 'fixed', left: x + 14, top: y - 10, zIndex: 9999, pointerEvents: 'none' }}
|
||||
>
|
||||
{/* Twelve inside eighteen with six of padding: the picture's corners follow the card's. */}
|
||||
{photo ? (
|
||||
<img src={photo} alt="" className="block h-14 w-14 flex-none rounded-[12px] bg-surface-tertiary object-cover" />
|
||||
) : (
|
||||
<span className="grid h-14 w-14 flex-none place-items-center rounded-[12px]"
|
||||
style={{ background: tone ? tintOf(tone, 14) : 'var(--bg-tertiary)' }}>
|
||||
<span
|
||||
className="grid h-14 w-14 flex-none place-items-center rounded-[12px]"
|
||||
style={{ background: tone ? tintOf(tone, 14) : 'var(--bg-tertiary)' }}
|
||||
>
|
||||
<CatIcon size={18} strokeWidth={2} style={{ color: tone || 'var(--text-faint)' }} />
|
||||
</span>
|
||||
)}
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="min-w-0 truncate font-semibold text-content" style={fs(13, 'body')}>{name}</span>
|
||||
<span className="min-w-0 truncate font-semibold text-content" style={fs(13, 'body')}>
|
||||
{name}
|
||||
</span>
|
||||
{typeof rating === 'number' && rating > 0 && (
|
||||
<span className="inline-flex flex-none items-center gap-0.5 font-geist tabular-nums text-content-secondary" style={fs(11)}>
|
||||
<span
|
||||
className="inline-flex flex-none items-center gap-0.5 font-geist tabular-nums text-content-secondary"
|
||||
style={fs(11)}
|
||||
>
|
||||
<Star size={10} strokeWidth={2} className="fill-current text-warning" aria-hidden />
|
||||
{/* One decimal only when it earns it: "4" reads faster than "4.0". */}
|
||||
{Number.isInteger(rating) ? rating : rating.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{categoryName && <span className="truncate text-content-muted" style={fs(11)}>{categoryName}</span>}
|
||||
{address && <span className="truncate text-content-faint" style={fs(11)}>{address}</span>}
|
||||
{categoryName && (
|
||||
<span className="truncate text-content-muted" style={fs(11)}>
|
||||
{categoryName}
|
||||
</span>
|
||||
)}
|
||||
{address && (
|
||||
<span className="truncate text-content-faint" style={fs(11)}>
|
||||
{address}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,203 +1,223 @@
|
||||
// FE-COMP-POIPILL-001 to FE-COMP-POIPILL-018
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import PoiCategoryPill from './PoiCategoryPill'
|
||||
import { POI_CATEGORIES } from './poiCategories'
|
||||
import { corePoiCategories, pluginPoiCategories, type PoiCategoryGroups } from './usePoiCategories'
|
||||
import { fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import PoiCategoryPill from './PoiCategoryPill';
|
||||
import { POI_CATEGORIES } from './poiCategories';
|
||||
import { corePoiCategories, pluginPoiCategories, type PoiCategoryGroups } from './usePoiCategories';
|
||||
|
||||
const CAFE = POI_CATEGORIES.find(c => c.key === 'cafe')!
|
||||
const BAR = POI_CATEGORIES.find(c => c.key === 'bar')!
|
||||
const CAFE = POI_CATEGORIES.find((c) => c.key === 'cafe')!;
|
||||
const BAR = POI_CATEGORIES.find((c) => c.key === 'bar')!;
|
||||
|
||||
// The labels the English UI gives the core chips, as usePoiCategories hands them over.
|
||||
const EN: Record<string, string> = {
|
||||
'poi.cat.restaurants': 'Restaurants', 'poi.cat.cafes': 'Cafés', 'poi.cat.bars': 'Bars & nightlife',
|
||||
'poi.cat.hotels': 'Accommodation', 'poi.cat.sights': 'Sights', 'poi.cat.museums': 'Museums & culture',
|
||||
'poi.cat.nature': 'Nature & parks', 'poi.cat.activities': 'Activities',
|
||||
}
|
||||
const CORE_ONLY: PoiCategoryGroups = { core: corePoiCategories(key => EN[key] ?? key), plugin: [] }
|
||||
'poi.cat.restaurants': 'Restaurants',
|
||||
'poi.cat.cafes': 'Cafés',
|
||||
'poi.cat.bars': 'Bars & nightlife',
|
||||
'poi.cat.hotels': 'Accommodation',
|
||||
'poi.cat.sights': 'Sights',
|
||||
'poi.cat.museums': 'Museums & culture',
|
||||
'poi.cat.nature': 'Nature & parks',
|
||||
'poi.cat.activities': 'Activities',
|
||||
};
|
||||
const CORE_ONLY: PoiCategoryGroups = { core: corePoiCategories((key) => EN[key] ?? key), plugin: [] };
|
||||
const WITH_PLUGINS: PoiCategoryGroups = {
|
||||
core: CORE_ONLY.core,
|
||||
plugin: pluginPoiCategories([{
|
||||
id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null,
|
||||
poiCategories: [
|
||||
{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' },
|
||||
{ id: 'water', label: 'Drinking water', icon: 'Droplet', color: '#0369a1' },
|
||||
plugin: pluginPoiCategories(
|
||||
[
|
||||
{
|
||||
id: 'trail-finder',
|
||||
name: 'Trail finder',
|
||||
type: 'integration',
|
||||
icon: null,
|
||||
poiCategories: [
|
||||
{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' },
|
||||
{ id: 'water', label: 'Drinking water', icon: 'Droplet', color: '#0369a1' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}], 'en'),
|
||||
}
|
||||
const TRAILHEADS = 'plugin:trail-finder/trailheads'
|
||||
'en'
|
||||
),
|
||||
};
|
||||
const TRAILHEADS = 'plugin:trail-finder/trailheads';
|
||||
|
||||
function pill(props: Partial<React.ComponentProps<typeof PoiCategoryPill>> = {}) {
|
||||
return render(
|
||||
<PoiCategoryPill categories={CORE_ONLY} active={new Set()} onToggle={vi.fn()} {...props} />,
|
||||
)
|
||||
return render(<PoiCategoryPill categories={CORE_ONLY} active={new Set()} onToggle={vi.fn()} {...props} />);
|
||||
}
|
||||
|
||||
// The spinner replaces the category icon, so "is this segment spinning" reads as
|
||||
// "does its button hold an .animate-spin element".
|
||||
const spinning = () => screen.getAllByRole('button')
|
||||
.filter(b => b.querySelector('.animate-spin'))
|
||||
.map(b => b.getAttribute('aria-label'))
|
||||
const spinning = () =>
|
||||
screen
|
||||
.getAllByRole('button')
|
||||
.filter((b) => b.querySelector('.animate-spin'))
|
||||
.map((b) => b.getAttribute('aria-label'));
|
||||
|
||||
const labels = () => screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))
|
||||
const labels = () => screen.getAllByRole('button').map((b) => b.getAttribute('aria-label'));
|
||||
|
||||
describe('PoiCategoryPill', () => {
|
||||
it('FE-COMP-POIPILL-001: renders one segment per category, none pressed', () => {
|
||||
pill()
|
||||
const buttons = screen.getAllByRole('button')
|
||||
expect(buttons).toHaveLength(POI_CATEGORIES.length)
|
||||
expect(buttons.every(b => b.getAttribute('aria-pressed') === 'false')).toBe(true)
|
||||
})
|
||||
pill();
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons).toHaveLength(POI_CATEGORIES.length);
|
||||
expect(buttons.every((b) => b.getAttribute('aria-pressed') === 'false')).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-002: clicking a segment toggles its category', () => {
|
||||
const onToggle = vi.fn()
|
||||
pill({ onToggle })
|
||||
fireEvent.click(screen.getAllByRole('button')[1])
|
||||
expect(onToggle).toHaveBeenCalledWith(POI_CATEGORIES[1].key)
|
||||
})
|
||||
const onToggle = vi.fn();
|
||||
pill({ onToggle });
|
||||
fireEvent.click(screen.getAllByRole('button')[1]);
|
||||
expect(onToggle).toHaveBeenCalledWith(POI_CATEGORIES[1].key);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-003: the active category spins while its fetch is in flight', () => {
|
||||
pill({ active: new Set([CAFE.key]), loadingKeys: new Set([CAFE.key]) })
|
||||
expect(spinning()).toEqual(['Cafés'])
|
||||
})
|
||||
pill({ active: new Set([CAFE.key]), loadingKeys: new Set([CAFE.key]) });
|
||||
expect(spinning()).toEqual(['Cafés']);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-004: a deselected category never spins, even with a lingering loading key', () => {
|
||||
pill({ active: new Set([BAR.key]), loadingKeys: new Set([CAFE.key, BAR.key]) })
|
||||
expect(spinning()).toEqual(['Bars & nightlife'])
|
||||
})
|
||||
pill({ active: new Set([BAR.key]), loadingKeys: new Set([CAFE.key, BAR.key]) });
|
||||
expect(spinning()).toEqual(['Bars & nightlife']);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-005: a failed category offers a retry', () => {
|
||||
pill({ active: new Set([CAFE.key]), errorKeys: new Set([CAFE.key]) })
|
||||
expect(screen.getByText('Search this area')).toBeInTheDocument()
|
||||
})
|
||||
pill({ active: new Set([CAFE.key]), errorKeys: new Set([CAFE.key]) });
|
||||
expect(screen.getByText('Search this area')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-006: "search this area" reports the moved viewport', () => {
|
||||
const onSearchArea = vi.fn()
|
||||
pill({ active: new Set([CAFE.key]), moved: true, onSearchArea })
|
||||
fireEvent.click(screen.getByText('Search this area'))
|
||||
expect(onSearchArea).toHaveBeenCalled()
|
||||
})
|
||||
const onSearchArea = vi.fn();
|
||||
pill({ active: new Set([CAFE.key]), moved: true, onSearchArea });
|
||||
fireEvent.click(screen.getByText('Search this area'));
|
||||
expect(onSearchArea).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The phone map hands the bar the whole width between the screen margins, so
|
||||
// its segments end up the size of everything else the thumb aims at there.
|
||||
it('FE-COMP-POIPILL-007: fullWidth stretches the bar and spreads the segments', () => {
|
||||
pill({ fullWidth: true })
|
||||
const button = screen.getAllByRole('button')[0]
|
||||
expect(button.style.flexGrow).toBe('1')
|
||||
expect(button.style.width).toBe('auto')
|
||||
expect((button.parentElement as HTMLElement).style.display).toBe('flex')
|
||||
})
|
||||
pill({ fullWidth: true });
|
||||
const button = screen.getAllByRole('button')[0];
|
||||
expect(button.style.flexGrow).toBe('1');
|
||||
expect(button.style.width).toBe('auto');
|
||||
expect((button.parentElement as HTMLElement).style.display).toBe('flex');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-008: without it the bar stays content-width, as the desktop map floats it', () => {
|
||||
pill()
|
||||
const button = screen.getAllByRole('button')[0]
|
||||
expect(button.style.flexGrow).toBe('')
|
||||
expect(button.style.width).toBe('34px')
|
||||
expect((button.parentElement as HTMLElement).style.display).toBe('inline-flex')
|
||||
})
|
||||
pill();
|
||||
const button = screen.getAllByRole('button')[0];
|
||||
expect(button.style.flexGrow).toBe('');
|
||||
expect(button.style.width).toBe('34px');
|
||||
expect((button.parentElement as HTMLElement).style.display).toBe('inline-flex');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-009: without plugin categories there is no divider and every segment sits in the bar', () => {
|
||||
pill()
|
||||
expect(screen.queryByRole('separator')).toBeNull()
|
||||
const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement
|
||||
expect(bar.children).toHaveLength(POI_CATEGORIES.length)
|
||||
})
|
||||
pill();
|
||||
expect(screen.queryByRole('separator')).toBeNull();
|
||||
const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement;
|
||||
expect(bar.children).toHaveLength(POI_CATEGORIES.length);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-010: plugin categories follow the core ones after a labelled divider', () => {
|
||||
pill({ categories: WITH_PLUGINS })
|
||||
expect(labels()).toEqual([...CORE_ONLY.core.map(c => c.label), 'Trailheads', 'Drinking water'])
|
||||
const divider = screen.getByRole('separator', { name: 'Categories from plugins' })
|
||||
const bar = divider.parentElement as HTMLElement
|
||||
pill({ categories: WITH_PLUGINS });
|
||||
expect(labels()).toEqual([...CORE_ONLY.core.map((c) => c.label), 'Trailheads', 'Drinking water']);
|
||||
const divider = screen.getByRole('separator', { name: 'Categories from plugins' });
|
||||
const bar = divider.parentElement as HTMLElement;
|
||||
// In the same bar, straight after the last core segment.
|
||||
expect(Array.from(bar.children).indexOf(divider)).toBe(POI_CATEGORIES.length)
|
||||
expect(divider.getAttribute('aria-orientation')).toBe('vertical')
|
||||
})
|
||||
expect(Array.from(bar.children).indexOf(divider)).toBe(POI_CATEGORIES.length);
|
||||
expect(divider.getAttribute('aria-orientation')).toBe('vertical');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-011: a plugin segment toggles its namespaced key and fills with its own colour', () => {
|
||||
const onToggle = vi.fn()
|
||||
const { rerender } = pill({ categories: WITH_PLUGINS, onToggle })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Trailheads' }))
|
||||
expect(onToggle).toHaveBeenCalledWith(TRAILHEADS)
|
||||
const onToggle = vi.fn();
|
||||
const { rerender } = pill({ categories: WITH_PLUGINS, onToggle });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Trailheads' }));
|
||||
expect(onToggle).toHaveBeenCalledWith(TRAILHEADS);
|
||||
|
||||
rerender(<PoiCategoryPill categories={WITH_PLUGINS} active={new Set([TRAILHEADS])} onToggle={onToggle} errorKeys={new Set([TRAILHEADS])} />)
|
||||
const segment = screen.getByRole('button', { name: 'Trailheads' })
|
||||
expect(segment.getAttribute('aria-pressed')).toBe('true')
|
||||
expect(segment.style.background).toBe('rgb(47, 133, 90)')
|
||||
rerender(
|
||||
<PoiCategoryPill
|
||||
categories={WITH_PLUGINS}
|
||||
active={new Set([TRAILHEADS])}
|
||||
onToggle={onToggle}
|
||||
errorKeys={new Set([TRAILHEADS])}
|
||||
/>
|
||||
);
|
||||
const segment = screen.getByRole('button', { name: 'Trailheads' });
|
||||
expect(segment.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(segment.style.background).toBe('rgb(47, 133, 90)');
|
||||
// A failing plugin category offers the same retry a core one does.
|
||||
expect(screen.getByText('Search this area')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText('Search this area')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-012: the bar scrolls sideways once it runs out of room', () => {
|
||||
pill({ categories: WITH_PLUGINS, fullWidth: true })
|
||||
const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement
|
||||
expect(bar.style.overflowX).toBe('auto')
|
||||
expect(bar.style.maxWidth).toBe('100%')
|
||||
pill({ categories: WITH_PLUGINS, fullWidth: true });
|
||||
const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement;
|
||||
expect(bar.style.overflowX).toBe('auto');
|
||||
expect(bar.style.maxWidth).toBe('100%');
|
||||
// The column around it may shrink, or the bar would push past its container instead.
|
||||
expect((bar.parentElement as HTMLElement).style.minWidth).toBe('0px')
|
||||
})
|
||||
expect((bar.parentElement as HTMLElement).style.minWidth).toBe('0px');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-013: a phone segment never shrinks below the 34px touch target', () => {
|
||||
pill({ categories: WITH_PLUGINS, fullWidth: true })
|
||||
pill({ categories: WITH_PLUGINS, fullWidth: true });
|
||||
for (const button of screen.getAllByRole('button')) {
|
||||
expect(button.style.minWidth).toBe('34px')
|
||||
expect(button.style.height).toBe('34px')
|
||||
expect(button.style.minWidth).toBe('34px');
|
||||
expect(button.style.height).toBe('34px');
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-014: a desktop segment keeps its 34px instead of shrinking in a narrow corridor', () => {
|
||||
pill({ categories: WITH_PLUGINS })
|
||||
pill({ categories: WITH_PLUGINS });
|
||||
for (const button of screen.getAllByRole('button')) {
|
||||
expect(button.style.flexShrink).toBe('0')
|
||||
expect(button.style.minWidth).toBe('34px')
|
||||
expect(button.style.flexShrink).toBe('0');
|
||||
expect(button.style.minWidth).toBe('34px');
|
||||
}
|
||||
expect((screen.getByRole('separator').style.flexShrink)).toBe('0')
|
||||
})
|
||||
expect(screen.getByRole('separator').style.flexShrink).toBe('0');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-015: hovering highlights an idle segment and leaves an active one its colour', () => {
|
||||
pill({ categories: WITH_PLUGINS, active: new Set([TRAILHEADS]) })
|
||||
const idle = screen.getByRole('button', { name: 'Drinking water' })
|
||||
fireEvent.mouseEnter(idle)
|
||||
expect(idle.style.background).toBe('var(--bg-hover)')
|
||||
fireEvent.mouseLeave(idle)
|
||||
expect(idle.style.background).toBe('transparent')
|
||||
pill({ categories: WITH_PLUGINS, active: new Set([TRAILHEADS]) });
|
||||
const idle = screen.getByRole('button', { name: 'Drinking water' });
|
||||
fireEvent.mouseEnter(idle);
|
||||
expect(idle.style.background).toBe('var(--bg-hover)');
|
||||
fireEvent.mouseLeave(idle);
|
||||
expect(idle.style.background).toBe('transparent');
|
||||
|
||||
const on = screen.getByRole('button', { name: 'Trailheads' })
|
||||
fireEvent.mouseEnter(on)
|
||||
fireEvent.mouseLeave(on)
|
||||
expect(on.style.background).toBe('rgb(47, 133, 90)')
|
||||
})
|
||||
const on = screen.getByRole('button', { name: 'Trailheads' });
|
||||
fireEvent.mouseEnter(on);
|
||||
fireEvent.mouseLeave(on);
|
||||
expect(on.style.background).toBe('rgb(47, 133, 90)');
|
||||
});
|
||||
|
||||
// jsdom lays nothing out, so the bar is given the widths a narrow desktop corridor would.
|
||||
const barOf = (clientWidth: number, scrollWidth: number) => {
|
||||
const bar = screen.getByRole('separator').parentElement as HTMLElement
|
||||
Object.defineProperty(bar, 'clientWidth', { configurable: true, value: clientWidth })
|
||||
Object.defineProperty(bar, 'scrollWidth', { configurable: true, value: scrollWidth })
|
||||
return bar
|
||||
}
|
||||
const bar = screen.getByRole('separator').parentElement as HTMLElement;
|
||||
Object.defineProperty(bar, 'clientWidth', { configurable: true, value: clientWidth });
|
||||
Object.defineProperty(bar, 'scrollWidth', { configurable: true, value: scrollWidth });
|
||||
return bar;
|
||||
};
|
||||
|
||||
it('FE-COMP-POIPILL-016: a mouse wheel scrolls an overflowing desktop bar sideways, in pixels, lines or pages', () => {
|
||||
pill({ categories: WITH_PLUGINS })
|
||||
const bar = barOf(300, 450)
|
||||
fireEvent.wheel(bar, { deltaY: 100 })
|
||||
expect(bar.scrollLeft).toBe(100)
|
||||
fireEvent.wheel(bar, { deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_LINE })
|
||||
expect(bar.scrollLeft).toBe(134)
|
||||
fireEvent.wheel(bar, { deltaY: 0.5, deltaMode: WheelEvent.DOM_DELTA_PAGE })
|
||||
expect(bar.scrollLeft).toBe(284)
|
||||
})
|
||||
pill({ categories: WITH_PLUGINS });
|
||||
const bar = barOf(300, 450);
|
||||
fireEvent.wheel(bar, { deltaY: 100 });
|
||||
expect(bar.scrollLeft).toBe(100);
|
||||
fireEvent.wheel(bar, { deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_LINE });
|
||||
expect(bar.scrollLeft).toBe(134);
|
||||
fireEvent.wheel(bar, { deltaY: 0.5, deltaMode: WheelEvent.DOM_DELTA_PAGE });
|
||||
expect(bar.scrollLeft).toBe(284);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-017: the wheel is left alone when the bar fits or the turn is already sideways', () => {
|
||||
pill({ categories: WITH_PLUGINS })
|
||||
const bar = barOf(450, 450)
|
||||
fireEvent.wheel(bar, { deltaY: 100 })
|
||||
expect(bar.scrollLeft).toBe(0)
|
||||
pill({ categories: WITH_PLUGINS });
|
||||
const bar = barOf(450, 450);
|
||||
fireEvent.wheel(bar, { deltaY: 100 });
|
||||
expect(bar.scrollLeft).toBe(0);
|
||||
// A trackpad swipe or Shift+wheel scrolls the bar natively; adding to it would double it.
|
||||
barOf(300, 450)
|
||||
fireEvent.wheel(bar, { deltaX: 40, deltaY: 10 })
|
||||
expect(bar.scrollLeft).toBe(0)
|
||||
})
|
||||
barOf(300, 450);
|
||||
fireEvent.wheel(bar, { deltaX: 40, deltaY: 10 });
|
||||
expect(bar.scrollLeft).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIPILL-018: in a right-to-left language a wheel-down still moves toward the plugin chips', () => {
|
||||
// The app sets the page direction from the language (TranslationContext) and the bar
|
||||
@@ -205,13 +225,13 @@ describe('PoiCategoryPill', () => {
|
||||
render(
|
||||
<div dir="rtl">
|
||||
<PoiCategoryPill categories={WITH_PLUGINS} active={new Set()} onToggle={vi.fn()} />
|
||||
</div>,
|
||||
)
|
||||
const bar = barOf(300, 450)
|
||||
</div>
|
||||
);
|
||||
const bar = barOf(300, 450);
|
||||
// An RTL scroller counts scrollLeft from 0 at the start down to negative at the end.
|
||||
fireEvent.wheel(bar, { deltaY: 100 })
|
||||
expect(bar.scrollLeft).toBe(-100)
|
||||
fireEvent.wheel(bar, { deltaY: -40 })
|
||||
expect(bar.scrollLeft).toBe(-60)
|
||||
})
|
||||
})
|
||||
fireEvent.wheel(bar, { deltaY: 100 });
|
||||
expect(bar.scrollLeft).toBe(-100);
|
||||
fireEvent.wheel(bar, { deltaY: -40 });
|
||||
expect(bar.scrollLeft).toBe(-60);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
import { RotateCw, AlertTriangle } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import type { ExplorePoiCategory, PoiCategoryGroups } from './usePoiCategories'
|
||||
import { AlertTriangle, RotateCw } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import type { ExplorePoiCategory, PoiCategoryGroups } from './usePoiCategories';
|
||||
|
||||
interface Props {
|
||||
/** The chips to offer, from usePoiCategories by way of usePoiExplore. */
|
||||
categories: PoiCategoryGroups
|
||||
active: Set<string>
|
||||
onToggle: (key: string) => void
|
||||
loadingKeys?: Set<string>
|
||||
categories: PoiCategoryGroups;
|
||||
active: Set<string>;
|
||||
onToggle: (key: string) => void;
|
||||
loadingKeys?: Set<string>;
|
||||
/** categories whose last fetch failed → show a retry affordance */
|
||||
errorKeys?: Set<string>
|
||||
errorKeys?: Set<string>;
|
||||
/** true when the map moved since the last search → offer "search this area" */
|
||||
moved?: boolean
|
||||
onSearchArea?: () => void
|
||||
moved?: boolean;
|
||||
onSearchArea?: () => void;
|
||||
/** Stretch the bar across its container and spread the segments evenly.
|
||||
* The phone map gives it the full width between the screen margins; on
|
||||
* desktop it floats, so it stays content-width there. */
|
||||
fullWidth?: boolean
|
||||
fullWidth?: boolean;
|
||||
}
|
||||
|
||||
// The touch target every segment keeps, however many categories there are.
|
||||
const SEGMENT = 34
|
||||
const SEGMENT = 34;
|
||||
|
||||
// How far one wheel step moves the bar. Firefox counts a mouse wheel in lines and
|
||||
// some drivers in pages; a line moves about one segment, a page one bar width.
|
||||
function wheelPixels(e: React.WheelEvent, barWidth: number): number {
|
||||
if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) return e.deltaY * SEGMENT
|
||||
if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) return e.deltaY * barWidth
|
||||
return e.deltaY
|
||||
if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) return e.deltaY * SEGMENT;
|
||||
if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) return e.deltaY * barWidth;
|
||||
return e.deltaY;
|
||||
}
|
||||
|
||||
// The bar only ever overflows sideways and a plain mouse wheel only turns vertically,
|
||||
@@ -38,19 +38,19 @@ function wheelPixels(e: React.WheelEvent, barWidth: number): number {
|
||||
// In a right-to-left language the chips overflow to the left and scrollLeft runs from 0
|
||||
// down into negative numbers, so the same turn has to count the other way to reach them.
|
||||
function wheelSideways(e: React.WheelEvent<HTMLDivElement>) {
|
||||
const bar = e.currentTarget
|
||||
if (bar.scrollWidth <= bar.clientWidth || Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return
|
||||
const towardEnd = getComputedStyle(bar).direction === 'rtl' ? -1 : 1
|
||||
bar.scrollLeft += towardEnd * wheelPixels(e, bar.clientWidth)
|
||||
const bar = e.currentTarget;
|
||||
if (bar.scrollWidth <= bar.clientWidth || Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
|
||||
const towardEnd = getComputedStyle(bar).direction === 'rtl' ? -1 : 1;
|
||||
bar.scrollLeft += towardEnd * wheelPixels(e, bar.clientWidth);
|
||||
}
|
||||
|
||||
interface SegmentProps {
|
||||
cat: ExplorePoiCategory
|
||||
on: boolean
|
||||
loading: boolean
|
||||
failed: boolean
|
||||
fullWidth?: boolean
|
||||
onToggle: (key: string) => void
|
||||
cat: ExplorePoiCategory;
|
||||
on: boolean;
|
||||
loading: boolean;
|
||||
failed: boolean;
|
||||
fullWidth?: boolean;
|
||||
onToggle: (key: string) => void;
|
||||
}
|
||||
|
||||
function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly<SegmentProps>) {
|
||||
@@ -64,27 +64,41 @@ function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly<Seg
|
||||
className={on ? '' : 'text-content-muted'}
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexGrow: fullWidth ? 1 : undefined,
|
||||
// Spread on the phone, fixed on desktop, and never narrower than the touch
|
||||
// target either way: past that the bar scrolls instead of squeezing.
|
||||
flexShrink: fullWidth ? 1 : 0,
|
||||
flexBasis: fullWidth ? 0 : undefined,
|
||||
minWidth: SEGMENT,
|
||||
width: fullWidth ? 'auto' : SEGMENT, height: SEGMENT, borderRadius: 999, border: 'none', cursor: 'pointer',
|
||||
width: fullWidth ? 'auto' : SEGMENT,
|
||||
height: SEGMENT,
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
background: on ? cat.color : 'transparent',
|
||||
color: on ? '#fff' : undefined,
|
||||
transition: 'background 0.14s, color 0.14s',
|
||||
}}
|
||||
onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent' }}
|
||||
onMouseEnter={(e) => {
|
||||
if (!on) e.currentTarget.style.background = 'var(--bg-hover)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (!on) e.currentTarget.style.background = 'transparent';
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<span
|
||||
className="animate-spin"
|
||||
style={{
|
||||
width: 14, height: 14, borderRadius: 999, display: 'inline-block',
|
||||
border: '2px solid', borderColor: on ? 'rgba(255,255,255,0.45)' : 'var(--border-primary)',
|
||||
width: 14,
|
||||
height: 14,
|
||||
borderRadius: 999,
|
||||
display: 'inline-block',
|
||||
border: '2px solid',
|
||||
borderColor: on ? 'rgba(255,255,255,0.45)' : 'var(--border-primary)',
|
||||
borderTopColor: on ? '#fff' : 'var(--text-muted)',
|
||||
}}
|
||||
/>
|
||||
@@ -92,14 +106,22 @@ function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly<Seg
|
||||
<cat.Icon size={16} strokeWidth={2} />
|
||||
)}
|
||||
{on && !loading && failed && (
|
||||
<span style={{
|
||||
position: 'absolute', top: 2, right: 2, width: 8, height: 8,
|
||||
borderRadius: 999, background: 'var(--danger)', border: '1.5px solid var(--sidebar-bg)',
|
||||
}} />
|
||||
<span
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 2,
|
||||
right: 2,
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: 999,
|
||||
background: 'var(--danger)',
|
||||
border: '1.5px solid var(--sidebar-bg)',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Frosted, icon-only segmented control that floats over the map. Active segments
|
||||
@@ -108,22 +130,31 @@ function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly<Seg
|
||||
// and whatever plugins add follows a thin divider (#1781); once that is more than the
|
||||
// width holds, the bar scrolls sideways (by swipe, trackpad or mouse wheel) rather than
|
||||
// shrinking a segment below the touch target.
|
||||
export default function PoiCategoryPill({ categories, active, onToggle, loadingKeys, errorKeys, moved, onSearchArea, fullWidth }: Readonly<Props>) {
|
||||
const { t } = useTranslation()
|
||||
const anyError = !!errorKeys && Array.from(active).some(k => errorKeys.has(k))
|
||||
export default function PoiCategoryPill({
|
||||
categories,
|
||||
active,
|
||||
onToggle,
|
||||
loadingKeys,
|
||||
errorKeys,
|
||||
moved,
|
||||
onSearchArea,
|
||||
fullWidth,
|
||||
}: Readonly<Props>) {
|
||||
const { t } = useTranslation();
|
||||
const anyError = !!errorKeys && Array.from(active).some((k) => errorKeys.has(k));
|
||||
|
||||
const frosted: React.CSSProperties = {
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: 'var(--sidebar-shadow, 0 4px 16px rgba(0,0,0,0.14))',
|
||||
}
|
||||
};
|
||||
|
||||
const segment = (cat: ExplorePoiCategory) => {
|
||||
const on = active.has(cat.key)
|
||||
const on = active.has(cat.key);
|
||||
// Only an active category can be loading: a deselected one whose fetch
|
||||
// is still winding down must not keep spinning.
|
||||
const loading = on && !!loadingKeys?.has(cat.key)
|
||||
const loading = on && !!loadingKeys?.has(cat.key);
|
||||
return (
|
||||
<Segment
|
||||
key={cat.key}
|
||||
@@ -134,23 +165,50 @@ export default function PoiCategoryPill({ categories, active, onToggle, loadingK
|
||||
fullWidth={fullWidth}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: fullWidth ? '100%' : undefined, maxWidth: '100%', minWidth: 0 }}>
|
||||
<div onWheel={wheelSideways} style={{
|
||||
display: fullWidth ? 'flex' : 'inline-flex',
|
||||
alignSelf: fullWidth ? 'stretch' : undefined,
|
||||
alignItems: 'center', gap: 2, padding: 4, borderRadius: 999, pointerEvents: 'auto', ...frosted,
|
||||
maxWidth: '100%', overflowX: 'auto', scrollbarWidth: 'none',
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
width: fullWidth ? '100%' : undefined,
|
||||
maxWidth: '100%',
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onWheel={wheelSideways}
|
||||
style={{
|
||||
display: fullWidth ? 'flex' : 'inline-flex',
|
||||
alignSelf: fullWidth ? 'stretch' : undefined,
|
||||
alignItems: 'center',
|
||||
gap: 2,
|
||||
padding: 4,
|
||||
borderRadius: 999,
|
||||
pointerEvents: 'auto',
|
||||
...frosted,
|
||||
maxWidth: '100%',
|
||||
overflowX: 'auto',
|
||||
scrollbarWidth: 'none',
|
||||
}}
|
||||
>
|
||||
{categories.core.map(segment)}
|
||||
{categories.plugin.length > 0 && (
|
||||
<hr
|
||||
aria-orientation="vertical"
|
||||
aria-label={t('poi.pluginCategories')}
|
||||
style={{ flexShrink: 0, width: 1, height: 20, margin: '0 3px', border: 'none', background: 'var(--border-primary)' }}
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
width: 1,
|
||||
height: 20,
|
||||
margin: '0 3px',
|
||||
border: 'none',
|
||||
background: 'var(--border-primary)',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{categories.plugin.map(segment)}
|
||||
@@ -162,19 +220,25 @@ export default function PoiCategoryPill({ categories, active, onToggle, loadingK
|
||||
onClick={onSearchArea}
|
||||
className="text-content"
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '6px 13px', borderRadius: 999, border: 'none', cursor: 'pointer',
|
||||
fontSize: 'calc(12px * var(--fs-scale-caption, 1))', fontWeight: 600, fontFamily: 'inherit', pointerEvents: 'auto',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
padding: '6px 13px',
|
||||
borderRadius: 999,
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
fontSize: 'calc(12px * var(--fs-scale-caption, 1))',
|
||||
fontWeight: 600,
|
||||
fontFamily: 'inherit',
|
||||
pointerEvents: 'auto',
|
||||
color: anyError ? '#ef4444' : undefined,
|
||||
...frosted,
|
||||
}}
|
||||
>
|
||||
{anyError
|
||||
? <AlertTriangle size={13} strokeWidth={2.4} />
|
||||
: <RotateCw size={13} strokeWidth={2.4} />}
|
||||
{anyError ? <AlertTriangle size={13} strokeWidth={2.4} /> : <RotateCw size={13} strokeWidth={2.4} />}
|
||||
{t('poi.searchThisArea')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,22 +1,45 @@
|
||||
import { Fragment, createElement, useMemo, useState } from 'react'
|
||||
import { renderIconMarkup } from '../../utils/iconMarkup'
|
||||
import { Marker, Polyline, Tooltip, useMap, useMapEvents } from 'react-leaflet'
|
||||
import L from 'leaflet'
|
||||
import { Plane, Train, Ship, Car, Bus, Sailboat, CableCar, Bike, CarTaxiFront, Route, TramFront } from 'lucide-react'
|
||||
import { escapeHtml } from '@trek/shared'
|
||||
import { getTransitMapSegments, type TransitMapSegment } from './transitGeometry'
|
||||
import { geodesicArcs } from './flightGeodesy'
|
||||
import { cleanEndpointName } from './reservationName'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { hopIsVisible, labelFloorPx } from '../../utils/reservationRoutes'
|
||||
import type { Reservation, ReservationEndpoint } from '../../types'
|
||||
import { escapeHtml } from '@trek/shared';
|
||||
import L from 'leaflet';
|
||||
import { Bike, Bus, CableCar, Car, CarTaxiFront, Plane, Route, Sailboat, Ship, Train, TramFront } from 'lucide-react';
|
||||
import { Fragment, createElement, useMemo, useState } from 'react';
|
||||
import { Marker, Polyline, Tooltip, useMap, useMapEvents } from 'react-leaflet';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { Reservation, ReservationEndpoint } from '../../types';
|
||||
import { renderIconMarkup } from '../../utils/iconMarkup';
|
||||
import { hopIsVisible, labelFloorPx } from '../../utils/reservationRoutes';
|
||||
import { geodesicArcs } from './flightGeodesy';
|
||||
import { cleanEndpointName } from './reservationName';
|
||||
import { getTransitMapSegments, type TransitMapSegment } from './transitGeometry';
|
||||
|
||||
const ENDPOINT_PANE = 'reservation-endpoints'
|
||||
const ENDPOINT_PANE = 'reservation-endpoints';
|
||||
|
||||
type TransportType = 'flight' | 'train' | 'cruise' | 'car' | 'bus' | 'taxi' | 'bicycle' | 'ferry' | 'cable_car' | 'transit' | 'transport_other'
|
||||
const TRANSPORT_TYPES: TransportType[] = ['flight', 'train', 'cruise', 'car', 'bus', 'taxi', 'bicycle', 'ferry', 'cable_car', 'transit', 'transport_other']
|
||||
type TransportType =
|
||||
| 'flight'
|
||||
| 'train'
|
||||
| 'cruise'
|
||||
| 'car'
|
||||
| 'bus'
|
||||
| 'taxi'
|
||||
| 'bicycle'
|
||||
| 'ferry'
|
||||
| 'cable_car'
|
||||
| 'transit'
|
||||
| 'transport_other';
|
||||
const TRANSPORT_TYPES: TransportType[] = [
|
||||
'flight',
|
||||
'train',
|
||||
'cruise',
|
||||
'car',
|
||||
'bus',
|
||||
'taxi',
|
||||
'bicycle',
|
||||
'ferry',
|
||||
'cable_car',
|
||||
'transit',
|
||||
'transport_other',
|
||||
];
|
||||
|
||||
const TRANSPORT_COLOR = '#3b82f6'
|
||||
const TRANSPORT_COLOR = '#3b82f6';
|
||||
|
||||
const TYPE_META: Record<TransportType, { color: string; icon: typeof Plane; geodesic: boolean }> = {
|
||||
flight: { color: TRANSPORT_COLOR, icon: Plane, geodesic: true },
|
||||
@@ -31,25 +54,27 @@ const TYPE_META: Record<TransportType, { color: string; icon: typeof Plane; geod
|
||||
cable_car: { color: TRANSPORT_COLOR, icon: CableCar, geodesic: false },
|
||||
transit: { color: TRANSPORT_COLOR, icon: TramFront, geodesic: false },
|
||||
transport_other: { color: TRANSPORT_COLOR, icon: Route, geodesic: false },
|
||||
}
|
||||
};
|
||||
|
||||
function useEndpointPane() {
|
||||
const map = useMap()
|
||||
const map = useMap();
|
||||
useMemo(() => {
|
||||
if (typeof map?.getPane !== 'function' || typeof map?.createPane !== 'function') return
|
||||
if (typeof map?.getPane !== 'function' || typeof map?.createPane !== 'function') return;
|
||||
if (!map.getPane(ENDPOINT_PANE)) {
|
||||
const pane = map.createPane(ENDPOINT_PANE)
|
||||
pane.style.zIndex = '650'
|
||||
pane.style.pointerEvents = 'auto'
|
||||
const pane = map.createPane(ENDPOINT_PANE);
|
||||
pane.style.zIndex = '650';
|
||||
pane.style.pointerEvents = 'auto';
|
||||
}
|
||||
}, [map])
|
||||
}, [map]);
|
||||
}
|
||||
|
||||
function endpointIcon(type: TransportType, label: string | null): L.DivIcon {
|
||||
const { icon: IconCmp, color } = TYPE_META[type]
|
||||
const svg = renderIconMarkup(createElement(IconCmp, { size: 13, color: 'white', strokeWidth: 2.5 }))
|
||||
const labelHtml = label ? `<span style="display:inline-flex;align-items:center;line-height:1">${escapeHtml(label)}</span>` : ''
|
||||
const estWidth = label ? Math.max(40, label.length * 6 + 28) : 26
|
||||
const { icon: IconCmp, color } = TYPE_META[type];
|
||||
const svg = renderIconMarkup(createElement(IconCmp, { size: 13, color: 'white', strokeWidth: 2.5 }));
|
||||
const labelHtml = label
|
||||
? `<span style="display:inline-flex;align-items:center;line-height:1">${escapeHtml(label)}</span>`
|
||||
: '';
|
||||
const estWidth = label ? Math.max(40, label.length * 6 + 28) : 26;
|
||||
return L.divIcon({
|
||||
className: 'trek-endpoint-marker',
|
||||
html: `<div style="
|
||||
@@ -63,180 +88,221 @@ function endpointIcon(type: TransportType, label: string | null): L.DivIcon {
|
||||
iconSize: [estWidth, 22],
|
||||
iconAnchor: [estWidth / 2, 11],
|
||||
popupAnchor: [0, -11],
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
function toRad(d: number) { return d * Math.PI / 180 }
|
||||
function toRad(d: number) {
|
||||
return (d * Math.PI) / 180;
|
||||
}
|
||||
|
||||
function haversineKm(a: [number, number], b: [number, number]): number {
|
||||
const R = 6371
|
||||
const dLat = toRad(b[0] - a[0])
|
||||
const dLng = toRad(b[1] - a[1])
|
||||
const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2
|
||||
return 2 * R * Math.asin(Math.sqrt(h))
|
||||
const R = 6371;
|
||||
const dLat = toRad(b[0] - a[0]);
|
||||
const dLng = toRad(b[1] - a[1]);
|
||||
const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2;
|
||||
return 2 * R * Math.asin(Math.sqrt(h));
|
||||
}
|
||||
|
||||
function parseInTz(isoLocal: string, tz: string): number {
|
||||
const [datePart, timePart] = isoLocal.split('T')
|
||||
const [y, mo, d] = datePart.split('-').map(Number)
|
||||
const [h, mi] = (timePart || '00:00').split(':').map(Number)
|
||||
const guess = Date.UTC(y, mo - 1, d, h, mi)
|
||||
const [datePart, timePart] = isoLocal.split('T');
|
||||
const [y, mo, d] = datePart.split('-').map(Number);
|
||||
const [h, mi] = (timePart || '00:00').split(':').map(Number);
|
||||
const guess = Date.UTC(y, mo - 1, d, h, mi);
|
||||
// A malformed date/time (e.g. an imported booking whose time is missing its
|
||||
// minutes) makes Date.UTC NaN; bail before formatToParts, which throws on a
|
||||
// non-finite date and would blank the whole trip. computeDuration's finiteness
|
||||
// check then drops the duration cleanly.
|
||||
if (!Number.isFinite(guess)) return Number.NaN
|
||||
if (!Number.isFinite(guess)) return Number.NaN;
|
||||
const fmt = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: tz, hour12: false,
|
||||
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
||||
})
|
||||
const parts = Object.fromEntries(fmt.formatToParts(new Date(guess)).filter(p => p.type !== 'literal').map(p => [p.type, p.value]))
|
||||
const asUtc = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour) % 24, Number(parts.minute), Number(parts.second))
|
||||
return guess - (asUtc - guess)
|
||||
timeZone: tz,
|
||||
hour12: false,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
const parts = Object.fromEntries(
|
||||
fmt
|
||||
.formatToParts(new Date(guess))
|
||||
.filter((p) => p.type !== 'literal')
|
||||
.map((p) => [p.type, p.value])
|
||||
);
|
||||
const asUtc = Date.UTC(
|
||||
Number(parts.year),
|
||||
Number(parts.month) - 1,
|
||||
Number(parts.day),
|
||||
Number(parts.hour) % 24,
|
||||
Number(parts.minute),
|
||||
Number(parts.second)
|
||||
);
|
||||
return guess - (asUtc - guess);
|
||||
}
|
||||
|
||||
function computeDuration(from: ReservationEndpoint, to: ReservationEndpoint, fallbackStart: string | null, fallbackEnd: string | null): string | null {
|
||||
let start = from.local_date && from.local_time ? `${from.local_date}T${from.local_time}` : fallbackStart
|
||||
let end = to.local_date && to.local_time ? `${to.local_date}T${to.local_time}` : fallbackEnd
|
||||
if (!start || !end) return null
|
||||
function computeDuration(
|
||||
from: ReservationEndpoint,
|
||||
to: ReservationEndpoint,
|
||||
fallbackStart: string | null,
|
||||
fallbackEnd: string | null
|
||||
): string | null {
|
||||
let start = from.local_date && from.local_time ? `${from.local_date}T${from.local_time}` : fallbackStart;
|
||||
let end = to.local_date && to.local_time ? `${to.local_date}T${to.local_time}` : fallbackEnd;
|
||||
if (!start || !end) return null;
|
||||
|
||||
if (!start.includes('T') && end.includes('T')) start = `${end.split('T')[0]}T${start}`
|
||||
if (!end.includes('T') && start.includes('T')) end = `${start.split('T')[0]}T${end}`
|
||||
if (!start.includes('T') || !end.includes('T')) return null
|
||||
if (!start.includes('T') && end.includes('T')) start = `${end.split('T')[0]}T${start}`;
|
||||
if (!end.includes('T') && start.includes('T')) end = `${start.split('T')[0]}T${end}`;
|
||||
if (!start.includes('T') || !end.includes('T')) return null;
|
||||
|
||||
const fromTz = from.timezone || to.timezone
|
||||
const toTz = to.timezone || fromTz
|
||||
const fromTz = from.timezone || to.timezone;
|
||||
const toTz = to.timezone || fromTz;
|
||||
|
||||
let startMs: number, endMs: number
|
||||
let startMs: number, endMs: number;
|
||||
if (fromTz && toTz) {
|
||||
startMs = parseInTz(start, fromTz)
|
||||
endMs = parseInTz(end, toTz)
|
||||
startMs = parseInTz(start, fromTz);
|
||||
endMs = parseInTz(end, toTz);
|
||||
} else {
|
||||
startMs = new Date(start).getTime()
|
||||
endMs = new Date(end).getTime()
|
||||
startMs = new Date(start).getTime();
|
||||
endMs = new Date(end).getTime();
|
||||
}
|
||||
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null
|
||||
if (endMs <= startMs) endMs += 24 * 60 * 60000
|
||||
const minutes = Math.round((endMs - startMs) / 60000)
|
||||
if (minutes <= 0 || minutes > 48 * 60) return null
|
||||
const h = Math.floor(minutes / 60)
|
||||
const m = minutes % 60
|
||||
return h > 0 ? `${h}h ${m}m` : `${m}m`
|
||||
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null;
|
||||
if (endMs <= startMs) endMs += 24 * 60 * 60000;
|
||||
const minutes = Math.round((endMs - startMs) / 60000);
|
||||
if (minutes <= 0 || minutes > 48 * 60) return null;
|
||||
const h = Math.floor(minutes / 60);
|
||||
const m = minutes % 60;
|
||||
return h > 0 ? `${h}h ${m}m` : `${m}m`;
|
||||
}
|
||||
|
||||
/** What a hop will draw: the road it was routed along when there is one, else its arcs. */
|
||||
function linesFor(item: TransportItem, roadRoutes: Map<number, [number, number][]> | undefined): [number, number][][] {
|
||||
const road = roadRoutes?.get(item.res.id)
|
||||
return road && road.length >= 2 ? [road] : item.arcs
|
||||
const road = roadRoutes?.get(item.res.id);
|
||||
return road && road.length >= 2 ? [road] : item.arcs;
|
||||
}
|
||||
|
||||
interface TransportItem {
|
||||
res: Reservation
|
||||
from: ReservationEndpoint
|
||||
to: ReservationEndpoint
|
||||
waypoints: ReservationEndpoint[]
|
||||
type: TransportType
|
||||
arcs: [number, number][][]
|
||||
transitSegs: TransitMapSegment[]
|
||||
res: Reservation;
|
||||
from: ReservationEndpoint;
|
||||
to: ReservationEndpoint;
|
||||
waypoints: ReservationEndpoint[];
|
||||
type: TransportType;
|
||||
arcs: [number, number][][];
|
||||
transitSegs: TransitMapSegment[];
|
||||
// Route ("VIE → LHR") and duration/distance line. Computed on every update but
|
||||
// not drawn since the stats badge was dropped; computeDuration still guards the
|
||||
// non-finite date that used to blank the trip (#1620).
|
||||
mainLabel: string | null
|
||||
subLabel: string | null
|
||||
mainLabel: string | null;
|
||||
subLabel: string | null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
reservations: Reservation[]
|
||||
showConnections: boolean
|
||||
reservations: Reservation[];
|
||||
showConnections: boolean;
|
||||
// Accepted for call-site compatibility only: the floating route/duration badge
|
||||
// on the arc is no longer drawn, so nothing is gated on this.
|
||||
showStats: boolean
|
||||
onEndpointClick?: (reservationId: number) => void
|
||||
showStats: boolean;
|
||||
onEndpointClick?: (reservationId: number) => void;
|
||||
// Real road-network geometry for car/bus/taxi/bicycle bookings, keyed by
|
||||
// reservation id. When present it is drawn instead of the straight arc.
|
||||
roadRoutes?: Map<number, [number, number][]>
|
||||
roadRoutes?: Map<number, [number, number][]>;
|
||||
}
|
||||
|
||||
export default function ReservationOverlay({ reservations, showConnections, onEndpointClick, roadRoutes }: Props) {
|
||||
useEndpointPane()
|
||||
const map = useMap()
|
||||
const [zoom, setZoom] = useState(() => map.getZoom())
|
||||
useEndpointPane();
|
||||
const map = useMap();
|
||||
const [zoom, setZoom] = useState(() => map.getZoom());
|
||||
useMapEvents({
|
||||
zoomend: () => setZoom(map.getZoom()),
|
||||
})
|
||||
const showEndpointLabels = useSettingsStore(s => s.settings.map_booking_labels) === true
|
||||
});
|
||||
const showEndpointLabels = useSettingsStore((s) => s.settings.map_booking_labels) === true;
|
||||
|
||||
const items = useMemo<TransportItem[]>(() => {
|
||||
const out: TransportItem[] = []
|
||||
const out: TransportItem[] = [];
|
||||
for (const r of reservations) {
|
||||
if (!TRANSPORT_TYPES.includes(r.type as TransportType)) continue
|
||||
if (!TRANSPORT_TYPES.includes(r.type as TransportType)) continue;
|
||||
// Ordered waypoints (from · stops · to). A single-leg booking has exactly two,
|
||||
// so the arc + markers below are byte-identical to before for it.
|
||||
const waypoints = (r.endpoints || [])
|
||||
.filter(e => e.role === 'from' || e.role === 'to' || e.role === 'stop')
|
||||
.filter((e) => e.role === 'from' || e.role === 'to' || e.role === 'stop')
|
||||
.slice()
|
||||
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
if (waypoints.length < 2) continue
|
||||
const from = waypoints[0]
|
||||
const to = waypoints[waypoints.length - 1]
|
||||
const type = r.type as TransportType
|
||||
const isGeo = TYPE_META[type].geodesic
|
||||
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
|
||||
if (waypoints.length < 2) continue;
|
||||
const from = waypoints[0];
|
||||
const to = waypoints[waypoints.length - 1];
|
||||
const type = r.type as TransportType;
|
||||
const isGeo = TYPE_META[type].geodesic;
|
||||
// One arc per leg (between consecutive waypoints), concatenated.
|
||||
const arcs: [number, number][][] = []
|
||||
let distanceKm = 0
|
||||
const arcs: [number, number][][] = [];
|
||||
let distanceKm = 0;
|
||||
for (let i = 0; i < waypoints.length - 1; i++) {
|
||||
const a = waypoints[i]
|
||||
const b = waypoints[i + 1]
|
||||
const a = waypoints[i];
|
||||
const b = waypoints[i + 1];
|
||||
const segArcs = isGeo
|
||||
? geodesicArcs([a.lat, a.lng], [b.lat, b.lng], true)
|
||||
: [[[a.lat, a.lng], [b.lat, b.lng]] as [number, number][]]
|
||||
arcs.push(...segArcs)
|
||||
distanceKm += haversineKm([a.lat, a.lng], [b.lat, b.lng])
|
||||
: [
|
||||
[
|
||||
[a.lat, a.lng],
|
||||
[b.lat, b.lng],
|
||||
] as [number, number][],
|
||||
];
|
||||
arcs.push(...segArcs);
|
||||
distanceKm += haversineKm([a.lat, a.lng], [b.lat, b.lng]);
|
||||
}
|
||||
const duration = computeDuration(from, to, r.reservation_time || null, r.reservation_end_time || null)
|
||||
const distance = `${Math.round(distanceKm)} km`
|
||||
const duration = computeDuration(from, to, r.reservation_time || null, r.reservation_end_time || null);
|
||||
const distance = `${Math.round(distanceKm)} km`;
|
||||
// Show the full route (FRA → BER → HND) when every waypoint has a code.
|
||||
const mainLabel = waypoints.every(w => w.code)
|
||||
? waypoints.map(w => w.code).join(' → ')
|
||||
: (from.code && to.code ? `${from.code} → ${to.code}` : null)
|
||||
const subParts = [duration, distance].filter(Boolean) as string[]
|
||||
const subLabel = subParts.length > 0 ? subParts.join(' · ') : null
|
||||
const mainLabel = waypoints.every((w) => w.code)
|
||||
? waypoints.map((w) => w.code).join(' → ')
|
||||
: from.code && to.code
|
||||
? `${from.code} → ${to.code}`
|
||||
: null;
|
||||
const subParts = [duration, distance].filter(Boolean) as string[];
|
||||
const subLabel = subParts.length > 0 ? subParts.join(' · ') : null;
|
||||
|
||||
out.push({ res: r, from, to, waypoints, type, arcs, transitSegs: type === 'transit' ? getTransitMapSegments(r) : [], mainLabel, subLabel })
|
||||
out.push({
|
||||
res: r,
|
||||
from,
|
||||
to,
|
||||
waypoints,
|
||||
type,
|
||||
arcs,
|
||||
transitSegs: type === 'transit' ? getTransitMapSegments(r) : [],
|
||||
mainLabel,
|
||||
subLabel,
|
||||
});
|
||||
}
|
||||
return out
|
||||
}, [reservations])
|
||||
return out;
|
||||
}, [reservations]);
|
||||
|
||||
const visibleItems = useMemo(() => {
|
||||
const project = (p: readonly [number, number]) => map.latLngToContainerPoint([p[0], p[1]])
|
||||
return items.filter(item => {
|
||||
const project = (p: readonly [number, number]) => map.latLngToContainerPoint([p[0], p[1]]);
|
||||
return items.filter((item) => {
|
||||
// A transit journey draws its real rail/bus alignment, not a straight from->to
|
||||
// line, so the endpoint-proximity declutter (which exists to hide tiny no-op
|
||||
// straight connectors) must not suppress it. Otherwise a zoomed-out day — e.g. one
|
||||
// with no other places to tighten the map onto — hides the whole route (#1570).
|
||||
if (item.transitSegs.length > 0) return true
|
||||
if (item.transitSegs.length > 0) return true;
|
||||
// Measured along what is drawn, not between the ends: a routed drive can
|
||||
// cover half the screen while its endpoints sit close together (#2275).
|
||||
return hopIsVisible(item.type, linesFor(item, roadRoutes), project)
|
||||
})
|
||||
}, [items, zoom, map, roadRoutes])
|
||||
return hopIsVisible(item.type, linesFor(item, roadRoutes), project);
|
||||
});
|
||||
}, [items, zoom, map, roadRoutes]);
|
||||
|
||||
const labelVisibleIds = useMemo(() => {
|
||||
const set = new Set<number>()
|
||||
const set = new Set<number>();
|
||||
for (const item of visibleItems) {
|
||||
const fromPx = map.latLngToContainerPoint([item.from.lat, item.from.lng])
|
||||
const toPx = map.latLngToContainerPoint([item.to.lat, item.to.lng])
|
||||
if (fromPx.distanceTo(toPx) >= labelFloorPx(item.type)) set.add(item.res.id)
|
||||
const fromPx = map.latLngToContainerPoint([item.from.lat, item.from.lng]);
|
||||
const toPx = map.latLngToContainerPoint([item.to.lat, item.to.lng]);
|
||||
if (fromPx.distanceTo(toPx) >= labelFloorPx(item.type)) set.add(item.res.id);
|
||||
}
|
||||
return set
|
||||
}, [visibleItems, zoom, map])
|
||||
return set;
|
||||
}, [visibleItems, zoom, map]);
|
||||
|
||||
if (!showConnections) return null
|
||||
if (!showConnections) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{visibleItems.map(item => {
|
||||
{visibleItems.map((item) => {
|
||||
if (item.transitSegs.length > 0) {
|
||||
return item.transitSegs.map((seg, segIdx) => (
|
||||
<Fragment key={`transit-${item.res.id}-${segIdx}`}>
|
||||
@@ -248,12 +314,20 @@ export default function ReservationOverlay({ reservations, showConnections, onEn
|
||||
)}
|
||||
<Polyline
|
||||
positions={seg.coords}
|
||||
pathOptions={seg.walk
|
||||
? { color: '#64748b', weight: 3, opacity: 0.8, dashArray: '1, 7', lineCap: 'round' }
|
||||
: { color: seg.color || TYPE_META.transit.color, weight: 3.5, opacity: 0.95, lineCap: 'round', lineJoin: 'round' }}
|
||||
pathOptions={
|
||||
seg.walk
|
||||
? { color: '#64748b', weight: 3, opacity: 0.8, dashArray: '1, 7', lineCap: 'round' }
|
||||
: {
|
||||
color: seg.color || TYPE_META.transit.color,
|
||||
weight: 3.5,
|
||||
opacity: 0.95,
|
||||
lineCap: 'round',
|
||||
lineJoin: 'round',
|
||||
}
|
||||
}
|
||||
/>
|
||||
</Fragment>
|
||||
))
|
||||
));
|
||||
}
|
||||
// Prefer the real road route (car/bus/taxi/bicycle) over the straight arc.
|
||||
return linesFor(item, roadRoutes).map((seg, segIdx) => (
|
||||
@@ -267,24 +341,33 @@ export default function ReservationOverlay({ reservations, showConnections, onEn
|
||||
dashArray: item.res.status === 'confirmed' ? undefined : '6, 6',
|
||||
}}
|
||||
/>
|
||||
))
|
||||
));
|
||||
})}
|
||||
|
||||
{visibleItems.flatMap(item => item.waypoints.map((wp, wi) => (
|
||||
<Marker
|
||||
key={`wp-${item.res.id}-${wi}`}
|
||||
position={[wp.lat, wp.lng]}
|
||||
icon={endpointIcon(item.type, showEndpointLabels && labelVisibleIds.has(item.res.id) ? (wp.code || cleanEndpointName(wp.name)) : null)}
|
||||
pane={ENDPOINT_PANE}
|
||||
zIndexOffset={1000}
|
||||
eventHandlers={{ click: () => onEndpointClick?.(item.res.id) }}
|
||||
>
|
||||
<Tooltip direction="top" offset={[0, -8]} opacity={1} className="map-tooltip">
|
||||
<div style={{ fontWeight: 600, fontSize: 12 }}>{wp.name}</div>
|
||||
{item.res.title && <div className="text-content-muted" style={{ fontSize: 11 }}>{item.res.title}</div>}
|
||||
</Tooltip>
|
||||
</Marker>
|
||||
)))}
|
||||
{visibleItems.flatMap((item) =>
|
||||
item.waypoints.map((wp, wi) => (
|
||||
<Marker
|
||||
key={`wp-${item.res.id}-${wi}`}
|
||||
position={[wp.lat, wp.lng]}
|
||||
icon={endpointIcon(
|
||||
item.type,
|
||||
showEndpointLabels && labelVisibleIds.has(item.res.id) ? wp.code || cleanEndpointName(wp.name) : null
|
||||
)}
|
||||
pane={ENDPOINT_PANE}
|
||||
zIndexOffset={1000}
|
||||
eventHandlers={{ click: () => onEndpointClick?.(item.res.id) }}
|
||||
>
|
||||
<Tooltip direction="top" offset={[0, -8]} opacity={1} className="map-tooltip">
|
||||
<div style={{ fontWeight: 600, fontSize: 12 }}>{wp.name}</div>
|
||||
{item.res.title && (
|
||||
<div className="text-content-muted" style={{ fontSize: 11 }}>
|
||||
{item.res.title}
|
||||
</div>
|
||||
)}
|
||||
</Tooltip>
|
||||
</Marker>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Marker, Tooltip, useMap } from 'react-leaflet'
|
||||
import L from 'leaflet'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { useStableVias } from './viaMarkerState'
|
||||
import type { RoadtripVia } from '@trek/shared'
|
||||
import type { RoadtripVia } from '@trek/shared';
|
||||
import L from 'leaflet';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Marker, Tooltip, useMap } from 'react-leaflet';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import { useStableVias } from './viaMarkerState';
|
||||
|
||||
/**
|
||||
* The handles that shape a drive.
|
||||
@@ -22,31 +22,33 @@ const VIA_ICON = L.divIcon({
|
||||
"></span>`,
|
||||
iconSize: [12, 12],
|
||||
iconAnchor: [6, 6],
|
||||
})
|
||||
});
|
||||
|
||||
interface RoadtripViaMarkersProps {
|
||||
viasByDay: Record<number, RoadtripVia[]>
|
||||
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void
|
||||
onRemoveVia?: (dayId: number, id: number) => void
|
||||
viasByDay: Record<number, RoadtripVia[]>;
|
||||
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void;
|
||||
onRemoveVia?: (dayId: number, id: number) => void;
|
||||
}
|
||||
|
||||
/** Leaflet's half; the GL renderers draw their own inside `MapViewGL`. */
|
||||
/** Below this the handles are not drawn. Shared with the GL renderer's own copy. */
|
||||
const VIA_MIN_ZOOM = 9
|
||||
const VIA_MIN_ZOOM = 9;
|
||||
|
||||
export default function RoadtripViaMarkers({
|
||||
viasByDay, onMoveVia, onRemoveVia,
|
||||
viasByDay,
|
||||
onMoveVia,
|
||||
onRemoveVia,
|
||||
}: RoadtripViaMarkersProps): React.ReactElement | null {
|
||||
const { t } = useTranslation()
|
||||
const vias = useStableVias(viasByDay)
|
||||
const { t } = useTranslation();
|
||||
const vias = useStableVias(viasByDay);
|
||||
// Read through a ref so the handlers below can stay the same objects across renders.
|
||||
// Both callbacks are rebuilt on every render of the planner, and react-leaflet compares
|
||||
// its props by identity: a fresh `eventHandlers` unbinds and rebinds every listener,
|
||||
// and a fresh `position` array calls `setLatLng` on every marker. Doing either while a
|
||||
// drag is in flight is how a freshly placed via lost its first drag.
|
||||
const handlersRef = useRef({ onMoveVia, onRemoveVia })
|
||||
handlersRef.current = { onMoveVia, onRemoveVia }
|
||||
const draggable = !!onMoveVia
|
||||
const handlersRef = useRef({ onMoveVia, onRemoveVia });
|
||||
handlersRef.current = { onMoveVia, onRemoveVia };
|
||||
const draggable = !!onMoveVia;
|
||||
/**
|
||||
* Zoomed out, the handles go away.
|
||||
*
|
||||
@@ -55,33 +57,39 @@ export default function RoadtripViaMarkers({
|
||||
* aim at, and a drag there moves the route by kilometres per pixel. Below this the drive
|
||||
* is read, not shaped.
|
||||
*/
|
||||
const map = useMap()
|
||||
const [zoomedIn, setZoomedIn] = useState(() => map.getZoom() >= VIA_MIN_ZOOM)
|
||||
const map = useMap();
|
||||
const [zoomedIn, setZoomedIn] = useState(() => map.getZoom() >= VIA_MIN_ZOOM);
|
||||
useEffect(() => {
|
||||
const update = () => setZoomedIn(map.getZoom() >= VIA_MIN_ZOOM)
|
||||
update()
|
||||
map.on('zoomend', update)
|
||||
return () => { map.off('zoomend', update) }
|
||||
}, [map])
|
||||
const update = () => setZoomedIn(map.getZoom() >= VIA_MIN_ZOOM);
|
||||
update();
|
||||
map.on('zoomend', update);
|
||||
return () => {
|
||||
map.off('zoomend', update);
|
||||
};
|
||||
}, [map]);
|
||||
|
||||
const markers = useMemo(() => vias.map(via => ({
|
||||
via,
|
||||
position: [via.lat, via.lng] as [number, number],
|
||||
handlers: {
|
||||
dragend: (e: { target: { getLatLng: () => { lat: number; lng: number } } }) => {
|
||||
const at = e.target.getLatLng()
|
||||
handlersRef.current.onMoveVia?.(via.day_id, via.id, at.lat, at.lng)
|
||||
},
|
||||
// Right-click rather than a delete handle: a 12px dot has no room for one,
|
||||
// and the same gesture removes things elsewhere on the map.
|
||||
contextmenu: (e: { originalEvent: MouseEvent }) => {
|
||||
e.originalEvent.preventDefault()
|
||||
handlersRef.current.onRemoveVia?.(via.day_id, via.id)
|
||||
},
|
||||
},
|
||||
})), [vias])
|
||||
const markers = useMemo(
|
||||
() =>
|
||||
vias.map((via) => ({
|
||||
via,
|
||||
position: [via.lat, via.lng] as [number, number],
|
||||
handlers: {
|
||||
dragend: (e: { target: { getLatLng: () => { lat: number; lng: number } } }) => {
|
||||
const at = e.target.getLatLng();
|
||||
handlersRef.current.onMoveVia?.(via.day_id, via.id, at.lat, at.lng);
|
||||
},
|
||||
// Right-click rather than a delete handle: a 12px dot has no room for one,
|
||||
// and the same gesture removes things elsewhere on the map.
|
||||
contextmenu: (e: { originalEvent: MouseEvent }) => {
|
||||
e.originalEvent.preventDefault();
|
||||
handlersRef.current.onRemoveVia?.(via.day_id, via.id);
|
||||
},
|
||||
},
|
||||
})),
|
||||
[vias]
|
||||
);
|
||||
|
||||
if (!markers.length || !zoomedIn) return null
|
||||
if (!markers.length || !zoomedIn) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -100,5 +108,5 @@ export default function RoadtripViaMarkers({
|
||||
</Marker>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,125 +1,162 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { TripRouteOverviewPill, TripRouteOverviewPanel } from './TripRouteOverview'
|
||||
import type { TripRouteOverview } from './useTripRouteOverview'
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { TripRouteOverviewPanel, TripRouteOverviewPill } from './TripRouteOverview';
|
||||
import type { TripRouteOverview } from './useTripRouteOverview';
|
||||
|
||||
const overview = (over: Partial<TripRouteOverview> = {}): TripRouteOverview => ({
|
||||
days: [
|
||||
{ dayId: 1, dayNumber: 1, date: '2025-06-01', title: null, color: { line: '#0a84ff', casing: '#0a5cc2' }, lines: [], segments: [], distance: 82000, duration: 3600, modes: ['driving'] },
|
||||
{ dayId: 2, dayNumber: 2, date: '2025-06-02', title: 'Coast road', color: { line: '#ff9f0a', casing: '#c2740a' }, lines: [], segments: [], distance: 140500, duration: 7200, modes: ['driving', 'walking'] },
|
||||
{
|
||||
dayId: 1,
|
||||
dayNumber: 1,
|
||||
date: '2025-06-01',
|
||||
title: null,
|
||||
color: { line: '#0a84ff', casing: '#0a5cc2' },
|
||||
lines: [],
|
||||
segments: [],
|
||||
distance: 82000,
|
||||
duration: 3600,
|
||||
modes: ['driving'],
|
||||
},
|
||||
{
|
||||
dayId: 2,
|
||||
dayNumber: 2,
|
||||
date: '2025-06-02',
|
||||
title: 'Coast road',
|
||||
color: { line: '#ff9f0a', casing: '#c2740a' },
|
||||
lines: [],
|
||||
segments: [],
|
||||
distance: 140500,
|
||||
duration: 7200,
|
||||
modes: ['driving', 'walking'],
|
||||
},
|
||||
],
|
||||
lines: [], lineColors: [], segments: [], focusPoints: [],
|
||||
totalDistance: 222500, totalDuration: 10800, loading: false,
|
||||
lines: [],
|
||||
lineColors: [],
|
||||
segments: [],
|
||||
focusPoints: [],
|
||||
totalDistance: 222500,
|
||||
totalDuration: 10800,
|
||||
loading: false,
|
||||
...over,
|
||||
})
|
||||
});
|
||||
|
||||
describe('TripRouteOverviewPill', () => {
|
||||
it('FE-MAP-TROU-001: says which way it will take you, and reports its state', () => {
|
||||
const onToggle = vi.fn()
|
||||
const { rerender } = render(<TripRouteOverviewPill active={false} onToggle={onToggle} />)
|
||||
const onToggle = vi.fn();
|
||||
const { rerender } = render(<TripRouteOverviewPill active={false} onToggle={onToggle} />);
|
||||
|
||||
const button = screen.getByTestId('trip-overview-pill')
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false')
|
||||
expect(button).toHaveAttribute('aria-label', 'map.overview.show')
|
||||
const button = screen.getByTestId('trip-overview-pill');
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(button).toHaveAttribute('aria-label', 'map.overview.show');
|
||||
|
||||
fireEvent.click(button)
|
||||
expect(onToggle).toHaveBeenCalledTimes(1)
|
||||
fireEvent.click(button);
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(<TripRouteOverviewPill active onToggle={onToggle} />)
|
||||
expect(screen.getByTestId('trip-overview-pill')).toHaveAttribute('aria-label', 'map.overview.hide')
|
||||
})
|
||||
})
|
||||
rerender(<TripRouteOverviewPill active onToggle={onToggle} />);
|
||||
expect(screen.getByTestId('trip-overview-pill')).toHaveAttribute('aria-label', 'map.overview.hide');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TripRouteOverviewPanel', () => {
|
||||
it('FE-MAP-TROU-002: leads with the trip total in the reader\'s own unit', () => {
|
||||
const { rerender } = render(<TripRouteOverviewPanel overview={overview()} unit="metric" />)
|
||||
expect(screen.getByText('222.5 km')).toBeInTheDocument()
|
||||
it("FE-MAP-TROU-002: leads with the trip total in the reader's own unit", () => {
|
||||
const { rerender } = render(<TripRouteOverviewPanel overview={overview()} unit="metric" />);
|
||||
expect(screen.getByText('222.5 km')).toBeInTheDocument();
|
||||
|
||||
rerender(<TripRouteOverviewPanel overview={overview()} unit="imperial" />)
|
||||
expect(screen.getByText('138.3 mi')).toBeInTheDocument()
|
||||
})
|
||||
rerender(<TripRouteOverviewPanel overview={overview()} unit="imperial" />);
|
||||
expect(screen.getByText('138.3 mi')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-003: names every day, its distance and how it is travelled', () => {
|
||||
render(<TripRouteOverviewPanel overview={overview()} unit="metric" />)
|
||||
render(<TripRouteOverviewPanel overview={overview()} unit="metric" />);
|
||||
|
||||
expect(screen.getByText('dayplan.dayN')).toBeInTheDocument()
|
||||
expect(screen.getByText('dayplan.dayN')).toBeInTheDocument();
|
||||
// A day with a title is named by it rather than by its number.
|
||||
expect(screen.getByText('Coast road')).toBeInTheDocument()
|
||||
expect(screen.getByText('82 km')).toBeInTheDocument()
|
||||
expect(screen.getByText('140.5 km')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText('Coast road')).toBeInTheDocument();
|
||||
expect(screen.getByText('82 km')).toBeInTheDocument();
|
||||
expect(screen.getByText('140.5 km')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-004: marks the total as partial while legs are still coming in', () => {
|
||||
const { container, rerender } = render(<TripRouteOverviewPanel overview={overview({ loading: true })} unit="metric" />)
|
||||
expect(container.textContent).toContain('…')
|
||||
const { container, rerender } = render(
|
||||
<TripRouteOverviewPanel overview={overview({ loading: true })} unit="metric" />
|
||||
);
|
||||
expect(container.textContent).toContain('…');
|
||||
|
||||
rerender(<TripRouteOverviewPanel overview={overview()} unit="metric" />)
|
||||
expect(container.textContent).not.toContain('…')
|
||||
})
|
||||
rerender(<TripRouteOverviewPanel overview={overview()} unit="metric" />);
|
||||
expect(container.textContent).not.toContain('…');
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-005: a day row picks that day when the shell offers it', () => {
|
||||
const onSelectDay = vi.fn()
|
||||
render(<TripRouteOverviewPanel overview={overview()} unit="metric" selectedDayId={2} onSelectDay={onSelectDay} />)
|
||||
const onSelectDay = vi.fn();
|
||||
render(<TripRouteOverviewPanel overview={overview()} unit="metric" selectedDayId={2} onSelectDay={onSelectDay} />);
|
||||
|
||||
fireEvent.click(screen.getByText('Coast road'))
|
||||
expect(onSelectDay).toHaveBeenCalledWith(2)
|
||||
})
|
||||
fireEvent.click(screen.getByText('Coast road'));
|
||||
expect(onSelectDay).toHaveBeenCalledWith(2);
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-006: read-only shells get rows, not buttons', () => {
|
||||
render(<TripRouteOverviewPanel overview={overview()} unit="metric" />)
|
||||
expect(screen.queryAllByRole('button')).toHaveLength(0)
|
||||
})
|
||||
render(<TripRouteOverviewPanel overview={overview()} unit="metric" />);
|
||||
expect(screen.queryAllByRole('button')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-008: hugs its rows, and takes the cap the shell gives it', () => {
|
||||
const { container, rerender } = render(<TripRouteOverviewPanel overview={overview()} unit="metric" />)
|
||||
const card = () => screen.getByTestId('trip-overview-panel')
|
||||
const { container, rerender } = render(<TripRouteOverviewPanel overview={overview()} unit="metric" />);
|
||||
const card = () => screen.getByTestId('trip-overview-panel');
|
||||
|
||||
expect(card().style.width).toBe('fit-content')
|
||||
expect(card().style.maxWidth).toBe('320px')
|
||||
expect(card().style.width).toBe('fit-content');
|
||||
expect(card().style.maxWidth).toBe('320px');
|
||||
|
||||
// The phone shell asks for a narrower card so the map keeps the space.
|
||||
rerender(<TripRouteOverviewPanel overview={overview()} unit="metric" maxWidth={240} />)
|
||||
expect(card().style.maxWidth).toBe('240px')
|
||||
expect(container).not.toBeEmptyDOMElement()
|
||||
})
|
||||
rerender(<TripRouteOverviewPanel overview={overview()} unit="metric" maxWidth={240} />);
|
||||
expect(card().style.maxWidth).toBe('240px');
|
||||
expect(container).not.toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-007: draws nothing at all for a trip with no routed day', () => {
|
||||
const { container } = render(<TripRouteOverviewPanel overview={overview({ days: [], totalDistance: 0 })} unit="metric" />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
const { container } = render(
|
||||
<TripRouteOverviewPanel overview={overview({ days: [], totalDistance: 0 })} unit="metric" />
|
||||
);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-009: says when legs could not be routed, and marks the day that is short', () => {
|
||||
// A refused leg stays a straight line and adds nothing to the sum, so a total shown
|
||||
// without a word about it reads as the whole trip when it is not.
|
||||
const days = overview().days
|
||||
const days = overview().days;
|
||||
const short = overview({
|
||||
days: [{ ...days[0], unroutedLegs: 1 }, { ...days[1], unroutedLegs: 0 }],
|
||||
days: [
|
||||
{ ...days[0], unroutedLegs: 1 },
|
||||
{ ...days[1], unroutedLegs: 0 },
|
||||
],
|
||||
unroutedLegs: 1,
|
||||
})
|
||||
render(<TripRouteOverviewPanel overview={short} unit="metric" />)
|
||||
});
|
||||
render(<TripRouteOverviewPanel overview={short} unit="metric" />);
|
||||
|
||||
expect(screen.getByTestId('trip-overview-unrouted')).toHaveTextContent('map.overview.unrouted')
|
||||
expect(screen.getAllByRole('img', { name: 'map.overview.dayUnrouted' })).toHaveLength(1)
|
||||
})
|
||||
expect(screen.getByTestId('trip-overview-unrouted')).toHaveTextContent('map.overview.unrouted');
|
||||
expect(screen.getAllByRole('img', { name: 'map.overview.dayUnrouted' })).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-010: does not call a leg unrouted while the round is still running', () => {
|
||||
// Every leg still waiting is unrouted too; the ellipsis already says the number grows.
|
||||
const days = overview().days
|
||||
const days = overview().days;
|
||||
const running = overview({
|
||||
days: [{ ...days[0], unroutedLegs: 1 }, { ...days[1], unroutedLegs: 1 }],
|
||||
days: [
|
||||
{ ...days[0], unroutedLegs: 1 },
|
||||
{ ...days[1], unroutedLegs: 1 },
|
||||
],
|
||||
unroutedLegs: 2,
|
||||
loading: true,
|
||||
})
|
||||
render(<TripRouteOverviewPanel overview={running} unit="metric" />)
|
||||
});
|
||||
render(<TripRouteOverviewPanel overview={running} unit="metric" />);
|
||||
|
||||
expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull()
|
||||
expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull()
|
||||
})
|
||||
expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull();
|
||||
expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MAP-TROU-011: a fully routed trip carries no warning at all', () => {
|
||||
render(<TripRouteOverviewPanel overview={overview({ unroutedLegs: 0 })} unit="metric" />)
|
||||
render(<TripRouteOverviewPanel overview={overview({ unroutedLegs: 0 })} unit="metric" />);
|
||||
|
||||
expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull()
|
||||
expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull()
|
||||
})
|
||||
})
|
||||
expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull();
|
||||
expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { AlertTriangle, Route } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { MapTogglePill } from './MapTogglePill'
|
||||
import { routeModeIcon } from '../Planner/routeModes'
|
||||
import { formatDistance } from '../../utils/units'
|
||||
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
|
||||
import type { DistanceUnit } from '../../types'
|
||||
import { AlertTriangle, Route } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import type { DistanceUnit } from '../../types';
|
||||
import { formatDistance } from '../../utils/units';
|
||||
import { routeModeIcon } from '../Planner/routeModes';
|
||||
import { MapTogglePill } from './MapTogglePill';
|
||||
import type { TripRouteOverview as Overview } from './useTripRouteOverview';
|
||||
|
||||
/**
|
||||
* Toggle for the whole-trip route overview (#1736). Same frosted shell as the other
|
||||
* map controls, so it lines up with the compass and the layer switcher.
|
||||
*/
|
||||
export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; onToggle: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<MapTogglePill
|
||||
active={active}
|
||||
@@ -20,7 +20,7 @@ export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; o
|
||||
testId="trip-overview-pill"
|
||||
icon={<Route size={17} strokeWidth={2} />}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,25 +29,33 @@ export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; o
|
||||
* One component for both shells: the phone and the desktop place it differently but the
|
||||
* rows are the same rows, and a second copy of them is a second thing to keep in step.
|
||||
*/
|
||||
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = 320 }: {
|
||||
overview: Overview
|
||||
unit: DistanceUnit
|
||||
selectedDayId?: number | null
|
||||
onSelectDay?: (dayId: number) => void
|
||||
export function TripRouteOverviewPanel({
|
||||
overview,
|
||||
unit,
|
||||
selectedDayId,
|
||||
onSelectDay,
|
||||
maxWidth = 320,
|
||||
}: {
|
||||
overview: Overview;
|
||||
unit: DistanceUnit;
|
||||
selectedDayId?: number | null;
|
||||
onSelectDay?: (dayId: number) => void;
|
||||
/** How wide the card may grow before day names start to ellipsize. */
|
||||
maxWidth?: number
|
||||
maxWidth?: number;
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
if (!overview.days.length) return null
|
||||
const { t } = useTranslation();
|
||||
if (!overview.days.length) return null;
|
||||
// Only once the round is over: while it runs every leg still waiting is unrouted too,
|
||||
// and the ellipsis on the total already says the number is growing.
|
||||
const unrouted = overview.loading ? 0 : (overview.unroutedLegs ?? 0)
|
||||
const unrouted = overview.loading ? 0 : (overview.unroutedLegs ?? 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="trip-overview-panel"
|
||||
style={{
|
||||
pointerEvents: 'auto', borderRadius: 14, overflow: 'hidden',
|
||||
pointerEvents: 'auto',
|
||||
borderRadius: 14,
|
||||
overflow: 'hidden',
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
@@ -55,11 +63,27 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
// Sized to its rows rather than to the space available: a trip of short day
|
||||
// names left a band of empty card over the map, which on a phone is most of
|
||||
// what there is to look at.
|
||||
width: 'fit-content', maxWidth,
|
||||
width: 'fit-content',
|
||||
maxWidth,
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, padding: '10px 14px 8px' }}>
|
||||
<span className="text-content-muted" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: 0.4 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'baseline',
|
||||
justifyContent: 'space-between',
|
||||
gap: 12,
|
||||
padding: '10px 14px 8px',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className="text-content-muted"
|
||||
style={{
|
||||
fontSize: 'calc(11px * var(--fs-scale-caption, 1))',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: 0.4,
|
||||
}}
|
||||
>
|
||||
{t('map.overview.total')}
|
||||
</span>
|
||||
{/* Same tier as the label beside it: the two read as one line rather than as a
|
||||
@@ -68,7 +92,12 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
{formatDistance(overview.totalDistance / 1000, unit)}
|
||||
{/* Still routing: the number is a partial sum, and saying so beats a total
|
||||
that silently grows while you read it. */}
|
||||
{overview.loading && <span className="text-content-muted" style={{ fontWeight: 400 }}>{' '}…</span>}
|
||||
{overview.loading && (
|
||||
<span className="text-content-muted" style={{ fontWeight: 400 }}>
|
||||
{' '}
|
||||
…
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{/* A leg the router refused stays a straight line and adds nothing to the sum, so
|
||||
@@ -78,26 +107,41 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
<div
|
||||
data-testid="trip-overview-unrouted"
|
||||
className="text-warning"
|
||||
style={{ display: 'flex', alignItems: 'flex-start', gap: 6, padding: '0 14px 8px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: 6,
|
||||
padding: '0 14px 8px',
|
||||
fontSize: 'calc(11px * var(--fs-scale-caption, 1))',
|
||||
}}
|
||||
>
|
||||
<AlertTriangle size={12} style={{ flexShrink: 0, marginTop: 1 }} aria-hidden />
|
||||
<span>{t('map.overview.unrouted', { count: unrouted })}</span>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ maxHeight: 220, overflowY: 'auto', borderTop: '1px solid var(--border-primary)' }}>
|
||||
{overview.days.map(day => {
|
||||
const label = day.title || t('dayplan.dayN', { n: day.dayNumber })
|
||||
const dayUnrouted = overview.loading ? 0 : (day.unroutedLegs ?? 0)
|
||||
{overview.days.map((day) => {
|
||||
const label = day.title || t('dayplan.dayN', { n: day.dayNumber });
|
||||
const dayUnrouted = overview.loading ? 0 : (day.unroutedLegs ?? 0);
|
||||
const row = (
|
||||
<>
|
||||
<span style={{ width: 8, height: 8, borderRadius: 999, background: day.color.line, flexShrink: 0 }} aria-hidden />
|
||||
<span className="text-content" style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
<span
|
||||
style={{ width: 8, height: 8, borderRadius: 999, background: day.color.line, flexShrink: 0 }}
|
||||
aria-hidden
|
||||
/>
|
||||
<span
|
||||
className="text-content"
|
||||
style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, flexShrink: 0 }} className="text-content-muted">
|
||||
{day.modes.map(mode => {
|
||||
const Icon = routeModeIcon(mode)
|
||||
return <Icon key={mode} size={12} strokeWidth={2} aria-hidden />
|
||||
<span
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 3, flexShrink: 0 }}
|
||||
className="text-content-muted"
|
||||
>
|
||||
{day.modes.map((mode) => {
|
||||
const Icon = routeModeIcon(mode);
|
||||
return <Icon key={mode} size={12} strokeWidth={2} aria-hidden />;
|
||||
})}
|
||||
</span>
|
||||
{/* The day's own share of the shortfall, so the reader knows which figure
|
||||
@@ -115,23 +159,34 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
{formatDistance(day.distance / 1000, unit)}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
);
|
||||
const style = {
|
||||
display: 'flex', alignItems: 'center', gap: 8, width: '100%',
|
||||
padding: '7px 14px', textAlign: 'left' as const,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
width: '100%',
|
||||
padding: '7px 14px',
|
||||
textAlign: 'left' as const,
|
||||
fontSize: 'calc(12px * var(--fs-scale-body, 1))',
|
||||
background: day.dayId === selectedDayId ? 'var(--bg-hover)' : 'transparent',
|
||||
border: 'none',
|
||||
}
|
||||
};
|
||||
return onSelectDay ? (
|
||||
<button key={day.dayId} type="button" onClick={() => onSelectDay(day.dayId)} style={{ ...style, cursor: 'pointer' }}>
|
||||
<button
|
||||
key={day.dayId}
|
||||
type="button"
|
||||
onClick={() => onSelectDay(day.dayId)}
|
||||
style={{ ...style, cursor: 'pointer' }}
|
||||
>
|
||||
{row}
|
||||
</button>
|
||||
) : (
|
||||
<div key={day.dayId} style={style}>{row}</div>
|
||||
)
|
||||
<div key={day.dayId} style={style}>
|
||||
{row}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@
|
||||
* what is under test is the wiring: which style goes in, what happens on a style
|
||||
* change, and what is left behind on teardown.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { render, waitFor } from '@testing-library/react'
|
||||
import type * as L from 'leaflet'
|
||||
import { maplibreGL as bridge } from '@maplibre/maplibre-gl-leaflet'
|
||||
import { hasWebGL } from '../../utils/webgl'
|
||||
import { maplibreGL as bridge } from '@maplibre/maplibre-gl-leaflet';
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import type * as L from 'leaflet';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { OFM_ATTRIBUTION, OFM_DARK, OFM_POSITRON, RASTER_FALLBACK_TILE_URL } from '../../constants/mapDefaults';
|
||||
import { hasWebGL } from '../../utils/webgl';
|
||||
import {
|
||||
VectorBasemap,
|
||||
attachVectorBasemap,
|
||||
@@ -19,27 +20,26 @@ import {
|
||||
restyleBasemap,
|
||||
type BasemapLayer,
|
||||
type GlLeafletLayer,
|
||||
} from './VectorBasemap'
|
||||
import { OFM_POSITRON, OFM_DARK, OFM_ATTRIBUTION, RASTER_FALLBACK_TILE_URL } from '../../constants/mapDefaults'
|
||||
} from './VectorBasemap';
|
||||
|
||||
const addAttribution = vi.fn()
|
||||
const addAttribution = vi.fn();
|
||||
/** Only the two things the component touches; casting keeps the mock honest about that. */
|
||||
const asMap = (m: object) => m as unknown as L.Map
|
||||
const leafletMap = asMap({ attributionControl: { addAttribution } })
|
||||
const asMap = (m: object) => m as unknown as L.Map;
|
||||
const leafletMap = asMap({ attributionControl: { addAttribution } });
|
||||
/** A map built without an attribution control, like the atlas. */
|
||||
const bareMap = asMap({})
|
||||
const bareMap = asMap({});
|
||||
|
||||
// TileLayer as well as useMap: the component renders one when the browser has no
|
||||
// WebGL, and jsdom is exactly such a browser.
|
||||
vi.mock('react-leaflet', () => ({
|
||||
useMap: () => leafletMap,
|
||||
TileLayer: ({ url }: { url: string }) => <div data-testid="raster-basemap" data-url={url} />,
|
||||
}))
|
||||
}));
|
||||
|
||||
// jsdom has no WebGL, so without this every case below would take the raster
|
||||
// branch. The suite is about the GL wiring; the raster branch has its own cases.
|
||||
vi.mock('../../utils/webgl', () => ({ hasWebGL: vi.fn(() => true), resetWebGLProbe: vi.fn() }))
|
||||
vi.mock('./engines/maplibre', () => ({ default: { __engine: 'maplibre' } }))
|
||||
vi.mock('../../utils/webgl', () => ({ hasWebGL: vi.fn(() => true), resetWebGLProbe: vi.fn() }));
|
||||
vi.mock('./engines/maplibre', () => ({ default: { __engine: 'maplibre' } }));
|
||||
vi.mock('@maplibre/maplibre-gl-leaflet', () => {
|
||||
const maplibreGL = vi.fn(() => {
|
||||
// One GL map per layer, kept stable: a fresh object per call would hand the
|
||||
@@ -57,168 +57,168 @@ vi.mock('@maplibre/maplibre-gl-leaflet', () => {
|
||||
],
|
||||
})),
|
||||
setLayoutProperty: vi.fn(),
|
||||
}
|
||||
const layer: Record<string, unknown> = { remove: vi.fn(), getMaplibreMap: vi.fn(() => gl) }
|
||||
layer.addTo = vi.fn(() => layer)
|
||||
return layer
|
||||
})
|
||||
return { maplibreGL, default: maplibreGL }
|
||||
})
|
||||
};
|
||||
const layer: Record<string, unknown> = { remove: vi.fn(), getMaplibreMap: vi.fn(() => gl) };
|
||||
layer.addTo = vi.fn(() => layer);
|
||||
return layer;
|
||||
});
|
||||
return { maplibreGL, default: maplibreGL };
|
||||
});
|
||||
|
||||
const maplibreGL = vi.mocked(bridge as unknown as ReturnType<typeof vi.fn>)
|
||||
const maplibreGL = vi.mocked(bridge as unknown as ReturnType<typeof vi.fn>);
|
||||
|
||||
type Spy = ReturnType<typeof vi.fn>
|
||||
type Spy = ReturnType<typeof vi.fn>;
|
||||
|
||||
/** The GL map behind a mocked layer, typed as spies so assertions can reach them. */
|
||||
interface MockGl {
|
||||
setStyle: Spy
|
||||
on: Spy
|
||||
isStyleLoaded: Spy
|
||||
getStyle: Spy
|
||||
setLayoutProperty: Spy
|
||||
setStyle: Spy;
|
||||
on: Spy;
|
||||
isStyleLoaded: Spy;
|
||||
getStyle: Spy;
|
||||
setLayoutProperty: Spy;
|
||||
}
|
||||
|
||||
/** The layer the last maplibreGL() call produced, and its GL map. */
|
||||
function lastLayer(): { layer: GlLeafletLayer; gl: MockGl } {
|
||||
const results = maplibreGL.mock.results
|
||||
const raw = results[results.length - 1]!.value as { getMaplibreMap: () => MockGl }
|
||||
return { layer: raw as unknown as GlLeafletLayer, gl: raw.getMaplibreMap() }
|
||||
const results = maplibreGL.mock.results;
|
||||
const raw = results[results.length - 1]!.value as { getMaplibreMap: () => MockGl };
|
||||
return { layer: raw as unknown as GlLeafletLayer, gl: raw.getMaplibreMap() };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('VectorBasemap', () => {
|
||||
it('FE-COMP-VECBM-001: hangs the style into the map, non-interactive', async () => {
|
||||
render(<VectorBasemap style={OFM_POSITRON} />)
|
||||
render(<VectorBasemap style={OFM_POSITRON} />);
|
||||
|
||||
await waitFor(() => expect(maplibreGL).toHaveBeenCalledTimes(1))
|
||||
await waitFor(() => expect(maplibreGL).toHaveBeenCalledTimes(1));
|
||||
expect(maplibreGL.mock.calls[0]![0]).toMatchObject({
|
||||
style: OFM_POSITRON,
|
||||
// Leaflet keeps handling the gestures; a second interactive map underneath
|
||||
// would fight it for the wheel and the drag.
|
||||
interactive: false,
|
||||
attributionControl: false,
|
||||
})
|
||||
expect(lastLayer().layer.addTo).toHaveBeenCalledWith(leafletMap)
|
||||
})
|
||||
});
|
||||
expect(lastLayer().layer.addTo).toHaveBeenCalledWith(leafletMap);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-002: credits OpenFreeMap, not just OpenStreetMap', async () => {
|
||||
// The data is OSM, but the rendering and the hosting are not, and the licence
|
||||
// asks for both.
|
||||
render(<VectorBasemap style={OFM_POSITRON} />)
|
||||
await waitFor(() => expect(addAttribution).toHaveBeenCalledWith(OFM_ATTRIBUTION))
|
||||
})
|
||||
render(<VectorBasemap style={OFM_POSITRON} />);
|
||||
await waitFor(() => expect(addAttribution).toHaveBeenCalledWith(OFM_ATTRIBUTION));
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-003: a theme switch restyles in place instead of rebuilding', async () => {
|
||||
const { rerender } = render(<VectorBasemap style={OFM_POSITRON} />)
|
||||
await waitFor(() => expect(maplibreGL).toHaveBeenCalledTimes(1))
|
||||
const { gl } = lastLayer()
|
||||
const { rerender } = render(<VectorBasemap style={OFM_POSITRON} />);
|
||||
await waitFor(() => expect(maplibreGL).toHaveBeenCalledTimes(1));
|
||||
const { gl } = lastLayer();
|
||||
|
||||
rerender(<VectorBasemap style={OFM_DARK} />)
|
||||
rerender(<VectorBasemap style={OFM_DARK} />);
|
||||
|
||||
// Swapping the layer would leak a WebGL context per toggle, and browsers cap
|
||||
// those in the low teens: a dozen theme switches and the map goes blank.
|
||||
expect(gl.setStyle).toHaveBeenCalledWith(OFM_DARK)
|
||||
expect(maplibreGL).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(gl.setStyle).toHaveBeenCalledWith(OFM_DARK);
|
||||
expect(maplibreGL).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-004: takes the layer off the map on unmount', async () => {
|
||||
const { unmount } = render(<VectorBasemap style={OFM_POSITRON} />)
|
||||
await waitFor(() => expect(maplibreGL).toHaveBeenCalledTimes(1))
|
||||
const { layer } = lastLayer()
|
||||
const { unmount } = render(<VectorBasemap style={OFM_POSITRON} />);
|
||||
await waitFor(() => expect(maplibreGL).toHaveBeenCalledTimes(1));
|
||||
const { layer } = lastLayer();
|
||||
|
||||
unmount()
|
||||
expect(layer.remove).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
unmount();
|
||||
expect(layer.remove).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('attachVectorBasemap', () => {
|
||||
it('FE-COMP-VECBM-005: hands the caller the layer it attached', async () => {
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
const map = { id: 'imperative' }
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
const map = { id: 'imperative' };
|
||||
|
||||
await attachVectorBasemap(asMap(map), OFM_DARK, ref, () => false)
|
||||
await attachVectorBasemap(asMap(map), OFM_DARK, ref, () => false);
|
||||
|
||||
expect(maplibreGL.mock.calls[0]![0]).toMatchObject({ style: OFM_DARK, interactive: false })
|
||||
expect(ref.current).toBe(lastLayer().layer)
|
||||
expect(lastLayer().layer.addTo).toHaveBeenCalledWith(map)
|
||||
})
|
||||
expect(maplibreGL.mock.calls[0]![0]).toMatchObject({ style: OFM_DARK, interactive: false });
|
||||
expect(ref.current).toBe(lastLayer().layer);
|
||||
expect(lastLayer().layer.addTo).toHaveBeenCalledWith(map);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-006: a map torn down mid-load gets no layer', async () => {
|
||||
// maplibre-gl only ever arrives through a dynamic import, so there is always a
|
||||
// gap between "the map wants a basemap" and "the basemap is here". Leaving the
|
||||
// layer attached to a dead map keeps its WebGL context alive for good.
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
|
||||
await attachVectorBasemap(bareMap, OFM_DARK, ref, () => true)
|
||||
await attachVectorBasemap(bareMap, OFM_DARK, ref, () => true);
|
||||
|
||||
expect(maplibreGL).not.toHaveBeenCalled()
|
||||
expect(ref.current).toBeNull()
|
||||
})
|
||||
expect(maplibreGL).not.toHaveBeenCalled();
|
||||
expect(ref.current).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-007: credits OpenFreeMap on a map that has an attribution control', async () => {
|
||||
// The raster layer it replaces carried the credit, so dropping it silently
|
||||
// would leave the journey map crediting nobody.
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
await attachVectorBasemap(leafletMap, OFM_POSITRON, ref, () => false)
|
||||
expect(addAttribution).toHaveBeenCalledWith(OFM_ATTRIBUTION)
|
||||
})
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
await attachVectorBasemap(leafletMap, OFM_POSITRON, ref, () => false);
|
||||
expect(addAttribution).toHaveBeenCalledWith(OFM_ATTRIBUTION);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-008: stays quiet on a map built without one', async () => {
|
||||
// The atlas turns the control off on purpose; asking for it there would throw.
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
await expect(attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false)).resolves.toBeUndefined()
|
||||
expect(addAttribution).not.toHaveBeenCalled()
|
||||
})
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
await expect(attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false)).resolves.toBeUndefined();
|
||||
expect(addAttribution).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-009: hides the labels when asked to', async () => {
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
|
||||
await attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false, { hideLabels: true })
|
||||
await attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false, { hideLabels: true });
|
||||
|
||||
const { gl } = lastLayer()
|
||||
expect(gl.on).toHaveBeenCalledWith('style.load', expect.any(Function))
|
||||
})
|
||||
})
|
||||
const { gl } = lastLayer();
|
||||
expect(gl.on).toHaveBeenCalledWith('style.load', expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe('hideLabelLayers', () => {
|
||||
it('FE-COMP-VECBM-010: hides every symbol layer and nothing else', async () => {
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
await attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false)
|
||||
const { layer, gl } = lastLayer()
|
||||
gl.isStyleLoaded.mockReturnValue(true)
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
await attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false);
|
||||
const { layer, gl } = lastLayer();
|
||||
gl.isStyleLoaded.mockReturnValue(true);
|
||||
|
||||
hideLabelLayers(layer)
|
||||
hideLabelLayers(layer);
|
||||
|
||||
// The atlas draws country names into its own fills, so basemap labels repeat
|
||||
// them. Borders and coastlines are line/fill layers and have to survive.
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledWith('place-city', 'visibility', 'none')
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledWith('country-label', 'visibility', 'none')
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledWith('place-city', 'visibility', 'none');
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledWith('country-label', 'visibility', 'none');
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-011: re-hides them after every restyle', async () => {
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null }
|
||||
await attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false)
|
||||
const { layer, gl } = lastLayer()
|
||||
const ref: { current: GlLeafletLayer | null } = { current: null };
|
||||
await attachVectorBasemap(bareMap, OFM_POSITRON, ref, () => false);
|
||||
const { layer, gl } = lastLayer();
|
||||
|
||||
hideLabelLayers(layer)
|
||||
expect(gl.setLayoutProperty).not.toHaveBeenCalled() // style not loaded yet
|
||||
hideLabelLayers(layer);
|
||||
expect(gl.setLayoutProperty).not.toHaveBeenCalled(); // style not loaded yet
|
||||
|
||||
// setStyle discards the layout properties along with the old style, so the
|
||||
// theme toggle would bring the labels back without this.
|
||||
const onStyleLoad = gl.on.mock.calls.find((c: unknown[]) => c[0] === 'style.load')![1] as () => void
|
||||
onStyleLoad()
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
const onStyleLoad = gl.on.mock.calls.find((c: unknown[]) => c[0] === 'style.load')![1] as () => void;
|
||||
onStyleLoad();
|
||||
expect(gl.setLayoutProperty).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-012: does nothing when the GL map is not up yet', () => {
|
||||
const layer = { getMaplibreMap: () => undefined } as unknown as GlLeafletLayer
|
||||
expect(() => hideLabelLayers(layer)).not.toThrow()
|
||||
})
|
||||
})
|
||||
const layer = { getMaplibreMap: () => undefined } as unknown as GlLeafletLayer;
|
||||
expect(() => hideLabelLayers(layer)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A browser that will not give MapLibre a WebGL context (#2288).
|
||||
@@ -228,59 +228,59 @@ describe('hideLabelLayers', () => {
|
||||
* catch, and the layer it left behind took the page down on the way out.
|
||||
*/
|
||||
describe('VectorBasemap without WebGL', () => {
|
||||
const noWebGL = vi.mocked(hasWebGL)
|
||||
const noWebGL = vi.mocked(hasWebGL);
|
||||
|
||||
/** A map real Leaflet will accept, which the raster stand-in needs. */
|
||||
const rasterMap = () => asMap({ addLayer: vi.fn(), attributionControl: { addAttribution } })
|
||||
const rasterMap = () => asMap({ addLayer: vi.fn(), attributionControl: { addAttribution } });
|
||||
|
||||
beforeEach(() => {
|
||||
noWebGL.mockReturnValue(false)
|
||||
})
|
||||
noWebGL.mockReturnValue(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-013: draws raster tiles and never asks for the maplibre chunk', async () => {
|
||||
// Not loading it is half the point: about a megabyte for a browser that could
|
||||
// never have drawn it.
|
||||
const { findByTestId } = render(<VectorBasemap style={OFM_POSITRON} />)
|
||||
const { findByTestId } = render(<VectorBasemap style={OFM_POSITRON} />);
|
||||
|
||||
const tiles = await findByTestId('raster-basemap')
|
||||
expect(tiles.getAttribute('data-url')).toBe(RASTER_FALLBACK_TILE_URL)
|
||||
expect(maplibreGL).not.toHaveBeenCalled()
|
||||
})
|
||||
const tiles = await findByTestId('raster-basemap');
|
||||
expect(tiles.getAttribute('data-url')).toBe(RASTER_FALLBACK_TILE_URL);
|
||||
expect(maplibreGL).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-014: unmounting is quiet, with nothing to take off the map', () => {
|
||||
const { unmount } = render(<VectorBasemap style={OFM_POSITRON} />)
|
||||
const { unmount } = render(<VectorBasemap style={OFM_POSITRON} />);
|
||||
// The crash in #2288 came from teardown, not from the failed attach.
|
||||
expect(() => unmount()).not.toThrow()
|
||||
})
|
||||
expect(() => unmount()).not.toThrow();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-015: the imperative maps get the raster stand-in in their ref', async () => {
|
||||
const ref: { current: BasemapLayer | null } = { current: null }
|
||||
const map = rasterMap()
|
||||
const ref: { current: BasemapLayer | null } = { current: null };
|
||||
const map = rasterMap();
|
||||
|
||||
await attachVectorBasemap(map, OFM_POSITRON, ref, () => false)
|
||||
await attachVectorBasemap(map, OFM_POSITRON, ref, () => false);
|
||||
|
||||
expect(maplibreGL).not.toHaveBeenCalled()
|
||||
expect(ref.current).not.toBeNull()
|
||||
expect(maplibreGL).not.toHaveBeenCalled();
|
||||
expect(ref.current).not.toBeNull();
|
||||
// OpenStreetMap rather than OpenFreeMap: different tiles, different credit.
|
||||
expect(addAttribution).toHaveBeenCalledWith(expect.stringContaining('openstreetmap.org/copyright'))
|
||||
})
|
||||
expect(addAttribution).toHaveBeenCalledWith(expect.stringContaining('openstreetmap.org/copyright'));
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-016: a map torn down mid-probe still gets nothing', async () => {
|
||||
const ref: { current: BasemapLayer | null } = { current: null }
|
||||
await attachVectorBasemap(rasterMap(), OFM_POSITRON, ref, () => true)
|
||||
expect(ref.current).toBeNull()
|
||||
})
|
||||
const ref: { current: BasemapLayer | null } = { current: null };
|
||||
await attachVectorBasemap(rasterMap(), OFM_POSITRON, ref, () => true);
|
||||
expect(ref.current).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-017: the raster stand-in ignores a restyle and a label sweep', async () => {
|
||||
const ref: { current: BasemapLayer | null } = { current: null }
|
||||
await attachVectorBasemap(rasterMap(), OFM_POSITRON, ref, () => false)
|
||||
const ref: { current: BasemapLayer | null } = { current: null };
|
||||
await attachVectorBasemap(rasterMap(), OFM_POSITRON, ref, () => false);
|
||||
|
||||
// Both are GL-only operations. Called on raster tiles they must do nothing
|
||||
// rather than reach for a maplibre map that is not there.
|
||||
expect(() => restyleBasemap(ref.current, OFM_DARK)).not.toThrow()
|
||||
expect(() => hideLabelLayers(ref.current!)).not.toThrow()
|
||||
})
|
||||
})
|
||||
expect(() => restyleBasemap(ref.current, OFM_DARK)).not.toThrow();
|
||||
expect(() => hideLabelLayers(ref.current!)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('detachBasemapLayer', () => {
|
||||
it('FE-COMP-VECBM-018: a GL layer whose context never came off cleanly anyway', () => {
|
||||
@@ -289,21 +289,25 @@ describe('detachBasemapLayer', () => {
|
||||
// refused context there is not. It ran inside a React cleanup, so the throw
|
||||
// reached a boundary and replaced the page.
|
||||
const remove = vi.fn(function (this: { _glMap?: { remove: () => void } }) {
|
||||
this._glMap!.remove()
|
||||
})
|
||||
const halfBuilt = { getMaplibreMap: () => undefined, remove } as unknown as GlLeafletLayer
|
||||
this._glMap!.remove();
|
||||
});
|
||||
const halfBuilt = { getMaplibreMap: () => undefined, remove } as unknown as GlLeafletLayer;
|
||||
|
||||
expect(() => detachBasemapLayer(halfBuilt)).not.toThrow()
|
||||
expect(remove).toHaveBeenCalled()
|
||||
})
|
||||
expect(() => detachBasemapLayer(halfBuilt)).not.toThrow();
|
||||
expect(remove).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-019: a layer that throws for any other reason is swallowed too', () => {
|
||||
// Unmounting a map is never allowed to fail because its basemap did.
|
||||
const layer = { remove: vi.fn(() => { throw new Error('boom') }) } as unknown as BasemapLayer
|
||||
expect(() => detachBasemapLayer(layer)).not.toThrow()
|
||||
})
|
||||
const layer = {
|
||||
remove: vi.fn(() => {
|
||||
throw new Error('boom');
|
||||
}),
|
||||
} as unknown as BasemapLayer;
|
||||
expect(() => detachBasemapLayer(layer)).not.toThrow();
|
||||
});
|
||||
|
||||
it('FE-COMP-VECBM-020: nothing to detach is not an error', () => {
|
||||
expect(() => detachBasemapLayer(null)).not.toThrow()
|
||||
})
|
||||
})
|
||||
expect(() => detachBasemapLayer(null)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,28 +1,24 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { TileLayer, useMap } from 'react-leaflet'
|
||||
import L from 'leaflet'
|
||||
import type { MaplibreGL } from '@maplibre/maplibre-gl-leaflet'
|
||||
import {
|
||||
RASTER_FALLBACK_MAX_ZOOM,
|
||||
RASTER_FALLBACK_TILE_URL,
|
||||
attributionForTile,
|
||||
} from '../../constants/mapDefaults'
|
||||
import { hasWebGL } from '../../utils/webgl'
|
||||
import { isChunkLoadError, reloadOnceForChunk } from '../../utils/chunkReload'
|
||||
import type { MaplibreGL } from '@maplibre/maplibre-gl-leaflet';
|
||||
import L from 'leaflet';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { TileLayer, useMap } from 'react-leaflet';
|
||||
import { RASTER_FALLBACK_MAX_ZOOM, RASTER_FALLBACK_TILE_URL, attributionForTile } from '../../constants/mapDefaults';
|
||||
import { isChunkLoadError, reloadOnceForChunk } from '../../utils/chunkReload';
|
||||
import { hasWebGL } from '../../utils/webgl';
|
||||
|
||||
/** The Leaflet layer maplibre-gl-leaflet hands back. */
|
||||
export type GlLeafletLayer = InstanceType<typeof MaplibreGL>
|
||||
export type GlLeafletLayer = InstanceType<typeof MaplibreGL>;
|
||||
|
||||
/**
|
||||
* What a map ended up drawing with. Every caller keeps one ref for both kinds, so
|
||||
* there is no code path that knows only about the GL layer and falls over the
|
||||
* raster stand-in the moment a browser has no WebGL (#2288).
|
||||
*/
|
||||
export type BasemapLayer = GlLeafletLayer | L.TileLayer
|
||||
export type BasemapLayer = GlLeafletLayer | L.TileLayer;
|
||||
|
||||
/** A GL layer rather than the raster stand-in. Prototype method, so `in` finds it. */
|
||||
function isGlLayer(layer: BasemapLayer): layer is GlLeafletLayer {
|
||||
return 'getMaplibreMap' in layer
|
||||
return 'getMaplibreMap' in layer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,29 +35,26 @@ function isGlLayer(layer: BasemapLayer): layer is GlLeafletLayer {
|
||||
* sealed namespace object.
|
||||
*/
|
||||
async function loadLayerFactory() {
|
||||
const [, bridge] = await Promise.all([
|
||||
import('./engines/maplibre'),
|
||||
import('@maplibre/maplibre-gl-leaflet'),
|
||||
])
|
||||
return bridge.maplibreGL
|
||||
const [, bridge] = await Promise.all([import('./engines/maplibre'), import('@maplibre/maplibre-gl-leaflet')]);
|
||||
return bridge.maplibreGL;
|
||||
}
|
||||
|
||||
/** The factory, or null when its chunk never arrived. A dead chunk is not the basemap's problem. */
|
||||
async function loadLayerFactoryOrNull() {
|
||||
try {
|
||||
return await loadLayerFactory()
|
||||
return await loadLayerFactory();
|
||||
} catch (err) {
|
||||
// A chunk gone after a deploy is the global handler's case and heals itself
|
||||
// with one reload; here it only means there is no GL layer to attach.
|
||||
if (isChunkLoadError(err)) reloadOnceForChunk()
|
||||
else console.warn('[basemap] the maplibre chunk did not load', err)
|
||||
return null
|
||||
if (isChunkLoadError(err)) reloadOnceForChunk();
|
||||
else console.warn('[basemap] the maplibre chunk did not load', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Credit the basemap on a map that has an attribution control; a no-op on one that does not. */
|
||||
function creditBasemap(map: L.Map, style: string): void {
|
||||
map.attributionControl?.addAttribution(attributionForTile(style))
|
||||
map.attributionControl?.addAttribution(attributionForTile(style));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,8 +69,8 @@ function creditBasemap(map: L.Map, style: string): void {
|
||||
* layer already has a GL map and is left alone.
|
||||
*/
|
||||
function disarmGlLayer(layer: GlLeafletLayer): void {
|
||||
const internals = layer as unknown as { _glMap?: { remove: () => void } | null }
|
||||
if (!internals._glMap) internals._glMap = { remove: () => {} }
|
||||
const internals = layer as unknown as { _glMap?: { remove: () => void } | null };
|
||||
if (!internals._glMap) internals._glMap = { remove: () => {} };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,14 +86,14 @@ function disarmGlLayer(layer: GlLeafletLayer): void {
|
||||
*/
|
||||
function attachGlLayer(map: L.Map, layer: GlLeafletLayer, style: string): boolean {
|
||||
try {
|
||||
layer.addTo(map)
|
||||
layer.addTo(map);
|
||||
} catch (err) {
|
||||
console.warn('[basemap] no WebGL context for the vector basemap, drawing raster tiles', err)
|
||||
detachBasemapLayer(layer)
|
||||
return false
|
||||
console.warn('[basemap] no WebGL context for the vector basemap, drawing raster tiles', err);
|
||||
detachBasemapLayer(layer);
|
||||
return false;
|
||||
}
|
||||
creditBasemap(map, style)
|
||||
return true
|
||||
creditBasemap(map, style);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,10 +105,10 @@ function attachRasterFallback(map: L.Map): L.TileLayer {
|
||||
const layer = L.tileLayer(RASTER_FALLBACK_TILE_URL, {
|
||||
maxZoom: RASTER_FALLBACK_MAX_ZOOM,
|
||||
referrerPolicy: 'strict-origin-when-cross-origin',
|
||||
} as L.TileLayerOptions)
|
||||
layer.addTo(map)
|
||||
creditBasemap(map, RASTER_FALLBACK_TILE_URL)
|
||||
return layer
|
||||
} as L.TileLayerOptions);
|
||||
layer.addTo(map);
|
||||
creditBasemap(map, RASTER_FALLBACK_TILE_URL);
|
||||
return layer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,12 +116,12 @@ function attachRasterFallback(map: L.Map): L.TileLayer {
|
||||
* fail because its basemap did (#2288).
|
||||
*/
|
||||
export function detachBasemapLayer(layer: BasemapLayer | null | undefined): void {
|
||||
if (!layer) return
|
||||
if (isGlLayer(layer)) disarmGlLayer(layer)
|
||||
if (!layer) return;
|
||||
if (isGlLayer(layer)) disarmGlLayer(layer);
|
||||
try {
|
||||
layer.remove()
|
||||
layer.remove();
|
||||
} catch (err) {
|
||||
console.warn('[basemap] teardown failed, leaving the layer where it is', err)
|
||||
console.warn('[basemap] teardown failed, leaving the layer where it is', err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,8 +134,8 @@ export function detachBasemapLayer(layer: BasemapLayer | null | undefined): void
|
||||
* than refetching the same tiles.
|
||||
*/
|
||||
export function restyleBasemap(layer: BasemapLayer | null | undefined, style: string): void {
|
||||
if (!layer || !isGlLayer(layer)) return
|
||||
layer.getMaplibreMap()?.setStyle(style)
|
||||
if (!layer || !isGlLayer(layer)) return;
|
||||
layer.getMaplibreMap()?.setStyle(style);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,25 +156,25 @@ export function restyleBasemap(layer: BasemapLayer | null | undefined, style: st
|
||||
* browser that could never have used it.
|
||||
*/
|
||||
export function VectorBasemap({ style }: { style: string }) {
|
||||
const map = useMap()
|
||||
const layerRef = useRef<GlLeafletLayer | null>(null)
|
||||
const styleRef = useRef(style)
|
||||
styleRef.current = style
|
||||
const map = useMap();
|
||||
const layerRef = useRef<GlLeafletLayer | null>(null);
|
||||
const styleRef = useRef(style);
|
||||
styleRef.current = style;
|
||||
// State rather than a plain constant: the probe can say yes and the attach can
|
||||
// still fail once the page has spent its context budget, and that has to reach
|
||||
// the render or the raster tiles never appear.
|
||||
const [glUsable, setGlUsable] = useState(hasWebGL)
|
||||
const [glUsable, setGlUsable] = useState(hasWebGL);
|
||||
|
||||
useEffect(() => {
|
||||
if (!glUsable) return
|
||||
let cancelled = false
|
||||
if (!glUsable) return;
|
||||
let cancelled = false;
|
||||
|
||||
void (async () => {
|
||||
const maplibreGL = await loadLayerFactoryOrNull()
|
||||
if (cancelled) return
|
||||
const maplibreGL = await loadLayerFactoryOrNull();
|
||||
if (cancelled) return;
|
||||
if (!maplibreGL) {
|
||||
setGlUsable(false)
|
||||
return
|
||||
setGlUsable(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// The style is read through a ref, never from the dependency list: a style
|
||||
@@ -191,24 +184,24 @@ export function VectorBasemap({ style }: { style: string }) {
|
||||
style: styleRef.current,
|
||||
interactive: false,
|
||||
attributionControl: false,
|
||||
})
|
||||
});
|
||||
if (!attachGlLayer(map, layer, styleRef.current)) {
|
||||
setGlUsable(false)
|
||||
return
|
||||
setGlUsable(false);
|
||||
return;
|
||||
}
|
||||
layerRef.current = layer
|
||||
})()
|
||||
layerRef.current = layer;
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
detachBasemapLayer(layerRef.current)
|
||||
layerRef.current = null
|
||||
}
|
||||
}, [map, glUsable])
|
||||
cancelled = true;
|
||||
detachBasemapLayer(layerRef.current);
|
||||
layerRef.current = null;
|
||||
};
|
||||
}, [map, glUsable]);
|
||||
|
||||
useEffect(() => {
|
||||
restyleBasemap(layerRef.current, style)
|
||||
}, [style])
|
||||
restyleBasemap(layerRef.current, style);
|
||||
}, [style]);
|
||||
|
||||
// No WebGL, no vector tiles. Raster keeps the map readable instead of leaving
|
||||
// markers, routes and clusters floating over grey; see mapDefaults for why this
|
||||
@@ -226,12 +219,12 @@ export function VectorBasemap({ style }: { style: string }) {
|
||||
updateWhenIdle={true}
|
||||
referrerPolicy="strict-origin-when-cross-origin"
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
export default VectorBasemap
|
||||
export default VectorBasemap;
|
||||
|
||||
/**
|
||||
* The same basemap for the maps that build Leaflet imperatively rather than
|
||||
@@ -248,31 +241,31 @@ export async function attachVectorBasemap(
|
||||
style: string,
|
||||
ref: { current: BasemapLayer | null },
|
||||
cancelled: () => boolean,
|
||||
opts: { hideLabels?: boolean } = {},
|
||||
opts: { hideLabels?: boolean } = {}
|
||||
): Promise<void> {
|
||||
// Same gate as the component: a browser without WebGL never pays for the
|
||||
// maplibre chunk and gets raster tiles rather than an empty map (#2288).
|
||||
if (!hasWebGL()) {
|
||||
if (!cancelled()) ref.current = attachRasterFallback(map)
|
||||
return
|
||||
if (!cancelled()) ref.current = attachRasterFallback(map);
|
||||
return;
|
||||
}
|
||||
|
||||
const maplibreGL = await loadLayerFactoryOrNull()
|
||||
if (cancelled()) return
|
||||
const maplibreGL = await loadLayerFactoryOrNull();
|
||||
if (cancelled()) return;
|
||||
if (!maplibreGL) {
|
||||
ref.current = attachRasterFallback(map)
|
||||
return
|
||||
ref.current = attachRasterFallback(map);
|
||||
return;
|
||||
}
|
||||
|
||||
const layer = maplibreGL({ style, interactive: false, attributionControl: false })
|
||||
const layer = maplibreGL({ style, interactive: false, attributionControl: false });
|
||||
// The raster layer this replaces carried the credit, and OpenFreeMap asks for
|
||||
// one of its own; attachGlLayer adds it once the layer is actually on the map.
|
||||
if (!attachGlLayer(map, layer, style)) {
|
||||
ref.current = attachRasterFallback(map)
|
||||
return
|
||||
ref.current = attachRasterFallback(map);
|
||||
return;
|
||||
}
|
||||
ref.current = layer
|
||||
if (opts.hideLabels) hideLabelLayers(layer)
|
||||
ref.current = layer;
|
||||
if (opts.hideLabels) hideLabelLayers(layer);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -291,15 +284,15 @@ export function hideLabelLayers(layer: BasemapLayer): void {
|
||||
// A WebGL-less atlas therefore shows country names twice, which is cosmetic and
|
||||
// the price of having a basemap at all, because the only keyless alternative is
|
||||
// none.
|
||||
if (!isGlLayer(layer)) return
|
||||
const gl = layer.getMaplibreMap()
|
||||
if (!gl) return
|
||||
if (!isGlLayer(layer)) return;
|
||||
const gl = layer.getMaplibreMap();
|
||||
if (!gl) return;
|
||||
const apply = () => {
|
||||
for (const l of gl.getStyle()?.layers ?? []) {
|
||||
if (l.type === 'symbol') gl.setLayoutProperty(l.id, 'visibility', 'none')
|
||||
if (l.type === 'symbol') gl.setLayoutProperty(l.id, 'visibility', 'none');
|
||||
}
|
||||
}
|
||||
gl.on('style.load', apply)
|
||||
};
|
||||
gl.on('style.load', apply);
|
||||
// The first style may already be in when we get here.
|
||||
if (gl.isStyleLoaded()) apply()
|
||||
if (gl.isStyleLoaded()) apply();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { lazyWithRetry } from '../../utils/lazyWithRetry'
|
||||
import { lazyWithRetry } from '../../utils/lazyWithRetry';
|
||||
|
||||
/**
|
||||
* The six ways into a GL map, one chunk per engine.
|
||||
@@ -19,58 +19,46 @@ import { lazyWithRetry } from '../../utils/lazyWithRetry'
|
||||
*/
|
||||
|
||||
export const MapViewGLMapbox = lazyWithRetry(async () => {
|
||||
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/mapbox')])
|
||||
const MapViewGL = component.MapViewGL
|
||||
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/mapbox')]);
|
||||
const MapViewGL = component.MapViewGL;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> }
|
||||
})
|
||||
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> };
|
||||
});
|
||||
|
||||
export const MapViewGLMaplibre = lazyWithRetry(async () => {
|
||||
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/maplibre')])
|
||||
const MapViewGL = component.MapViewGL
|
||||
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/maplibre')]);
|
||||
const MapViewGL = component.MapViewGL;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> }
|
||||
})
|
||||
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> };
|
||||
});
|
||||
|
||||
export const JourneyMapGLMapbox = lazyWithRetry(async () => {
|
||||
const [component, engine] = await Promise.all([
|
||||
import('../Journey/JourneyMapGL'),
|
||||
import('./engines/mapbox'),
|
||||
])
|
||||
const JourneyMapGL = component.default
|
||||
const [component, engine] = await Promise.all([import('../Journey/JourneyMapGL'), import('./engines/mapbox')]);
|
||||
const JourneyMapGL = component.default;
|
||||
// The journey map exposes an imperative handle (highlightMarker / focusMarker /
|
||||
// invalidateSize). Since React 19 its ref is an ordinary prop, so it rides
|
||||
// through the spread and the binding needs no forwardRef wrapper.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return { default: (props: any) => <JourneyMapGL {...props} gl={engine.default} /> }
|
||||
})
|
||||
return { default: (props: any) => <JourneyMapGL {...props} gl={engine.default} /> };
|
||||
});
|
||||
|
||||
export const JourneyMapGLMaplibre = lazyWithRetry(async () => {
|
||||
const [component, engine] = await Promise.all([
|
||||
import('../Journey/JourneyMapGL'),
|
||||
import('./engines/maplibre'),
|
||||
])
|
||||
const JourneyMapGL = component.default
|
||||
const [component, engine] = await Promise.all([import('../Journey/JourneyMapGL'), import('./engines/maplibre')]);
|
||||
const JourneyMapGL = component.default;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return { default: (props: any) => <JourneyMapGL {...props} gl={engine.default} /> }
|
||||
})
|
||||
return { default: (props: any) => <JourneyMapGL {...props} gl={engine.default} /> };
|
||||
});
|
||||
|
||||
export const GlMapPreviewMapbox = lazyWithRetry(async () => {
|
||||
const [component, engine] = await Promise.all([
|
||||
import('../Settings/MapboxPreview'),
|
||||
import('./engines/mapbox'),
|
||||
])
|
||||
const GlMapPreview = component.default
|
||||
const [component, engine] = await Promise.all([import('../Settings/MapboxPreview'), import('./engines/mapbox')]);
|
||||
const GlMapPreview = component.default;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return { default: (props: any) => <GlMapPreview {...props} gl={engine.default} /> }
|
||||
})
|
||||
return { default: (props: any) => <GlMapPreview {...props} gl={engine.default} /> };
|
||||
});
|
||||
|
||||
export const GlMapPreviewMaplibre = lazyWithRetry(async () => {
|
||||
const [component, engine] = await Promise.all([
|
||||
import('../Settings/MapboxPreview'),
|
||||
import('./engines/maplibre'),
|
||||
])
|
||||
const GlMapPreview = component.default
|
||||
const [component, engine] = await Promise.all([import('../Settings/MapboxPreview'), import('./engines/maplibre')]);
|
||||
const GlMapPreview = component.default;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return { default: (props: any) => <GlMapPreview {...props} gl={engine.default} /> }
|
||||
})
|
||||
return { default: (props: any) => <GlMapPreview {...props} gl={engine.default} /> };
|
||||
});
|
||||
|
||||
@@ -97,15 +97,19 @@
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
font-size: 0;
|
||||
transition: background-color 150ms ease, color 150ms ease !important;
|
||||
transition:
|
||||
background-color 150ms ease,
|
||||
color 150ms ease !important;
|
||||
}
|
||||
|
||||
.leaflet-container .trek-hazard-popup a.leaflet-popup-close-button span {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.trek-hazard-popup :is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button)::before,
|
||||
.trek-hazard-popup :is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button)::after {
|
||||
.trek-hazard-popup
|
||||
:is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button)::before,
|
||||
.trek-hazard-popup
|
||||
:is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
@@ -117,11 +121,13 @@
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
.trek-hazard-popup :is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button)::after {
|
||||
.trek-hazard-popup
|
||||
:is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button)::after {
|
||||
transform: rotate(-45deg);
|
||||
}
|
||||
|
||||
.trek-hazard-popup :is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button):hover {
|
||||
.trek-hazard-popup
|
||||
:is(.leaflet-popup-close-button, .mapboxgl-popup-close-button, .maplibregl-popup-close-button):hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
transform: none;
|
||||
|
||||
@@ -1,119 +1,135 @@
|
||||
// FE-COMP-POICATS-001 to FE-COMP-POICATS-009
|
||||
import React from 'react'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { MapPin, Signpost, Waves } from 'lucide-react'
|
||||
import type { PluginPoiCategory } from '@trek/shared'
|
||||
import { TranslationProvider } from '../../i18n'
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { POI_CATEGORIES } from './poiCategories'
|
||||
import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
|
||||
import {
|
||||
corePoiCategories,
|
||||
findPoiCategory,
|
||||
pluginPoiCategories,
|
||||
usePoiCategories,
|
||||
} from './usePoiCategories'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { PluginPoiCategory } from '@trek/shared';
|
||||
import { MapPin, Signpost, Waves } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { TranslationProvider } from '../../i18n';
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { POI_DEFAULT_COLOR } from './pluginPoiIcons';
|
||||
import { POI_CATEGORIES } from './poiCategories';
|
||||
import { corePoiCategories, findPoiCategory, pluginPoiCategories, usePoiCategories } from './usePoiCategories';
|
||||
|
||||
const TRAILHEADS: PluginPoiCategory = {
|
||||
id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a',
|
||||
}
|
||||
const SWIMMING: PluginPoiCategory = { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' }
|
||||
id: 'trailheads',
|
||||
label: 'Trailheads',
|
||||
labels: { de: 'Wanderparkplätze' },
|
||||
icon: 'Signpost',
|
||||
color: '#2f855a',
|
||||
};
|
||||
const SWIMMING: PluginPoiCategory = { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' };
|
||||
|
||||
function plugin(id: string, poiCategories?: PluginPoiCategory[]): ActivePlugin {
|
||||
return { id, name: id, type: 'integration', icon: null, ...(poiCategories ? { poiCategories } : {}) }
|
||||
return { id, name: id, type: 'integration', icon: null, ...(poiCategories ? { poiCategories } : {}) };
|
||||
}
|
||||
|
||||
const initialPlugins = usePluginStore.getState()
|
||||
const initialSettings = useSettingsStore.getState()
|
||||
const initialPlugins = usePluginStore.getState();
|
||||
const initialSettings = useSettingsStore.getState();
|
||||
|
||||
// Reset before rather than after: an afterEach would change the language under a hook
|
||||
// that is still mounted, and the provider would load the other locale outside act.
|
||||
beforeEach(() => {
|
||||
usePluginStore.setState(initialPlugins, true)
|
||||
useSettingsStore.setState(initialSettings, true)
|
||||
})
|
||||
usePluginStore.setState(initialPlugins, true);
|
||||
useSettingsStore.setState(initialSettings, true);
|
||||
});
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => <TranslationProvider>{children}</TranslationProvider>
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => <TranslationProvider>{children}</TranslationProvider>;
|
||||
|
||||
describe('corePoiCategories', () => {
|
||||
it('FE-COMP-POICATS-001: the core list in its own order, labels translated', () => {
|
||||
const core = corePoiCategories(key => `t:${key}`)
|
||||
expect(core.map(c => c.key)).toEqual(POI_CATEGORIES.map(c => c.key))
|
||||
expect(core[0]).toEqual({ key: 'restaurant', label: 't:poi.cat.restaurants', Icon: POI_CATEGORIES[0].Icon, color: POI_CATEGORIES[0].color })
|
||||
expect(core.every(c => c.pluginId === undefined)).toBe(true)
|
||||
})
|
||||
})
|
||||
const core = corePoiCategories((key) => `t:${key}`);
|
||||
expect(core.map((c) => c.key)).toEqual(POI_CATEGORIES.map((c) => c.key));
|
||||
expect(core[0]).toEqual({
|
||||
key: 'restaurant',
|
||||
label: 't:poi.cat.restaurants',
|
||||
Icon: POI_CATEGORIES[0].Icon,
|
||||
color: POI_CATEGORIES[0].color,
|
||||
});
|
||||
expect(core.every((c) => c.pluginId === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pluginPoiCategories', () => {
|
||||
it('FE-COMP-POICATS-002: feed order, then declaration order, each under its namespaced key', () => {
|
||||
const cats = pluginPoiCategories([plugin('trail-finder', [TRAILHEADS, SWIMMING]), plugin('flights'), plugin('eco-map', [SWIMMING])], 'en')
|
||||
expect(cats.map(c => c.key)).toEqual([
|
||||
const cats = pluginPoiCategories(
|
||||
[plugin('trail-finder', [TRAILHEADS, SWIMMING]), plugin('flights'), plugin('eco-map', [SWIMMING])],
|
||||
'en'
|
||||
);
|
||||
expect(cats.map((c) => c.key)).toEqual([
|
||||
'plugin:trail-finder/trailheads',
|
||||
'plugin:trail-finder/swimming',
|
||||
'plugin:eco-map/swimming',
|
||||
])
|
||||
expect(cats.map(c => c.pluginId)).toEqual(['trail-finder', 'trail-finder', 'eco-map'])
|
||||
expect(cats[0]).toMatchObject({ label: 'Trailheads', Icon: Signpost, color: '#2f855a' })
|
||||
expect(cats[1]).toMatchObject({ Icon: Waves, color: '#0369a1' })
|
||||
})
|
||||
]);
|
||||
expect(cats.map((c) => c.pluginId)).toEqual(['trail-finder', 'trail-finder', 'eco-map']);
|
||||
expect(cats[0]).toMatchObject({ label: 'Trailheads', Icon: Signpost, color: '#2f855a' });
|
||||
expect(cats[1]).toMatchObject({ Icon: Waves, color: '#0369a1' });
|
||||
});
|
||||
|
||||
it('FE-COMP-POICATS-003: the label follows the language and falls back to the default', () => {
|
||||
const plugins = [plugin('trail-finder', [TRAILHEADS, SWIMMING])]
|
||||
expect(pluginPoiCategories(plugins, 'de').map(c => c.label)).toEqual(['Wanderparkplätze', 'Swimming spots'])
|
||||
expect(pluginPoiCategories(plugins, 'fr').map(c => c.label)).toEqual(['Trailheads', 'Swimming spots'])
|
||||
})
|
||||
const plugins = [plugin('trail-finder', [TRAILHEADS, SWIMMING])];
|
||||
expect(pluginPoiCategories(plugins, 'de').map((c) => c.label)).toEqual(['Wanderparkplätze', 'Swimming spots']);
|
||||
expect(pluginPoiCategories(plugins, 'fr').map((c) => c.label)).toEqual(['Trailheads', 'Swimming spots']);
|
||||
});
|
||||
|
||||
it('FE-COMP-POICATS-004: a colour or icon that got past the store is checked again', () => {
|
||||
const forged = { ...TRAILHEADS, color: 'red;background:url(https://x)', icon: 'Skull' } as unknown as PluginPoiCategory
|
||||
const [cat] = pluginPoiCategories([plugin('trail-finder', [forged])], 'en')
|
||||
expect(cat.color).toBe(POI_DEFAULT_COLOR)
|
||||
expect(cat.Icon).toBe(MapPin)
|
||||
})
|
||||
})
|
||||
const forged = {
|
||||
...TRAILHEADS,
|
||||
color: 'red;background:url(https://x)',
|
||||
icon: 'Skull',
|
||||
} as unknown as PluginPoiCategory;
|
||||
const [cat] = pluginPoiCategories([plugin('trail-finder', [forged])], 'en');
|
||||
expect(cat.color).toBe(POI_DEFAULT_COLOR);
|
||||
expect(cat.Icon).toBe(MapPin);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findPoiCategory', () => {
|
||||
it('FE-COMP-POICATS-005: finds a core and a plugin chip by key, and nothing for an unknown one', () => {
|
||||
const groups = { core: corePoiCategories(k => k), plugin: pluginPoiCategories([plugin('trail-finder', [TRAILHEADS])], 'en') }
|
||||
expect(findPoiCategory(groups, 'cafe')?.key).toBe('cafe')
|
||||
expect(findPoiCategory(groups, 'plugin:trail-finder/trailheads')?.label).toBe('Trailheads')
|
||||
expect(findPoiCategory(groups, 'plugin:trail-finder/swimming')).toBeUndefined()
|
||||
expect(findPoiCategory(groups, 'fuel')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
const groups = {
|
||||
core: corePoiCategories((k) => k),
|
||||
plugin: pluginPoiCategories([plugin('trail-finder', [TRAILHEADS])], 'en'),
|
||||
};
|
||||
expect(findPoiCategory(groups, 'cafe')?.key).toBe('cafe');
|
||||
expect(findPoiCategory(groups, 'plugin:trail-finder/trailheads')?.label).toBe('Trailheads');
|
||||
expect(findPoiCategory(groups, 'plugin:trail-finder/swimming')).toBeUndefined();
|
||||
expect(findPoiCategory(groups, 'fuel')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePoiCategories', () => {
|
||||
it('FE-COMP-POICATS-006: without plugin categories only the core chips, translated', () => {
|
||||
const { result } = renderHook(() => usePoiCategories(), { wrapper })
|
||||
expect(result.current.core.map(c => c.key)).toEqual(POI_CATEGORIES.map(c => c.key))
|
||||
expect(result.current.core[1].label).toBe('Cafés')
|
||||
expect(result.current.plugin).toEqual([])
|
||||
})
|
||||
const { result } = renderHook(() => usePoiCategories(), { wrapper });
|
||||
expect(result.current.core.map((c) => c.key)).toEqual(POI_CATEGORIES.map((c) => c.key));
|
||||
expect(result.current.core[1].label).toBe('Cafés');
|
||||
expect(result.current.plugin).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-COMP-POICATS-007: follows the plugin feed, so a plugin switched off takes its chips with it', () => {
|
||||
usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] })
|
||||
const { result } = renderHook(() => usePoiCategories(), { wrapper })
|
||||
expect(result.current.plugin.map(c => c.key)).toEqual(['plugin:trail-finder/trailheads'])
|
||||
usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] });
|
||||
const { result } = renderHook(() => usePoiCategories(), { wrapper });
|
||||
expect(result.current.plugin.map((c) => c.key)).toEqual(['plugin:trail-finder/trailheads']);
|
||||
|
||||
act(() => { usePluginStore.setState({ plugins: [] }) })
|
||||
expect(result.current.plugin).toEqual([])
|
||||
expect(result.current.core).toHaveLength(POI_CATEGORIES.length)
|
||||
})
|
||||
act(() => {
|
||||
usePluginStore.setState({ plugins: [] });
|
||||
});
|
||||
expect(result.current.plugin).toEqual([]);
|
||||
expect(result.current.core).toHaveLength(POI_CATEGORIES.length);
|
||||
});
|
||||
|
||||
it('FE-COMP-POICATS-008: core and plugin labels both follow the user language', async () => {
|
||||
useSettingsStore.setState(s => ({ settings: { ...s.settings, language: 'de' } }))
|
||||
usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] })
|
||||
const { result } = renderHook(() => usePoiCategories(), { wrapper })
|
||||
expect(result.current.plugin[0].label).toBe('Wanderparkplätze')
|
||||
await waitFor(() => expect(result.current.core[5].label).toBe('Museen & Kultur'))
|
||||
})
|
||||
useSettingsStore.setState((s) => ({ settings: { ...s.settings, language: 'de' } }));
|
||||
usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] });
|
||||
const { result } = renderHook(() => usePoiCategories(), { wrapper });
|
||||
expect(result.current.plugin[0].label).toBe('Wanderparkplätze');
|
||||
await waitFor(() => expect(result.current.core[5].label).toBe('Museen & Kultur'));
|
||||
});
|
||||
|
||||
it('FE-COMP-POICATS-009: keeps the same lists across renders while nothing changed', () => {
|
||||
usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] })
|
||||
const { result, rerender } = renderHook(() => usePoiCategories(), { wrapper })
|
||||
const first = result.current
|
||||
rerender()
|
||||
expect(result.current).toBe(first)
|
||||
})
|
||||
})
|
||||
usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] });
|
||||
const { result, rerender } = renderHook(() => usePoiCategories(), { wrapper });
|
||||
const first = result.current;
|
||||
rerender();
|
||||
expect(result.current).toBe(first);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
// FE-COMP-POIEXPLORE-001 to FE-COMP-POIEXPLORE-028
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { PluginPoiCategory } from '@trek/shared'
|
||||
import { TranslationProvider } from '../../i18n'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { pluginPoisApi } from '../../api/pluginPois'
|
||||
import { pluginPoiRepo } from '../../repo/pluginPoiRepo'
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
|
||||
import { usePoiExplore, type Bbox } from './usePoiExplore'
|
||||
import type { Poi } from './poiCategories'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { PluginPoiCategory } from '@trek/shared';
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mapsApi } from '../../api/client';
|
||||
import { pluginPoisApi } from '../../api/pluginPois';
|
||||
import { TranslationProvider } from '../../i18n';
|
||||
import { pluginPoiRepo } from '../../repo/pluginPoiRepo';
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
|
||||
import type { Poi } from './poiCategories';
|
||||
import { usePoiExplore, type Bbox } from './usePoiExplore';
|
||||
|
||||
const net = vi.hoisted(() => ({ offline: false }))
|
||||
const net = vi.hoisted(() => ({ offline: false }));
|
||||
vi.mock('../../sync/networkMode', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../sync/networkMode')>()),
|
||||
isEffectivelyOffline: () => net.offline,
|
||||
}))
|
||||
}));
|
||||
|
||||
type PoiResponse = Awaited<ReturnType<typeof mapsApi.pois>>
|
||||
type PoiResponse = Awaited<ReturnType<typeof mapsApi.pois>>;
|
||||
|
||||
const BBOX: Bbox = { south: 48.1, west: 16.3, north: 48.3, east: 16.4 }
|
||||
const BBOX: Bbox = { south: 48.1, west: 16.3, north: 48.3, east: 16.4 };
|
||||
|
||||
function poi(over: Partial<Poi> = {}): Poi {
|
||||
return {
|
||||
@@ -36,428 +36,618 @@ function poi(over: Partial<Poi> = {}): Poi {
|
||||
cuisine: null,
|
||||
source: 'openstreetmap',
|
||||
...over,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function response(pois: Poi[]): PoiResponse {
|
||||
return { pois, source: 'openstreetmap', truncated: false }
|
||||
return { pois, source: 'openstreetmap', truncated: false };
|
||||
}
|
||||
|
||||
// Hand-controlled promise so a test can hold a request "in flight" and decide
|
||||
// exactly when — and in which order — it settles.
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
|
||||
return { promise, resolve, reject }
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<TranslationProvider>{children}</TranslationProvider>
|
||||
)
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => <TranslationProvider>{children}</TranslationProvider>;
|
||||
|
||||
function setup() {
|
||||
return renderHook(() => usePoiExplore(), { wrapper })
|
||||
return renderHook(() => usePoiExplore(), { wrapper });
|
||||
}
|
||||
|
||||
const spyOnPois = () => vi.spyOn(mapsApi, 'pois')
|
||||
let pois: ReturnType<typeof spyOnPois>
|
||||
const spyOnPois = () => vi.spyOn(mapsApi, 'pois');
|
||||
let pois: ReturnType<typeof spyOnPois>;
|
||||
|
||||
const initialPlugins = usePluginStore.getState()
|
||||
const initialPlugins = usePluginStore.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
pois = spyOnPois().mockResolvedValue(response([poi()]))
|
||||
net.offline = false
|
||||
usePluginStore.setState(initialPlugins, true)
|
||||
})
|
||||
pois = spyOnPois().mockResolvedValue(response([poi()]));
|
||||
net.offline = false;
|
||||
usePluginStore.setState(initialPlugins, true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('usePoiExplore', () => {
|
||||
it('FE-COMP-POIEXPLORE-001: starts with nothing selected, loaded or failed', () => {
|
||||
const { result } = setup()
|
||||
expect(result.current.active.size).toBe(0)
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.loadingKeys.size).toBe(0)
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
expect(result.current.moved).toBe(false)
|
||||
})
|
||||
const { result } = setup();
|
||||
expect(result.current.active.size).toBe(0);
|
||||
expect(result.current.pois).toEqual([]);
|
||||
expect(result.current.loadingKeys.size).toBe(0);
|
||||
expect(result.current.errorKeys.size).toBe(0);
|
||||
expect(result.current.moved).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-002: panning with nothing active does not offer "search this area"', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
expect(result.current.moved).toBe(false)
|
||||
})
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
expect(result.current.moved).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-003: toggling before the map reported a viewport selects but does not fetch', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.active.has('cafe')).toBe(true)
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
})
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
expect(result.current.active.has('cafe')).toBe(true);
|
||||
expect(pois).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-004: toggling fetches the category for the current viewport', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(pois).toHaveBeenCalledWith('cafe', BBOX, 'en-US', expect.any(AbortSignal))
|
||||
expect(result.current.pois[0].osm_id).toBe('node/1')
|
||||
})
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(pois).toHaveBeenCalledWith('cafe', BBOX, 'en-US', expect.any(AbortSignal));
|
||||
expect(result.current.pois[0].osm_id).toBe('node/1');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-005: the spinner is on while the request is in flight and off when it lands', async () => {
|
||||
const d = deferred<PoiResponse>()
|
||||
pois.mockReturnValue(d.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
const d = deferred<PoiResponse>();
|
||||
pois.mockReturnValue(d.promise);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(true)
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(true);
|
||||
|
||||
await act(async () => { d.resolve(response([poi()])) })
|
||||
await waitFor(() => expect(result.current.loadingKeys.has('cafe')).toBe(false))
|
||||
})
|
||||
await act(async () => {
|
||||
d.resolve(response([poi()]));
|
||||
});
|
||||
await waitFor(() => expect(result.current.loadingKeys.has('cafe')).toBe(false));
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-006: toggling the active category turns it off and drops its markers', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.active.size).toBe(0)
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(pois).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
expect(result.current.active.size).toBe(0);
|
||||
expect(result.current.pois).toEqual([]);
|
||||
expect(pois).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-007: the pill is single-select — a second category replaces the first', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/2', category: 'bar', name: 'Loos Bar' })]))
|
||||
act(() => { result.current.toggle('bar') })
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/2', category: 'bar', name: 'Loos Bar' })]));
|
||||
act(() => {
|
||||
result.current.toggle('bar');
|
||||
});
|
||||
// The previous category's markers vanish immediately, before the new results land.
|
||||
expect(result.current.active).toEqual(new Set(['bar']))
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.active).toEqual(new Set(['bar']));
|
||||
expect(result.current.pois).toEqual([]);
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.pois[0].osm_id).toBe('node/2')
|
||||
})
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(result.current.pois[0].osm_id).toBe('node/2');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-008: panning with a category active marks the results stale', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.moved).toBe(false)
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(result.current.moved).toBe(false);
|
||||
|
||||
act(() => { result.current.onViewportChange({ ...BBOX, south: 48.0 }) })
|
||||
expect(result.current.moved).toBe(true)
|
||||
})
|
||||
act(() => {
|
||||
result.current.onViewportChange({ ...BBOX, south: 48.0 });
|
||||
});
|
||||
expect(result.current.moved).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-009: searchArea refetches the active category for the new viewport', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
|
||||
const moved: Bbox = { south: 40, west: 10, north: 41, east: 11 }
|
||||
act(() => { result.current.onViewportChange(moved) })
|
||||
act(() => { result.current.searchArea() })
|
||||
const moved: Bbox = { south: 40, west: 10, north: 41, east: 11 };
|
||||
act(() => {
|
||||
result.current.onViewportChange(moved);
|
||||
});
|
||||
act(() => {
|
||||
result.current.searchArea();
|
||||
});
|
||||
|
||||
expect(result.current.moved).toBe(false)
|
||||
await waitFor(() => expect(pois).toHaveBeenCalledTimes(2))
|
||||
expect(pois).toHaveBeenLastCalledWith('cafe', moved, 'en-US', expect.any(AbortSignal))
|
||||
})
|
||||
expect(result.current.moved).toBe(false);
|
||||
await waitFor(() => expect(pois).toHaveBeenCalledTimes(2));
|
||||
expect(pois).toHaveBeenLastCalledWith('cafe', moved, 'en-US', expect.any(AbortSignal));
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-010: searchArea without a viewport is a no-op', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.searchArea() })
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
expect(result.current.moved).toBe(false)
|
||||
})
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.searchArea();
|
||||
});
|
||||
expect(pois).not.toHaveBeenCalled();
|
||||
expect(result.current.moved).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-011: searchArea with nothing active fetches nothing', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.searchArea() })
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
})
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.searchArea();
|
||||
});
|
||||
expect(pois).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-012: a failed fetch surfaces a retryable error instead of a silent empty', async () => {
|
||||
pois.mockRejectedValue(new Error('all Overpass mirrors down'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
pois.mockRejectedValue(new Error('all Overpass mirrors down'));
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(false)
|
||||
})
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true));
|
||||
expect(result.current.pois).toEqual([]);
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-013: a retry that succeeds clears the error flag', async () => {
|
||||
pois.mockRejectedValueOnce(new Error('timeout'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))
|
||||
pois.mockRejectedValueOnce(new Error('timeout'));
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true));
|
||||
|
||||
act(() => { result.current.searchArea() })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.errorKeys.has('cafe')).toBe(false)
|
||||
})
|
||||
act(() => {
|
||||
result.current.searchArea();
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(result.current.errorKeys.has('cafe')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-014: switching category clears a previous error flag', async () => {
|
||||
pois.mockRejectedValueOnce(new Error('timeout'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))
|
||||
pois.mockRejectedValueOnce(new Error('timeout'));
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true));
|
||||
|
||||
act(() => { result.current.toggle('bar') })
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
})
|
||||
act(() => {
|
||||
result.current.toggle('bar');
|
||||
});
|
||||
expect(result.current.errorKeys.size).toBe(0);
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-015: results that land after the category was switched off are dropped', async () => {
|
||||
const d = deferred<PoiResponse>()
|
||||
pois.mockReturnValue(d.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.active.size).toBe(0)
|
||||
const d = deferred<PoiResponse>();
|
||||
pois.mockReturnValue(d.promise);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
expect(result.current.active.size).toBe(0);
|
||||
|
||||
await act(async () => { d.resolve(response([poi()])) })
|
||||
expect(result.current.pois).toEqual([])
|
||||
})
|
||||
await act(async () => {
|
||||
d.resolve(response([poi()]));
|
||||
});
|
||||
expect(result.current.pois).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-016: a superseded request is not reported as a failure', async () => {
|
||||
const first = deferred<PoiResponse>()
|
||||
pois.mockReturnValueOnce(first.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
const first = deferred<PoiResponse>();
|
||||
pois.mockReturnValueOnce(first.promise);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/9', category: 'bar' })]))
|
||||
act(() => { result.current.toggle('bar') })
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/9', category: 'bar' })]));
|
||||
act(() => {
|
||||
result.current.toggle('bar');
|
||||
});
|
||||
|
||||
// The abandoned cafe request rejects with axios' cancellation error.
|
||||
await act(async () => { first.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
|
||||
await act(async () => {
|
||||
first.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' }));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
expect(result.current.pois[0].osm_id).toBe('node/9')
|
||||
})
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(result.current.errorKeys.size).toBe(0);
|
||||
expect(result.current.pois[0].osm_id).toBe('node/9');
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-017: the abandoned category stops loading when the selection moves on', async () => {
|
||||
const first = deferred<PoiResponse>()
|
||||
pois.mockReturnValueOnce(first.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(true)
|
||||
const first = deferred<PoiResponse>();
|
||||
pois.mockReturnValueOnce(first.promise);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(true);
|
||||
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/9', category: 'bar' })]))
|
||||
act(() => { result.current.toggle('bar') })
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/9', category: 'bar' })]));
|
||||
act(() => {
|
||||
result.current.toggle('bar');
|
||||
});
|
||||
|
||||
await act(async () => { first.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
|
||||
await act(async () => {
|
||||
first.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' }));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.loadingKeys.has('cafe')).toBe(false))
|
||||
expect(result.current.loadingKeys.has('bar')).toBe(false)
|
||||
})
|
||||
await waitFor(() => expect(result.current.loadingKeys.has('cafe')).toBe(false));
|
||||
expect(result.current.loadingKeys.has('bar')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-018: turning the category off stops its spinner as well', async () => {
|
||||
const d = deferred<PoiResponse>()
|
||||
pois.mockReturnValue(d.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
const d = deferred<PoiResponse>();
|
||||
pois.mockReturnValue(d.promise);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
|
||||
await act(async () => { d.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
|
||||
await act(async () => {
|
||||
d.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' }));
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.loadingKeys.size).toBe(0))
|
||||
})
|
||||
})
|
||||
await waitFor(() => expect(result.current.loadingKeys.size).toBe(0));
|
||||
});
|
||||
});
|
||||
|
||||
// Plugin POI categories (#1781): a chip a plugin added is asked of that plugin, through
|
||||
// the repo, with the same single selection, cancelling and retry as a core one.
|
||||
describe('usePoiExplore with plugin categories', () => {
|
||||
const TRAILHEADS: PluginPoiCategory = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' }
|
||||
const KEY = 'plugin:trail-finder/trailheads'
|
||||
const TRAIL_FINDER: ActivePlugin = { id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null, poiCategories: [TRAILHEADS] }
|
||||
const TRAILHEADS: PluginPoiCategory = {
|
||||
id: 'trailheads',
|
||||
label: 'Trailheads',
|
||||
labels: { de: 'Wanderparkplätze' },
|
||||
icon: 'Signpost',
|
||||
color: '#2f855a',
|
||||
};
|
||||
const KEY = 'plugin:trail-finder/trailheads';
|
||||
const TRAIL_FINDER: ActivePlugin = {
|
||||
id: 'trail-finder',
|
||||
name: 'Trail finder',
|
||||
type: 'integration',
|
||||
icon: null,
|
||||
poiCategories: [TRAILHEADS],
|
||||
};
|
||||
|
||||
type PluginAnswer = Awaited<ReturnType<typeof pluginPoiRepo.search>>
|
||||
type PluginAnswer = Awaited<ReturnType<typeof pluginPoiRepo.search>>;
|
||||
|
||||
function pluginPoi(over: Partial<Poi> = {}): Poi {
|
||||
return {
|
||||
osm_id: 'plugin:trail-finder:th-1', name: 'Hochalm trailhead', lat: 48.2, lng: 16.35,
|
||||
category: KEY, poi_type: KEY, address: null, website: null, phone: null,
|
||||
opening_hours: null, cuisine: null, brand: null, brand_wikidata: null, charging: null,
|
||||
source: 'plugin:trail-finder', pluginId: 'trail-finder', rating: null,
|
||||
details: [{ label: 'Parking', value: '40 spaces' }], icon: 'Signpost', color: '#2f855a',
|
||||
osm_id: 'plugin:trail-finder:th-1',
|
||||
name: 'Hochalm trailhead',
|
||||
lat: 48.2,
|
||||
lng: 16.35,
|
||||
category: KEY,
|
||||
poi_type: KEY,
|
||||
address: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
opening_hours: null,
|
||||
cuisine: null,
|
||||
brand: null,
|
||||
brand_wikidata: null,
|
||||
charging: null,
|
||||
source: 'plugin:trail-finder',
|
||||
pluginId: 'trail-finder',
|
||||
rating: null,
|
||||
details: [{ label: 'Parking', value: '40 spaces' }],
|
||||
icon: 'Signpost',
|
||||
color: '#2f855a',
|
||||
...over,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function answer(rows: Poi[]): PluginAnswer {
|
||||
return { pois: rows, source: 'plugin:trail-finder', truncated: false, clamped: false }
|
||||
return { pois: rows, source: 'plugin:trail-finder', truncated: false, clamped: false };
|
||||
}
|
||||
|
||||
let search: ReturnType<typeof vi.spyOn>
|
||||
let search: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
usePluginStore.setState({ plugins: [TRAIL_FINDER], loaded: true })
|
||||
search = vi.spyOn(pluginPoiRepo, 'search').mockResolvedValue(answer([pluginPoi()]))
|
||||
})
|
||||
usePluginStore.setState({ plugins: [TRAIL_FINDER], loaded: true });
|
||||
search = vi.spyOn(pluginPoiRepo, 'search').mockResolvedValue(answer([pluginPoi()]));
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-019: hands the pill the core chips and then the plugin ones', () => {
|
||||
const { result } = setup()
|
||||
expect(result.current.categories.core.map(c => c.key)).toContain('cafe')
|
||||
expect(result.current.categories.plugin.map(c => c.key)).toEqual([KEY])
|
||||
})
|
||||
const { result } = setup();
|
||||
expect(result.current.categories.core.map((c) => c.key)).toContain('cafe');
|
||||
expect(result.current.categories.plugin.map((c) => c.key)).toEqual([KEY]);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-020: a plugin key asks the plugin POI repo, never the core search', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
// The TREK language rather than the locale: that is what the SDK promises a plugin.
|
||||
expect(search).toHaveBeenCalledWith('trail-finder', 'trailheads', BBOX, 'en', expect.any(AbortSignal))
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
expect(result.current.pois[0]).toMatchObject({ osm_id: 'plugin:trail-finder:th-1', color: '#2f855a', icon: 'Signpost' })
|
||||
expect(result.current.pois[0].details).toEqual([{ label: 'Parking', value: '40 spaces' }])
|
||||
})
|
||||
expect(search).toHaveBeenCalledWith('trail-finder', 'trailheads', BBOX, 'en', expect.any(AbortSignal));
|
||||
expect(pois).not.toHaveBeenCalled();
|
||||
expect(result.current.pois[0]).toMatchObject({
|
||||
osm_id: 'plugin:trail-finder:th-1',
|
||||
color: '#2f855a',
|
||||
icon: 'Signpost',
|
||||
});
|
||||
expect(result.current.pois[0].details).toEqual([{ label: 'Parking', value: '40 spaces' }]);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-021: offline the chip fails at once and no request is made', async () => {
|
||||
search.mockRestore()
|
||||
net.offline = true
|
||||
const api = vi.spyOn(pluginPoisApi, 'search')
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
search.mockRestore();
|
||||
net.offline = true;
|
||||
const api = vi.spyOn(pluginPoisApi, 'search');
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
|
||||
expect(api).not.toHaveBeenCalled()
|
||||
expect(result.current.loadingKeys.has(KEY)).toBe(false)
|
||||
expect(result.current.pois).toEqual([])
|
||||
})
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true));
|
||||
expect(api).not.toHaveBeenCalled();
|
||||
expect(result.current.loadingKeys.has(KEY)).toBe(false);
|
||||
expect(result.current.pois).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-022: switching to a core category cancels the plugin request without an error', async () => {
|
||||
const pending = deferred<PluginAnswer>()
|
||||
let signal: AbortSignal | undefined
|
||||
const pending = deferred<PluginAnswer>();
|
||||
let signal: AbortSignal | undefined;
|
||||
search.mockImplementation((...args: unknown[]) => {
|
||||
signal = args[4] as AbortSignal
|
||||
return pending.promise
|
||||
})
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(signal?.aborted).toBe(true)
|
||||
signal = args[4] as AbortSignal;
|
||||
return pending.promise;
|
||||
});
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
expect(signal?.aborted).toBe(true);
|
||||
|
||||
await act(async () => { pending.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.pois[0].category).toBe('cafe')
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
expect(result.current.loadingKeys.size).toBe(0)
|
||||
})
|
||||
await act(async () => {
|
||||
pending.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' }));
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(result.current.pois[0].category).toBe('cafe');
|
||||
expect(result.current.errorKeys.size).toBe(0);
|
||||
expect(result.current.loadingKeys.size).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-023: a failed plugin answer is retried like a core one', async () => {
|
||||
search.mockRejectedValueOnce(new Error('The plugin did not answer'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
|
||||
search.mockRejectedValueOnce(new Error('The plugin did not answer'));
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true));
|
||||
|
||||
act(() => { result.current.searchArea() })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
expect(search).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
act(() => {
|
||||
result.current.searchArea();
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
expect(result.current.errorKeys.size).toBe(0);
|
||||
expect(search).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-024: an answer landing after the plugin chip was switched off is dropped', async () => {
|
||||
const pending = deferred<PluginAnswer>()
|
||||
search.mockReturnValue(pending.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
const pending = deferred<PluginAnswer>();
|
||||
search.mockReturnValue(pending.promise);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
|
||||
await act(async () => { pending.resolve(answer([pluginPoi()])) })
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.active.size).toBe(0)
|
||||
})
|
||||
await act(async () => {
|
||||
pending.resolve(answer([pluginPoi()]));
|
||||
});
|
||||
expect(result.current.pois).toEqual([]);
|
||||
expect(result.current.active.size).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-025: a plugin chip that leaves the feed takes its selection and markers with it', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
|
||||
// The admin switched the plugin off, and the feed was read again.
|
||||
act(() => { usePluginStore.setState({ plugins: [] }) })
|
||||
expect(result.current.active.size).toBe(0)
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.categories.plugin).toEqual([])
|
||||
})
|
||||
act(() => {
|
||||
usePluginStore.setState({ plugins: [] });
|
||||
});
|
||||
expect(result.current.active.size).toBe(0);
|
||||
expect(result.current.pois).toEqual([]);
|
||||
expect(result.current.categories.plugin).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-026: a request in flight when the chip leaves the feed is cancelled', async () => {
|
||||
const pending = deferred<PluginAnswer>()
|
||||
let signal: AbortSignal | undefined
|
||||
const pending = deferred<PluginAnswer>();
|
||||
let signal: AbortSignal | undefined;
|
||||
search.mockImplementation((...args: unknown[]) => {
|
||||
signal = args[4] as AbortSignal
|
||||
return pending.promise
|
||||
})
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
signal = args[4] as AbortSignal;
|
||||
return pending.promise;
|
||||
});
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
|
||||
act(() => { usePluginStore.setState({ plugins: [{ ...TRAIL_FINDER, poiCategories: undefined }] }) })
|
||||
expect(signal?.aborted).toBe(true)
|
||||
await act(async () => { pending.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
|
||||
await waitFor(() => expect(result.current.loadingKeys.size).toBe(0))
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
})
|
||||
act(() => {
|
||||
usePluginStore.setState({ plugins: [{ ...TRAIL_FINDER, poiCategories: undefined }] });
|
||||
});
|
||||
expect(signal?.aborted).toBe(true);
|
||||
await act(async () => {
|
||||
pending.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' }));
|
||||
});
|
||||
await waitFor(() => expect(result.current.loadingKeys.size).toBe(0));
|
||||
expect(result.current.errorKeys.size).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-027: a core selection outlives any change to the plugin feed', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle('cafe');
|
||||
});
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1));
|
||||
|
||||
act(() => { usePluginStore.setState({ plugins: [] }) })
|
||||
expect(result.current.active).toEqual(new Set(['cafe']))
|
||||
expect(result.current.pois).toHaveLength(1)
|
||||
})
|
||||
act(() => {
|
||||
usePluginStore.setState({ plugins: [] });
|
||||
});
|
||||
expect(result.current.active).toEqual(new Set(['cafe']));
|
||||
expect(result.current.pois).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-POIEXPLORE-028: a 404 means the category is gone, so the plugin feed is read again', async () => {
|
||||
const loadPlugins = vi.fn(async () => {})
|
||||
usePluginStore.setState({ loadPlugins })
|
||||
search.mockRejectedValue(Object.assign(new Error('Request failed with status code 404'), { response: { status: 404 } }))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
const loadPlugins = vi.fn(async () => {});
|
||||
usePluginStore.setState({ loadPlugins });
|
||||
search.mockRejectedValue(
|
||||
Object.assign(new Error('Request failed with status code 404'), { response: { status: 404 } })
|
||||
);
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
result.current.onViewportChange(BBOX);
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
|
||||
expect(loadPlugins).toHaveBeenCalledTimes(1)
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true));
|
||||
expect(loadPlugins).toHaveBeenCalledTimes(1);
|
||||
// The fresh feed no longer lists it, so the chip and its selection go.
|
||||
act(() => { usePluginStore.setState({ plugins: [] }) })
|
||||
expect(result.current.active.size).toBe(0)
|
||||
expect(result.current.categories.plugin).toEqual([])
|
||||
act(() => {
|
||||
usePluginStore.setState({ plugins: [] });
|
||||
});
|
||||
expect(result.current.active.size).toBe(0);
|
||||
expect(result.current.categories.plugin).toEqual([]);
|
||||
|
||||
// Any other failure keeps the feed as it is.
|
||||
act(() => { usePluginStore.setState({ plugins: [TRAIL_FINDER] }) })
|
||||
search.mockRejectedValue(Object.assign(new Error('Request failed with status code 502'), { response: { status: 502 } }))
|
||||
act(() => { result.current.toggle(KEY) })
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
|
||||
expect(loadPlugins).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
act(() => {
|
||||
usePluginStore.setState({ plugins: [TRAIL_FINDER] });
|
||||
});
|
||||
search.mockRejectedValue(
|
||||
Object.assign(new Error('Request failed with status code 502'), { response: { status: 502 } })
|
||||
);
|
||||
act(() => {
|
||||
result.current.toggle(KEY);
|
||||
});
|
||||
await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true));
|
||||
expect(loadPlugins).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user