Spaces:
Running
Running
| import { useSearchParams, useLocation } from "react-router-dom"; | |
| import { useCallback, useEffect } from "react"; | |
| /** | |
| * Hook personnalisé pour gérer l'état de l'URL | |
| * @returns {Object} Méthodes et données pour gérer l'état de l'URL | |
| */ | |
| export const useUrlState = () => { | |
| const [searchParams, setSearchParams] = useSearchParams(); | |
| const location = useLocation(); | |
| // Convertit les searchParams en objet | |
| const getParams = useCallback(() => { | |
| const params = {}; | |
| for (const [key, value] of searchParams.entries()) { | |
| if (key === "categories") { | |
| params[key] = value.split(",").filter(Boolean); | |
| } else if (key === "arena") { | |
| params[key] = value === "true"; | |
| } else { | |
| params[key] = value; | |
| } | |
| } | |
| return params; | |
| }, [searchParams]); | |
| // Met à jour les paramètres d'URL | |
| const updateParams = useCallback( | |
| (newParams) => { | |
| const updatedParams = new URLSearchParams(searchParams); | |
| Object.entries(newParams).forEach(([key, value]) => { | |
| if (value && (Array.isArray(value) ? value.length > 0 : true)) { | |
| if (Array.isArray(value)) { | |
| updatedParams.set(key, value.join(",")); | |
| } else { | |
| updatedParams.set(key, value.toString()); | |
| } | |
| } else { | |
| updatedParams.delete(key); | |
| } | |
| }); | |
| setSearchParams(updatedParams); | |
| }, | |
| [searchParams, setSearchParams] | |
| ); | |
| // Réinitialise tous les paramètres d'URL | |
| const resetParams = useCallback(() => { | |
| setSearchParams(new URLSearchParams()); | |
| }, [setSearchParams]); | |
| // Gestion de l'intégration avec Hugging Face | |
| useEffect(() => { | |
| const isHFSpace = window.location !== window.parent.location; | |
| if (!isHFSpace) return; | |
| window.parent.postMessage( | |
| { | |
| queryString: location.search, | |
| hash: location.hash, | |
| }, | |
| "https://huggingface.co" | |
| ); | |
| }, [location]); | |
| return { | |
| params: getParams(), | |
| updateParams, | |
| resetParams, | |
| searchParams, | |
| location, | |
| }; | |
| }; | |