# Rating

> A row of native radios from 1 to `max`, with one label and one value, that previews the value under the pointer.

`<slab-rating>` · Form · built on `[role=radiogroup] + <input type=radio>s`

## Install

```sh
pnpm add slab-elements lit
```

## Usage

```html
<script type="module">
  import 'slab-elements/rating.js';
</script>

<slab-rating label="Rating" name="rating" value="3"></slab-rating>
```

## Example

Here's a styled version, `<slab-styled-rating>`. It's not in the package — it's an example of what you can build with the headless element. Copy it and make it yours at the bottom of this page.

```html
<slab-styled-rating label="Finish" step="0.5" value="3.5">
  <span slot="description">How smooth the slab came out of the trowel.</span>
</slab-styled-rating>
```

Swap `slab-styled-` for `slab-` in that markup and you've got the same example as it ships: the headless elements with no CSS at all. That's your starting point.

Nothing is drawn, so give each `::part(star)` a look, and `::part(filled)` the look of the value. The radios are named by their numbers and the group by `label`, so a screenreader reads "Rating, 3, radio button, 3 of 5". While the pointer is over a radio, the radios up to it are `filled` instead and the host is `:state(previewing)`, which can tell a preview apart from the value.

With `step="0.5"`, each star is two radios, named "0.5", "1", "1.5" and so on, and the value can be a half. A star's first radio is also `::part(start)` and its second `::part(end)`, so style each as half of a star, such as by clipping each to its half.

## Keyboard

| Key                   | What it does                                                       |
| --------------------- | ------------------------------------------------------------------ |
| Tab                   | Moves into the rating at the checked radio, or the first, and out. |
| Up, Down, Left, Right | Moves to the previous or next radio and checks it.                 |
| Space                 | Checks the focused radio.                                          |
| Enter                 | Submits the form, as on a native radio.                            |

## Behavior

A rating with no visual styles: a row of native radios, one for each point from 1 to `max`, with one label, one value, and one validity for all of them. With `step="0.5"`, there's one for each half point instead, two to a star.

The radios are the platform's, in the shadow root, so they're checked, moved between with the arrow keys, and read the way a native radio group is. Each is named by its number, and the group by `label`, so a screenreader reads "Label, 3, radio button, 3 of 5".

Each radio is a `star` part. Those up to the value are `filled` as well, and while one is hovered, those up to it are `filled` instead, so a pointer previews the value it would pick. The host is `:state(previewing)` while it does. Nothing is drawn, so a star, a heart, or a radio button is yours to decide. With half steps, each star's two radios are its `start` and `end` halves, so a half-filled star is a filled `start` beside an unfilled `end`.

Style it through its parts and through `:state(disabled)`, `:state(error)`, `:state(previewing)`, and `:state(required)`. How the radios are arranged is layout, so it's left to the styles around them.

## API

### `<slab-rating>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  |  |
| `disabled` | `boolean` | `false` |  |
| `hide-label` | `boolean` | `false` |  |
| `max` | `number` | `5` | How many stars there are. Anything but a whole number of 1 or more is 5. |
| `name` | `string` | `''` |  |
| `required` | `boolean` | `false` |  |
| `step` | `1 \| 0.5` | `1` | 1 for whole stars, or 0.5 for half stars. Anything else is 1. |
| `value` | `string` | `''` | The checked radio's number. Like a native input, the attribute is the default value and the property is the current one. A value that isn't one of the radios' numbers, from `step` to `max`, checks nothing and reads back as an empty string. |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `form` (read-only) | `HTMLFormElement \| null` |  |
| `validity` (read-only) | `ValidityState` |  |

#### Methods

| Signature | Description |
| --- | --- |
| `checkValidity(): boolean` |  |
| `focus(options?: FocusOptions): void` |  |
| `reportValidity(): boolean` |  |
| `resetValidityFeedback(): void` | Clears the validity feedback without changing `validity`. |
| `setCustomValidity(message: string): void` |  |
| `setValidity(flags?: ValidityStateFlags, message?: string): void` |  |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `input` | `Event` |  |
| `change` | `Event` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `description` | `Element \| string` |  |

#### CSS parts

| Name | Description |
| --- | --- |
| `description` | Text about the rating, and its validity message when it has one |
| `end` | With half steps, the radio for the second half of a star |
| `filled` | Each radio up to the value, or up to the hovered one |
| `label` | The label |
| `star` | Each radio |
| `stars` | The radios |
| `start` | With half steps, the radio for the first half of a star |
| `validity-message` |  |

## Copy and own it

`<slab-styled-rating>` isn't in the package. It's an example — copy it into your project and change whatever you want. Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. Keyboard, focus, ARIA, forms, and events all come from the headless element, and the styles only reach in through `::part()` and `:state()`, same as yours would.

To use it, copy these files, swap the tag in `@customElement()` for one of your own, and import it. `tokens.styles.ts` holds the colors and fonts every styled example shares, so you only need it once.

### TypeScript

