87 lines
2.2 KiB
TypeScript
87 lines
2.2 KiB
TypeScript
import { useState, useEffect } from 'react';
|
|
|
|
const STORAGE_KEY = 'emberclone_favorites';
|
|
const FAVORITES_EVENT = 'emberclone_favorites_updated';
|
|
|
|
export const favoritesUtils = {
|
|
getFavorites: (): Record<string, Set<string>> => {
|
|
const data = localStorage.getItem(STORAGE_KEY);
|
|
if (!data) return {};
|
|
try {
|
|
const parsed = JSON.parse(data);
|
|
const result: Record<string, Set<string>> = {};
|
|
for (const [type, ids] of Object.entries(parsed)) {
|
|
result[type] = new Set(ids as string[]);
|
|
}
|
|
return result;
|
|
} catch {
|
|
return {};
|
|
}
|
|
},
|
|
|
|
saveFavorites: (favorites: Record<string, Set<string>>) => {
|
|
const data: Record<string, string[]> = {};
|
|
for (const [type, ids] of Object.entries(favorites)) {
|
|
data[type] = Array.from(ids);
|
|
}
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
|
window.dispatchEvent(new CustomEvent(FAVORITES_EVENT));
|
|
},
|
|
|
|
isFavorite: (type: string, id: string): boolean => {
|
|
const favs = favoritesUtils.getFavorites();
|
|
return favs[type]?.has(id) ?? false;
|
|
},
|
|
|
|
toggleFavorite: (type: string, id: string) => {
|
|
const favs = favoritesUtils.getFavorites();
|
|
if (!favs[type]) {
|
|
favs[type] = new Set();
|
|
}
|
|
|
|
if (favs[type].has(id)) {
|
|
favs[type].delete(id);
|
|
} else {
|
|
favs[type].add(id);
|
|
}
|
|
|
|
favoritesUtils.saveFavorites(favs);
|
|
},
|
|
|
|
getAllFavorites: (type: string): string[] => {
|
|
const favs = favoritesUtils.getFavorites();
|
|
return Array.from(favs[type] || []);
|
|
}
|
|
};
|
|
|
|
export function useFavorites() {
|
|
const [favorites, setFavorites] = useState(() => favoritesUtils.getFavorites());
|
|
|
|
useEffect(() => {
|
|
const handleUpdate = () => {
|
|
setFavorites(favoritesUtils.getFavorites());
|
|
};
|
|
|
|
window.addEventListener(FAVORITES_EVENT, handleUpdate);
|
|
return () => window.removeEventListener(FAVORITES_EVENT, handleUpdate);
|
|
}, []);
|
|
|
|
const isFavorite = (type: string, id: string) => {
|
|
return favorites[type]?.has(id) ?? false;
|
|
};
|
|
|
|
const toggle = (type: string, id: string) => {
|
|
favoritesUtils.toggleFavorite(type, id);
|
|
};
|
|
|
|
const getAll = (type: string) => {
|
|
return Array.from(favorites[type] || []);
|
|
};
|
|
|
|
return {
|
|
isFavorite,
|
|
toggle,
|
|
getAll,
|
|
favorites
|
|
};
|
|
} |