Change a rule, add or remove a key, refuse a change, and build your own behavior on top of one.

Compose Behaviors built a rating from createChange and createRovingFocus. Each behavior came with rules of its own: roving focus decides which keys move focus, where each one goes, and which star Tab lands on. When your component needs something different, keep the behavior and change it in one of these places:

You Want ToWhere
Change one of its rulesAn option
Add a key, or take one awayYour api, around the call
Choose what happens after it runsWhat the call returns
Reuse your version in other componentsA function around the behavior
Change a behavior other than roving focusThe same places, by behavior
Stop a change from outsideThe change callback
Take a key from outside the componentYour own event handler

We'll keep working on that rating. Each step changes a few lines of rating.ts or the code that renders it.

Change a Rule

Each rule a behavior follows is an option. The rating wraps from the last star to the first because it passes loop. To stop at either end, change that option in createRovingFocus:

loop: () => false,

Most options are functions, so a rule can depend on state or on the component's own options. They run each time the behavior needs an answer.

Start here for any behavior: its options are listed with its guide, and All Behaviors links to each one. For roving focus, Focus and Keys covers orientation, loop, disabled, focusable, preferred and remember.

One option goes further. move replaces every built-in key, which fits a layout the built-in keys don't describe, such as a keypad. To add one key and keep the rest, wrap the call.

Add a Key

Roving focus doesn't listen for keys by itself. The star's keydown handler calls api.keydown, and that calls roving.keydown. The call is yours, so you can handle a key before the behavior sees it.

Let's make the number keys jump to a star. Update keydown in the object returned from api:

keydown(event: KeyboardEvent, el: HTMLElement) {
  const modified = event.ctrlKey || event.metaKey || event.altKey
  const star = modified
    ? undefined
    : roving.items().find((item) => item.key === event.key)
  if (star) {
    event.preventDefault()
    roving.focus(star.key)
    change("value", Number(star.key), {
      reason: "list-navigation",
      event,
    })
    return
  }

  const moved = roving.keydown(event, el)
  if (moved) {
    change("value", Number(moved.key), {
      reason: "list-navigation",
      event,
    })
  }
},
  • roving.items() returns the stars that can take focus. Each star's key is its value, so pressing 4 finds the fourth star.
  • roving.focus(key) moves focus to that star. The tab stop follows the new rating, as it did before.
  • Every other key still reaches roving.keydown, so the arrows, Home and End work as before.
