|
| 1 | +import { useCallback, useEffect, useMemo, useState } from 'react'; |
| 2 | +import { validateWithinRadius } from '@/validation/validateGeolocation'; |
| 3 | + |
| 4 | +type GeoResult = { |
| 5 | + ok: boolean; |
| 6 | + distanceMeters: number; |
| 7 | + accuracyMeters: number | null; |
| 8 | +}; |
| 9 | + |
| 10 | +export function useGeoValidation(options?: { |
| 11 | + accuracyLimitMeters?: number; |
| 12 | + geolocationOptions?: PositionOptions; |
| 13 | +}) { |
| 14 | + const accuracyLimit = options?.accuracyLimitMeters ?? 250; |
| 15 | + // Current - new object every render |
| 16 | + |
| 17 | + const geoOptions = useMemo( |
| 18 | + () => |
| 19 | + options?.geolocationOptions ?? { |
| 20 | + enableHighAccuracy: true, |
| 21 | + timeout: 15000, |
| 22 | + maximumAge: 0, |
| 23 | + }, |
| 24 | + [options?.geolocationOptions], |
| 25 | + ); |
| 26 | + |
| 27 | + const [isOk, setIsOk] = useState<boolean | null>(null); |
| 28 | + const [error, setError] = useState<string | null>(null); |
| 29 | + const [result, setResult] = useState<GeoResult | null>(null); |
| 30 | + |
| 31 | + const validate = useCallback(() => { |
| 32 | + setError(null); |
| 33 | + |
| 34 | + if (typeof window === 'undefined' || !('geolocation' in navigator)) { |
| 35 | + setIsOk(false); |
| 36 | + setError('Geolocation is not available in this environment.'); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + navigator.geolocation.getCurrentPosition( |
| 41 | + (pos) => { |
| 42 | + const accuracy = pos.coords.accuracy ?? null; |
| 43 | + |
| 44 | + // Reject low-accuracy fixes first |
| 45 | + if (accuracy == null || accuracy > accuracyLimit) { |
| 46 | + const msg = `Location accuracy too low (${accuracy ? Math.round(accuracy) : '?'}m).`; |
| 47 | + setIsOk(false); |
| 48 | + setError(msg); |
| 49 | + setResult( |
| 50 | + accuracy == null |
| 51 | + ? null |
| 52 | + : { ok: false, distanceMeters: NaN, accuracyMeters: accuracy }, |
| 53 | + ); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + const r = validateWithinRadius(pos.coords); |
| 58 | + |
| 59 | + const payload: GeoResult = { |
| 60 | + ok: r.ok, |
| 61 | + distanceMeters: r.distanceMeters, |
| 62 | + accuracyMeters: accuracy, |
| 63 | + }; |
| 64 | + |
| 65 | + setResult(payload); |
| 66 | + setIsOk(r.ok); |
| 67 | + }, |
| 68 | + (err) => { |
| 69 | + setIsOk(false); |
| 70 | + setError(err.message); |
| 71 | + }, |
| 72 | + geoOptions, |
| 73 | + ); |
| 74 | + }, [accuracyLimit, geoOptions]); |
| 75 | + |
| 76 | + // Run validation once on mount |
| 77 | + useEffect(() => { |
| 78 | + validate(); |
| 79 | + }, [validate]); |
| 80 | + |
| 81 | + return { validate, isOk, error, result }; |
| 82 | +} |
0 commit comments