From 3a1a1e6dc2f6f0abceac5da0cfb530fdb45fc6f5 Mon Sep 17 00:00:00 2001 From: Ariel Costas Guerrero Date: Fri, 12 Dec 2025 10:24:43 +0100 Subject: Initial ultra-ñapa implementation of OTP integration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/frontend/app/hooks/usePlanner.ts | 101 +++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 src/frontend/app/hooks/usePlanner.ts (limited to 'src/frontend/app/hooks/usePlanner.ts') diff --git a/src/frontend/app/hooks/usePlanner.ts b/src/frontend/app/hooks/usePlanner.ts new file mode 100644 index 0000000..1572896 --- /dev/null +++ b/src/frontend/app/hooks/usePlanner.ts @@ -0,0 +1,101 @@ +import { useEffect, useState } from "react"; +import { + type PlannerSearchResult, + type RoutePlan, + planRoute, +} from "../data/PlannerApi"; + +const STORAGE_KEY = "planner_last_route"; +const EXPIRY_MS = 2 * 60 * 60 * 1000; // 2 hours + +interface StoredRoute { + timestamp: number; + origin: PlannerSearchResult; + destination: PlannerSearchResult; + plan: RoutePlan; +} + +export function usePlanner() { + const [origin, setOrigin] = useState(null); + const [destination, setDestination] = useState( + null + ); + const [plan, setPlan] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + // Load from storage on mount + useEffect(() => { + const stored = localStorage.getItem(STORAGE_KEY); + if (stored) { + try { + const data: StoredRoute = JSON.parse(stored); + if (Date.now() - data.timestamp < EXPIRY_MS) { + setOrigin(data.origin); + setDestination(data.destination); + setPlan(data.plan); + } else { + localStorage.removeItem(STORAGE_KEY); + } + } catch (e) { + localStorage.removeItem(STORAGE_KEY); + } + } + }, []); + + const searchRoute = async ( + from: PlannerSearchResult, + to: PlannerSearchResult, + time?: Date, + arriveBy: boolean = false + ) => { + setLoading(true); + setError(null); + try { + const result = await planRoute( + from.lat, + from.lon, + to.lat, + to.lon, + time, + arriveBy + ); + setPlan(result); + setOrigin(from); + setDestination(to); + + // Save to storage + const toStore: StoredRoute = { + timestamp: Date.now(), + origin: from, + destination: to, + plan: result, + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(toStore)); + } catch (err) { + setError("Failed to calculate route. Please try again."); + setPlan(null); + } finally { + setLoading(false); + } + }; + + const clearRoute = () => { + setPlan(null); + setOrigin(null); + setDestination(null); + localStorage.removeItem(STORAGE_KEY); + }; + + return { + origin, + setOrigin, + destination, + setDestination, + plan, + loading, + error, + searchRoute, + clearRoute, + }; +} -- cgit v1.3