Untitled
unknown
plain_text
2 months ago
2.5 kB
1
Indexable
import { useContext } from 'react'; import { Context } from '@components/SecondaryNavigation/common/context/context'; import { MORE_BUTTON_ITEM_ID } from '@components/SecondaryNavigation/common/constants'; import { menuStructureService } from '@components/SecondaryNavigation/common/services'; import { FlatMenuItem, FlatMenuItemChildsData } from '../types'; export const useMenu = () => { const context = useContext(Context); if (!context || !context.flatMenu || !context.setFlatMenu) { throw new Error("useMenu must be used within a Provider"); } const { flatMenu, setFlatMenu } = context; const getItem = (itemId: string) => flatMenu[itemId] || null; const getIsActiveItem = (itemId: string): boolean => { const item = getItem(itemId); if (!item) { return false; } if (item.active) { return true; } return item.childIds.some(id => getIsActiveItem(id)); } const getAllItemsList = () => Object.values(flatMenu); const getTopLevelItems = () => getAllItemsList().filter(menuStructureService.isTopLevelItem); const getChildItems = (parentId: string) => flatMenu[parentId]?.childIds.map((id) => flatMenu[id]) || []; const getMoreButtonItem = () => flatMenu[MORE_BUTTON_ITEM_ID]; const getVisibleItems = () => { return getAllItemsList().filter(item => !item.parentId && item.id !== MORE_BUTTON_ITEM_ID); } const updateChildsMoreButtonItem = (childsData: FlatMenuItemChildsData) => { setFlatMenu(prev => { const prevMoreButtonItem = prev[MORE_BUTTON_ITEM_ID]; const updatedTopLeveItems = Object.values(prev).filter(menuStructureService.isTopLevelItem).reduce<Record<string, FlatMenuItem>>((acc, item) => { acc[item.id] = { ...item, parentId: childsData.childIdsCollection[item.id] ? MORE_BUTTON_ITEM_ID : undefined }; return acc; }, {}); const isMoreButtonChildsNotChanged = JSON.stringify(prevMoreButtonItem.childIdsCollection) === JSON.stringify(childsData.childIdsCollection); if (isMoreButtonChildsNotChanged) { return prev; } return { ...prev, ...updatedTopLeveItems, [MORE_BUTTON_ITEM_ID]: { ...prevMoreButtonItem, ...childsData } }; }); }; return { getItem, getTopLevelItems, getChildItems, getVisibleItems, getMoreButtonItem, getIsActiveItem, updateChildsMoreButtonItem }; };
Editor is loading...
Leave a Comment