1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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<PlannerSearchResult | null>(null);
const [destination, setDestination] = useState<PlannerSearchResult | null>(
null
);
const [plan, setPlan] = useState<RoutePlan | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(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,
};
}
|