MCPcopy Index your code
hub / github.com/primer/react / swapMenuItemWithListItem

Function swapMenuItemWithListItem

packages/react/src/UnderlineNav/UnderlineNav.tsx:208–233  ·  view source on GitHub ↗
(
      prospectiveListItem: React.ReactElement,
      indexOfProspectiveListItem: number,
      event: React.MouseEvent<HTMLAnchorElement> | React.KeyboardEvent<HTMLAnchorElement>,
      callback: (props: ResponsiveProps, displayIcons: boolean) => void,
    )

Source from the content-addressed store, hash-verified

206 }
207
208 const swapMenuItemWithListItem = (
209 prospectiveListItem: React.ReactElement,
210 indexOfProspectiveListItem: number,
211 event: React.MouseEvent<HTMLAnchorElement> | React.KeyboardEvent<HTMLAnchorElement>,
212 callback: (props: ResponsiveProps, displayIcons: boolean) => void,
213 ) => {
214 // get the selected menu item's width
215 const widthToFitIntoList = getItemsWidth(prospectiveListItem.props.children)
216 // Check if there is any empty space on the right side of the list
217 const availableSpace =
218 navRef.current.getBoundingClientRect().width - (listRef.current?.getBoundingClientRect().width ?? 0)
219
220 // Calculate how many items need to be pulled in to the menu to make room for the selected menu item
221 // I.e. if we need to pull 2 items in (index 0 and index 1), breakpoint (index) will return 1.
222 const index = getBreakpointForItemSwapping(widthToFitIntoList, availableSpace)
223 const indexToSliceAt = responsiveProps.items.length - 1 - index
224 // Form the new list of items
225 const itemsLeftInList = [...responsiveProps.items].slice(0, indexToSliceAt)
226 const updatedItemList = [...itemsLeftInList, prospectiveListItem]
227 // Form the new menu items
228 const itemsToAddToMenu = [...responsiveProps.items].slice(indexToSliceAt)
229 const updatedMenuItems = [...menuItems]
230 // Add itemsToAddToMenu array's items to the menu at the index of the prospectiveListItem and remove 1 count of items (prospectiveListItem)
231 updatedMenuItems.splice(indexOfProspectiveListItem, 1, ...itemsToAddToMenu)
232 callback({items: updatedItemList, menuItems: updatedMenuItems}, false)
233 }
234 // How many items do we need to pull in to the menu to make room for the selected menu item.
235 function getBreakpointForItemSwapping(widthToFitIntoList: number, availableSpace: number) {
236 let widthToSwap = 0

Callers 1

UnderlineNav.tsxFile · 0.85

Calls 2

getItemsWidthFunction · 0.85

Tested by

no test coverage detected