# Rating

> Star ratings from @salmonui/inputs/rating on native radios, with half precision, read-only quarter and exact display, clearing, labels, custom icons, a value bubble and RTL mirroring.

Canonical: https://salmonui.dev/docs/inputs/rating

`Rating` is a star rating input. Each step is a transparent native
radio over its item, named by `localeText.item` ("3 of 5 stars"), inside a
`<fieldset role="radiogroup">` named by `label`. Keyboard, focus, form
submission and screen reader output are the browser's radio group; the
stars are CSS.

```tsx
import { Rating } from '@salmonui/inputs/rating';
import '@salmonui/inputs/rating/styles.css';

<Rating name="service" label="Service" defaultValue={3} clearable showLabel />
<Rating label="Average" readOnly precision="exact" value={4.3} />
```

### Live demo: Rating basics

Live demo: https://salmonui.dev/demos/inputs/rating-basics

Interactive ratings with half precision, clearing, labels and a value bubble, plus a read-only exact average.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Rating } from '@salmonui/inputs/rating';

// Half precision with clearing, labels and the value bubble; a read-only exact average.
export default function RatingBasicsDemo() {
  const [value, setValue] = useState(3.5);
  const [hover, setHover] = useState<number | null>(null);
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Rating label="Your rating" precision="half" value={value} onValueChange={setValue} onHoverChange={setHover} clearable showLabel showTooltip />
      <output>{hover === null ? `Value: ${value}` : `Preview: ${hover}`}</output>
      <Rating label="Average of 1,284 reviews" readOnly precision="exact" value={4.32} showLabel renderLabel={({ value: v }) => v.toFixed(2)} />
      <Rating label="Favorites" icon="♥" emptyIcon="♡" count={3} defaultValue={2} size="lg" />
    </div>
  );
}
```

## Value

`value` / `defaultValue` / `onValueChange(value, details)` and `count`
(default 5). `details.reason` is `'select'`, `'clear'` or `'reset'`
(form reset), `details.source` `'pointer'`, `'touch'`, `'keyboard'` or
`'api'`. `min` (default 0) is the default value, the cleared value
and the lowest value a pick can set: choosing a lower step selects `min`.
Controlled with `value`, uncontrolled with `defaultValue` (restored by a
form reset).

## Precision

- `precision: 'full' | 'half'` while editing. Half precision
  renders two radios per item over half-width hit areas, so a click on the
  first half picks `n - 0.5` and arrow keys step by halves.
- `readOnly` with `precision: 'quarter' | 'exact'` renders one
  `role="img"` named "3.7 of 5 stars" with each item's fill clipped to the
  value. Interactive quarter or exact precision falls back to half
  with a development warning.

## Clearing, highlighting and labels

- `clearable` adds a clear button (named by `localeText.clear`, default
  "Clear rating") while the value is above `min`; clearing sets
  `min` and focuses the first radio.
- `highlightSelectedOnly` fills only the selected item.
- `showLabel` shows the value; `labelPlacement: 'top' | 'bottom' | 'start'
  | 'end'` (default `'end'`) places it and `renderLabel({ value, count })`
  formats it.

## Icons

`icon` and `emptyIcon` (`ReactNode`; default the ★ character, the empty
one in the border color) replace the glyphs; `renderItem({ index, state,
fill })` replaces both, with `state` `'full' | 'half' | 'empty'`.
The filled icon is clipped from the inline start, so the fill mirrors in
right-to-left content.

### Live demo: Rating icons and minimum

Live demo: https://salmonui.dev/demos/inputs/rating-custom

Rating with a minimum value, highlightSelectedOnly, custom icon and emptyIcon, and items drawn by renderItem from their index and state.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Rating } from '@salmonui/inputs/rating';

const FACES = ['😠', '🙁', '😐', '🙂', '😍'];

// A minimum value, highlighting only the selected item, custom full and
// empty icons, and items drawn by renderItem from their index and state.
export default function RatingCustomDemo() {
  const [stars, setStars] = useState(1);
  const [face, setFace] = useState(3);
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Rating label="Hotel stars" min={1} value={stars} onValueChange={setStars} showLabel description="min={1}: one star is the lowest value" />
      <output>Stars: {stars}</output>
      <Rating
        label="How was your stay?"
        highlightSelectedOnly
        value={face}
        onValueChange={setFace}
        renderItem={({ index, state }) => (
          <span aria-hidden="true" style={{ fontSize: '1.5em', filter: state === 'empty' ? 'grayscale(1)' : 'none', opacity: state === 'empty' ? 0.45 : 1 }}>
            {FACES[index - 1]}
          </span>
        )}
        description="highlightSelectedOnly with renderItem: only the chosen face is in color"
      />
      <output>Face: {face}</output>
      <Rating label="Spiciness" icon="🌶️" emptyIcon="·" defaultValue={2} count={4} description="icon and emptyIcon replace the star" />
    </div>
  );
}
```

