freshyo/apps/web-ui/src/routes/location-selector.tsx
2026-10-26 15:05:08 +05:30

350 lines
13 KiB
TypeScript

import { createFileRoute } from '@tanstack/react-router'
import { useCallback, useEffect, useRef, useState } from 'react'
import { AlertCircle, Loader2, Minus, Plus } from 'lucide-react'
export const Route = createFileRoute('/location-selector')({
// Optional centre override (?lat=&lng=&zoom=) so the map can be opened for a
// specific region; defaults to the Mahabubnagar town centre.
validateSearch: (search: Record<string, unknown>) => {
// TanStack's default search parser is parseSearchWith(JSON.parse), so
// `?lat=16.3570899` arrives here as a NUMBER, not a string. Accept both:
// requiring a string made every param validate to undefined, which dropped
// the query string from the URL entirely and left the map on its default
// centre for every region.
const num = (value: unknown): number | undefined => {
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
if (typeof value !== 'string' || value.trim() === '') return undefined
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : undefined
}
return {
lat: num(search.lat),
lng: num(search.lng),
zoom: num(search.zoom),
}
},
component: LocationSelectorPage,
})
type LatLngLiteral = { lat: number; lng: number }
// Minimal structural typings for the small slice of the Google Maps JS API used
// here, so this route does not require the @types/google.maps package.
interface GoogleMapClickEvent {
latLng?: { lat: () => number; lng: () => number } | null
}
interface GoogleMap {
addListener: (event: string, handler: (event: GoogleMapClickEvent) => void) => void
setZoom: (zoom: number) => void
getZoom: () => number | undefined
}
interface GoogleMarker {
setMap: (map: GoogleMap | null) => void
setPosition: (position: LatLngLiteral) => void
getPosition: () => { lat: () => number; lng: () => number } | null | undefined
addListener: (event: string, handler: () => void) => void
}
interface GoogleMapConstructor {
new (element: HTMLElement, options: Record<string, unknown>): GoogleMap
}
interface GoogleMarkerConstructor {
new (options: Record<string, unknown>): GoogleMarker
}
// The resolved `maps` + `marker` libraries (both constructors present).
interface GoogleMapsApi {
Map: GoogleMapConstructor
Marker: GoogleMarkerConstructor
}
type GoogleImportLibrary = (library: string, ...rest: string[]) => Promise<any>
// The global `google.maps` namespace, including the dynamic-import entry point.
interface GoogleMapsNamespace {
importLibrary?: GoogleImportLibrary
// Set by the bootstrap; the API invokes it once the namespace is fully ready.
__ib__?: () => void
}
type ReactNativeWebViewBridge = { postMessage: (message: string) => void }
type GoogleWindow = Window & {
google?: { maps?: GoogleMapsNamespace }
// Injected by react-native-webview when this page is embedded in user-ui.
ReactNativeWebView?: ReactNativeWebViewBridge
}
// Mahabubnagar (Mahbubnagar), Telangana, India — default map center.
const MAHABUBNAGAR_CENTER: LatLngLiteral = { lat: 16.7488, lng: 77.9851 }
const DEFAULT_ZOOM = 15
// Google Maps JS API key. Provide it via a Vite env var, e.g. in
// apps/web-ui/.env:
// VITE_GOOGLE_MAPS_API_KEY=your-key
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY as string | undefined
let googleMapsLoader: Promise<GoogleMapsApi> | null = null
/**
* Google's recommended "Dynamic Library Import" bootstrap
* (https://goo.gle/js-api-loading).
*
* It defines `google.maps.importLibrary` synchronously and loads the API with
* the `callback` signal, so we never read `google.maps` before it exists. A raw
* `<script onload>` check races with `loading=async` (onload fires before the
* namespace is populated) and reports the namespace as unavailable.
*/
function ensureImportLibrary(apiKey: string): GoogleImportLibrary {
const w = window as GoogleWindow
const g = (w.google ??= {})
const maps = (g.maps ??= {})
if (maps.importLibrary) return maps.importLibrary
const requested = new Set<string>()
let loading: Promise<void> | null = null
const load = () => {
if (loading) return loading
loading = new Promise<void>((resolve, reject) => {
const params = new URLSearchParams()
params.set('key', apiKey)
params.set('v', 'weekly')
params.set('libraries', Array.from(requested).join(','))
params.set('loading', 'async')
params.set('callback', 'google.maps.__ib__')
const script = document.createElement('script')
script.src = `https://maps.googleapis.com/maps/api/js?${params.toString()}`
script.async = true
const nonce = document.querySelector('script[nonce]')?.getAttribute('nonce')
if (nonce) script.setAttribute('nonce', nonce)
script.onerror = () => reject(new Error('The Google Maps JavaScript API could not load.'))
// The API calls this once it — and its namespace — is ready.
maps.__ib__ = () => resolve()
document.head.appendChild(script)
})
return loading
}
const importLibrary: GoogleImportLibrary = (library, ...rest) => {
requested.add(library)
for (const name of rest) requested.add(name)
return load().then(() => {
const real = maps.importLibrary
if (!real || real === importLibrary) {
throw new Error('Google Maps importLibrary did not initialize.')
}
return real(library, ...rest)
})
}
maps.importLibrary = importLibrary
return importLibrary
}
function loadGoogleMaps(apiKey: string): Promise<GoogleMapsApi> {
if (googleMapsLoader) return googleMapsLoader
googleMapsLoader = (async () => {
const importLibrary = ensureImportLibrary(apiKey)
// Register both libraries so the bootstrap fetches them together.
const [mapsLib, markerLib] = await Promise.all([
importLibrary('maps'),
importLibrary('marker'),
])
const Map: GoogleMapConstructor | undefined = mapsLib?.Map
const Marker: GoogleMarkerConstructor | undefined = markerLib?.Marker
if (!Map || !Marker) {
throw new Error('Google Maps loaded but the maps/marker libraries are unavailable.')
}
return { Map, Marker }
})()
return googleMapsLoader
}
// When embedded in the user-ui WebView, hand the confirmed coordinates back to
// the native host. This is undefined in a normal browser, where the console.log
// below remains the only signal.
function sendCoordsToHost(coords: LatLngLiteral) {
const payload = { type: 'location-selected', latitude: coords.lat, longitude: coords.lng }
// Embedded in the user-ui native app.
const bridge = (window as GoogleWindow).ReactNativeWebView
if (bridge?.postMessage) {
bridge.postMessage(JSON.stringify(payload))
return
}
// Embedded as an iframe in the web app.
if (window.parent && window.parent !== window) {
window.parent.postMessage(payload, window.location.origin)
}
}
function LocationSelectorPage() {
const mapContainerRef = useRef<HTMLDivElement | null>(null)
const mapRef = useRef<GoogleMap | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [loadError, setLoadError] = useState<string | null>(null)
// The chosen point. `null` = untouched: the pin is on the map, but the user
// has not tapped/dragged it yet, so Continue stays disabled.
const [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null)
const search = Route.useSearch()
useEffect(() => {
if (!GOOGLE_MAPS_API_KEY) {
setLoadError(
'Google Maps API key is not configured yet. Set VITE_GOOGLE_MAPS_API_KEY to enable the map.'
)
setIsLoading(false)
return
}
const container = mapContainerRef.current
if (!container || mapRef.current) return
const center: LatLngLiteral =
search.lat != null && search.lng != null
? { lat: search.lat, lng: search.lng }
: MAHABUBNAGAR_CENTER
const zoom = search.zoom ?? DEFAULT_ZOOM
let cancelled = false
loadGoogleMaps(GOOGLE_MAPS_API_KEY)
.then((maps) => {
if (cancelled) return
const map = new maps.Map(container, {
center,
zoom,
mapTypeControl: false,
streetViewControl: false,
fullscreenControl: false,
zoomControl: false,
clickableIcons: false,
})
mapRef.current = map
// The pin is on the map from the start, at the map centre. Continue is
// disabled until the user touches it (tap anywhere on the map, tap the
// pin, or drag the pin), which is what writes `pendingCoords`.
const marker = new maps.Marker({
map,
position: center,
draggable: true,
})
const chooseMarkerPosition = () => {
const position = marker.getPosition()
if (!position) return
setPendingCoords({ lat: position.lat(), lng: position.lng() })
}
// `dragstart` enables Continue as soon as the pin is grabbed; `dragend`
// stores the final position. A plain tap on the pin also selects it.
marker.addListener('dragstart', chooseMarkerPosition)
marker.addListener('dragend', chooseMarkerPosition)
marker.addListener('click', chooseMarkerPosition)
map.addListener('click', (event) => {
const latLng = event.latLng
if (!latLng) return
const coords = { lat: latLng.lat(), lng: latLng.lng() }
marker.setPosition(coords)
setPendingCoords(coords)
})
setIsLoading(false)
})
.catch((error: unknown) => {
if (cancelled) return
setLoadError(error instanceof Error ? error.message : 'Failed to load Google Maps.')
setIsLoading(false)
})
return () => {
cancelled = true
}
}, [])
const handleConfirm = useCallback(() => {
if (!pendingCoords) return
// Required behavior: log the chosen coordinates to the console.
console.log('[location-selector] confirmed coordinates:', {
latitude: pendingCoords.lat,
longitude: pendingCoords.lng,
})
// Hand the coordinates back to the native host when embedded.
sendCoordsToHost(pendingCoords)
}, [pendingCoords])
const handleZoom = useCallback((delta: number) => {
const map = mapRef.current
if (!map) return
const current = map.getZoom() ?? DEFAULT_ZOOM
map.setZoom(Math.min(21, Math.max(1, current + delta)))
}, [])
return (
<div className="fixed inset-0 bg-white">
<div ref={mapContainerRef} className="h-full w-full" />
{!isLoading && !loadError && (
<div className="absolute right-4 top-4 z-10 flex flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-md">
<button
type="button"
aria-label="Zoom in"
onClick={() => handleZoom(1)}
className="flex h-10 w-10 items-center justify-center text-gray-700 transition-colors hover:bg-gray-50"
>
<Plus className="h-5 w-5" />
</button>
<div className="h-px bg-gray-200" />
<button
type="button"
aria-label="Zoom out"
onClick={() => handleZoom(-1)}
className="flex h-10 w-10 items-center justify-center text-gray-700 transition-colors hover:bg-gray-50"
>
<Minus className="h-5 w-5" />
</button>
</div>
)}
{isLoading && !loadError && (
<div className="absolute inset-0 flex flex-col items-center justify-center bg-white/70">
<Loader2 className="h-7 w-7 animate-spin text-brand-500" />
<p className="mt-2 text-sm text-gray-600">Loading map...</p>
</div>
)}
{loadError && (
<div className="absolute inset-0 flex flex-col items-center justify-center bg-white/90 p-6 text-center">
<AlertCircle className="mb-2 h-9 w-9 text-amber-500" />
<p className="max-w-md text-sm text-gray-700">{loadError}</p>
</div>
)}
{!isLoading && !loadError && (
<div
className="absolute inset-x-0 bottom-0 z-10 border-t border-gray-100 bg-white px-4 pt-3 shadow-[0_-2px_10px_rgba(0,0,0,0.06)]"
style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}
>
<p className="mb-2 text-center text-xs text-gray-500">
Drag the pin or tap the map to choose your exact location
</p>
<button
type="button"
onClick={handleConfirm}
disabled={pendingCoords === null}
className="w-full rounded-lg bg-brand-600 px-5 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:hover:bg-gray-300"
>
Continue
</button>
</div>
)}
</div>
)
}