All files / src/components/VoteReaction index.tsx

90.66% Statements 136/150
87.17% Branches 34/39
100% Functions 1/1
90.66% Lines 136/150

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 2091x 1x     1x     1x 1x               1x     1x 1x     1x 1x     1x                         1x 1x   1x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x   53x 53x 53x 53x 53x 53x   53x 53x   53x 53x   53x 53x 53x     53x 53x   53x 39x                               53x   53x 53x 13x   13x 13x 13x 13x   13x 13x     13x 13x 13x   13x 4x 2x 4x 4x   13x 3x 2x 2x 3x 1x 1x 1x 3x 3x   6x     6x 13x   13x 1x 1x 1x 1x 1x   12x   13x 12x 12x 12x 12x 12x   13x 2x 2x 13x 2x 2x 2x 2x   12x 12x 13x 53x 53x   53x   53x 53x 53x 53x 53x 53x 53x 53x 53x   53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x   53x 53x 53x 53x 53x 53x 53x 53x 53x 53x   53x  
import { useCallback, useEffect, useState, useRef } from 'react';
import { toast } from 'sonner';
 
// Types
import { UserReaction } from '@/types';
 
// Components
import { ReactionButton } from './ReactionButton';
import {
  LikeIcon,
  SelectedLikeIcon,
  DislikeIcon,
  SelectedDislikeIcon,
} from '@/components/icons/reacts';
 
// Services
import { auth, reactionService } from '@/services';
 
// Hooks
import { useReaction } from '@/hooks/useReaction';
import { useVoteOpen } from '@/hooks/useVoteOpen';
 
// Constants
import { ERROR_MESSAGES } from '@/constants';
import { STATUS_CODE, STATUS_MESSAGES } from '@shared/constants';
 
// Utils
import { getNowMs } from '@/utils';
 
interface IVoteReaction {
  id: string;
  countLike: number;
  countDislike: number;
  userReaction?: UserReaction;
  disabled?: boolean;
  date?: Date;
  openHour?: number;
  openMinute?: number;
}
 
const CLICK_COOLDOWN_MS = 500;
const WS_SYNC_GRACE_MS = 900;
 
export const VoteReaction = ({
  id,
  countLike,
  countDislike,
  userReaction,
  disabled,
  date,
  openHour = 11,
  openMinute = 30,
}: IVoteReaction) => {
  const dataWsReaction = useReaction(id);
  const canVote = date ? useVoteOpen(date, openHour, openMinute) : false;
 
  const [active, setActive] = useState<UserReaction | null>(
    userReaction ?? null,
  );
  const [likes, setLikes] = useState(countLike);
  const [dislikes, setDislikes] = useState(countDislike);
  const [loading, setLoading] = useState<UserReaction | null>(null);
 
  const [showLikeBubble, setShowLikeBubble] = useState(false);
  const [showDislikeBubble, setShowDislikeBubble] = useState(false);
 
  const [isLikeAnimating, setIsLikeAnimating] = useState(false);
  const [isDislikeAnimating, setIsDislikeAnimating] = useState(false);
 
  const [pendingReaction, setPendingReaction] = useState<UserReaction | null>(
    null,
  );
 
  // Prevent rapid repeat requests when users spam-click reaction buttons.
  const lastAcceptedClickAt = useRef(0);
  const ignoreWsUntil = useRef(0);
 
  useEffect(() => {
    if (!dataWsReaction) return;
    if (getNowMs() < ignoreWsUntil.current) return;
 
    if (!pendingReaction) {
      // only update if numbers are different, clamp to >= 0
      setLikes((prev) =>
        prev !== dataWsReaction.likes
          ? Math.max(0, dataWsReaction.likes)
          : prev,
      );
      setDislikes((prev) =>
        prev !== dataWsReaction.dislikes
          ? Math.max(0, dataWsReaction.dislikes)
          : prev,
      );
    }
  }, [dataWsReaction, pendingReaction]);
 
  const handleClick = useCallback(
    async (type: UserReaction) => {
      if (disabled || loading !== null) return;
 
      const now = getNowMs();
      if (now - lastAcceptedClickAt.current < CLICK_COOLDOWN_MS) return;
      lastAcceptedClickAt.current = now;
      ignoreWsUntil.current = now + WS_SYNC_GRACE_MS;
 
      setLoading(type);
      setPendingReaction(type);
 
      // optimistic UI update
      setActive((prev) => {
        const isDeselect = prev === type;
        const isSwitch = prev !== null && prev !== type;
 
        if (isDeselect) {
          if (type === UserReaction.LIKE) setLikes((l) => Math.max(0, l - 1));
          else setDislikes((d) => Math.max(0, d - 1));
          return null;
        }
 
        if (isSwitch) {
          if (type === UserReaction.LIKE) {
            setLikes((l) => l + 1);
            setDislikes((d) => Math.max(0, d - 1));
          } else {
            setDislikes((d) => d + 1);
            setLikes((l) => Math.max(0, l - 1));
          }
          return type;
        }
 
        if (type === UserReaction.LIKE) setLikes((l) => l + 1);
        else setDislikes((d) => d + 1);
 
        return type;
      });
 
      if (!auth.currentUser) {
        toast.error(STATUS_MESSAGES[STATUS_CODE.UNAUTHORIZED]);
        setLoading(null);
        setPendingReaction(null);
        return;
      }
 
      try {
        // Use cached token when still valid to avoid long waits between clicks.
        const token = await auth.currentUser?.getIdToken();
        const { success, error } = await reactionService({
          lunchMenuId: id,
          token,
          type,
        });
 
        if (!success) {
          toast.error(error?.message || ERROR_MESSAGES.DEFAULT);
        }
      } catch (error) {
        toast.error(
          error instanceof Error ? error.message : ERROR_MESSAGES.DEFAULT,
        );
      }
 
      setLoading(null);
      setPendingReaction(null);
    },
    [id, disabled, loading],
  );
 
  const finalDisabled = disabled || !canVote;
 
  return (
    <div className="w-full flex justify-between">
      <ReactionButton
        type={UserReaction.LIKE}
        active={active === UserReaction.LIKE}
        count={likes}
        icon={<LikeIcon />}
        selectedIcon={
          <SelectedLikeIcon className="text-primary-350 h-[54px] w-[54px] sm:h-[36px] sm:w-[36px]" />
        }
        isAnimating={isLikeAnimating}
        setIsAnimating={setIsLikeAnimating}
        showBubble={showLikeBubble}
        setShowBubble={setShowLikeBubble}
        onClick={handleClick}
        disabled={loading !== null || finalDisabled}
        align="right"
        isTimeDisabled={!canVote}
      />
      <ReactionButton
        type={UserReaction.DISLIKE}
        active={active === UserReaction.DISLIKE}
        count={dislikes}
        icon={<DislikeIcon />}
        selectedIcon={
          <SelectedDislikeIcon className="text-primary-550 h-[54px] w-[54px] sm:h-[36px] sm:w-[36px]" />
        }
        isAnimating={isDislikeAnimating}
        setIsAnimating={setIsDislikeAnimating}
        showBubble={showDislikeBubble}
        setShowBubble={setShowDislikeBubble}
        onClick={handleClick}
        disabled={loading !== null || finalDisabled}
        align="left"
        isTimeDisabled={!canVote}
      />
    </div>
  );
};