# Product reviews

Reviews for one product: the average with stars and a count, a five-to-one star distribution whose bars filter the list, a sort `Select`, and reviews with a verified-buyer `Badge` and a helpful vote. Write a review opens a `Modal` with a star `RadioGroup`, a `Textarea` and validation.

**Example: Customer reviews** (`examples/recipes/product-reviews.tsx`)

```tsx
'use client'

import {
  Badge,
  Body,
  BodySmall,
  Button,
  Field,
  Heading,
  Modal,
  Radio,
  RadioGroup,
  Select,
  Stack,
  Text,
  Textarea,
  toastSuccess,
} from '@blocks/design-system'
import { BadgeCheck, Star, ThumbsUp } from 'lucide-react'
import { type FormEvent, useId, useState } from 'react'
import styles from './product-reviews.module.css'

interface Review {
  id: string
  rating: number
  title: string
  body: string
  author: string
  date: string
  verified: boolean
  helpful: number
}

const initialReviews: Review[] = [
  {
    id: 'r1',
    rating: 5,
    title: 'Warm at the trailhead, light in the pack',
    body: 'Wore it for dawn starts in the Cascades at −6 °C with just a base layer underneath. It stuffs into its chest pocket and rides in the lid of my pack.',
    author: 'Mara K.',
    date: '2026-11-21',
    verified: true,
    helpful: 24,
  },
  {
    id: 'r2',
    rating: 4,
    title: 'Great jacket, sleeves run long',
    body: 'Insulation and fit through the body are spot on. The sleeves come past my knuckles in a medium, which I’ve grown to like with gloves.',
    author: 'Theo B.',
    date: '2026-11-14',
    verified: true,
    helpful: 12,
  },
  {
    id: 'r3',
    rating: 5,
    title: 'Stayed warm through a soggy week',
    body: 'Five days of coastal drizzle and it never went flat. Dried overnight hanging in the tent vestibule.',
    author: 'June A.',
    date: '2026-11-03',
    verified: true,
    helpful: 31,
  },
  {
    id: 'r4',
    rating: 3,
    title: 'Warm, but the hood won’t go over a helmet',
    body: 'Fine for hiking. For climbing I wanted a helmet-compatible hood, and this one is cut close to the head.',
    author: 'Ravi P.',
    date: '2026-10-29',
    verified: false,
    helpful: 9,
  },
  {
    id: 'r5',
    rating: 5,
    title: 'My go-to belay jacket',
    body: 'Throw it on at the anchor, off again for the next pitch. The two-way zip makes it easy to clip in.',
    author: 'Sol M.',
    date: '2026-10-20',
    verified: true,
    helpful: 7,
  },
  {
    id: 'r6',
    rating: 2,
    title: 'Zipper snagged within a month',
    body: 'The main zip started catching on the storm flap after a few weeks. Support repaired it for free, but I expected better.',
    author: 'Ines G.',
    date: '2026-10-11',
    verified: true,
    helpful: 15,
  },
  {
    id: 'r7',
    rating: 4,
    title: 'Packs small, a little noisy',
    body: 'The shell crinkles more than my old one. Otherwise light, warm and the Spruce color is lovely.',
    author: 'Owen L.',
    date: '2026-09-30',
    verified: true,
    helpful: 4,
  },
]

const sorts = [
  { value: 'helpful', label: 'Most helpful' },
  { value: 'newest', label: 'Newest' },
  { value: 'highest', label: 'Highest rated' },
  { value: 'lowest', label: 'Lowest rated' },
]

const compare: Record<string, (a: Review, b: Review) => number> = {
  helpful: (a, b) => b.helpful - a.helpful,
  newest: (a, b) => b.date.localeCompare(a.date),
  highest: (a, b) => b.rating - a.rating || b.date.localeCompare(a.date),
  lowest: (a, b) => a.rating - b.rating || b.date.localeCompare(a.date),
}

// Dates are stored as YYYY-MM-DD and formatted in UTC so the server and the
// browser render the same text.
const formatDate = (date: string) =>
  new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' })

// Reviews for one product. The summary and the distribution are derived from
// the list, so a new review updates them; the distribution bars filter it.
export default function ProductReviews() {
  const [reviews, setReviews] = useState(initialReviews)
  const [filter, setFilter] = useState<number | null>(null)
  const [sort, setSort] = useState<string | null>('helpful')
  const [voted, setVoted] = useState<Set<string>>(new Set())
  const headingId = useId()

  const average = reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length
  const counts = [5, 4, 3, 2, 1].map((stars) => ({ stars, count: reviews.filter((review) => review.rating === stars).length }))
  const visible = reviews.filter((review) => filter === null || review.rating === filter).sort(compare[sort ?? 'helpful'])

  function toggleHelpful(id: string) {
    setVoted((current) => {
      const next = new Set(current)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  function addReview(review: Review) {
    setReviews((current) => [review, ...current])
    setFilter(null)
    setSort('newest')
    toastSuccess('Thanks for your review', { description: 'It’s at the top of the list.' })
  }

  return (
    <Stack as="section" gap="xl" aria-labelledby={headingId} dangerouslySetClassName={styles.root}>
      <div className={styles.summary}>
        <Stack gap="xs">
          <Heading as="h2" id={headingId} fontSize="lg">
            Customer reviews
          </Heading>
          <Stack direction="row" gap="md" align="center">
            <Text fontSize="xxxl" fontWeight="bold" lineHeight="heading">
              {average.toFixed(1)}
            </Text>
            <Stack gap="xxs">
              <Stars value={average} />
              <Text fontSize="sm" color="text-muted">
                {reviews.length} reviews
              </Text>
            </Stack>
          </Stack>
          <WriteReview onSubmit={addReview} nextId={`r${reviews.length + 1}`} />
        </Stack>

        <ul aria-label="Filter by rating" className={styles.distribution}>
          {counts.map(({ stars, count }) => (
            <li key={stars}>
              <button
                type="button"
                aria-pressed={filter === stars}
                aria-label={`${stars} stars, ${count} ${count === 1 ? 'review' : 'reviews'}`}
                disabled={count === 0}
                onClick={() => setFilter(filter === stars ? null : stars)}
                className={styles.bar}
              >
                <span className={styles.barLabel}>
                  {stars} <Star aria-hidden className={styles.barStar} />
                </span>
                <span className={styles.track}>
                  <span className={styles.fill} style={{ width: `${(count / reviews.length) * 100}%` }} />
                </span>
                <span className={styles.barCount}>{count}</span>
              </button>
            </li>
          ))}
        </ul>
      </div>

      <Stack direction="row" justify="space-between" align="end" gap="md" wrap="wrap">
        <Stack direction="row" gap="sm" align="center" wrap="wrap">
          <Text fontSize="sm" aria-live="polite">
            {filter === null
              ? `Showing all ${visible.length} reviews`
              : `Showing ${visible.length} ${filter}-star ${visible.length === 1 ? 'review' : 'reviews'}`}
          </Text>
          {filter !== null && (
            <Button type="button" variant="link" size="sm" onClick={() => setFilter(null)}>
              Clear filter
            </Button>
          )}
        </Stack>
        <Select items={sorts} value={sort} onValueChange={setSort}>
          <Stack direction="row" gap="sm" align="center">
            <Select.Label dangerouslySetClassName={styles.nowrap}>Sort by</Select.Label>
            <Select.Trigger size="sm" dangerouslySetClassName={styles.sort} />
          </Stack>
          <Select.Content>
            {sorts.map((option) => (
              <Select.Item key={option.value} value={option.value}>
                {option.label}
              </Select.Item>
            ))}
          </Select.Content>
        </Select>
      </Stack>

      <ol aria-label="Reviews" className={styles.reviews}>
        {visible.map((review) => (
          <li key={review.id}>
            <Stack as="article" gap="sm" aria-labelledby={`${headingId}-${review.id}`}>
              <Stack gap="xs">
                <Stars value={review.rating} />
                <Heading as="h3" id={`${headingId}-${review.id}`} fontSize="md">
                  {review.title}
                </Heading>
              </Stack>
              <Stack direction="row" gap="sm" align="center" wrap="wrap">
                <Text fontSize="sm" fontWeight="semibold">
                  {review.author}
                </Text>
                <Text fontSize="sm" color="text-muted">
                  <time dateTime={review.date}>{formatDate(review.date)}</time>
                </Text>
                {review.verified && (
                  <Badge tone="success">
                    <BadgeCheck aria-hidden />
                    Verified buyer
                  </Badge>
                )}
              </Stack>
              <Body margin="none">{review.body}</Body>
              <Stack direction="row" gap="sm" align="center">
                <BodySmall as="span" margin="none" color="text-muted">
                  Helpful?
                </BodySmall>
                <Button
                  type="button"
                  size="sm"
                  variant={voted.has(review.id) ? 'primary' : 'base'}
                  aria-pressed={voted.has(review.id)}
                  aria-label={`Helpful, ${review.helpful + (voted.has(review.id) ? 1 : 0)} votes`}
                  onClick={() => toggleHelpful(review.id)}
                >
                  <ThumbsUp aria-hidden className={styles.icon} />
                  {review.helpful + (voted.has(review.id) ? 1 : 0)}
                </Button>
              </Stack>
            </Stack>
          </li>
        ))}
      </ol>
    </Stack>
  )
}

function Stars({ value }: { value: number }) {
  return (
    <span role="img" aria-label={`${Number(value.toFixed(1))} out of 5 stars`} className={styles.stars}>
      {[1, 2, 3, 4, 5].map((star) => (
        <Star key={star} aria-hidden className={star <= Math.round(value) ? styles.starFilled : styles.star} />
      ))}
    </span>
  )
}

type ReviewErrors = Partial<Record<'rating' | 'body' | 'author', string>>

function WriteReview({ onSubmit, nextId }: { onSubmit: (review: Review) => void; nextId: string }) {
  const [open, setOpen] = useState(false)
  const [rating, setRating] = useState(0)
  const [errors, setErrors] = useState<ReviewErrors>({})
  const id = useId()

  function openChange(next: boolean) {
    setOpen(next)
    if (next) {
      setRating(0)
      setErrors({})
    }
  }

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const data = new FormData(event.currentTarget)
    const title = String(data.get('title')).trim()
    const body = String(data.get('body')).trim()
    const author = String(data.get('author')).trim()

    const next: ReviewErrors = {}
    if (rating === 0) next.rating = 'Choose a star rating.'
    if (body.length < 20) next.body = 'Write at least 20 characters about the jacket.'
    if (!author) next.author = 'Add the name to show with your review.'
    setErrors(next)
    if (Object.keys(next).length > 0) return

    onSubmit({
      id: nextId,
      rating,
      title: title || `${rating} stars`,
      body,
      author,
      date: new Date().toISOString().slice(0, 10),
      verified: false,
      helpful: 0,
    })
    setOpen(false)
  }

  return (
    <Modal open={open} onOpenChange={openChange}>
      <Modal.Trigger render={<Button type="button" dangerouslySetClassName={styles.write} />}>Write a review</Modal.Trigger>
      <Modal.Content>
        <Modal.Header>Review the Ridgeline insulated jacket</Modal.Header>
        <form onSubmit={submit} noValidate>
          <Stack gap="lg" padding="lg">
            <Stack gap="xs">
              <Text id={`${id}-rating`} fontSize="sm" fontWeight="semibold">
                Overall rating
              </Text>
              <RadioGroup
                aria-labelledby={`${id}-rating`}
                aria-describedby={errors.rating ? `${id}-rating-error` : undefined}
                value={rating || null}
                onValueChange={(value) => {
                  setRating(Number(value))
                  setErrors(({ rating: _cleared, ...rest }) => rest)
                }}
                dangerouslySetClassName={styles.starPicker}
              >
                {[1, 2, 3, 4, 5].map((star) => (
                  <Radio key={star} value={star} dangerouslySetClassName={styles.starInput}>
                    <Star aria-hidden className={star <= rating ? styles.pickFilled : styles.pick} />
                    <span className={styles.visuallyHidden}>
                      {star} {star === 1 ? 'star' : 'stars'}
                    </span>
                  </Radio>
                ))}
              </RadioGroup>
              {errors.rating && (
                <Text id={`${id}-rating-error`} fontSize="sm" color="danger-text">
                  {errors.rating}
                </Text>
              )}
            </Stack>
            <Field name="title">
              <Field.Label>Title (optional)</Field.Label>
              <Field.Control maxLength={80} placeholder="Sum it up in a few words" />
            </Field>
            <Field name="body" invalid={errors.body !== undefined}>
              <Field.Label>Your review</Field.Label>
              <Field.Control render={<Textarea rows={4} />} />
              {errors.body ? <Field.Error match>{errors.body}</Field.Error> : <Field.Description>How did it fit, and where did you wear it?</Field.Description>}
            </Field>
            <Field name="author" invalid={errors.author !== undefined}>
              <Field.Label>Display name</Field.Label>
              <Field.Control autoComplete="nickname" />
              {errors.author && <Field.Error match>{errors.author}</Field.Error>}
            </Field>
          </Stack>
          <Modal.Footer>
            <Modal.Close render={<Button type="button" variant="ghost" />}>Cancel</Modal.Close>
            <Button type="submit" variant="primary">
              Post review
            </Button>
          </Modal.Footer>
        </form>
      </Modal.Content>
    </Modal>
  )
}
```