import * as React from "react"
import { StarIcon } from "lucide-react"
import {
  createChange,
  createRovingFocus,
  definePrimitive,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
    focused: null as string | null,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus(context, {
      slot: "star",
      key: "focused",
      orientation: () => "both",
      loop: () => true,
      remember: false,
      preferred: (star) => Number(star.key) === context.store.get().value,
      claims: (state, star) =>
        state.value ? Number(star.key) === state.value : star.key === "1",
    })
    return {
      roving,
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
      keydown(event: KeyboardEvent, el: HTMLElement) {
        const modified = event.ctrlKey || event.metaKey || event.altKey
        const star = modified
          ? undefined
          : roving.items().find((item) => item.key === event.key)
        if (star) {
          event.preventDefault()
          roving.focus(star.key)
          change("value", Number(star.key), {
            reason: "list-navigation",
            event,
          })
          return
        }

        const moved = roving.keydown(event, el)
        if (moved) {
          change("value", Number(moved.key), {
            reason: "list-navigation",
            event,
          })
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
    star: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        role: "radio",
        "aria-checked": String(Number(part.key) === state.value),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-filled": Number(part.key) <= state.value ? "" : undefined,
      }),
      press: ({ api, key }, event) => api.rate(Number(key), event),
      on: {
        keydown: (event, { el, api }) => {
          if (el) {
            api.keydown(event, el)
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(rating, { root: "div", star: "button" })

const Rating = parts.Root

const RatingStar = parts.Star

function Example() {
  const [value, setValue] = React.useState(3)
  return (
    <div data-slot="stack">
      <div data-slot="rating-readout">
        <output
          data-slot="rating-value"
          data-value
          aria-label="Rating out of 5"
        >
          {value}
        </output>
        <span data-slot="hint">out of 5</span>
      </div>
      <Rating value={value} onValueChange={setValue} aria-label="Rating">
        {Array.from({ length: 5 }, (_, index) => (
          <RatingStar
            key={index}
            value={String(index + 1)}
            aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
          >
            <StarIcon aria-hidden="true" />
          </RatingStar>
        ))}
      </Rating>
    </div>
  )
}

export { Example, rating }
Focus a star and press 4. The arrows, Home and End still work.

Take a Key Away

To drop a key, return before the call. Add this at the top of keydown, and Home and End no longer change the rating:

if (event.key === "Home" || event.key === "End") {
  return
}

The behavior never sees the key, so the browser handles it as usual.

Choose What a Move Does

roving.keydown moves focus and tells you where it went. It returns key, the item it moved to, from, the item it left, and shift, whether Shift was held. For a key that isn't its own, it returns undefined.

What a move means is up to the component. The rating selects the star it lands on:

const moved = roving.keydown(event, el)
if (moved) {
  change("value", Number(moved.key), { reason: "list-navigation", event })
}

A row of buttons can ignore the result, so focus moves and nothing else changes. A file list uses shift to extend a selection, as Ranges and Select All shows.

Extend a Behavior

The number keys now live inside the rating. To use them in other components, move them into a function that wraps the behavior and returns it with your keydown in place of the original:

number-keys.ts
import {
  createRovingFocus,
  type PrimitiveContext,
  type RovingFocusOptions,
} from "@ui-sdk/core"

function createNumberKeys<State extends object>(
  context: PrimitiveContext<any, State, any>,
  options: RovingFocusOptions<State>
) {
  const roving = createRovingFocus(context, options)

  return {
    ...roving,
    keydown(event: KeyboardEvent, el: HTMLElement) {
      const modified = event.ctrlKey || event.metaKey || event.altKey
      const items = roving.items()
      const from = items.find((item) => item.el === el)
      const to = modified
        ? undefined
        : items.find((item) => item.key === event.key)
      if (from && to) {
        event.preventDefault()
        roving.focus(to.key)
        return { key: to.key, from: from.key, shift: event.shiftKey }
      }

      return roving.keydown(event, el)
    },
  }
}

export { createNumberKeys }
  • It takes the same context and options as createRovingFocus, so each component still passes its own rules.
  • ...roving keeps bind, tabIndex, items and the rest.
  • Its keydown returns the same result as the original, so a component treats a number key like any other move.

In rating.ts, call createNumberKeys in place of createRovingFocus and leave its options as they are. keydown goes back to what it was in Compose Behaviors:

keydown(event: KeyboardEvent, el: HTMLElement) {
  const moved = roving.keydown(event, el)
  if (moved) {
    change("value", Number(moved.key), { reason: "list-navigation", event })
  }
},

Any group whose keys are numbers can use it now. A row of page buttons passes its own slot and orientation, and gets the number keys with them.

Your keydown runs wherever your component calls it. You can replace focus or tabIndex the same way. Inside, the behavior keeps using its own methods: when focus lands on an item, it calls the original remember. To change what it does by itself, use its options.

Other Behaviors

The other behaviors change in the same places. Their rules are options too. Where roving focus returns each move from keydown, a behavior that changes a value hands you the value to write, through set.

A selection writes each new value through set, so a limit goes there. This one allows three toppings:

const selection = createSelection(context, {
  key: "value",
  set: (value, details) => value.length <= 3 && change("value", value, details),
  order: () => roving.items().map((item) => item.key),
  multiple: () => true,
})

set returns whether the value went through. Returning false leaves the selection as it was.

Here's where to look in the behaviors you'll use most. Each name links to its guide:

BehaviorRules You Can ChangeWhat It Hands You
createRovingFocusorientation, loop, disabled, focusable, moveEach move, returned from keydown
createGridFocusdisabled, pageSizeEach move, in onMove
createSelectionmultiple, selectableEach selection, in set
createListboxfilter, loopEach highlight, in onHighlight
createReorderorientation, group, disabledEach order, in set, and each announcement, in message
createTransferaccepts, order, disabledEach move between lists, in set, and each announcement, in message
createMovebounds, step, disabledEach position, in set, and each announcement, in message
createResizemin, max, aspect, boundsEach size, in set, and each announcement, in message
createPopupA preset, and roleEach open and close, in onOpenChange

A message can reword one announcement and keep the others, since each default is exported: reorderMessage, transferMessage, moveMessage and resizeMessage. What's Read Out shows one.

Refuse a Change

The next two steps need no changes to rating.ts. They're for whoever renders the rating.

Every change the rating makes goes through change, which calls onValueChange before it writes the value. The callback can refuse. Here a review form keeps the value as it is while it saves:

<Rating
  aria-label="Rating"
  onValueChange={(value, details) => {
    if (saving) {
      details.cancel()
    }
  }}
>
  {children}
</Rating>

It refuses a press, an arrow key and a number key alike, since they all ask through change. To refuse only some of them, check details.reason: the rating reports item-press and list-navigation. What a Change Reports lists everything a callback gets.

Focus still follows the keys while a change is refused. Only the value stays.

cancel() refuses a change the rating would write itself. If you pass value, you decide instead: keep the old value and the rating stays where it is.

Handle an Event First

An event handler you pass to a part runs before the part's own. Call event.preventDefault() and the part skips its handler for that event.

Say the rating sits in a table row, where Up and Down move between rows. Take those two keys and leave the others to the rating:

<RatingStar
  value="3"
  onKeyDown={(event) => {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      event.preventDefault()
      moveRow(event.key)
    }
  }}
/>

Left, Right, Home, End and the number keys still belong to the rating. preventDefault() also stops what the browser would do with the key, such as scrolling the page.

Both work the same way on the ready-made components, since they're built from the same pieces. Tabs takes onValueChange with details.cancel(), and a key handler on its list runs before the arrow keys do. With web components, listen in the capture phase there too.

Replace One Behavior

Behaviors don't know about each other. The rating's createChange and createRovingFocus meet only in your api. So when a component needs focus rules of its own, you can write that one piece yourself and keep the rest: changes, callbacks and controlled state stay as they are.

Keep Building

  • Focus and Keys has every roving focus option, with a demo for each.
  • Handle Changes goes further into callbacks, reasons and controlled state.
  • Testing checks that the keyboard still matches the pattern after you change it.