index-bar.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { pinyin } from 'pinyin-pro'
  2. import type { FC, RefObject } from 'react'
  3. export const groupItems = (items: Array<any>, getFirstChar: (item: string) => string) => {
  4. const groups = items.reduce((acc, item) => {
  5. const firstChar = getFirstChar(item)
  6. if (!firstChar || firstChar.length === 0)
  7. return acc
  8. let letter
  9. // transform Chinese to pinyin
  10. if (/[\u4E00-\u9FA5]/.test(firstChar))
  11. letter = pinyin(firstChar, { pattern: 'first', toneType: 'none' })[0].toUpperCase()
  12. else
  13. letter = firstChar.toUpperCase()
  14. if (!/[A-Z]/.test(letter))
  15. letter = '#'
  16. if (!acc[letter])
  17. acc[letter] = []
  18. acc[letter].push(item)
  19. return acc
  20. }, {})
  21. const letters = Object.keys(groups).sort()
  22. // move '#' to the end
  23. const hashIndex = letters.indexOf('#')
  24. if (hashIndex !== -1) {
  25. letters.splice(hashIndex, 1)
  26. letters.push('#')
  27. }
  28. return { letters, groups }
  29. }
  30. type IndexBarProps = {
  31. letters: string[]
  32. itemRefs: RefObject<{ [key: string]: HTMLElement | null }>
  33. }
  34. const IndexBar: FC<IndexBarProps> = ({ letters, itemRefs }) => {
  35. const handleIndexClick = (letter: string) => {
  36. const element = itemRefs.current?.[letter]
  37. if (element)
  38. element.scrollIntoView({ behavior: 'smooth' })
  39. }
  40. return (
  41. <div className="index-bar fixed right-4 top-36 flex flex-col items-center text-xs font-medium text-gray-500">
  42. {letters.map(letter => (
  43. <div className="hover:text-gray-900 cursor-pointer" key={letter} onClick={() => handleIndexClick(letter)}>
  44. {letter}
  45. </div>
  46. ))}
  47. </div>
  48. )
  49. }
  50. export default IndexBar