All files / src/components/ui/StarRating index.tsx

99.5% Statements 202/203
100% Branches 29/29
75% Functions 6/8
99.5% Lines 202/203

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 2041x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 3x 3x 3x 208x 208x 208x 208x   208x 208x 208x 208x 208x 208x 208x 1045x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 1028x 1028x 1028x 1028x 1028x 1028x 1045x 1045x 1045x 1045x 1045x 208x 208x 208x 208x 208x 208x 208x 208x 208x 1045x 1045x 1045x 1045x 1045x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 855x 855x 855x 855x 855x 855x 855x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 208x 38x 208x 170x 170x 170x 208x 208x 208x 94x 94x 94x 208x 208x 208x 208x 208x 208x 30x 30x 30x 30x 30x 30x 178x 178x 178x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x  
'use client';
 
import Link from 'next/link';
import { Icon } from '@/components/ui/icons';
import { cn } from '@/lib/core';
import { Button } from '@/components/ui/Button';
import { Tooltip } from '@/components/ui/Tooltip';
import { StarRatingProps } from '@/types/ui';
 
const sizeConfig = {
  sm: { star: 12, gap: 'gap-0.5', text: 'text-xs' },
  md: { star: 14, gap: 'gap-1', text: 'text-custom-sm' },
  lg: { star: 16, gap: 'gap-1', text: 'text-sm' },
};
 
/**
 * StarRating - Reusable star rating display and input component
 *
 * Features:
 * - Support for partial ratings (4.5 stars shows 4 full + 1 half star)
 * - Multiple sizes
 * - Optional review count display
 * - Interactive mode for rating submission
 * - Accessible with aria-label
 *
 * @example
 * ```tsx
 * // Display mode with review count
 * <StarRating
 *   rating={4.5}
 *   reviewCount={128}
 *   showCount={true}
 * />
 *
 * // Interactive mode for reviews
 * <StarRating
 *   rating={rating}
 *   interactive={true}
 *   onRatingChange={setRating}
 * />
 *
 * // Large size without count
 * <StarRating
 *   rating={5}
 *   size="lg"
 * />
 * ```
 */
export function StarRating({
  rating = 0,
  maxStars = 5,
  reviewCount,
  size = 'md',
  showCount = true,
  interactive = false,
  onRatingChange,
  productId,
  className}: StarRatingProps) {
  const config = sizeConfig[size];
  const clampedRating = Math.max(0, Math.min(maxStars, rating));
  const fullStars = Math.floor(clampedRating);
  const hasHalfStar = clampedRating % 1 >= 0.5;
 
  const handleStarClick = (starIndex: number) => {
    if (interactive && onRatingChange) {
      onRatingChange(starIndex + 1);
    }
  };
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleStarHover = (_starIndex: number) => {
    // Reserved for hover preview in interactive mode
  };
 
  // Format rating for tooltip display
  const tooltipContent = `${clampedRating.toFixed(1)} out of ${maxStars}`;
 
  // Render a single star icon
  const renderStarIcon = (isFilled: boolean, isHalf: boolean) => {
    if (isHalf) {
      return (
        <span className="relative inline-block">
          {/* Background empty star */}
          <Icon
            name="star"
            size={config.star}
            className="text-gray-300 fill-current"
          />
          {/* Foreground half-filled star */}
          <span className="absolute inset-0 overflow-hidden" style={{ width: '50%' }}>
            <Icon
              name="star"
              size={config.star}
              className="text-yellow-400 fill-current"
            />
          </span>
        </span>
      );
    }
    return (
      <Icon
        name="star"
        size={config.star}
        className={cn(
          'fill-current transition-colors',
          isFilled ? 'text-yellow-400' : 'text-gray-300',
          interactive && 'hover:text-yellow-500'
        )}
      />
    );
  };
 
  const starsContent = (
    <span
      className={cn('inline-flex items-center', config.gap)}
      role="img"
      aria-label={`Rating: ${clampedRating} out of ${maxStars} stars`}
    >
      {Array.from({ length: maxStars }, (_, index) => {
        const isFilled = index < fullStars;
        const isHalf = index === fullStars && hasHalfStar;
 
        // Use Button only for interactive mode, otherwise use span
        if (interactive) {
          return (
            <Button
              key={index}
              type="button"
              onClick={() => handleStarClick(index)}
              onMouseEnter={() => handleStarHover(index)}
              variant="ghost"
              size="sm"
              className="relative p-0 cursor-pointer hover:scale-110 transition-transform"
              aria-label={`${index + 1} star${index !== 0 ? 's' : ''}`}
            >
              {renderStarIcon(isFilled, isHalf)}
            </Button>
          );
        }
 
        // Non-interactive: use span for display only
        return (
          <span key={index} className="relative inline-flex">
            {renderStarIcon(isFilled, isHalf)}
          </span>
        );
      })}
    </span>
  );
 
  // Build the review link URL if productId is provided
  const reviewLink = productId ? `/product/${productId}#reviews` : null;
 
  const ratingContent = (
    <div className={cn(
      'flex items-center gap-2.5',
      reviewLink && 'cursor-pointer hover:opacity-80 transition-opacity',
      className
    )}>
      {interactive ? (
        starsContent
      ) : (
        <Tooltip content={reviewLink ? `${tooltipContent} - Click to see reviews` : tooltipContent} position="top">
          {starsContent}
        </Tooltip>
      )}
 
      {showCount && reviewCount !== undefined && (
        <p className={cn(config.text, 'text-gray-600 dark:text-gray-400')}>
          ({reviewCount})
        </p>
      )}
    </div>
  );
 
  // Wrap in Link if productId is provided (makes rating clickable to reviews)
  if (reviewLink && !interactive) {
    return (
      <Link href={reviewLink} className="inline-flex">
        {ratingContent}
      </Link>
    );
  }
 
  return ratingContent;
}
 
/**
 * Compact star rating display (just stars, no count)
 */
export function StarRatingCompact({ rating = 0, size = 'sm' }: Pick<StarRatingProps, 'rating' | 'size'>) {
  return <StarRating rating={rating} size={size} showCount={false} />;
}
 
/**
 * Star rating with count always shown
 */
export function StarRatingWithCount({
  rating = 0,
  reviewCount = 0,
  size = 'md'}: Pick<StarRatingProps, 'rating' | 'reviewCount' | 'size'>) {
  return <StarRating rating={rating} reviewCount={reviewCount} size={size} showCount={true} />;
}