|
| 1 | +// LocalStorage utility for recent itineraries |
| 2 | +export interface RecentItinerary { |
| 3 | + id: string; |
| 4 | + title: string; |
| 5 | + visitedAt: string; |
| 6 | +} |
| 7 | + |
| 8 | +const STORAGE_KEY = 'tabitabi_recent_itineraries'; |
| 9 | +const MAX_RECENT = 5; |
| 10 | + |
| 11 | +export function saveRecentItinerary(id: string, title: string): void { |
| 12 | + if (typeof window === 'undefined') return; |
| 13 | + |
| 14 | + try { |
| 15 | + const recent = getRecentItineraries(); |
| 16 | + |
| 17 | + // Remove existing entry with same id |
| 18 | + const filtered = recent.filter(item => item.id !== id); |
| 19 | + |
| 20 | + // Add new entry at the beginning |
| 21 | + const updated: RecentItinerary[] = [ |
| 22 | + { id, title, visitedAt: new Date().toISOString() }, |
| 23 | + ...filtered |
| 24 | + ].slice(0, MAX_RECENT); |
| 25 | + |
| 26 | + localStorage.setItem(STORAGE_KEY, JSON.stringify(updated)); |
| 27 | + } catch (error) { |
| 28 | + console.error('Failed to save recent itinerary:', error); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +export function getRecentItineraries(): RecentItinerary[] { |
| 33 | + if (typeof window === 'undefined') return []; |
| 34 | + |
| 35 | + try { |
| 36 | + const stored = localStorage.getItem(STORAGE_KEY); |
| 37 | + if (!stored) return []; |
| 38 | + |
| 39 | + const items = JSON.parse(stored) as RecentItinerary[]; |
| 40 | + return Array.isArray(items) ? items : []; |
| 41 | + } catch (error) { |
| 42 | + console.error('Failed to load recent itineraries:', error); |
| 43 | + return []; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export function clearRecentItineraries(): void { |
| 48 | + if (typeof window === 'undefined') return; |
| 49 | + |
| 50 | + try { |
| 51 | + localStorage.removeItem(STORAGE_KEY); |
| 52 | + } catch (error) { |
| 53 | + console.error('Failed to clear recent itineraries:', error); |
| 54 | + } |
| 55 | +} |
0 commit comments