Refactor point value object and add observability
This commit is contained in:
Generated
+58
@@ -13,6 +13,7 @@
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"i18next": "^25.5.3",
|
||||
@@ -1156,6 +1157,40 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@radix-ui/react-toast": {
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.15.tgz",
|
||||
"integrity": "sha512-3OSz3TacUWy4WtOXV38DggwxoqJK4+eDkNMl5Z/MJZaoUPaP4/9lf81xXMe1I2ReTAptverZUpbPY4wWwWyL5g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@radix-ui/primitive": "1.1.3",
|
||||
"@radix-ui/react-collection": "1.1.7",
|
||||
"@radix-ui/react-compose-refs": "1.1.2",
|
||||
"@radix-ui/react-context": "1.1.2",
|
||||
"@radix-ui/react-dismissable-layer": "1.1.11",
|
||||
"@radix-ui/react-portal": "1.1.9",
|
||||
"@radix-ui/react-presence": "1.1.5",
|
||||
"@radix-ui/react-primitive": "2.1.3",
|
||||
"@radix-ui/react-use-callback-ref": "1.1.1",
|
||||
"@radix-ui/react-use-controllable-state": "1.2.2",
|
||||
"@radix-ui/react-use-layout-effect": "1.1.1",
|
||||
"@radix-ui/react-visually-hidden": "1.2.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "*",
|
||||
"@types/react-dom": "*",
|
||||
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@radix-ui/react-use-callback-ref": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
|
||||
@@ -1241,6 +1276,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@radix-ui/react-visually-hidden": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.3.tgz",
|
||||
"integrity": "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@radix-ui/react-primitive": "2.1.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "*",
|
||||
"@types/react-dom": "*",
|
||||
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm64": {
|
||||
"version": "1.0.0-beta.41",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-beta.41.tgz",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"i18next": "^25.5.3",
|
||||
|
||||
+87
-28
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { Layers, Menu, PanelRightClose, PanelRightOpen } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Layers, Loader2, Menu, PanelRightClose, PanelRightOpen } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { AppHeader } from '@/components/layout/AppHeader'
|
||||
@@ -23,12 +23,39 @@ import { useHotspotFeed } from '@/hooks/useHotspotFeed'
|
||||
import { useLeafletHeatmap, type TileProvider } from '@/hooks/useLeafletHeatmap'
|
||||
import { useUserLocation } from '@/hooks/useUserLocation'
|
||||
import { cn, distanceInKm, formatCoordinate, formatRelativeTime, formatTimestamp } from '@/lib/utils'
|
||||
import type { LatLng } from '@/types/api'
|
||||
import type { Point } from '@/types/api'
|
||||
import { Toaster } from '@/components/ui/toaster'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
|
||||
const RADIUS_KM = 1
|
||||
|
||||
interface LocationGateProps {
|
||||
title: string
|
||||
message: string
|
||||
actionLabel: string
|
||||
onRetry: () => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
function LocationGate({ title, message, actionLabel, onRetry, isLoading }: LocationGateProps) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-background px-6 text-center">
|
||||
<div className="max-w-md space-y-6">
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-foreground">{title}</h1>
|
||||
<p className="text-sm text-muted-foreground">{message}</p>
|
||||
</div>
|
||||
<Button onClick={onRetry} disabled={isLoading} className="inline-flex items-center gap-2">
|
||||
{isLoading && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
<span>{actionLabel}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [pendingSpot, setPendingSpot] = useState<LatLng | null>(null)
|
||||
const [pendingSpot, setPendingSpot] = useState<Point | null>(null)
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false)
|
||||
const [isConfirming, setIsConfirming] = useState(false)
|
||||
const [tileProvider, setTileProvider] = useState<TileProvider>('openstreetmap')
|
||||
@@ -44,6 +71,7 @@ export default function App() {
|
||||
}
|
||||
return window.innerWidth < 768
|
||||
})
|
||||
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = i18n.language === 'fr' ? 'fr-FR' : 'en-US'
|
||||
const distanceFormatter = useMemo(
|
||||
@@ -63,6 +91,13 @@ export default function App() {
|
||||
[t],
|
||||
)
|
||||
|
||||
const {
|
||||
location: userLocation,
|
||||
error: locationError,
|
||||
isRequesting: isRequestingLocation,
|
||||
refresh: refreshLocation,
|
||||
} = useUserLocation()
|
||||
|
||||
const {
|
||||
status,
|
||||
error,
|
||||
@@ -73,9 +108,7 @@ export default function App() {
|
||||
selectVisibleLatestByUser,
|
||||
myLatestPoint,
|
||||
lastUpdated,
|
||||
} = useHotspotFeed()
|
||||
|
||||
const { location: userLocation, error: locationError, isRequesting: isRequestingLocation } = useUserLocation()
|
||||
} = useHotspotFeed({ userLocation: userLocation ?? null })
|
||||
|
||||
const visibleDensity = useMemo(
|
||||
() => selectVisibleDensity(userLocation ?? null),
|
||||
@@ -102,7 +135,7 @@ export default function App() {
|
||||
if (!myLatestPoint) {
|
||||
return null
|
||||
}
|
||||
if (userLocation && distanceInKm(userLocation, myLatestPoint) > RADIUS_KM) {
|
||||
if (userLocation && distanceInKm(userLocation, myLatestPoint.signalLocation) > RADIUS_KM) {
|
||||
return null
|
||||
}
|
||||
return myLatestPoint
|
||||
@@ -135,12 +168,27 @@ export default function App() {
|
||||
tileProvider,
|
||||
})
|
||||
|
||||
const { toast } = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
if (!error) {
|
||||
return
|
||||
}
|
||||
const description = error.detail ?? t(error.key, error.values ?? {})
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: t('errors.title'),
|
||||
description,
|
||||
duration: 6000,
|
||||
})
|
||||
}, [error, t, toast])
|
||||
|
||||
const handleConfirmSignal = useCallback(async () => {
|
||||
if (!pendingSpot) {
|
||||
return
|
||||
}
|
||||
setIsConfirming(true)
|
||||
const result = await submitPoint(pendingSpot.lat, pendingSpot.lng)
|
||||
const result = await submitPoint(pendingSpot)
|
||||
setIsConfirming(false)
|
||||
if (result.success) {
|
||||
setIsConfirmOpen(false)
|
||||
@@ -164,7 +212,7 @@ export default function App() {
|
||||
|
||||
const handleFocusMySignal = useCallback(() => {
|
||||
if (myVisibleSignal) {
|
||||
focusOn({ lat: myVisibleSignal.lat, lng: myVisibleSignal.lng }, 15)
|
||||
focusOn({ lat: myVisibleSignal.signalLocation.lat, lng: myVisibleSignal.signalLocation.lng }, 15)
|
||||
}
|
||||
}, [focusOn, myVisibleSignal])
|
||||
|
||||
@@ -209,12 +257,12 @@ export default function App() {
|
||||
.slice(0, 8)
|
||||
.map((point) => {
|
||||
const coordinates = t('common.coordinates', {
|
||||
lat: formatCoordinate(point.lat, locale),
|
||||
lng: formatCoordinate(point.lng, locale),
|
||||
lat: formatCoordinate(point.signalLocation.lat, locale),
|
||||
lng: formatCoordinate(point.signalLocation.lng, locale),
|
||||
})
|
||||
const distanceLabel = userLocation
|
||||
? t('activityItem.distance', {
|
||||
distance: `${distanceFormatter.format(distanceInKm(userLocation, point))} km`,
|
||||
distance: `${distanceFormatter.format(distanceInKm(userLocation, point.signalLocation))} km`,
|
||||
})
|
||||
: formatTimestamp(point.createdAt, locale)
|
||||
return {
|
||||
@@ -223,7 +271,7 @@ export default function App() {
|
||||
subtitle: t('activityItem.user', { id: point.userKey.slice(0, 4).toUpperCase() }),
|
||||
timestampLabel: formatRelativeTime(point.createdAt, locale),
|
||||
distanceLabel,
|
||||
onFocus: () => focusOn({ lat: point.lat, lng: point.lng }, 15),
|
||||
onFocus: () => focusOn({ lat: point.signalLocation.lat, lng: point.signalLocation.lng }, 15),
|
||||
}
|
||||
}),
|
||||
[visiblePoints, userLocation, focusOn, distanceFormatter, t, locale],
|
||||
@@ -240,10 +288,27 @@ export default function App() {
|
||||
: 'translate-y-[calc(100%+1rem)] sm:translate-x-[calc(100%+2rem)]',
|
||||
)
|
||||
|
||||
if (!userLocation) {
|
||||
const gateTitle = t('location.gate.title')
|
||||
const gateMessage = locationError ? t(locationError) : t('location.gate.description')
|
||||
const gateAction = isRequestingLocation ? t('location.gate.loading') : t('location.gate.action')
|
||||
|
||||
return (
|
||||
<LocationGate
|
||||
title={gateTitle}
|
||||
message={gateMessage}
|
||||
actionLabel={gateAction}
|
||||
onRetry={refreshLocation}
|
||||
isLoading={isRequestingLocation}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative min-h-screen w-full overflow-hidden bg-background text-foreground">
|
||||
<MapViewport
|
||||
containerRef={mapContainerRef}
|
||||
<>
|
||||
<div className="relative min-h-screen w-full overflow-hidden bg-background text-foreground">
|
||||
<MapViewport
|
||||
containerRef={mapContainerRef}
|
||||
isPosting={isPosting || isConfirming}
|
||||
isLoading={isLoading}
|
||||
confirmationHint={isConfirmOpen ? t('map.confirmationHint') : null}
|
||||
@@ -401,24 +466,18 @@ export default function App() {
|
||||
<span className="text-muted-foreground">{t('dialog.confirmSignal.longitude')}</span>
|
||||
<span className="font-medium text-foreground">{confirmationLng}°</span>
|
||||
</div>
|
||||
<p className="mt-4 text-xs text-muted-foreground">{t('dialog.confirmSignal.reach', { radius: RADIUS_KM })}</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('dialog.confirmSignal.reach', { radius: RADIUS_KM })}
|
||||
</p>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isConfirming}>{t('dialog.confirmSignal.cancel')}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={isDialogDisabled}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
handleConfirmSignal().catch(() => undefined)
|
||||
}}
|
||||
>
|
||||
<AlertDialogAction onClick={handleConfirmSignal} disabled={isDialogDisabled}>
|
||||
{isConfirming ? t('dialog.confirmSignal.sending') : t('dialog.confirmSignal.confirm')}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
<Toaster />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import * as React from 'react'
|
||||
import * as ToastPrimitives from '@radix-ui/react-toast'
|
||||
import { cva, type VariantProps } from 'class-variance-authority'
|
||||
import { X } from 'lucide-react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-x-0 top-4 z-[1000] mx-auto flex w-full max-w-sm flex-col gap-2 px-4 sm:right-4 sm:left-auto sm:mx-0 sm:w-96',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
|
||||
const toastVariants = cva(
|
||||
'group pointer-events-auto relative flex w-full items-start gap-3 overflow-hidden rounded-2xl border border-border bg-background p-4 shadow-lg transition-all',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-background text-foreground',
|
||||
destructive: 'border-destructive/60 bg-destructive text-destructive-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
|
||||
>(({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props}>
|
||||
{props.children}
|
||||
</ToastPrimitives.Root>
|
||||
)
|
||||
})
|
||||
Toast.displayName = ToastPrimitives.Root.displayName
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Action
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex h-8 shrink-0 items-center justify-center rounded-full border border-border/60 bg-background px-3 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
||||
|
||||
const ToastClose = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'absolute right-3 top-3 rounded-full p-1 text-foreground/70 transition-colors hover:bg-foreground/10 hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
className,
|
||||
)}
|
||||
toast-close=""
|
||||
{...props}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Title ref={ref} className={cn('text-sm font-semibold leading-none tracking-tight', className)} {...props} />
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
||||
|
||||
export type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
||||
export type ToastActionElement = React.ReactElement<typeof ToastAction>
|
||||
|
||||
export {
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastAction,
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
Toast,
|
||||
ToastClose,
|
||||
ToastDescription,
|
||||
ToastProvider,
|
||||
ToastTitle,
|
||||
ToastViewport,
|
||||
} from '@/components/ui/toast'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
|
||||
export function Toaster() {
|
||||
const { toasts, dismiss } = useToast()
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
{toasts.map(({ id, title, description, action, ...props }) => (
|
||||
<Toast
|
||||
key={id}
|
||||
{...props}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
dismiss(id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
{title ? <ToastTitle>{title}</ToastTitle> : null}
|
||||
{description ? <ToastDescription>{description}</ToastDescription> : null}
|
||||
</div>
|
||||
{action}
|
||||
<ToastClose />
|
||||
</Toast>
|
||||
))}
|
||||
<ToastViewport />
|
||||
</ToastProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import * as React from 'react'
|
||||
|
||||
import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
title?: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
action?: ToastActionElement
|
||||
}
|
||||
|
||||
type ToastState = {
|
||||
toasts: ToasterToast[]
|
||||
}
|
||||
|
||||
type ToastAction =
|
||||
| { type: 'ADD_TOAST'; toast: ToasterToast }
|
||||
| { type: 'UPDATE_TOAST'; toast: Partial<ToasterToast> & { id: string } }
|
||||
| { type: 'DISMISS_TOAST'; toastId?: string }
|
||||
| { type: 'REMOVE_TOAST'; toastId?: string }
|
||||
|
||||
const TOAST_LIMIT = 5
|
||||
const TOAST_REMOVE_DELAY = 1000
|
||||
|
||||
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
const listeners = new Set<(state: ToastState) => void>()
|
||||
|
||||
let memoryState: ToastState = { toasts: [] }
|
||||
|
||||
function dispatch(action: ToastAction) {
|
||||
memoryState = reducer(memoryState, action)
|
||||
listeners.forEach((listener) => {
|
||||
listener(memoryState)
|
||||
})
|
||||
}
|
||||
|
||||
function reducer(state: ToastState, action: ToastAction): ToastState {
|
||||
switch (action.type) {
|
||||
case 'ADD_TOAST': {
|
||||
return {
|
||||
...state,
|
||||
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
|
||||
}
|
||||
}
|
||||
case 'UPDATE_TOAST': {
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((toast) =>
|
||||
toast.id === action.toast.id ? { ...toast, ...action.toast } : toast,
|
||||
),
|
||||
}
|
||||
}
|
||||
case 'DISMISS_TOAST': {
|
||||
const { toastId } = action
|
||||
if (toastId) {
|
||||
addToRemoveQueue(toastId)
|
||||
} else {
|
||||
state.toasts.forEach((toast) => {
|
||||
addToRemoveQueue(toast.id)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((toast) =>
|
||||
toast.id === toastId || toastId === undefined
|
||||
? { ...toast, open: false }
|
||||
: toast,
|
||||
),
|
||||
}
|
||||
}
|
||||
case 'REMOVE_TOAST': {
|
||||
if (action.toastId === undefined) {
|
||||
return { ...state, toasts: [] }
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.filter((toast) => toast.id !== action.toastId),
|
||||
}
|
||||
}
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
function addToRemoveQueue(toastId: string) {
|
||||
if (toastTimeouts.has(toastId)) {
|
||||
return
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
toastTimeouts.delete(toastId)
|
||||
dispatch({ type: 'REMOVE_TOAST', toastId })
|
||||
}, TOAST_REMOVE_DELAY)
|
||||
|
||||
toastTimeouts.set(toastId, timeout)
|
||||
}
|
||||
|
||||
function genId() {
|
||||
return Math.random().toString(36).slice(2, 10)
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const [state, setState] = React.useState<ToastState>(memoryState)
|
||||
|
||||
React.useEffect(() => {
|
||||
listeners.add(setState)
|
||||
return () => {
|
||||
listeners.delete(setState)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return {
|
||||
...state,
|
||||
toast: (props: Omit<ToasterToast, 'id'>) => {
|
||||
const id = genId()
|
||||
dispatch({ type: 'ADD_TOAST', toast: { ...props, id, open: true } })
|
||||
return id
|
||||
},
|
||||
dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }),
|
||||
}
|
||||
}
|
||||
|
||||
export const toast = (props: Omit<ToasterToast, 'id'>) => {
|
||||
const id = genId()
|
||||
dispatch({ type: 'ADD_TOAST', toast: { ...props, id, open: true } })
|
||||
return id
|
||||
}
|
||||
@@ -1,15 +1,40 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { distanceInKm } from '@/lib/utils'
|
||||
import type { ApiDensityCell, ApiPoint, ApiSnapshot, FeedStatus, LatLng } from '@/types/api'
|
||||
import type {
|
||||
ApiDensityCell,
|
||||
ApiPoint,
|
||||
ApiSnapshot,
|
||||
FeedStatus,
|
||||
Point,
|
||||
SnapshotEventPayload,
|
||||
} from '@/types/api'
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE ?? 'http://localhost:8000/api/signals'
|
||||
const SNAPSHOT_LIMIT = 750
|
||||
const DEFAULT_REFRESH_MS = 7000
|
||||
const MERCURE_HUB = import.meta.env.VITE_MERCURE_HUB ?? 'http://localhost:3000/.well-known/mercure'
|
||||
const MERCURE_TOPIC = import.meta.env.VITE_MERCURE_TOPIC ?? 'https://points-of-interest.local/signals'
|
||||
const VISIBLE_RADIUS_KM = 1
|
||||
|
||||
type ProblemDetails = {
|
||||
detail?: unknown
|
||||
}
|
||||
|
||||
function extractProblemDetail(payload: unknown): string | null {
|
||||
if (payload && typeof payload === 'object') {
|
||||
const { detail } = payload as ProblemDetails
|
||||
if (typeof detail === 'string' && detail.trim().length > 0) {
|
||||
return detail
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
interface UseHotspotFeedOptions {
|
||||
autoRefreshMs?: number
|
||||
userLocation: Point | null
|
||||
snapshotLimit?: number
|
||||
mercureHub?: string
|
||||
mercureTopic?: string
|
||||
}
|
||||
|
||||
interface SubmitResult {
|
||||
@@ -19,9 +44,15 @@ interface SubmitResult {
|
||||
export interface FeedError {
|
||||
key: string
|
||||
values?: Record<string, unknown>
|
||||
detail?: string
|
||||
}
|
||||
|
||||
export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspotFeedOptions = {}) {
|
||||
export function useHotspotFeed({
|
||||
userLocation,
|
||||
snapshotLimit = SNAPSHOT_LIMIT,
|
||||
mercureHub = MERCURE_HUB,
|
||||
mercureTopic = MERCURE_TOPIC,
|
||||
}: UseHotspotFeedOptions) {
|
||||
const [status, setStatus] = useState<FeedStatus>('loading')
|
||||
const [error, setError] = useState<FeedError | null>(null)
|
||||
const [rawPoints, setRawPoints] = useState<ApiPoint[]>([])
|
||||
@@ -32,14 +63,51 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
|
||||
|
||||
const statusRef = useRef<FeedStatus>('loading')
|
||||
const initialLoadRef = useRef(true)
|
||||
const eventSourceRef = useRef<EventSource | null>(null)
|
||||
|
||||
const setStatusSafe = useCallback((next: FeedStatus) => {
|
||||
statusRef.current = next
|
||||
setStatus(next)
|
||||
}, [])
|
||||
|
||||
const resetState = useCallback(() => {
|
||||
setRawPoints([])
|
||||
setRawDensity([])
|
||||
setRawLatestByUser([])
|
||||
setLastUpdated(null)
|
||||
setClientKey(null)
|
||||
setError(null)
|
||||
eventSourceRef.current?.close()
|
||||
eventSourceRef.current = null
|
||||
initialLoadRef.current = true
|
||||
setStatusSafe('loading')
|
||||
}, [setStatusSafe])
|
||||
|
||||
const applySnapshot = useCallback(
|
||||
(snapshot: ApiSnapshot, options?: { preserveClientKey?: boolean }) => {
|
||||
setRawPoints(snapshot.points)
|
||||
setRawDensity(snapshot.density)
|
||||
setRawLatestByUser(snapshot.latestByUser)
|
||||
if (!options?.preserveClientKey) {
|
||||
setClientKey(snapshot.clientKey ?? null)
|
||||
}
|
||||
setLastUpdated(snapshot.updatedAt ?? new Date().toISOString())
|
||||
setError(null)
|
||||
initialLoadRef.current = false
|
||||
if (statusRef.current !== 'posting') {
|
||||
setStatusSafe('idle')
|
||||
}
|
||||
},
|
||||
[setStatusSafe],
|
||||
)
|
||||
|
||||
const fetchSnapshot = useCallback(
|
||||
async (options?: { silent?: boolean }) => {
|
||||
if (!userLocation) {
|
||||
resetState()
|
||||
return
|
||||
}
|
||||
|
||||
const silent = options?.silent ?? false
|
||||
const previousStatus = statusRef.current
|
||||
const isInitial = initialLoadRef.current
|
||||
@@ -53,26 +121,24 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}?limit=${SNAPSHOT_LIMIT}`, { cache: 'no-store' })
|
||||
const response = await fetch(`${API_BASE}?limit=${snapshotLimit}`, { cache: 'no-store' })
|
||||
if (!response.ok) {
|
||||
throw new Error('feed-unavailable')
|
||||
const payload = await response.json().catch(() => null)
|
||||
const detail = extractProblemDetail(payload)
|
||||
setError({ key: 'errors.feedUnavailable', detail: detail ?? undefined })
|
||||
if (initialLoadRef.current) {
|
||||
setStatusSafe('error')
|
||||
} else if (previousStatus !== 'posting') {
|
||||
setStatusSafe('idle')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const data: ApiSnapshot = await response.json()
|
||||
setRawPoints(data.points ?? [])
|
||||
setRawDensity(data.density ?? [])
|
||||
setRawLatestByUser(data.latestByUser ?? [])
|
||||
setClientKey(data.clientKey ?? null)
|
||||
setLastUpdated(data.updatedAt ?? new Date().toISOString())
|
||||
setError(null)
|
||||
initialLoadRef.current = false
|
||||
|
||||
const nextStatus = previousStatus === 'posting' ? 'posting' : 'idle'
|
||||
setStatusSafe(nextStatus)
|
||||
applySnapshot(data)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : null
|
||||
const key = message === 'feed-unavailable' ? 'errors.feedUnavailable' : 'errors.feedUnknown'
|
||||
setError({ key })
|
||||
const detail = error instanceof Error && error.message ? error.message : null
|
||||
setError({ key: 'errors.feedUnknown', detail: detail ?? undefined })
|
||||
if (initialLoadRef.current) {
|
||||
setStatusSafe('error')
|
||||
} else if (previousStatus !== 'posting') {
|
||||
@@ -80,39 +146,92 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
|
||||
}
|
||||
}
|
||||
},
|
||||
[setStatusSafe],
|
||||
[userLocation, snapshotLimit, resetState, setStatusSafe, applySnapshot],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
fetchSnapshot().catch(() => undefined)
|
||||
if (!autoRefreshMs) {
|
||||
const connectToStream = useCallback(() => {
|
||||
if (!userLocation) {
|
||||
return
|
||||
}
|
||||
|
||||
const interval = window.setInterval(() => {
|
||||
fetchSnapshot({ silent: true }).catch(() => undefined)
|
||||
}, autoRefreshMs)
|
||||
try {
|
||||
const url = new URL(mercureHub)
|
||||
url.searchParams.append('topic', mercureTopic)
|
||||
|
||||
const eventSource = new EventSource(url.toString())
|
||||
eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const payload: SnapshotEventPayload = JSON.parse(event.data)
|
||||
if (payload?.type === 'snapshot' && payload.payload) {
|
||||
applySnapshot(payload.payload, { preserveClientKey: true })
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error('Failed to parse stream payload', parseError)
|
||||
}
|
||||
}
|
||||
|
||||
eventSource.onerror = () => {
|
||||
if (statusRef.current !== 'loading') {
|
||||
setError({ key: 'errors.feedUnknown' })
|
||||
setStatusSafe('error')
|
||||
}
|
||||
}
|
||||
|
||||
eventSourceRef.current = eventSource
|
||||
} catch (connectionError) {
|
||||
console.error('Unable to subscribe to live updates', connectionError)
|
||||
setError({ key: 'errors.feedUnavailable' })
|
||||
setStatusSafe('error')
|
||||
}
|
||||
}, [applySnapshot, mercureHub, mercureTopic, setStatusSafe, userLocation])
|
||||
|
||||
useEffect(() => {
|
||||
if (!userLocation) {
|
||||
resetState()
|
||||
return undefined
|
||||
}
|
||||
|
||||
fetchSnapshot().catch(() => undefined)
|
||||
connectToStream()
|
||||
|
||||
return () => {
|
||||
window.clearInterval(interval)
|
||||
eventSourceRef.current?.close()
|
||||
eventSourceRef.current = null
|
||||
}
|
||||
}, [autoRefreshMs, fetchSnapshot])
|
||||
}, [connectToStream, fetchSnapshot, resetState, userLocation])
|
||||
|
||||
const submitPoint = useCallback(
|
||||
async (lat: number, lng: number): Promise<SubmitResult> => {
|
||||
async (target: Point): Promise<SubmitResult> => {
|
||||
if (!userLocation) {
|
||||
setError({
|
||||
key: 'errors.submitWithReason',
|
||||
values: { message: 'Location required before submitting.' },
|
||||
detail: 'Location required before submitting.',
|
||||
})
|
||||
setStatusSafe('error')
|
||||
return { success: false }
|
||||
}
|
||||
|
||||
setStatusSafe('posting')
|
||||
try {
|
||||
const response = await fetch(API_BASE, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ lat, lng }),
|
||||
body: JSON.stringify({
|
||||
signalLocation: target,
|
||||
userLocation,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null)
|
||||
const message = payload?.message as string | undefined
|
||||
if (message) {
|
||||
setError({ key: 'errors.submitWithReason', values: { message } })
|
||||
const detail = extractProblemDetail(payload)
|
||||
if (detail) {
|
||||
setError({
|
||||
key: 'errors.submitWithReason',
|
||||
values: { message: detail },
|
||||
detail,
|
||||
})
|
||||
} else {
|
||||
setError({ key: 'errors.submitUnavailable' })
|
||||
}
|
||||
@@ -120,14 +239,13 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
|
||||
return { success: false }
|
||||
}
|
||||
|
||||
await fetchSnapshot({ silent: true })
|
||||
setError(null)
|
||||
setStatusSafe('idle')
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : null
|
||||
if (message) {
|
||||
setError({ key: 'errors.submitWithReason', values: { message } })
|
||||
const detail = error instanceof Error && error.message ? error.message : null
|
||||
if (detail) {
|
||||
setError({ key: 'errors.submitWithReason', values: { message: detail }, detail })
|
||||
} else {
|
||||
setError({ key: 'errors.submitUnknown' })
|
||||
}
|
||||
@@ -135,13 +253,13 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
|
||||
return { success: false }
|
||||
}
|
||||
},
|
||||
[fetchSnapshot, setStatusSafe],
|
||||
[setStatusSafe, userLocation],
|
||||
)
|
||||
|
||||
const hasClientKey = Boolean(clientKey)
|
||||
|
||||
const filterWithinRadius = useCallback(
|
||||
<T extends LatLng>(collection: T[], origin: LatLng | null) => {
|
||||
const filterDensityWithinRadius = useCallback(
|
||||
(collection: ApiDensityCell[], origin: Point | null) => {
|
||||
if (!origin) {
|
||||
return []
|
||||
}
|
||||
@@ -150,19 +268,29 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
|
||||
[],
|
||||
)
|
||||
|
||||
const filterPointsWithinRadius = useCallback(
|
||||
(collection: ApiPoint[], origin: Point | null) => {
|
||||
if (!origin) {
|
||||
return []
|
||||
}
|
||||
return collection.filter((item) => distanceInKm(origin, item.signalLocation) <= VISIBLE_RADIUS_KM)
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const selectVisibleDensity = useCallback(
|
||||
(origin: LatLng | null) => filterWithinRadius(rawDensity, origin),
|
||||
[filterWithinRadius, rawDensity],
|
||||
(origin: Point | null) => filterDensityWithinRadius(rawDensity, origin),
|
||||
[filterDensityWithinRadius, rawDensity],
|
||||
)
|
||||
|
||||
const selectVisiblePoints = useCallback(
|
||||
(origin: LatLng | null) => filterWithinRadius(rawPoints, origin),
|
||||
[filterWithinRadius, rawPoints],
|
||||
(origin: Point | null) => filterPointsWithinRadius(rawPoints, origin),
|
||||
[filterPointsWithinRadius, rawPoints],
|
||||
)
|
||||
|
||||
const selectVisibleLatestByUser = useCallback(
|
||||
(origin: LatLng | null) => filterWithinRadius(rawLatestByUser, origin),
|
||||
[filterWithinRadius, rawLatestByUser],
|
||||
(origin: Point | null) => filterPointsWithinRadius(rawLatestByUser, origin),
|
||||
[filterPointsWithinRadius, rawLatestByUser],
|
||||
)
|
||||
|
||||
const myLatestPoint = useMemo(() => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import L, {
|
||||
} from 'leaflet'
|
||||
import 'leaflet.heat'
|
||||
|
||||
import type { ApiDensityCell, LatLng } from '@/types/api'
|
||||
import type { ApiDensityCell, Point } from '@/types/api'
|
||||
|
||||
type HeatPoint = [number, number, number?]
|
||||
|
||||
@@ -24,18 +24,24 @@ type LeafletWithHeat = typeof L & {
|
||||
|
||||
interface UseLeafletHeatmapParams {
|
||||
heatCells: ApiDensityCell[]
|
||||
userLocation: LatLng | null
|
||||
onRequestSpot?: (position: LatLng) => void
|
||||
userLocation: Point | null
|
||||
onRequestSpot?: (position: Point) => void
|
||||
tileProvider: TileProvider
|
||||
}
|
||||
|
||||
interface UseLeafletHeatmapResult {
|
||||
mapContainerRef: MutableRefObject<HTMLDivElement | null>
|
||||
focusOn: (position: LatLng, zoom?: number) => void
|
||||
focusOn: (position: Point, zoom?: number) => void
|
||||
fitToHeat: () => void
|
||||
map: LeafletMap | null
|
||||
}
|
||||
|
||||
type TileSource = {
|
||||
readonly url: string
|
||||
readonly attribution: string
|
||||
readonly options?: TileLayerOptions
|
||||
}
|
||||
|
||||
const TILE_SOURCES = {
|
||||
openstreetmap: {
|
||||
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
@@ -49,11 +55,11 @@ const TILE_SOURCES = {
|
||||
zoomOffset: -1,
|
||||
} satisfies TileLayerOptions,
|
||||
},
|
||||
} as const
|
||||
} as const satisfies Record<string, TileSource>
|
||||
|
||||
export type TileProvider = keyof typeof TILE_SOURCES
|
||||
|
||||
const INITIAL_VIEW: LatLng = { lat: 20, lng: 0 }
|
||||
const INITIAL_VIEW: Point = { lat: 20, lng: 0 }
|
||||
const DEFAULT_ZOOM = 3
|
||||
|
||||
export function useLeafletHeatmap({
|
||||
@@ -74,12 +80,13 @@ export function useLeafletHeatmap({
|
||||
const createTileLayer = useCallback(
|
||||
(provider: TileProvider) => {
|
||||
const leaflet = L as LeafletWithHeat
|
||||
const source = TILE_SOURCES[provider]
|
||||
const source: TileSource = TILE_SOURCES[provider]
|
||||
const options = source.options ?? {}
|
||||
return leaflet.tileLayer(source.url, {
|
||||
attribution: source.attribution,
|
||||
crossOrigin: true,
|
||||
maxZoom: 19,
|
||||
...(source.options ?? {}),
|
||||
...options,
|
||||
})
|
||||
},
|
||||
[],
|
||||
@@ -248,7 +255,7 @@ export function useLeafletHeatmap({
|
||||
}
|
||||
}, [userLocation])
|
||||
|
||||
const focusOn = useCallback((position: LatLng, zoom = 14) => {
|
||||
const focusOn = useCallback((position: Point, zoom = 14) => {
|
||||
const map = mapRef.current
|
||||
if (!map) {
|
||||
return
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import type { LatLng } from '@/types/api'
|
||||
import type { Point } from '@/types/api'
|
||||
|
||||
function geolocationErrorMessage(error: GeolocationPositionError): string {
|
||||
switch (error.code) {
|
||||
@@ -16,7 +16,7 @@ function geolocationErrorMessage(error: GeolocationPositionError): string {
|
||||
}
|
||||
|
||||
export function useUserLocation() {
|
||||
const [location, setLocation] = useState<LatLng | null>(null)
|
||||
const [location, setLocation] = useState<Point | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isRequesting, setIsRequesting] = useState<boolean>(false)
|
||||
const watchIdRef = useRef<number | null>(null)
|
||||
|
||||
@@ -99,6 +99,12 @@
|
||||
"timeout": "Timed out while fetching your location.",
|
||||
"generic": "Failed to retrieve your location.",
|
||||
"unsupported": "Geolocation is not supported in this browser."
|
||||
},
|
||||
"gate": {
|
||||
"title": "Share your location to continue",
|
||||
"description": "We need your location to personalise the live map feed.",
|
||||
"action": "Try location again",
|
||||
"loading": "Requesting location…"
|
||||
}
|
||||
},
|
||||
"activityItem": {
|
||||
@@ -128,6 +134,7 @@
|
||||
"french": "Français"
|
||||
},
|
||||
"errors": {
|
||||
"title": "Something went wrong",
|
||||
"feedUnavailable": "Unable to reach the hotspot feed.",
|
||||
"feedUnknown": "Unknown error while loading hotspots.",
|
||||
"submitUnavailable": "Unable to store your signal.",
|
||||
|
||||
@@ -99,6 +99,12 @@
|
||||
"timeout": "Délai dépassé lors de la récupération de votre localisation.",
|
||||
"generic": "Échec de la récupération de votre localisation.",
|
||||
"unsupported": "La géolocalisation n'est pas prise en charge par ce navigateur."
|
||||
},
|
||||
"gate": {
|
||||
"title": "Partagez votre position pour continuer",
|
||||
"description": "Nous avons besoin de votre localisation pour personnaliser la carte en direct.",
|
||||
"action": "Relancer la localisation",
|
||||
"loading": "Demande de localisation…"
|
||||
}
|
||||
},
|
||||
"activityItem": {
|
||||
@@ -128,6 +134,7 @@
|
||||
"french": "Français"
|
||||
},
|
||||
"errors": {
|
||||
"title": "Une erreur est survenue",
|
||||
"feedUnavailable": "Impossible d'atteindre le flux de signaux.",
|
||||
"feedUnknown": "Erreur inconnue lors du chargement des signaux.",
|
||||
"submitUnavailable": "Impossible d'enregistrer votre signal.",
|
||||
|
||||
+15
-10
@@ -1,9 +1,14 @@
|
||||
export type FeedStatus = 'loading' | 'idle' | 'error' | 'posting' | 'refreshing'
|
||||
|
||||
export interface Point {
|
||||
lat: number
|
||||
lng: number
|
||||
}
|
||||
|
||||
export interface ApiPoint {
|
||||
id: number
|
||||
lat: number
|
||||
lng: number
|
||||
signalLocation: Point
|
||||
userLocation: Point
|
||||
createdAt: string
|
||||
userKey: string
|
||||
}
|
||||
@@ -16,17 +21,17 @@ export interface ApiDensityCell {
|
||||
|
||||
export interface ApiSnapshot {
|
||||
clientKey?: string
|
||||
points?: ApiPoint[]
|
||||
density?: ApiDensityCell[]
|
||||
latestByUser?: ApiPoint[]
|
||||
totals?: {
|
||||
points: ApiPoint[]
|
||||
density: ApiDensityCell[]
|
||||
latestByUser: ApiPoint[]
|
||||
totals: {
|
||||
points: number
|
||||
contributors: number
|
||||
}
|
||||
updatedAt?: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type LatLng = {
|
||||
lat: number
|
||||
lng: number
|
||||
export interface SnapshotEventPayload {
|
||||
type: 'snapshot'
|
||||
payload: ApiSnapshot
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user