Files
nahodka-front/src/hooks/useCityOptions.js
2026-10-19 00:36:41 +03:00

29 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useMemo } from "react";
/**
* Общая логика выбора городов для CityFilter (десктоп) и CitySheet (мобильная шторка).
*
* @param {string[]} cities — доступные города (из /posts/cities)
* @param {string[]} value — выбранные города
* @param {string} query — введённый текст поиска
* @returns {{ options: string[], typedCity: string }}
* options — города, совпадающие с текстом (выбранные помечаются в UI галочкой);
* typedCity — введённый город, которого нет в списке (объявлений там нет).
* Пусто, если есть совпадения или город уже выбран. Применяется как фильтр
* по «Показать»/Enter — лента покажет «В этом городе нет объявлений».
*/
export function useCityOptions(cities, value, query) {
const normalizedQuery = query.trim().toLowerCase();
const options = useMemo(() => {
const q = normalizedQuery;
return cities.filter(c => c && (!q || c.toLowerCase().includes(q)));
}, [cities, normalizedQuery]);
const typedCity = normalizedQuery.length > 0 && options.length === 0 &&
!value.some(c => c.toLowerCase() === normalizedQuery)
? query.trim() : "";
return { options, typedCity };
}