import { useState } from 'react'; import { sectionsConfigType, SectionType } from '@digigov/react-modules/Faq'; import { slug } from '@digigov/react-modules/Faq/slug'; const removeAccents = (text: string) => { return text.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); }; export const useURLParamsSearch = ( searchFunc: (params: Record) => void, { navigate, filteredSections, }: { navigate: (url: string) => void; filteredSections: SectionType[] } ) => { const urlParams = new URLSearchParams(window.location.search); const currentParams = Object.fromEntries(urlParams.entries()); const hashId = window.location.hash ? window.location.hash.slice(1) : ''; // When filtered sections change, check if hash should be preserved const hashExistsInFilteredSections = filteredSections.some((section) => section.qa.some( ({ id, question }) => id === hashId || slug(question) === hashId ) ); const search = (params: Record) => { const updatedParams = Object.entries({ ...currentParams, ...params, }) .filter(([, value]) => Boolean(value)) // Ensure value is not empty .reduce( (acc, [key, value]) => { acc[key] = value as string; // Explicitly cast to string return acc; }, {} as Record ); // Ensure correct type const newUrl = Object.keys(updatedParams).length ? '?' + new URLSearchParams(updatedParams).toString() : window.location.pathname; // Reset to base URL if no params const finalURL = hashExistsInFilteredSections ? newUrl + `#${hashId}` : newUrl; navigate(finalURL); return searchFunc(params); }; return { search, values: { text: currentParams.text }, hashId }; }; export const useFaqSearch = (questions: sectionsConfigType) => { const [filteredSections, setFilteredSections] = useState(questions.sections); const search = (values: Record) => { if (!values || !values.text?.trim()) { setFilteredSections(questions.sections); return; } const searchValue: string = values.text.trim(); // Ensure no spaces-only search const normalizedSearchWord = removeAccents(searchValue.toLowerCase()); const filteredSections = questions.sections .map((section: SectionType) => { const filteredQa = section.qa.filter(({ question, answer }: any) => { const normalizedQuestion = removeAccents( question?.toLowerCase() || '' ); const normalizedAnswer = removeAccents(answer?.toLowerCase() || ''); return ( normalizedQuestion.includes(normalizedSearchWord) || normalizedAnswer.includes(normalizedSearchWord) ); }); return { ...section, qa: filteredQa }; }) .filter((section: SectionType) => section.qa.length > 0); setFilteredSections(filteredSections); }; return { filteredSections, search, }; };