# Rating

A score out of a few stars, which can be set or only shown.

A score out of a few stars, optionally in halves. Hovering previews the score, a click sets it; it can also only show a score (readOnly). Stars are filled in ink over line-strong ones (md 24px cells with 20px stars, sm 18px with 14px: the switch's heights). It is a radio group: one tab stop, arrow keys change the score. Behaviour by Ark UI's rating-group (Zag). Controlled or uncontrolled.

Kind: component · Category: Inputs · Status: beta · Targets: React, Vue, Svelte · Behaviour: Zag `rating-group` machine, through Ark UI

## Add

```bash
npx fndn add rating
```

It writes the folder `rating/` into the project's ui folder (`index.ts`, `rating.tsx`, `Rating.vue`, `Rating.svelte`, `rating.recipe.ts`). First time: [Installation](/installation.md).

## Usage

```tsx
import { Rating } from "@/components/ui/rating";
```

```vue
import { Rating } from "@/components/ui/rating";
```

```svelte
import { Rating } from "$lib/components/ui/rating";
```

## Parts

In the DOM the root carries `data-slot="rating"` and each part `data-slot="rating-<part>"`; in the recipe the root is the `base` slot and each part a slot named after it in camelCase.

| Part | Element | data-slot | Flags | Notes |
| --- | --- | --- | --- | --- |
| `root` | `div` | `rating` |  | Ark's rating-group root: a column, the label above the stars. Half opacity and inert when disabled. |
| `label` | `label` | `rating-label` | optional | Visible name (the label prop): text.sm, medium, ink, as the Field's label; it names the group. |
| `control` | `div` | `rating-control` |  | role=radiogroup: the stars side by side, no gap of their own (the cell is larger than its star). |
| `item` | `span` | `rating-item` | repeats | One star, role=radio named "3 stars". Two Phosphor stars (fill) in one cell: the empty one in color.line-strong, the filled one in color.ink over it, shown when the engine highlights the item (data-highlighted: within the score, or within the hover preview) and cut to its inline-start half for a half star (data-half). md 24px / 20px star, sm 18px / 14px; radius.chip for the focus ring. On a coarse pointer the hit area is 40px high. |
| `hidden-input` | `input` | `rating-hidden-input` | optional | Ark's hidden input with the score, for a form (name). |

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number` | `0` | Bindable (React: `defaultValue` and `onValueChange`; Vue: `v-model:value`; Svelte: `bind:value`). The score: 0 for none, up to count; in halves with allowHalf. |
| `count` | `number` | `5` | Number of stars. |
| `allowHalf` | `boolean` | `false` | The first half of a star picks .5 (the inline-start half, mirrored right-to-left). |
| `size` | `"sm" \| "md"` | `"md"` | md: 24px cells, 20px stars. sm: 18px cells, 14px stars. |
| `label` | `string` |  | Visible label above the stars. |
| `readOnly` | `boolean` | `false` | Shows the score; it cannot change. The checked star stays focusable, so the score is announced. |
| `disabled` | `boolean` | `false` |  |
| `name` | `string` |  | Form field name. |

Other attributes and `class` go to the root; `class` is merged through the recipe.

## Events

| Event | Payload |
| --- | --- |
| `valueChange` | (value: number) after a click or a key |

## States

`hover`, `press`, `highlighted`, `half`, `focus-visible`, `readonly`, `disabled`

## Keyboard and accessibility

Role: radiogroup.

Keyboard:

- Tab moves to the checked star (one tab stop)
- Arrow Right / Arrow Up: one more (a half with allowHalf); Arrow Left / Arrow Down: one less (mirrored right-to-left)
- Home / End: the lowest / the highest score
- Space: sets the score to the focused star

Notes:

- Each star is role=radio with aria-roledescription "rating", named "<n> stars", aria-checked on the score's star.
- Name the group with label (visible) or aria-label.
- Read-only: the checked star stays in the tab order and the score is read; nothing changes it.
- To set it from outside, control `value`: React value / onValueChange.

## Motion

- fill (pointer only): opacity over duration.fast as the hover preview or the score changes; instant from the keyboard (kbd-instant)
- press (pointer only): the star gives to motion.press-scale-sm over duration.press with easing.out-strong; not when read-only

## Tokens

`color.ink`, `color.line-strong`, `radius.chip`, `text.sm`, `duration.fast`, `duration.press`, `easing.out-strong`, `motion.press-scale-sm`

## Examples

### Rate a support chat

React · `support-feedback.tsx`

```tsx
import { useState } from "react";
import { Rating } from "@/components/ui/rating";

/* asking for a score: the label is the question, a word under the stars says what the score means */
const WORDS = ["", "Did not help", "Slow to help", "Solved it eventually", "Quick and clear", "Excellent"];

export default function SupportFeedback() {
  const [score, setScore] = useState(4);
  return (
    <div className="flex flex-col gap-2">
      <Rating label="How was your chat with Aiko Tanaka?" value={score} onValueChange={setScore} />
      <p className="h-4 text-xs text-ink-2" aria-live="polite">{WORDS[score]}</p>
    </div>
  );
}
```

Vue · `support-feedback.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { Rating } from "@/components/ui/rating";

/* asking for a score: the label is the question, a word under the stars says what the score means */
const WORDS = ["", "Did not help", "Slow to help", "Solved it eventually", "Quick and clear", "Excellent"];

const score = ref(4);
</script>

<template>
  <div class="flex flex-col gap-2">
    <Rating v-model:value="score" label="How was your chat with Aiko Tanaka?" />
    <p class="h-4 text-xs text-ink-2" aria-live="polite">{{ WORDS[score] }}</p>
  </div>
</template>
```

Svelte · `support-feedback.svelte`

```svelte
<script lang="ts">
  import { Rating } from "$lib/components/ui/rating";

  /* asking for a score: the label is the question, a word under the stars says what the score means */
  const WORDS = ["", "Did not help", "Slow to help", "Solved it eventually", "Quick and clear", "Excellent"];

  let score = $state(4);
</script>

<div class="flex flex-col gap-2">
  <Rating bind:value={score} label="How was your chat with Aiko Tanaka?" />
  <p class="h-4 text-xs text-ink-2" aria-live="polite">{WORDS[score]}</p>
</div>
```

### Rate a template (half stars)

React · `rate-template.tsx`

```tsx
import { useState } from "react";
import { Rating } from "@/components/ui/rating";

/* half stars: the first half of a star picks .5 */
export default function RateTemplate() {
  const [score, setScore] = useState(3.5);
  return (
    <div className="flex flex-col gap-2">
      <Rating label="Rate the Status page template" allowHalf value={score} onValueChange={setScore} />
      <p className="text-xs text-ink-2 tabular-nums">{score.toFixed(1)} of 5</p>
    </div>
  );
}
```

Vue · `rate-template.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { Rating } from "@/components/ui/rating";

/* half stars: the first half of a star picks .5 */
const score = ref(3.5);
</script>

<template>
  <div class="flex flex-col gap-2">
    <Rating v-model:value="score" label="Rate the Status page template" allow-half />
    <p class="text-xs text-ink-2 tabular-nums">{{ score.toFixed(1) }} of 5</p>
  </div>
</template>
```

Svelte · `rate-template.svelte`

```svelte
<script lang="ts">
  import { Rating } from "$lib/components/ui/rating";

  /* half stars: the first half of a star picks .5 */
  let score = $state(3.5);
</script>

<div class="flex flex-col gap-2">
  <Rating bind:value={score} label="Rate the Status page template" allowHalf />
  <p class="text-xs text-ink-2 tabular-nums">{score.toFixed(1)} of 5</p>
</div>
```

### Average rating in a list (read-only)

React · `template-average.tsx`

```tsx
import { Rating } from "@/components/ui/rating";

/* read-only and small: an average shown in a list row, still announced as a score */
const templates = [
  { name: "Status page", score: 4.5, ratings: "1,284" },
  { name: "Internal docs site with search", score: 4, ratings: "312" },
];

export default function TemplateAverage() {
  return (
    <ul className="flex w-80 flex-col gap-3">
      {templates.map((t) => (
        <li key={t.name} className="flex flex-col gap-1">
          <span className="text-sm text-ink">{t.name}</span>
          <span className="flex items-center gap-2 text-xs text-ink-2">
            <Rating aria-label={`Average rating of ${t.name}`} size="sm" allowHalf readOnly value={t.score} />
            {t.score.toFixed(1)} · {t.ratings} ratings
          </span>
        </li>
      ))}
    </ul>
  );
}
```

Vue · `template-average.vue`

```vue
<script setup lang="ts">
import { Rating } from "@/components/ui/rating";

/* read-only and small: an average shown in a list row, still announced as a score */
const templates = [
  { name: "Status page", score: 4.5, ratings: "1,284" },
  { name: "Internal docs site with search", score: 4, ratings: "312" },
];
</script>

<template>
  <ul class="flex w-80 flex-col gap-3">
    <li v-for="t in templates" :key="t.name" class="flex flex-col gap-1">
      <span class="text-sm text-ink">{{ t.name }}</span>
      <span class="flex items-center gap-2 text-xs text-ink-2">
        <Rating :aria-label="`Average rating of ${t.name}`" size="sm" allow-half read-only :value="t.score" />
        {{ t.score.toFixed(1) }} · {{ t.ratings }} ratings
      </span>
    </li>
  </ul>
</template>
```

Svelte · `template-average.svelte`

```svelte
<script lang="ts">
  import { Rating } from "$lib/components/ui/rating";

  /* read-only and small: an average shown in a list row, still announced as a score */
  const templates = [
    { name: "Status page", score: 4.5, ratings: "1,284" },
    { name: "Internal docs site with search", score: 4, ratings: "312" },
  ];
</script>

<ul class="flex w-80 flex-col gap-3">
  {#each templates as t (t.name)}
    <li class="flex flex-col gap-1">
      <span class="text-sm text-ink">{t.name}</span>
      <span class="flex items-center gap-2 text-xs text-ink-2">
        <Rating aria-label={`Average rating of ${t.name}`} size="sm" allowHalf readOnly value={t.score} />
        {t.score.toFixed(1)} · {t.ratings} ratings
      </span>
    </li>
  {/each}
</ul>
```

## Recipe

`rating.recipe.ts`:

```ts
import { tv, type VariantProps } from "../lib/tv";

/* rating — pick a score out of a few stars (Ark UI rating-group).
 *   md (default)  24px cells · 20px stars      sm  18px cells · 14px stars
 * The cell heights are the switch's (md 24, sm 18). Each item holds two stars in one grid cell: the
 * empty one in line-strong and the filled one in ink over it, shown when the engine highlights
 * the item (the value, or the hover preview), clipped to its first half for a half star (the
 * inline start, so it mirrors right-to-left). The fill fades fast under a pointer and is instant
 * from the keyboard (kbd-instant). A press gives the star a little, as the switch's thumb does.
 *
 * Touch: on a coarse pointer each cell's hit area reaches above and below it to 40px; side by
 * side the cells stay as wide as they look. */
export const rating = tv({
  slots: {
    base: "flex flex-col gap-1.5 min-w-0",
    label: "text-sm font-medium text-ink [overflow-wrap:anywhere] [unicode-bidi:plaintext]",
    control: "inline-flex flex-wrap items-center self-start max-w-full",
    item: [
      "relative grid place-items-center rounded-chip text-line-strong cursor-pointer",
      "[&>svg]:[grid-area:1/1]",
      "[&>svg:nth-child(2)]:text-ink [&>svg:nth-child(2)]:opacity-0 [&>svg:nth-child(2)]:motion-opacity-fast [&>svg:nth-child(2)]:kbd-instant",
      "data-highlighted:[&>svg:nth-child(2)]:opacity-100",
      "data-half:ltr:[&>svg:nth-child(2)]:[clip-path:inset(0_50%_0_0)] data-half:rtl:[&>svg:nth-child(2)]:[clip-path:inset(0_0_0_50%)]",
      "motion-transform-press [:root:not([data-fndn-input=keyboard])_&:not([data-readonly])]:active:squeeze-press-sm",
      "data-disabled:cursor-default data-readonly:cursor-default",
      "pointer-coarse:after:content-[''] pointer-coarse:after:absolute pointer-coarse:after:inset-x-0",
    ],
  },
  variants: {
    size: {
      md: { item: "size-6 text-[20px] pointer-coarse:after:-inset-y-2" },
      sm: { item: "size-[18px] text-[14px] pointer-coarse:after:-inset-y-[11px]" },
    },
    disabled: {
      true: { base: "opacity-50 pointer-events-none" },
    },
  },
  defaultVariants: { size: "md", disabled: false },
});

export type RatingRecipeProps = VariantProps<typeof rating>;
```
