category.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use client'
  2. import { useRef } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useContext } from 'use-context-selector'
  5. import { useMount } from 'ahooks'
  6. import cn from '@/utils/classnames'
  7. import { Apps02 } from '@/app/components/base/icons/src/vender/line/others'
  8. import I18n from '@/context/i18n'
  9. import { getLanguage } from '@/i18n/language'
  10. import { useStore as useLabelStore } from '@/app/components/tools/labels/store'
  11. import { fetchLabelList } from '@/service/tools'
  12. type Props = {
  13. value: string
  14. onSelect: (type: string) => void
  15. }
  16. const Icon = ({ svgString, active }: { svgString: string; active: boolean }) => {
  17. const svgRef = useRef<SVGSVGElement | null>(null)
  18. const SVGParser = (svg: string) => {
  19. if (!svg)
  20. return null
  21. const parser = new DOMParser()
  22. const doc = parser.parseFromString(svg, 'image/svg+xml')
  23. return doc.documentElement
  24. }
  25. useMount(() => {
  26. const svgElement = SVGParser(svgString)
  27. if (svgRef.current && svgElement)
  28. svgRef.current.appendChild(svgElement)
  29. })
  30. return <svg className={cn('w-4 h-4 text-gray-700', active && '!text-primary-600')} ref={svgRef} />
  31. }
  32. const Category = ({
  33. value,
  34. onSelect,
  35. }: Props) => {
  36. const { t } = useTranslation()
  37. const { locale } = useContext(I18n)
  38. const language = getLanguage(locale)
  39. const labelList = useLabelStore(s => s.labelList)
  40. const setLabelList = useLabelStore(s => s.setLabelList)
  41. useMount(() => {
  42. fetchLabelList().then((res) => {
  43. setLabelList(res)
  44. })
  45. })
  46. return (
  47. <div className='mb-3'>
  48. <div className='px-3 py-0.5 text-gray-500 text-xs leading-[18px] font-medium'>{t('tools.addToolModal.category').toLocaleUpperCase()}</div>
  49. <div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === '' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('')}>
  50. <Apps02 className='shrink-0 w-4 h-4 mr-2' />
  51. {t('tools.type.all')}
  52. </div>
  53. {labelList.map(label => (
  54. <div key={label.name} title={label.label[language]} className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white truncate overflow-hidden', value === label.name && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect(label.name)}>
  55. <div className='shrink-0 w-4 h-4 mr-2'>
  56. <Icon active={value === label.name} svgString={label.icon} />
  57. </div>
  58. {label.label[language]}
  59. </div>
  60. ))}
  61. </div>
  62. )
  63. }
  64. export default Category