feat: task 2.1 MapView singleton + mapReady gate
- pnpm add maplibre-gl + -D @types/geojson. - src/map/core/styles.ts: defaultStyle (OSM raster bootstrap; 2.2 replaces with the basemap-switcher descriptor table). - src/map/core/map-view.tsx: module-level Map singleton lazily created on first <MapView> mount, attached to a class="trm-map-host" detached <div> that React refs append/remove on mount/unmount. Style-data lifecycle flips mapReady false on every styledata event, polls loaded() at 33ms intervals, flips ready true once the style is loaded — the canonical MapLibre style-swap dance. - Exports getMap()/getMapReady()/subscribeMapReady()/useMapReady (via useSyncExternalStore for SSR-safe + concurrent-safe reads). getMap() throws if called pre-mount; the explicit failure mode beats a null-able top-level export. - src/routes/_authed/monitor.tsx: new /monitor route, full-viewport <MapView /> for 2.1 (no children — subsequent tasks plug in here). - src/routes/_authed/index.tsx: home-page card now links to /monitor. - eslint.config.js: override for src/map/** + src/live/** disables react-refresh/only-export-components. Same pattern as the existing overrides for shadcn primitives and route files. Deviation: spec sketched a top-level `map` constant export; implemented as `getMap(): MapLibreMap` (a function) so the singleton stays lazy until <MapView> mounts. Top-level constant would either force eager init (breaks SSR/tests) or be nullable (footgun). The function form throws a clear error if called pre-mount. Bundle: /monitor lazy chunk is 1MB raw / 274KB gzipped (MapLibre + CSS). Other routes unaffected. Vite chunk-size warning is harmless.
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
import { useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react';
|
||||
import maplibregl, { type Map as MapLibreMap } from 'maplibre-gl';
|
||||
import 'maplibre-gl/dist/maplibre-gl.css';
|
||||
import { defaultStyle } from './styles';
|
||||
|
||||
// ---------- Singleton ----------------------------------------------------
|
||||
|
||||
let _map: MapLibreMap | null = null;
|
||||
let _container: HTMLDivElement | null = null;
|
||||
|
||||
function getOrCreateMap(): MapLibreMap {
|
||||
if (_map && _container) return _map;
|
||||
_container = document.createElement('div');
|
||||
_container.className = 'trm-map-host';
|
||||
_container.style.width = '100%';
|
||||
_container.style.height = '100%';
|
||||
_map = new maplibregl.Map({
|
||||
container: _container,
|
||||
style: defaultStyle,
|
||||
attributionControl: { compact: true },
|
||||
});
|
||||
_map.on('styledata', onStyleData);
|
||||
return _map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only access to the singleton. Throws if called before `<MapView>`
|
||||
* has mounted (and therefore before the singleton is created).
|
||||
*
|
||||
* Side-effect-only `Map*` components should call this inside their
|
||||
* `useEffect` *after* the `mapReady` gate has flipped true — by which
|
||||
* point the singleton exists and the style has loaded.
|
||||
*/
|
||||
export function getMap(): MapLibreMap {
|
||||
if (!_map) {
|
||||
throw new Error(
|
||||
'getMap() called before <MapView> mounted. Wrap the call in a Map* component or wait for useMapReady().',
|
||||
);
|
||||
}
|
||||
return _map;
|
||||
}
|
||||
|
||||
// ---------- mapReady gate -----------------------------------------------
|
||||
|
||||
let _ready = false;
|
||||
const _readyListeners = new Set<(ready: boolean) => void>();
|
||||
|
||||
function setReady(value: boolean): void {
|
||||
if (_ready === value) return;
|
||||
_ready = value;
|
||||
for (const cb of _readyListeners) cb(value);
|
||||
}
|
||||
|
||||
export function getMapReady(): boolean {
|
||||
return _ready;
|
||||
}
|
||||
|
||||
export function subscribeMapReady(cb: (ready: boolean) => void): () => void {
|
||||
_readyListeners.add(cb);
|
||||
return () => {
|
||||
_readyListeners.delete(cb);
|
||||
};
|
||||
}
|
||||
|
||||
export function useMapReady(): boolean {
|
||||
return useSyncExternalStore(
|
||||
subscribeMapReady,
|
||||
getMapReady,
|
||||
() => false, // SSR fallback
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Style-data lifecycle handler.
|
||||
*
|
||||
* `styledata` fires for every style mutation (initial load, setStyle,
|
||||
* source updates). We treat it as "the style might have changed; re-check
|
||||
* loaded() and gate the children". `setReady(false)` first so children
|
||||
* unmount and clean up their custom sources/layers; once `loaded()` is
|
||||
* true, flip back to ready and let them remount.
|
||||
*/
|
||||
function onStyleData(): void {
|
||||
setReady(false);
|
||||
const check = (): void => {
|
||||
if (_map?.loaded()) {
|
||||
setReady(true);
|
||||
} else {
|
||||
setTimeout(check, 33);
|
||||
}
|
||||
};
|
||||
check();
|
||||
}
|
||||
|
||||
// ---------- <MapView> ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* The canonical entry point for any view that uses the map.
|
||||
*
|
||||
* Mounts the singleton's detached `<div>` into a React-managed ref on
|
||||
* mount; detaches on unmount. The map instance itself survives navigation
|
||||
* — its WebGL context, registered sprites, and basemap state all persist.
|
||||
*
|
||||
* Children render only when `mapReady` is true, so side-effect-only
|
||||
* `Map*` components can safely call `getMap().addSource(...)` from their
|
||||
* `useEffect` setup without racing the style load.
|
||||
*/
|
||||
export function MapView({ children }: { children?: ReactNode }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const ready = useMapReady();
|
||||
|
||||
useEffect(() => {
|
||||
const map = getOrCreateMap();
|
||||
const container = _container;
|
||||
const host = ref.current;
|
||||
if (!container || !host) return;
|
||||
|
||||
host.appendChild(container);
|
||||
map.resize();
|
||||
|
||||
const onWindowResize = (): void => {
|
||||
map.resize();
|
||||
};
|
||||
window.addEventListener('resize', onWindowResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', onWindowResize);
|
||||
// Detach but DON'T destroy the map — singleton lives on.
|
||||
if (container.parentNode === host) {
|
||||
host.removeChild(container);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="absolute inset-0">
|
||||
{ready && children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { StyleSpecification } from 'maplibre-gl';
|
||||
|
||||
/**
|
||||
* Bootstrap basemap style used until task 2.2 (basemap switcher) lands.
|
||||
*
|
||||
* Plain OSM raster tiles. Free, attribution-required, polite User-Agent
|
||||
* recommended for any production load. For dogfood-scale traffic this is
|
||||
* fine.
|
||||
*/
|
||||
export const defaultStyle: StyleSpecification = {
|
||||
version: 8,
|
||||
sources: {
|
||||
raster: {
|
||||
type: 'raster',
|
||||
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
|
||||
tileSize: 256,
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
minzoom: 0,
|
||||
maxzoom: 19,
|
||||
},
|
||||
},
|
||||
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf',
|
||||
layers: [{ id: 'raster', type: 'raster', source: 'raster' }],
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect } from 'react';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router';
|
||||
import { useAuthStore } from '@/auth';
|
||||
import { LogoutButton } from '@/ui/components/logout-button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/ui/primitives/card';
|
||||
@@ -40,11 +40,16 @@ function HomePage() {
|
||||
<CardHeader>
|
||||
<CardTitle>Live monitoring map</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The live-position map lands in Phase 2 once the Processor's WebSocket endpoint is
|
||||
shipped (Phase 1.5 — already complete on the processor side).
|
||||
Watch registered devices report their positions in real time.
|
||||
</p>
|
||||
<Link
|
||||
to="/monitor"
|
||||
className="inline-flex items-center gap-1 text-sm font-medium underline underline-offset-4"
|
||||
>
|
||||
Open live map →
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { MapView } from '@/map/core/map-view';
|
||||
|
||||
export const Route = createFileRoute('/_authed/monitor')({
|
||||
component: MonitorPage,
|
||||
});
|
||||
|
||||
function MonitorPage() {
|
||||
return (
|
||||
// 3.5rem ≈ 56 px reserved for a future top-bar (Phase 3 chrome).
|
||||
// For now the parent _authed layout has no top-bar, so the map can
|
||||
// fill the full viewport — adjust when chrome lands.
|
||||
<div className="relative h-[calc(100vh-0rem)] w-full">
|
||||
<MapView />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user