import type { ComponentProps } from 'react'; import { useMemo } from 'react'; import { usePopperTooltip } from 'react-popper-tooltip'; import { Badge } from '@tih/ui'; import 'react-popper-tooltip/dist/styles.css'; type BadgeProps = ComponentProps; export type QuestionAggregateBadgeProps = Omit & { statistics: Record; }; export default function QuestionAggregateBadge({ statistics, ...badgeProps }: QuestionAggregateBadgeProps) { const { getTooltipProps, setTooltipRef, setTriggerRef, visible } = usePopperTooltip({ interactive: true, placement: 'bottom-start', trigger: ['focus', 'hover'], }); const mostCommonStatistic = useMemo( () => Object.entries(statistics).reduce( (mostCommon, [key, value]) => { if (value > mostCommon.value) { return { key, value }; } return mostCommon; }, { key: '', value: 0 }, ), [statistics], ); const sortedStatistics = useMemo( () => Object.entries(statistics) .sort((a, b) => b[1] - a[1]) .map(([key, value]) => ({ key, value })), [statistics], ); const additionalStatisticCount = Object.keys(statistics).length - 1; const label = useMemo(() => { if (additionalStatisticCount === 0) { return mostCommonStatistic.key; } return `${mostCommonStatistic.key} (+${additionalStatisticCount})`; }, [mostCommonStatistic, additionalStatisticCount]); return ( <> {visible && (
    {sortedStatistics.map(({ key, value }) => (
  • {key} {value}
  • ))}
)} ); }