These files are TypeScript, and `@customElement()` is one of Lit's decorators (TypeScript's experimental flavor). You'll need two options in your tsconfig, per [Lit's docs](https://lit.dev/docs/components/decorators/#decorators-typescript): `experimentalDecorators` to compile them, and `useDefineForClassFields` turned off so class fields don't stomp on the accessors Lit sets up.

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "useDefineForClassFields": false
  }
}
```

Using plain JavaScript? Drop the types and register the class with `customElements.define()` instead of the decorator.

### rating.ts

```ts
import { customElement } from 'lit/decorators.js';
import Rating from 'slab-elements/rating.js';
import styles from './rating.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-rating': StyledRating;
  }
}

/**
 * Rating, styled: a course of bricks, laid in ember up to the value. With half
 * steps, each brick is split in two.
 */
@customElement('slab-styled-rating')
export default class StyledRating extends Rating {
  static override styles = [tokens, styles];
}
```

### rating.styles.ts

```ts
import { css } from 'lit';

export default css`
  :host {
    color: var(--ink);
    display: grid;
    font-family: var(--font-body);
  }

  [part~='label'] {
    font-family: var(--font-display);
    font-size: 1.0625rem;
    font-weight: 600;
    margin-block-end: 0.5rem;
  }

  :host(:state(required)) [part~='label']::after {
    color: var(--ember-deep);
    content: ' *' / '';
  }

  [part~='stars'] {
    display: flex;
    gap: 0.375rem;
  }

  [part~='star'] {
    appearance: none;
    background-color: var(--paper);
    block-size: 1.5rem;
    border: var(--border);
    border-radius: 0;
    box-sizing: border-box;
    cursor: pointer;
    inline-size: 2.75rem;
    margin: 0;

    &:focus-visible {
      outline: 3px solid var(--ember);
      outline-offset: 3px;
    }

    &:disabled {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }

  /*
    Half steps split each brick in two, butted together across the gap,
    with a thin seam between the halves.
  */
  [part~='start'] {
    border-inline-end-width: 1px;
    inline-size: 1.375rem;
  }

  [part~='end'] {
    border-inline-start-width: 1px;
    inline-size: 1.375rem;
    margin-inline-start: -0.375rem;
  }

  [part~='filled'] {
    background-color: var(--ember);
  }

  /*
    A lighter course while previewing, so what's hovered reads as a
    preview rather than as the value.
  */
  :host(:state(previewing)) [part~='filled'] {
    background-color: color-mix(in srgb, var(--ember) 55%, var(--paper));
  }

  /*
    Spaced by what's in it rather than by a gap, so a description with
    nothing in it takes no room.
  */
  [part~='description'] {
    color: var(--ash);
    display: grid;
    font-size: 0.875rem;
  }

  ::slotted([slot='description']) {
    margin-block-start: 0.375rem;
  }

  [part~='validity-message'] {
    color: var(--ember-deep);
    font-weight: 600;
    margin-block-start: 0.375rem;

    &::before {
      content: '■ ' / '';
    }
  }
`;
```

### tokens.styles.ts

```ts
import { css } from 'lit';

/*
  The styled components' palette and type, taken from the logo: ink for the
  courses, ember for the base, paper behind them.

  Each is a short alias for a "--slab-styled-*" property, with the default as
  its fallback. Retheming is "--slab-styled-ember" and the rest on ":root",
  which every shadow root inherits. Were the defaults declared under those
  names here instead, each host's own declaration would shadow the page's.

  Each default is "light-dark()", so the components follow the page's
  "color-scheme": "dark" for dark, "light" for light, and "light dark" to
  follow the operating system. Ink and paper trade places in the dark, so
  ink is always the text and paper always what's behind it. Contrast is given
  as light, then dark.
*/
export default css`
  :host {
    /* Secondary text. 6.8:1 and 6.9:1 on paper. */
    --ash: var(--slab-styled-ash, light-dark(#5e5a55, #a8a19a));
    --border: 2px solid var(--ink);

    /* Behind disabled and read-only controls, and hovered rows. */
    --chalk: var(--slab-styled-chalk, light-dark(#f4f1ec, #2b2926));

    /*
      The logo's orange, brighter in the dark. 4.25:1 and 5.2:1 on paper is
      enough for borders, fills and large text, but not always for small text,
      which takes "--ember-deep".
    */
    --ember: var(--slab-styled-ember, light-dark(#d9492a, #ec5f3b));

    /*
      Orange for small text on paper, and for paper text on it. 5.7:1 and
      7.4:1.
    */
    --ember-deep: var(--slab-styled-ember-deep, light-dark(#b3381a, #ff8566));
    --font-body: var(
      --slab-styled-font-body,
      'IBM Plex Sans',
      system-ui,
      sans-serif
    );
    --font-display: var(
      --slab-styled-font-display,
      'Zilla Slab',
      rockwell,
      'Roboto Slab',
      serif
    );
    --font-mono: var(
      --slab-styled-font-mono,
      'IBM Plex Mono',
      ui-monospace,
      monospace
    );
    --ink: var(--slab-styled-ink, light-dark(#1c1c1c, #f4f1ec));
    --paper: var(--slab-styled-paper, light-dark(#fff, #1a1918));

    /* The hard, offset shadow a raised surface casts. */
    --shadow: 4px 4px 0 var(--ink);
  }
`;
```
