import React, { useEffect, useRef, useState } from 'react'
import {
Box,
Button,
Center,
Flex,
Icon,
Image,
Input,
Text,
VStack,
} from '@chakra-ui/react'
import CollapseMenu, {
CollapseMenuItem,
CollapseMenuSection,
} from '../../../components/CollapseMenu'
import { Link, matchPath, useLocation } from 'react-router-dom'
import { RiCloseLine, RiSearchLine } from 'react-icons/ri'
import { useDispatch } from 'react-redux'
import {
setReferenceBreadcrumbs,
setReferenceSubBreadcrumbs,
} from '@/store/mainLayoutSlice'
import emptySearchResult from '../../../assets/emptyFilterResult.png'
const Menu = props => {
const { sections = [] } = props
const [searchQuery, setSearchQuery] = useState('')
const [forceOpenSections, setForceOpenSections] = useState({})
const [hasScroll, setHasScroll] = useState(false)
const inputRef = useRef(null)
const contentRef = useRef(null)
const dispatch = useDispatch()
const location = useLocation()
useEffect(() => {
let currentSection = null
let currentSubsection = null
sections.forEach(section => {
section.list.forEach(item => {
if (matchPath(item.link, decodeURI(location.pathname))) {
currentSection = section.title
currentSubsection = item.title
}
})
})
dispatch(setReferenceBreadcrumbs(currentSection))
dispatch(setReferenceSubBreadcrumbs(currentSubsection))
}, [location.pathname, sections, dispatch])
useEffect(() => {
if (searchQuery.trim()) {
const sectionsToOpen = {}
sections.forEach((section, index) => {
if (
section.list.some(item =>
item.title
.toLowerCase()
.includes(searchQuery.toLowerCase())
)
) {
sectionsToOpen[index] = true
}
})
setForceOpenSections(sectionsToOpen)
} else {
setForceOpenSections({})
}
}, [searchQuery, sections])
const highlightMatches = text => {
if (!searchQuery.trim()) return text
const regex = new RegExp(`(${searchQuery})`, 'gi')
const parts = text.split(regex)
return parts.map((part, index) =>
part.toLowerCase() === searchQuery.toLowerCase() ? (
<Text
as='span'
key={index}
bg='#DCE2EC'
>
{part}
</Text>
) : (
part
)
)
}
const filteredSections = sections.map((section, sectionIndex) => ({
...section,
list: searchQuery.trim()
? section.list.filter(item =>
item.title.toLowerCase().includes(searchQuery.toLowerCase())
)
: section.list,
forceOpen: !!forceOpenSections[sectionIndex],
}))
const hasSearchResults = filteredSections.some(
section => section.list.length > 0
)
const showEmptyState = searchQuery.trim() && !hasSearchResults
useEffect(() => {
const checkScroll = () => {
if (contentRef.current) {
const hasVerticalScroll =
contentRef.current.scrollHeight >
contentRef.current.clientHeight
setHasScroll(hasVerticalScroll)
}
}
checkScroll()
window.addEventListener('resize', checkScroll)
const observer = new MutationObserver(checkScroll)
if (contentRef.current) {
observer.observe(contentRef.current, {
childList: true,
subtree: true,
attributes: true,
characterData: true,
})
}
return () => {
window.removeEventListener('resize', checkScroll)
observer.disconnect()
}
}, [])
return (
<Box
w='260px'
bg='#FFFFFF'
borderRadius='20px'
flexShrink='0'
maxH='calc(100vh - 114.41px)'
display='flex'
flexDirection='column'
>
<Flex
alignItems='center'
gap='8px'
p='8px 16px 7px'
borderBottom={'1px solid'}
borderColor={'bia.neutral.400'}
>
<Icon
as={RiSearchLine}
w={'16px'}
h={'16px'}
color='bia.black.800'
/>
<Input
ref={inputRef}
name='menu_search'
border={'none'}
placeholder='Поиск по меню'
_focusVisible={{ outline: 'none' }}
p='0px'
h='24px'
value={searchQuery}
onChange={e => {
setSearchQuery(e.currentTarget.value)
}}
/>
{searchQuery ? (
<Center
borderRadius='4px'
p='2px'
_hover={{
bg: 'bia.neutral.300',
}}
>
<Icon
as={RiCloseLine}
width='20px'
height='20px'
cursor='pointer'
color='bia.black.800'
onClick={() => {
setSearchQuery('')
inputRef.current?.focus()
}}
/>
</Center>
) : undefined}
</Flex>
<Box
ref={contentRef}
flex='1'
overflowY='auto'
pb='8px'
>
{showEmptyState ? (
<VStack
gap='12px'
mt='12px'
>
<Image
src={emptySearchResult}
width='64px'
height='64px'
/>
<Box width='180px'>
<Text
textStyle='bia.highlight'
color='bia.black.800'
>
Справочник не найден
</Text>
<Text
textStyle='bia.tertiary_m'
color='bia.neutral.800'
mt='4px'
textAlign='center'
>
Проверьте запрос или очистите поиск
</Text>
</Box>
<Button
width='196px'
variant='secondary'
height='32px'
onClick={() => setSearchQuery('')}
>
Очистить
</Button>
</VStack>
) : (
<CollapseMenu>
{filteredSections.map((section, sectionIndex) => {
const shouldShowSection =
section.list.length > 0 || !searchQuery.trim()
return (
shouldShowSection && (
<CollapseMenuSection
title={section.title}
key={sectionIndex}
forceOpen={section.forceOpen}
>
{section.list.map(
(listItem, listItemIndex) => {
return (
<CollapseMenuItem
wrapper={
<Link
to={
listItem.link
}
style={{
width: '100%',
}}
/>
}
isActive={matchPath(
listItem.link,
decodeURI(
location.pathname
)
)}
isControlled={true}
key={listItemIndex}
validationAlertLevel={
listItem.validationAlertLevel
}
onItemClick={() =>
setSearchQuery('')
}
hasScroll={hasScroll}
>
{highlightMatches(
listItem.title
)}
</CollapseMenuItem>
)
}
)}
</CollapseMenuSection>
)
)
})}
</CollapseMenu>
)}
</Box>
</Box>
)
}
export default Menu
почему через какое то время появляется в консоли это
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.