## Hover and value bubble

The hover preview is pure CSS: no state, no re-render. `onHoverChange(value
| null)` reports the step under the pointer and `null` when it leaves;
pointer listeners exist only while the callback is bound.
`showTooltip` shows a small value bubble over the hovered or focused step,
`renderTooltip({ value, count })` formats it. The bubble is part of
the Rating stylesheet (the Layout Tooltip component is not required) and is
decorative: the radio's name already carries the value.

## Form submission

Give `name` to submit the value: the checked radio submits
`name=value` ("2.5" in half precision). Without `name` the radios carry
`form=""` and submit nothing. `required`, `form` and `disabled` are
forwarded.

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

## Keyboard

| Key | Action |
| --- | --- |
| Tab / Shift+Tab | Enters and leaves the rating (one tab stop) |
| Arrow Right / Arrow Up | Next step (in RTL, Arrow Left is next) |
| Arrow Left / Arrow Down | Previous step (in RTL, Arrow Right is previous) |
| Space | Selects the focused step |
| Enter or Space on the clear button | Clears to `min` |

`readOnly` keeps the radios focusable and ignores changes (`aria-readonly`).
Screen readers hear "3 of 5 stars, radio, 3 of 5" in the group named by
`label`. Try it in the [keyboard demo](https://salmonui.dev/demos/inputs/inputs-keyboard).

## SSR

The items and radios are markup and the fill is CSS, so the server output
is final; the radios work and submit before hydration.

## Design notes

- quarter and exact precision are display only: an interactive
  quarter or exact value has no usable keyboard model and no native
  control. Use `precision="half"` for input and `'exact'` for read-only
  averages.
- no visibility prop: React already renders conditionally. Use
  `{show && <Rating />}` or the `hidden` attribute.
- no reset method: resetting is a value change of the owner. Call
  `setValue(min)` on a controlled `value`; users clear with `clearable`.

## API

| Prop | Type | Default |
| --- | --- | --- |
| `value`, `defaultValue` | `number` | `min` |
| `onValueChange` | `(value, { source, reason }) => void` | |
| `count` | `number` | `5` |
| `min` | `number` | `0` |
| `precision` | `'full' \| 'half' \| 'quarter' \| 'exact'` | `'full'` |
| `readOnly`, `disabled`, `required` | `boolean` | `false` |
| `clearable`, `highlightSelectedOnly`, `showLabel`, `showTooltip` | `boolean` | `false` |
| `labelPlacement` | `'top' \| 'bottom' \| 'start' \| 'end'` | `'end'` |
| `renderLabel`, `renderTooltip` | `({ value, count }) => ReactNode` | |
| `icon`, `emptyIcon` | `ReactNode` | `'★'` |
| `renderItem` | `({ index, state, fill }) => ReactNode` | |
| `onHoverChange` | `(value \| null) => void` | |
| `name`, `form` | `string` | not submitted |
| `label`, `description`, `errorMessage`, `invalid` | see [Field](https://salmonui.dev/docs/inputs/field) | |
| `localeText` | `{ item, clear, validation* }` | `'{0} of {1} stars'`, `'Clear rating'` |
| `size` | `'sm' \| 'md' \| 'lg'` (item size 20, 24, 32 px) | `'md'` |
| `classNames` | `{ label, items, item, value, description, error }` | |
| `ref` | `HTMLElement` (the root) | |

Full signatures: [`@salmonui/inputs/rating` API reference](https://salmonui.dev/docs/reference/inputs/rating).
