ProductMenuShortcuts.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { useRouter } from 'next/router'
  2. import { useCallback } from 'react'
  3. import type { ProductMenuGroup, ProductMenuGroupItem } from './ProductMenu.types'
  4. import { useShortcut } from '@/state/shortcuts/useShortcut'
  5. interface ProductMenuShortcutsProps {
  6. menu: ProductMenuGroup[]
  7. }
  8. type ProductMenuShortcutItem = ProductMenuGroupItem & {
  9. shortcutId: NonNullable<ProductMenuGroupItem['shortcutId']>
  10. }
  11. const getShortcutItems = (items: ProductMenuGroupItem[]): ProductMenuShortcutItem[] => {
  12. return items.flatMap((item) => {
  13. const childItems = item.childItems ? getShortcutItems(item.childItems) : []
  14. if (!item.shortcutId || !item.url || item.disabled || item.isExternal) {
  15. return childItems
  16. }
  17. return [item as ProductMenuShortcutItem, ...childItems]
  18. })
  19. }
  20. const ProductMenuShortcut = ({ item }: { item: ProductMenuShortcutItem }) => {
  21. const router = useRouter()
  22. const { shortcutId, url } = item
  23. const navigate = useCallback(() => {
  24. router.push(url)
  25. }, [router, url])
  26. useShortcut(shortcutId, navigate)
  27. return null
  28. }
  29. export const ProductMenuShortcuts = ({ menu }: ProductMenuShortcutsProps) => {
  30. const shortcutItems = menu.flatMap((group) => getShortcutItems(group.items))
  31. return (
  32. <>
  33. {shortcutItems.map((item) => (
  34. <ProductMenuShortcut key={`${item.shortcutId}-${item.url}`} item={item} />
  35. ))}
  36. </>
  37. )
  38. }