Добавлено получение истории поиска с автодополнением в компоненте Header. Обновлены обработчики ввода для управления отображением истории и плейсхолдера. Внедрен запрос для получения последних поисковых запросов. Обновлены стили и логика отображения в компоненте Header.
This commit is contained in:
@ -79,21 +79,29 @@ const transformPartsIndexToTabData = (catalogs: PartsIndexCatalog[]) => {
|
||||
let links: string[] = [];
|
||||
|
||||
if (catalog.groups && catalog.groups.length > 0) {
|
||||
// Для каждой группы проверяем есть ли подгруппы
|
||||
// Сначала собираем все подгруппы из всех групп
|
||||
catalog.groups.forEach(group => {
|
||||
if (group.subgroups && group.subgroups.length > 0) {
|
||||
// Если есть подгруппы, добавляем их названия
|
||||
links.push(...group.subgroups.slice(0, 9 - links.length).map(subgroup => subgroup.name));
|
||||
} else {
|
||||
// Если подгрупп нет, добавляем название самой группы
|
||||
if (links.length < 9) {
|
||||
links.push(group.name);
|
||||
}
|
||||
group.subgroups.forEach(subgroup => {
|
||||
if (links.length < 9) {
|
||||
links.push(subgroup.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Если подгрупп не набралось достаточно, добавляем названия групп
|
||||
if (links.length < 9) {
|
||||
catalog.groups.forEach(group => {
|
||||
if (links.length < 9 && !links.includes(group.name)) {
|
||||
links.push(group.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Если подкатегорий нет, показываем название категории как указано в требованиях
|
||||
// Если подкатегорий всё ещё нет, добавляем название самой категории
|
||||
if (links.length === 0) {
|
||||
links = [catalog.name];
|
||||
}
|
||||
@ -258,20 +266,21 @@ const BottomHead = ({ menuOpen, onClose }: { menuOpen: boolean; onClose: () => v
|
||||
<span>{mobileCategory.label}</span>
|
||||
</div>
|
||||
<div className="mobile-subcategories">
|
||||
{mobileCategory.links.length === 1 ? (
|
||||
{mobileCategory.links.map((link: string, linkIndex: number) => (
|
||||
<div
|
||||
className="mobile-subcategory"
|
||||
key={link}
|
||||
onClick={() => {
|
||||
let subcategoryId = `${mobileCategory.catalogId}_0`;
|
||||
let subcategoryId = `${mobileCategory.catalogId}_${linkIndex}`;
|
||||
if (mobileCategory.groups) {
|
||||
for (const group of mobileCategory.groups) {
|
||||
if (group.subgroups && group.subgroups.length > 0) {
|
||||
const foundSubgroup = group.subgroups.find((subgroup: any) => subgroup.name === mobileCategory.links[0]);
|
||||
const foundSubgroup = group.subgroups.find((subgroup: any) => subgroup.name === link);
|
||||
if (foundSubgroup) {
|
||||
subcategoryId = foundSubgroup.id;
|
||||
break;
|
||||
}
|
||||
} else if (group.name === mobileCategory.links[0]) {
|
||||
} else if (group.name === link) {
|
||||
subcategoryId = group.id;
|
||||
break;
|
||||
}
|
||||
@ -279,42 +288,12 @@ const BottomHead = ({ menuOpen, onClose }: { menuOpen: boolean; onClose: () => v
|
||||
}
|
||||
const activeCatalog = catalogsData?.partsIndexCategoriesWithGroups?.[tabData.findIndex(tab => tab === mobileCategory)];
|
||||
const catalogId = activeCatalog?.id || 'fallback';
|
||||
handleCategoryClick(catalogId, mobileCategory.links[0], subcategoryId);
|
||||
handleCategoryClick(catalogId, link, subcategoryId);
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
Показать все
|
||||
{link}
|
||||
</div>
|
||||
) : (
|
||||
mobileCategory.links.map((link: string, linkIndex: number) => (
|
||||
<div
|
||||
className="mobile-subcategory"
|
||||
key={link}
|
||||
onClick={() => {
|
||||
let subcategoryId = `${mobileCategory.catalogId}_${linkIndex}`;
|
||||
if (mobileCategory.groups) {
|
||||
for (const group of mobileCategory.groups) {
|
||||
if (group.subgroups && group.subgroups.length > 0) {
|
||||
const foundSubgroup = group.subgroups.find((subgroup: any) => subgroup.name === link);
|
||||
if (foundSubgroup) {
|
||||
subcategoryId = foundSubgroup.id;
|
||||
break;
|
||||
}
|
||||
} else if (group.name === link) {
|
||||
subcategoryId = group.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const activeCatalog = catalogsData?.partsIndexCategoriesWithGroups?.[tabData.findIndex(tab => tab === mobileCategory)];
|
||||
const catalogId = activeCatalog?.id || 'fallback';
|
||||
handleCategoryClick(catalogId, link, subcategoryId);
|
||||
}}
|
||||
>
|
||||
{link}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
@ -518,66 +497,37 @@ const BottomHead = ({ menuOpen, onClose }: { menuOpen: boolean; onClose: () => v
|
||||
<h3 className="heading-16">{tab.heading}</h3>
|
||||
<div className="w-layout-hflex flex-block-92">
|
||||
<div className="w-layout-vflex flex-block-91">
|
||||
{tab.links.length === 1 ? (
|
||||
<div
|
||||
className="link-2"
|
||||
onClick={() => {
|
||||
const catalog = catalogsData?.partsIndexCategoriesWithGroups?.[idx];
|
||||
let subcategoryId = `fallback_${idx}_0`;
|
||||
if (catalog?.groups) {
|
||||
for (const group of catalog.groups) {
|
||||
if (group.subgroups && group.subgroups.length > 0) {
|
||||
const foundSubgroup = group.subgroups.find((subgroup: any) => subgroup.name === tab.links[0]);
|
||||
if (foundSubgroup) {
|
||||
subcategoryId = foundSubgroup.id;
|
||||
break;
|
||||
}
|
||||
} else if (group.name === tab.links[0]) {
|
||||
subcategoryId = group.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const catalogId = catalog?.id || 'fallback';
|
||||
handleCategoryClick(catalogId, tab.links[0], subcategoryId);
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
Показать все
|
||||
</div>
|
||||
) : (
|
||||
tab.links.map((link: string, linkIndex: number) => {
|
||||
const catalog = catalogsData?.partsIndexCategoriesWithGroups?.[idx];
|
||||
let subcategoryId = `fallback_${idx}_${linkIndex}`;
|
||||
if (catalog?.groups) {
|
||||
for (const group of catalog.groups) {
|
||||
if (group.subgroups && group.subgroups.length > 0) {
|
||||
const foundSubgroup = group.subgroups.find((subgroup: any) => subgroup.name === link);
|
||||
if (foundSubgroup) {
|
||||
subcategoryId = foundSubgroup.id;
|
||||
break;
|
||||
}
|
||||
} else if (group.name === link) {
|
||||
subcategoryId = group.id;
|
||||
{tab.links.map((link: string, linkIndex: number) => {
|
||||
const catalog = catalogsData?.partsIndexCategoriesWithGroups?.[idx];
|
||||
let subcategoryId = `fallback_${idx}_${linkIndex}`;
|
||||
if (catalog?.groups) {
|
||||
for (const group of catalog.groups) {
|
||||
if (group.subgroups && group.subgroups.length > 0) {
|
||||
const foundSubgroup = group.subgroups.find((subgroup: any) => subgroup.name === link);
|
||||
if (foundSubgroup) {
|
||||
subcategoryId = foundSubgroup.id;
|
||||
break;
|
||||
}
|
||||
} else if (group.name === link) {
|
||||
subcategoryId = group.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="link-2"
|
||||
key={link}
|
||||
onClick={() => {
|
||||
const catalogId = catalog?.id || 'fallback';
|
||||
handleCategoryClick(catalogId, link, subcategoryId);
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
{link}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="link-2"
|
||||
key={link}
|
||||
onClick={() => {
|
||||
const catalogId = catalog?.id || 'fallback';
|
||||
handleCategoryClick(catalogId, link, subcategoryId);
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
{link}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="w-layout-vflex flex-block-91-copy">
|
||||
<img src="https://d3e54v103j8qbb.cloudfront.net/plugins/Basic/assets/placeholder.60f9b1840c.svg" loading="lazy" alt="" className="image-17" />
|
||||
|
@ -9,6 +9,8 @@ import { FIND_LAXIMO_VEHICLE, DOC_FIND_OEM, FIND_LAXIMO_VEHICLE_BY_PLATE_GLOBAL,
|
||||
import { LaximoVehicleSearchResult, LaximoDocFindOEMResult, LaximoVehiclesByPartResult } from '@/types/laximo';
|
||||
import Link from "next/link";
|
||||
import CartButton from './CartButton';
|
||||
import SearchHistoryDropdown from './SearchHistoryDropdown';
|
||||
import { GET_RECENT_SEARCH_QUERIES, PartsSearchHistoryItem } from '@/lib/graphql/search-history';
|
||||
|
||||
interface HeaderProps {
|
||||
onOpenAuthModal?: () => void;
|
||||
@ -25,9 +27,14 @@ const Header: React.FC<HeaderProps> = ({ onOpenAuthModal = () => console.log('Au
|
||||
const [vehiclesByPartResults, setVehiclesByPartResults] = useState<LaximoVehiclesByPartResult | null>(null);
|
||||
const [searchType, setSearchType] = useState<'vin' | 'oem' | 'plate' | 'text'>('text');
|
||||
const [oemSearchMode, setOemSearchMode] = useState<'parts' | 'vehicles'>('parts');
|
||||
const [showSearchHistory, setShowSearchHistory] = useState(false);
|
||||
const [searchHistoryItems, setSearchHistoryItems] = useState<PartsSearchHistoryItem[]>([]);
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
const [showPlaceholder, setShowPlaceholder] = useState(true);
|
||||
const router = useRouter();
|
||||
const searchFormRef = useRef<HTMLFormElement>(null);
|
||||
const searchDropdownRef = useRef<HTMLDivElement>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const isClient = useIsClient();
|
||||
|
||||
// Эффект для восстановления поискового запроса из URL
|
||||
@ -111,11 +118,28 @@ const Header: React.FC<HeaderProps> = ({ onOpenAuthModal = () => console.log('Au
|
||||
}
|
||||
});
|
||||
|
||||
// Запрос для получения истории поиска
|
||||
const [getSearchHistory, { loading: historyLoading }] = useLazyQuery(GET_RECENT_SEARCH_QUERIES, {
|
||||
onCompleted: (data) => {
|
||||
setSearchHistoryItems(data.partsSearchHistory?.items || []);
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('❌ Ошибка загрузки истории поиска:', error);
|
||||
setSearchHistoryItems([]);
|
||||
}
|
||||
});
|
||||
|
||||
// Закрытие результатов при клике вне области
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (searchDropdownRef.current && !searchDropdownRef.current.contains(event.target as Node)) {
|
||||
setShowResults(false);
|
||||
setShowSearchHistory(false);
|
||||
setInputFocused(false);
|
||||
// Показываем placeholder обратно только если поле пустое
|
||||
if (searchQuery.trim() === '') {
|
||||
setShowPlaceholder(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@ -356,6 +380,54 @@ const Header: React.FC<HeaderProps> = ({ onOpenAuthModal = () => console.log('Au
|
||||
router.push(url);
|
||||
};
|
||||
|
||||
// Обработчик фокуса на поле ввода
|
||||
const handleInputFocus = () => {
|
||||
setInputFocused(true);
|
||||
setShowResults(false);
|
||||
setShowPlaceholder(false);
|
||||
if (searchQuery.trim() === '') {
|
||||
setShowSearchHistory(true);
|
||||
getSearchHistory({ variables: { limit: 5 } });
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик изменения значения поля ввода
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = e.target.value;
|
||||
setSearchQuery(value);
|
||||
|
||||
// Управляем placeholder в зависимости от наличия текста
|
||||
if (value.trim() === '') {
|
||||
setShowPlaceholder(false); // Скрываем placeholder пока в фокусе
|
||||
setShowSearchHistory(true);
|
||||
setShowResults(false);
|
||||
getSearchHistory({ variables: { limit: 5 } });
|
||||
} else {
|
||||
setShowPlaceholder(false); // Скрываем placeholder когда есть текст
|
||||
setShowSearchHistory(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик потери фокуса
|
||||
const handleInputBlur = () => {
|
||||
// Показываем placeholder обратно только если поле пустое
|
||||
if (searchQuery.trim() === '') {
|
||||
setShowPlaceholder(true);
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик клика по элементу истории
|
||||
const handleHistoryItemClick = (searchQuery: string) => {
|
||||
setSearchQuery(searchQuery);
|
||||
setShowSearchHistory(false);
|
||||
setInputFocused(false);
|
||||
setShowPlaceholder(false); // Скрываем placeholder так как теперь есть текст
|
||||
// Фокусируем поле ввода для возможности редактирования
|
||||
if (searchInputRef.current) {
|
||||
searchInputRef.current.focus();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* <section className="top_head">
|
||||
@ -421,7 +493,7 @@ const Header: React.FC<HeaderProps> = ({ onOpenAuthModal = () => console.log('Au
|
||||
</svg></div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="searcj w-form" style={{ position: 'relative' }}>
|
||||
<div className="searcj w-form" style={{ position: 'relative' }} ref={searchDropdownRef}>
|
||||
<form
|
||||
id="custom-search-form"
|
||||
name="custom-search-form"
|
||||
@ -444,23 +516,33 @@ const Header: React.FC<HeaderProps> = ({ onOpenAuthModal = () => console.log('Au
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
ref={searchInputRef}
|
||||
className="text-field w-input"
|
||||
maxLength={256}
|
||||
name="customSearch"
|
||||
data-custom-input="true"
|
||||
placeholder="Введите код запчасти, VIN номер или госномер автомобиля"
|
||||
placeholder={showPlaceholder ? "Введите код запчасти, VIN номер или госномер автомобиля" : ""}
|
||||
type="text"
|
||||
id="customSearchInput"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onChange={handleInputChange}
|
||||
onFocus={handleInputFocus}
|
||||
onBlur={handleInputBlur}
|
||||
disabled={isSearching}
|
||||
/>
|
||||
</form>
|
||||
|
||||
{/* История поиска */}
|
||||
<SearchHistoryDropdown
|
||||
isVisible={showSearchHistory && !showResults}
|
||||
historyItems={searchHistoryItems}
|
||||
onItemClick={handleHistoryItemClick}
|
||||
loading={historyLoading}
|
||||
/>
|
||||
|
||||
{/* Результаты поиска VIN */}
|
||||
{showResults && searchResults.length > 0 && (searchType === 'vin' || searchType === 'plate') && (
|
||||
<div
|
||||
ref={searchDropdownRef}
|
||||
className="absolute top-full left-0 right-0 bg-white border border-gray-200 rounded-lg shadow-lg mt-2 z-50 max-h-80 overflow-y-auto"
|
||||
>
|
||||
<div className="p-3 border-b border-gray-100">
|
||||
|
93
src/components/SearchHistoryDropdown.tsx
Normal file
93
src/components/SearchHistoryDropdown.tsx
Normal file
@ -0,0 +1,93 @@
|
||||
import React from 'react';
|
||||
import { PartsSearchHistoryItem } from '@/lib/graphql/search-history';
|
||||
|
||||
interface SearchHistoryDropdownProps {
|
||||
isVisible: boolean;
|
||||
historyItems: PartsSearchHistoryItem[];
|
||||
onItemClick: (searchQuery: string) => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
const SearchHistoryDropdown: React.FC<SearchHistoryDropdownProps> = ({
|
||||
isVisible,
|
||||
historyItems,
|
||||
onItemClick,
|
||||
loading = false
|
||||
}) => {
|
||||
if (!isVisible) return null;
|
||||
|
||||
// Фильтруем уникальные запросы
|
||||
const uniqueQueries = Array.from(
|
||||
new Map(
|
||||
historyItems.map(item => [item.searchQuery.toLowerCase(), item])
|
||||
).values()
|
||||
);
|
||||
|
||||
const getSearchTypeLabel = (type: string) => {
|
||||
switch (type) {
|
||||
case 'VIN':
|
||||
return 'VIN';
|
||||
case 'PLATE':
|
||||
return 'Госномер';
|
||||
case 'OEM':
|
||||
case 'ARTICLE':
|
||||
return 'Артикул';
|
||||
default:
|
||||
return 'Поиск';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="absolute top-full left-0 right-0 bg-white border border-gray-200 rounded-lg shadow-lg mt-2 z-50 max-h-60 overflow-y-auto">
|
||||
{loading ? (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
<div className="flex items-center justify-center">
|
||||
<svg className="animate-spin w-4 h-4 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
Загрузка истории...
|
||||
</div>
|
||||
</div>
|
||||
) : uniqueQueries.length > 0 ? (
|
||||
<>
|
||||
<div className="p-3 border-b border-gray-100">
|
||||
<h3 className="text-xs font-medium text-gray-500 uppercase tracking-wide">
|
||||
Последние запросы
|
||||
</h3>
|
||||
</div>
|
||||
{uniqueQueries.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => onItemClick(item.searchQuery)}
|
||||
className="w-full text-left p-3 hover:bg-gray-50 border-b border-gray-100 last:border-b-0 transition-colors cursor-pointer"
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">
|
||||
{item.searchQuery}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{getSearchTypeLabel(item.searchType)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="ml-2 flex-shrink-0">
|
||||
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
) : (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
<p className="text-sm">История поиска пуста</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SearchHistoryDropdown;
|
@ -24,6 +24,20 @@ export const GET_PARTS_SEARCH_HISTORY = gql`
|
||||
}
|
||||
`;
|
||||
|
||||
// Запрос для получения последних поисковых запросов для автодополнения
|
||||
export const GET_RECENT_SEARCH_QUERIES = gql`
|
||||
query GetRecentSearchQueries($limit: Int = 5) {
|
||||
partsSearchHistory(limit: $limit, offset: 0) {
|
||||
items {
|
||||
id
|
||||
searchQuery
|
||||
searchType
|
||||
createdAt
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const DELETE_SEARCH_HISTORY_ITEM = gql`
|
||||
mutation DeletePartsSearchHistoryItem($id: ID!) {
|
||||
deletePartsSearchHistoryItem(id: $id)
|
||||
|
Reference in New Issue
Block a user