Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions martin/martin-ui/src/components/dialogs/tile-inspect-map.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
'use client';

import MaplibreInspect from '@maplibre/maplibre-gl-inspect';
import type { MapRef } from '@vis.gl/react-maplibre';
import { Layer, Map as MapLibreMap, Source } from '@vis.gl/react-maplibre';
import { Popup } from 'maplibre-gl';
import { type ErrorInfo, useCallback, useEffect, useId, useRef } from 'react';
import { Toaster } from '@/components/ui/toaster';
import { useAsyncOperation } from '@/hooks/use-async-operation';
import { useToast } from '@/hooks/use-toast';
import { buildMartinUrl } from '@/lib/api';
import type { TileSource } from '@/lib/types';
import { ErrorBoundary } from '../error/error-boundary';

interface TileInspectDialogMapProps {
name: string;
source: TileSource;
}

interface TileJson {
bounds: [number, number, number, number];
maxzoom?: number;
minzoom?: number;
center?: [number, number, number];
}

const fetchTileJson = async (endpoint: string): Promise<TileJson> => {
const response = await fetch(buildMartinUrl(`/${endpoint}`));
if (!response.ok) {
throw new Error(`Failed to fetch tileJson: ${response.statusText}`);
}
return response.json();
};

export function TileInspectDialogMap({ name, source }: TileInspectDialogMapProps) {
const { toast } = useToast();
const id = useId();
const mapRef = useRef<MapRef>(null);
const inspectControlRef = useRef<MaplibreInspect>(null);

const tileJsonOperation = useAsyncOperation<TileJson>(() => fetchTileJson(name), {
onError: (error: Error) => console.error('TileJson Fetch Failed:', error),
showErrorToast: false,
});

const isImageSource = ['image/gif', 'image/jpeg', 'image/png', 'image/webp'].includes(
source.content_type,
);

// biome-ignore lint/correctness/useExhaustiveDependencies: if we list tileJson below, this is an infinte loop
useEffect(() => {
tileJsonOperation.execute();
}, []);

const configureMap = useCallback(() => {
if (!tileJsonOperation.data) {
return;
}
if (!mapRef.current) {
console.error('Map not found despite being initialized, this cannot happen');
return;
}
const map = mapRef.current.getMap();
const tileJson: TileJson = tileJsonOperation.data;
//Error when first value set to -180. it gets resolved on setting to -179 or lower. Other values work fine.
map.setMaxBounds([
[tileJson.bounds[0] === -180 ? -179 : tileJson.bounds[0], tileJson.bounds[1]],
[tileJson.bounds[2], tileJson.bounds[3]],
]);
if (tileJson.minzoom) {
map.setMinZoom(tileJson.minzoom);
map.setZoom(tileJson.minzoom);
}
if (tileJson.maxzoom) {
map.setMaxZoom(tileJson.maxzoom);
}
if (tileJson.center) {
map.setCenter([tileJson.center[0], tileJson.center[1]]);
}
}, [tileJsonOperation.data]);

const addInspectorToMap = useCallback(() => {
if (!mapRef.current) {
console.error('Map not found despite being initialized, this cannot happen');
return;
}
const map = mapRef.current.getMap();

map.addSource(name, { type: 'vector', url: buildMartinUrl(`/${name}`) });
// Import and add the inspect control
if (inspectControlRef.current) {
map.removeControl(inspectControlRef.current);
}

inspectControlRef.current = new MaplibreInspect({
popup: new Popup({
closeButton: false,
closeOnClick: false,
}),
showInspectButton: false,
showInspectMap: true,
showInspectMapPopup: true,
showInspectMapPopupOnHover: true,
showMapPopup: true,
});

map.addControl(inspectControlRef.current);

configureMap();
}, [name, configureMap]);

return (
<ErrorBoundary
onError={(error: Error, errorInfo: ErrorInfo) => {
console.error('Application error:', error, errorInfo);
toast({
description: 'An unexpected error occurred. The page will reload automatically.',
title: 'Application Error',
variant: 'destructive',
});

// Auto-reload after 3 seconds
setTimeout(() => {
window.location.reload();
}, 3000);
}}
>
{isImageSource ? (
<MapLibreMap
onLoad={configureMap}
ref={mapRef}
reuseMaps={false}
style={{
height: '500px',
width: '100%',
}}
>
<Source id={`${id}tile-source`} type="raster" url={buildMartinUrl(`/${name}`)} />
<Layer id={`${id}tile-layer`} source={`${id}tile-source`} type="raster" />
</MapLibreMap>
) : (
<MapLibreMap
onLoad={addInspectorToMap}
ref={mapRef}
reuseMaps={false}
style={{
height: '500px',
width: '100%',
}}
></MapLibreMap>
)}
<Toaster />
</ErrorBoundary>
);
}
77 changes: 14 additions & 63 deletions martin/martin-ui/src/components/dialogs/tile-inspect.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { useCallback, useId, useRef } from 'react';
import { Suspense } from 'react';
import {
Dialog,
DialogContent,
Expand All @@ -10,54 +10,25 @@ import {
} from '@/components/ui/dialog';
import type { TileSource } from '@/lib/types';
import '@maplibre/maplibre-gl-inspect/dist/maplibre-gl-inspect.css';
import MaplibreInspect from '@maplibre/maplibre-gl-inspect';
import type { MapRef } from '@vis.gl/react-maplibre';
import { Layer, Map as MapLibreMap, Source } from '@vis.gl/react-maplibre';
import { Database } from 'lucide-react';
import { Popup } from 'maplibre-gl';
import { buildMartinUrl } from '@/lib/api';
import { LoadingSpinner } from '../loading/loading-spinner';
import { TileInspectDialogMap } from './tile-inspect-map';

interface TileInspectDialogProps {
name: string;
source: TileSource;
onCloseAction: () => void;
}

export function TileInspectDialog({ name, source, onCloseAction }: TileInspectDialogProps) {
const id = useId();
const mapRef = useRef<MapRef>(null);
const inspectControlRef = useRef<MaplibreInspect>(null);

const addInspectorToMap = useCallback(() => {
if (!mapRef.current) {
console.error('Map not found despite being initialized, this cannot happen');
return;
}
const map = mapRef.current.getMap();

map.addSource(name, { type: 'vector', url: buildMartinUrl(`/${name}`) });
// Import and add the inspect control
if (inspectControlRef.current) {
map.removeControl(inspectControlRef.current);
}

inspectControlRef.current = new MaplibreInspect({
popup: new Popup({
closeButton: false,
closeOnClick: false,
}),
showInspectButton: false,
showInspectMap: true,
showInspectMapPopup: true,
showInspectMapPopupOnHover: true,
showMapPopup: true,
});

map.addControl(inspectControlRef.current);
}, [name]);
const isImageSource = ['image/gif', 'image/jpeg', 'image/png', 'image/webp'].includes(
source.content_type,
function TileMapLoading() {
return (
<div className="flex justify-center items-center text-white text-3xl w-full h-125">
<LoadingSpinner />
</div>
);
}

export function TileInspectDialog({ name, source, onCloseAction }: TileInspectDialogProps) {
return (
<Dialog onOpenChange={(v) => !v && onCloseAction()} open={true}>
<DialogContent className="max-w-6xl w-full p-6 max-h-[90vh] overflow-auto">
Expand All @@ -74,29 +45,9 @@ export function TileInspectDialog({ name, source, onCloseAction }: TileInspectDi

<div className="space-y-4">
<section className="border rounded-lg overflow-hidden">
{isImageSource ? (
<MapLibreMap
ref={mapRef}
reuseMaps={false}
style={{
height: '500px',
width: '100%',
}}
>
<Source id={`${id}tile-source`} type="raster" url={buildMartinUrl(`/${name}`)} />
<Layer id={`${id}tile-layer`} source={`${id}tile-source`} type="raster" />
</MapLibreMap>
) : (
<MapLibreMap
onLoad={addInspectorToMap}
ref={mapRef}
reuseMaps={false}
style={{
height: '500px',
width: '100%',
}}
></MapLibreMap>
)}
<Suspense fallback={<TileMapLoading />}>
<TileInspectDialogMap name={name} source={source} />
</Suspense>
</section>
{/* Source Information */}
<section className="bg-muted/30 p-4 rounded-lg">
Expand Down
Loading