## How it works

- The list of reviews is the only data. The average, the count and each bar are derived from it, so a posted review moves the summary too, and the list is filtered and sorted on every render.
- Each distribution bar is a toggle button with `aria-pressed` and a name like “4 stars, 2 reviews”; pressing the active bar again, or Clear filter, shows everything. A polite status line says what is showing. A star level with no reviews is disabled.
- Star ratings are an image with text (“4 out of 5 stars”), so they never rely on the icons. Helpful votes are toggle buttons with `aria-pressed` whose names include the count.
- In the modal, the rating is a `RadioGroup` drawn as stars: one tab stop, arrow keys to change it, and hidden text naming each option. Submitting checks the rating, the review’s length and the display name, shows `Field.Error`s where `Field` can link them, and on success closes the modal, sorts by newest and confirms with a toast.
- The review modal renders in a portal, outside the recipe’s container, so its CSS doesn’t depend on an ancestor class.

## App-owned CSS

`examples/recipes/product-reviews.module.css`:

```css
.root {
  container-type: inline-size;
}

/* Score on the left at its own width, distribution filling the rest. */
.summary {
  display: grid;
  gap: var(--ds-space-xl);
}

@container (min-width: 34rem) {
  .summary {
    grid-template-columns: max-content minmax(0, 1fr);
    align-items: center;
  }
}

.nowrap {
  white-space: nowrap;
}

.write {
  align-self: start;
  margin-top: var(--ds-space-md);
}

/* Stars */
.stars {
  display: inline-flex;
  gap: var(--ds-space-xxs);
}

.star,
.starFilled {
  width: var(--ds-icon-size-sm);
  height: var(--ds-icon-size-sm);
}

.star {
  color: var(--ds-color-border-strong);
}

.starFilled {
  color: var(--ds-color-warning);
  fill: currentColor;
}

/* Distribution bars, each a toggle button that filters the list. */
.distribution {
  display: grid;
  gap: var(--ds-space-xs);
  margin: 0;
  padding: 0;
  list-style: none;
}

.bar {
  display: grid;
  grid-template-columns: 2.5rem minmax(0, 1fr) 2rem;
  gap: var(--ds-space-md);
  align-items: center;
  width: 100%;
  padding: var(--ds-space-sm) var(--ds-space-md);
  font: inherit;
  font-size: var(--ds-font-size-sm);
  color: var(--ds-color-text);
  background: none;
  border: var(--ds-border-width-sm) solid transparent;
  border-radius: var(--ds-border-radius-md);
  cursor: pointer;

  &:hover:not(:disabled) {
    background-color: var(--ds-color-surface-hover);
  }

  &[aria-pressed="true"] {
    background-color: var(--ds-color-accent-subtle);
    border-color: var(--ds-color-accent);
  }

  &:disabled {
    color: var(--ds-color-text-muted);
    cursor: not-allowed;
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
    outline-offset: var(--ds-space-xxs);
  }
}

.barLabel {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-xs);
  font-weight: var(--ds-font-weight-medium);
}

.barStar {
  width: var(--ds-font-size-sm);
  height: var(--ds-font-size-sm);
  color: var(--ds-color-warning);
  fill: currentColor;
}

.track {
  height: var(--ds-space-md);
  overflow: hidden;
  background-color: var(--ds-color-surface);
  border-radius: var(--ds-border-radius-pill);
}

.fill {
  display: block;
  height: 100%;
  background-color: var(--ds-color-warning);
  border-radius: inherit;
}

.barCount {
  font-variant-numeric: tabular-nums;
  text-align: right;
  color: var(--ds-color-text-muted);
}

.sort {
  min-width: 10rem;
}

/* Reviews */
.reviews {
  margin: 0;
  padding: 0;
  list-style: none;
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);

  & > li {
    padding-block: var(--ds-space-lg);
    border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }
}

.icon {
  width: var(--ds-icon-size-sm);
  height: var(--ds-icon-size-sm);
}

/* The rating picker: a RadioGroup of stars with the radio dots hidden. */
/* Portaled with the modal, so it can't lean on .root for specificity. */
.starPicker[role="radiogroup"] {
  flex-direction: row;
  gap: var(--ds-space-xs);
}

.starPicker > label {
  position: relative;
  padding: var(--ds-space-xs);
  border-radius: var(--ds-border-radius-sm);

  &:has(:focus-visible) {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
  }
}

.pick,
.pickFilled {
  width: var(--ds-control-height-sm);
  height: var(--ds-control-height-sm);
}

.pick {
  color: var(--ds-color-border-strong);
}

.pickFilled {
  color: var(--ds-color-warning);
  fill: currentColor;
}

.visuallyHidden,
.starPicker .starInput {
  position: absolute;
  width: var(--ds-space-xxs);
  height: var(--ds-space-xxs);
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
```
