Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

2.7 KB
Raw Blame
"use client";
import { cn } from "@rallly/ui";
import { User2Icon } from "lucide-react";
import { AnimatePresence } from "motion/react";
import * as m from "motion/react-m";
import * as React from "react";
import { usePrevious } from "react-use";
import { usePollScores } from "@/features/poll/components/use-poll-scores";
import { IfScoresVisible } from "@/features/poll/components/visibility";

export interface PopularityScoreProps {
  yesScore: number;
  ifNeedBeScore?: number;
  highlight?: boolean;
  highScore: number;
  /**
   * When false the amber tentative marker is dropped. Tentative votes cast
   * before the poll turned the option off still count toward the total.
   */
  showTentative?: boolean;
}

export const ConnectedScoreSummary: React.FunctionComponent<{
  optionId: string;
}> = ({ optionId }) => {
  const { getScore, highScore, poll } = usePollScores();
  const { yes, ifNeedBe } = getScore(optionId);
  const score = yes + ifNeedBe;
  const highlight = score === highScore && score > 1;
  return (
    <IfScoresVisible>
      <ScoreSummary
        yesScore={yes}
        ifNeedBeScore={ifNeedBe}
        highScore={highScore}
        highlight={highlight}
        showTentative={poll.allowTentativeVotes}
      />
    </IfScoresVisible>
  );
};

function AnimatedNumber({ score }: { score: number }) {
  const prevScore = usePrevious(score);
  const direction = prevScore !== undefined ? score - prevScore : 0;

  return (
    <AnimatePresence initial={false} mode="wait">
      <m.span
        initial={{
          y: 10 * direction,
        }}
        transition={{
          duration: 0.1,
        }}
        animate={{ opacity: 1, y: 0 }}
        exit={{
          y: 10 * direction,
        }}
        key={score}
        className="relative"
      >
        {score}
      </m.span>
    </AnimatePresence>
  );
}

const ScoreSummary: React.FunctionComponent<PopularityScoreProps> = React.memo(
  function PopularityScore({
    yesScore = 0,
    ifNeedBeScore = 0,
    highlight,
    highScore,
    showTentative = true,
  }) {
    const score = yesScore + ifNeedBeScore;

    return (
      <span
        className={cn(
          "relative inline-flex items-center gap-x-1 text-xs",
          highlight
            ? "font-medium text-foreground"
            : "font-normal text-muted-foreground",
        )}
        style={{
          opacity: Math.max(score / highScore, 0.2),
        }}
      >
        <User2Icon className="size-4 opacity-75" />
        <AnimatedNumber score={score} />
        {highlight && showTentative ? (
          ifNeedBeScore > 0 ? (
            <span className="inline-block size-1.5 rounded-full bg-amber-400" />
          ) : null
        ) : null}
      </span>
    );
  },
);