# Animated Preferences for UI SDK (/docs/components/preferences)

Puts people's choices on data attributes for your CSS, with a switcher whose key stretches to the value and the four motion styles ready-made.

<ComponentPreview slug="preferences" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport { createPreference } from \&#x22;@ui-sdk/core\&#x22;\n\nimport { createMotionStyle, MotionStyleSwitcher, Preferences, PreferenceSwitcher } from \&#x22;@/components/keyframery/preferences\&#x22;\n\n/* Scoped and not saved in the lab, so the rest of the page keeps its own settings. In an app, add\n   `storage: createLocalStorage(\&#x22;density\&#x22;)` to remember the choice, and `global: true` to put the\n   attribute on <html>. */\nconst density = createPreference({\n  values: [\&#x22;comfortable\&#x22;, \&#x22;compact\&#x22;],\n  defaultValue: \&#x22;comfortable\&#x22;,\n  attribute: \&#x22;data-density\&#x22;,\n})\nconst demoMotion = createMotionStyle({ global: false, storageKey: null })\n\nconst pick = (label: string, n: number) => `[aria-label=\&#x22;${label}\&#x22;] [data-slot=\&#x22;segmented-control-item\&#x22;]:nth-of-type(${n})`\n\nconst walks = [\n  { name: \&#x22;Seven Sisters cliff path\&#x22;, route: \&#x22;Seaford to Eastbourne\&#x22;, km: 22, photo: \&#x22;/demo/coast-1.jpg\&#x22; },\n  { name: \&#x22;Regent's Canal towpath\&#x22;, route: \&#x22;Little Venice to Limehouse\&#x22;, km: 14, photo: \&#x22;/demo/canal.jpg\&#x22; },\n  { name: \&#x22;Derwentwater loop\&#x22;, route: \&#x22;From Keswick\&#x22;, km: 16, photo: \&#x22;/demo/lake.jpg\&#x22; },\n  { name: \&#x22;Durdle Door and back\&#x22;, route: \&#x22;From Lulworth Cove\&#x22;, km: 5, photo: \&#x22;/demo/coast-3.jpg\&#x22; },\n]\n\n/* Everything a preference changes eases to its new value on the house spring, at the page's speed. */\nconst eased = \&#x22;duration-[calc(420ms*var(--kf-speed,1))] ease-spring motion-reduce:transition-none\&#x22;\n\nexport default function PreferencesDemo({\n  orientation = \&#x22;horizontal\&#x22;,\n  disabled = false,\n  readOnly = false,\n  required = false,\n  loop = true,\n  initialDensity = \&#x22;comfortable\&#x22;,\n  title = \&#x22;Saved walks\&#x22;,\n  comfortable = \&#x22;Comfortable\&#x22;,\n  compact = \&#x22;Compact\&#x22;,\n  footer = \&#x22;Motion\&#x22;,\n  items = 4,\n  width = 400,\n  padding = 20,\n  gap = 2,\n  height = 32,\n  radius = 12,\n  track = \&#x22;\&#x22;,\n  keyColour = \&#x22;\&#x22;,\n  ink = \&#x22;\&#x22;,\n  selectedInk = \&#x22;\&#x22;,\n}: {\n  orientation?: \&#x22;horizontal\&#x22; | \&#x22;vertical\&#x22;\n  disabled?: boolean\n  readOnly?: boolean\n  required?: boolean\n  loop?: boolean\n  initialDensity?: \&#x22;comfortable\&#x22; | \&#x22;compact\&#x22;\n  title?: string\n  comfortable?: string\n  compact?: string\n  footer?: string\n  items?: number\n  width?: number\n  padding?: number\n  gap?: number\n  height?: number\n  radius?: number\n  track?: string\n  keyColour?: string\n  ink?: string\n  selectedInk?: string\n}) {\n  const theme = {\n    \&#x22;--preferences-height\&#x22;: `${height}px`,\n    \&#x22;--preferences-radius\&#x22;: `${radius}px`,\n    \&#x22;--preferences-key-radius\&#x22;: `${radius * 0.75}px`,\n    \&#x22;--preferences-gap\&#x22;: `${gap}px`,\n    ...(selectedInk ? { \&#x22;--preferences-selected-ink\&#x22;: selectedInk } : {}),\n    ...(track ? { \&#x22;--preferences-track\&#x22;: track } : {}),\n    ...(keyColour ? { \&#x22;--preferences-key\&#x22;: keyColour } : {}),\n    ...(ink ? { \&#x22;--preferences-ink\&#x22;: ink } : {}),\n  } as React.CSSProperties\n  React.useEffect(() => { density.set(initialDensity) }, [initialDensity])\n  return (\n    <Preferences preferences={[density, demoMotion]}>\n      <div style={{ ...theme, maxWidth: width, padding }} className=\&#x22;@container w-full max-w-[400px] rounded-[18px] bg-background p-5 shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)] dark:bg-card dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]\&#x22;>\n        <div className=\&#x22;flex items-center justify-between gap-3\&#x22;>\n          <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>{title}</div>\n          <PreferenceSwitcher preference={density} labels={{ comfortable, compact }} aria-label=\&#x22;Density\&#x22; orientation={orientation} disabled={disabled} readOnly={readOnly} required={required} loop={loop} />\n        </div>\n\n        <ul className={`mt-4 flex flex-col gap-2.5 transition-[gap] in-data-[density=compact]:gap-0.5 ${eased}`}>\n          {walks.slice(0, items).map((walk) => (\n            <li key={walk.name} className={`flex items-center gap-3 transition-[gap] in-data-[density=compact]:gap-2 ${eased}`}>\n              <img\n                src={walk.photo}\n                alt=\&#x22;\&#x22;\n                className={`size-11 shrink-0 rounded-[10px] bg-muted object-cover transition-[width,height,border-radius] in-data-[density=compact]:size-6 in-data-[density=compact]:rounded-[6px] ${eased}`}\n              />\n              <div className=\&#x22;min-w-0 flex-1\&#x22;>\n                <div className=\&#x22;truncate text-[13.5px] font-medium\&#x22;>{walk.name}</div>\n                {/* The second line folds away when the list is compact. */}\n                <div className={`grid grid-rows-[1fr] transition-[grid-template-rows,opacity] in-data-[density=compact]:grid-rows-[0fr] in-data-[density=compact]:opacity-0 ${eased}`}>\n                  <div className=\&#x22;min-h-0 overflow-hidden truncate text-[12px] text-muted-foreground\&#x22;>{walk.route}</div>\n                </div>\n              </div>\n              <div className=\&#x22;shrink-0 text-[12px] text-muted-foreground tabular-nums\&#x22;>{walk.km} km</div>\n            </li>\n          ))}\n        </ul>\n\n        <div className=\&#x22;mt-5 flex items-center justify-between gap-3 border-t border-border pt-4 @max-[22rem]:flex-col @max-[22rem]:items-start\&#x22;>\n          <div className=\&#x22;text-[12px] text-muted-foreground\&#x22;>{footer}</div>\n          <MotionStyleSwitcher preference={demoMotion} orientation={orientation} disabled={disabled} readOnly={readOnly} required={required} loop={loop} />\n        </div>\n      </div>\n    </Preferences>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;orientation&#x22;:[1468,1480],&#x22;disabled&#x22;:[1495,1500],&#x22;readOnly&#x22;:[1515,1520],&#x22;required&#x22;:[1535,1540],&#x22;loop&#x22;:[1551,1555],&#x22;initialDensity&#x22;:[1576,1589],&#x22;title&#x22;:[1601,1614],&#x22;comfortable&#x22;:[1632,1645],&#x22;compact&#x22;:[1659,1668],&#x22;footer&#x22;:[1681,1689],&#x22;items&#x22;:[1701,1702],&#x22;width&#x22;:[1714,1717],&#x22;padding&#x22;:[1731,1733],&#x22;gap&#x22;:[1743,1744],&#x22;height&#x22;:[1757,1759],&#x22;radius&#x22;:[1772,1774],&#x22;track&#x22;:[1786,1788],&#x22;keyColour&#x22;:[1804,1806],&#x22;ink&#x22;:[1816,1818],&#x22;selectedInk&#x22;:[1836,1838]},&#x22;root&#x22;:[2823,5269],&#x22;importOffset&#x22;:220}" />

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add @keyframery/preferences
```

This adds `components/keyframery/preferences.tsx` and its primitive to your project, and installs UI SDK, along with [segmented-control](/docs/components/segmented-control), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.9 @ui-sdk/react@0.1.0-beta.9 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"springy"` (the default), `"calm"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [segmented-control](/docs/components/segmented-control) the same way first.

**Copy the component**

**components/keyframery/preferences.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/preferences"

/* Theming (inherited; each default preserves the original light/dark appearance):
   --preferences-track: Switcher well (default: --muted)
   --preferences-key: Selected key (default: --background, --accent in dark)
   --preferences-ink: Unselected text (default: --muted-foreground)
   --preferences-selected-ink: Selected text (default: --foreground)
   --preferences-height: Option height (default: 2rem)
   --preferences-radius: Well corners (default: 12px)
   --preferences-key-radius: Option corners (default: 9px)
   --preferences-gap: Option gap (default: 0.125rem)
*/

/* Styled preferences: UI SDK's Preferences and usePreference, a switcher for any preference, and
   the motion style switcher built from it. */

import type { Preference } from "@ui-sdk/core"
import * as React from "react"

import {
  MotionStyle,
  motionStyle,
  type MotionStylePreference,
  type MotionStyleValue,
  Preferences,
  usePreference,
} from "@/components/keyframery/primitives/preferences"
import { cn } from "@/lib/utils"
import { SegmentedControl, SegmentedControlItem } from "@/components/keyframery/segmented-control"

const words = (value: string) => value.replace(/[-_]+/g, " ").replace(/^./, (first) => first.toUpperCase())

/* A segmented control that shows a preference and sets it, one item per value. Its key stretches
   to the value you pick. A global preference is applied to <html> by the switcher itself; for a
   scoped one, wrap the content it styles in `Preferences`. */
function PreferenceSwitcher<Value extends string>({
  preference,
  labels,
  className,
  style,
  ...props
}: Omit<React.ComponentProps<typeof SegmentedControl>, "value" | "defaultValue" | "onValueChange" | "children"> & {
  /** The preference to show and set, from `createPreference`. */
  preference: Preference<Value>
  /** What each value is called. A value without a label is shown as written, capitalised. */
  labels?: Partial<Record<Value, React.ReactNode>>
}) {
  const { value } = usePreference(preference)
  const theme = {
    "--segmented-control-track": "var(--preferences-track,var(--muted))",
    "--segmented-control-key": "var(--preferences-key,var(--kf-preferences-key))",
    "--segmented-control-ink": "var(--preferences-ink,var(--muted-foreground))",
    "--segmented-control-selected-ink": "var(--preferences-selected-ink,var(--foreground))",
    "--segmented-control-height": "var(--preferences-height,2rem)",
    "--segmented-control-radius": "var(--preferences-radius,12px)",
    "--segmented-control-key-radius": "var(--preferences-key-radius,9px)",
    "--segmented-control-gap": "var(--preferences-gap,0.125rem)",
  } as React.CSSProperties
  const appearance = "[--kf-preferences-key:var(--background)] dark:[--kf-preferences-key:var(--accent)]"
  const control = (
    <SegmentedControl
      value={value}
      onValueChange={(next, details) => {
        if (next) preference.set(next as Value, { reason: "press", event: details.event })
      }}
      {...props}
      className={typeof className === "function" ? (state) => cn(appearance, className(state)) : cn(appearance, className)}
      style={typeof style === "function" ? (state) => ({ ...theme, ...style(state) }) : { ...theme, ...style }}
    >
      {preference.values.map((option) => (
        <SegmentedControlItem key={option} value={option}>
          {labels?.[option] ?? words(option)}
        </SegmentedControlItem>
      ))}
    </SegmentedControl>
  )
  return preference.global ? <Preferences preferences={[preference]}>{control}</Preferences> : control
}

const motionLabels: Record<MotionStyleValue, string> = {
  calm: "Calm",
  springy: "Springy",
  snappy: "Snappy",
  playful: "Playful",
}

/* The motion style switcher: Calm, Springy, Snappy or Playful for every Keyframery component.
   Dropping it anywhere applies the choice to <html> and remembers it. */
function MotionStyleSwitcher({
  preference = motionStyle,
  "aria-label": ariaLabel = "Motion style",
  ...props
}: Omit<React.ComponentProps<typeof PreferenceSwitcher<MotionStyleValue>>, "preference" | "labels"> & {
  /** The motion style preference to show and set. Defaults to the global `motionStyle`. */
  preference?: MotionStylePreference
}) {
  return <PreferenceSwitcher preference={preference} labels={motionLabels} aria-label={ariaLabel} {...props} />
}

export {
  createMotionStyle,
  MotionStyle,
  motionStyle,
  type MotionStylePreference,
  motionStyles,
  type MotionStyleValue,
  Preferences,
  type PreferencesProps,
  usePreference,
} from "@/components/keyframery/primitives/preferences"
export { MotionStyleSwitcher, PreferenceSwitcher }
```

**components/keyframery/primitives/preferences.tsx**

```tsx
"use client"

/* Drop-in for `@ui-sdk/react/preferences`, plus Keyframery's own preference: the motion style.

   `Preferences` and `usePreference` pass through untouched. A preference only puts a value on a
   `data-*` attribute; what moves is whatever your CSS styles by it.

   The motion style is the preference every Keyframery component already follows. Each duration is
   written as calc(Nms * var(--kf-speed, 1)) and each easing reads --ease-house, --ease-spring or
   --ease-pop, so one `data-motion` attribute changes how the whole set moves: calm (slower, no
   bounce), springy (the default), snappy (fast, crisp) and playful (more spring).

   `motionStyle` is global (on <html>, so popups at the end of <body> follow it too) and saved in
   localStorage. Mount `MotionStyle` once to apply it. `createMotionStyle({ global: false })` makes a
   scoped one: its attribute goes on the MotionStyle element (display: contents) and only the
   content inside follows it. */

import { createLocalStorage, createPreference } from "@ui-sdk/core"
import { Preferences } from "@ui-sdk/react/preferences"
import * as React from "react"

export * from "@ui-sdk/react/preferences"

const motionStyles = ["calm", "springy", "snappy", "playful"] as const

type MotionStyleValue = (typeof motionStyles)[number]

function createMotionStyle({
  global = true,
  storageKey = "kf-motion-style",
}: {
  /** Put the attribute on <html> (default) or only on the MotionStyle element. */
  global?: boolean
  /** The localStorage key; null keeps the choice for this visit only. */
  storageKey?: string | null
} = {}) {
  return createPreference({
    values: motionStyles,
    defaultValue: "springy",
    attribute: "data-motion",
    global,
    storage: storageKey ? createLocalStorage(storageKey) : undefined,
  })
}

type MotionStylePreference = ReturnType<typeof createMotionStyle>

const motionStyle = createMotionStyle()

/* The springy reset (a springy area inside a calm page) lives in the motion tokens, with the other styles. */
function MotionStyle({
  preference = motionStyle,
  ...props
}: Omit<React.ComponentProps<typeof Preferences>, "preferences"> & { preference?: MotionStylePreference }) {
  return (
    <Preferences preferences={[preference]} {...props} />
  )
}

export { createMotionStyle, MotionStyle, motionStyle, type MotionStylePreference, motionStyles, type MotionStyleValue }
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

## Usage [#usage]

```tsx
import { createLocalStorage, createPreference } from "@ui-sdk/core"

import { Preferences, PreferenceSwitcher } from "@/components/keyframery/preferences"

const view = createPreference({
  values: ["list", "grid"],
  defaultValue: "list",
  attribute: "data-view",
  storage: createLocalStorage("files-view"),
})

export default function Usage() {
  return (
    <Preferences preferences={[view]}>
      <PreferenceSwitcher preference={view} aria-label="View" />
      <ul className="grid gap-2 in-data-[view=grid]:grid-cols-2">
        <li>Q3 roadmap.pdf</li>
        <li>Launch checklist.md</li>
      </ul>
    </Preferences>
  )
}
```

## Examples [#examples]

### A saved choice [#a-saved-choice]

The text size goes on a `data-size` attribute and the paragraph styles by it. Storage keeps the choice, so it is still there after a reload.

<ExamplePreview name="preferences/saved-choice">
  ```tsx
  import { createLocalStorage, createPreference } from "@ui-sdk/core"

  import { Preferences, PreferenceSwitcher } from "@/components/keyframery/preferences"

  const size = createPreference({
    values: ["small", "medium", "large"],
    defaultValue: "medium",
    attribute: "data-size",
    storage: createLocalStorage("kf-example-text-size"),
  })

  export default function PreferencesSavedChoice() {
    return (
      <Preferences preferences={[size]}>
        <div className="flex w-full max-w-[340px] flex-col items-center gap-4">
          <PreferenceSwitcher preference={size} aria-label="Text size" />
          <p className="text-center text-[14px] leading-[1.5] transition-[font-size] duration-[calc(380ms*var(--kf-speed,1))] ease-spring in-data-[size=large]:text-[17px] in-data-[size=small]:text-[12px] motion-reduce:transition-none">
            The path climbs out of Seaford and follows the cliff edge all the way to Birling Gap.
          </p>
        </div>
      </Preferences>
    )
  }
  ```
</ExamplePreview>

### Read the value [#read-the-value]

`usePreference` gives a component the current value, so it can render differently, not only restyle.

<ExamplePreview name="preferences/read-the-value">
  ```tsx
  import { createPreference } from "@ui-sdk/core"

  import { Preferences, PreferenceSwitcher, usePreference } from "@/components/keyframery/preferences"

  const units = createPreference({
    values: ["km", "miles"],
    defaultValue: "km",
    attribute: "data-units",
  })

  const walks = [
    { name: "Seven Sisters cliff path", km: 22 },
    { name: "Derwentwater loop", km: 16 },
  ]

  function Distance({ km }: { km: number }) {
    const { value } = usePreference(units)
    return <span className="text-muted-foreground tabular-nums">{value === "km" ? `${km} km` : `${(km * 0.621).toFixed(1)} mi`}</span>
  }

  export default function PreferencesReadTheValue() {
    return (
      <Preferences preferences={[units]}>
        <div className="flex w-full max-w-[300px] flex-col gap-3 text-[13.5px]">
          <PreferenceSwitcher preference={units} labels={{ km: "Kilometres", miles: "Miles" }} aria-label="Units" />
          {walks.map((walk) => (
            <div key={walk.name} className="flex items-center justify-between gap-3">
              <span>{walk.name}</span>
              <Distance km={walk.km} />
            </div>
          ))}
        </div>
      </Preferences>
    )
  }
  ```
</ExamplePreview>

### Motion style [#motion-style]

Keyframery's own preference. The switcher sets the motion style for the whole page and remembers it, and every Keyframery component follows.

<ExamplePreview name="preferences/motion-style">
  ```tsx
  import { MotionStyleSwitcher } from "@/components/keyframery/preferences"

  export default function PreferencesMotionStyle() {
    return <MotionStyleSwitcher />
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                              |
| ----------- | ------------------------------------------------------------------------------------------------------------------------- |
| **Stretch** | A preference switcher's key stretches to the value you pick, as the motion style switcher's does between the four styles. |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this preferences moves, pass `speed`:

```tsx
<PreferenceSwitcher preference={view} speed="fast" />
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                     | What it changes | Default                        |
| ---------------------------- | --------------- | ------------------------------ |
| `--preferences-track`        | Switcher well   | --muted                        |
| `--preferences-key`          | Selected key    | --background, --accent in dark |
| `--preferences-ink`          | Unselected text | --muted-foreground             |
| `--preferences-selected-ink` | Selected text   | --foreground                   |
| `--preferences-height`       | Option height   | 2rem                           |
| `--preferences-radius`       | Well corners    | 12px                           |
| `--preferences-key-radius`   | Option corners  | 9px                            |
| `--preferences-gap`          | Option gap      | 0.125rem                       |

## API reference [#api-reference]

Every part takes `className` and `children`. Parts from UI SDK also take `render`, to draw your own element, and a function of their state for `className` and `style`. Props not listed here are in the [UI SDK preferences reference](https://ui-sdk.dev/docs/components/preferences).

### PreferenceSwitcher [#preferenceswitcher]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;preference&#x22;,&#x22;type&#x22;:&#x22;Preference<Value>&#x22;,&#x22;full&#x22;:&#x22;Preference<Value>&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Preference instance to read and update.&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;labels&#x22;,&#x22;type&#x22;:&#x22;Partial<Record<Value, React.ReactNode>>&#x22;,&#x22;full&#x22;:&#x22;Partial<Record<Value, React.ReactNode>>&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Optional visible labels by preference value.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;form&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The id of a form to belong to, when the segmented control isn't inside that form.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;name&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The name the value submits under. Without one, the segmented control submits nothing.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;orientation&#x22;,&#x22;type&#x22;:&#x22;\&#x22;horizontal\&#x22; | \&#x22;vertical\&#x22;&#x22;,&#x22;full&#x22;:&#x22;SegmentedControlOrientation&#x22;,&#x22;default&#x22;:&#x22;\&#x22;horizontal\&#x22;&#x22;,&#x22;description&#x22;:&#x22;Horizontal or vertical arrangement.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;disabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Disables switching.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;loop&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;true&#x22;,&#x22;description&#x22;:&#x22;Wraps keyboard navigation between options.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;readOnly&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Keeps focus available while preventing changes.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;required&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Requires a selected value when used in a form.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;controller&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ getValue: () => string | null; setValue: (value: string | null, details?: SegmentedControlChangeOptions) => boolean; focus: () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Checks items from anywhere. Create one with `createSegmentedControlController()`.&#x22;,&#x22;required&#x22;:false}]" />

### MotionStyle [#motionstyle]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;preference&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ attribute: `data-${string}`; global: boolean; values: readonly (\&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;)[]; defaultValue: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; storage: { id: string; kind: \&#x22;local\&#x22; | \&#x22;session\&#x22; | \&#x22;cookie\&#x22;; readsOnServer: boolean; script: (options: StorageScriptOptions) => string; available: () => boolean; get: () => string | null; set: (value: string) => boolean; remove: () => boolean; subscribe(listener: (value: string | null) => void): () => void; }; initialState: { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }; get: () => { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }; set: (next: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;, change?: { reason?: ChangeReason; event?: Event; }) => boolean; subscribe: (listener: (state: { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }) => void) => () => void; follow: <Key extends string>(store: PreferenceStore<Key, { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }>, key: Key) => () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The preference to read and set. Defaults to the shared motion style, saved for the whole site.&#x22;,&#x22;required&#x22;:false}]" />

### Preferences [#preferences]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;preferences&#x22;,&#x22;type&#x22;:&#x22;readonly PreferenceLike[]&#x22;,&#x22;full&#x22;:&#x22;readonly PreferenceLike[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Preference instances whose data attributes should apply to the subtree or page.&#x22;,&#x22;required&#x22;:true}]" />

### MotionStyleSwitcher [#motionstyleswitcher]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;preference&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ attribute: `data-${string}`; global: boolean; values: readonly (\&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;)[]; defaultValue: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; storage: { id: string; kind: \&#x22;local\&#x22; | \&#x22;session\&#x22; | \&#x22;cookie\&#x22;; readsOnServer: boolean; script: (options: StorageScriptOptions) => string; available: () => boolean; get: () => string | null; set: (value: string) => boolean; remove: () => boolean; subscribe(listener: (value: string | null) => void): () => void; }; initialState: { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }; get: () => { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }; set: (next: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;, change?: { reason?: ChangeReason; event?: Event; }) => boolean; subscribe: (listener: (state: { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }) => void) => () => void; follow: <Key extends string>(store: PreferenceStore<Key, { value: \&#x22;calm\&#x22; | \&#x22;springy\&#x22; | \&#x22;snappy\&#x22; | \&#x22;playful\&#x22;; }>, key: Key) => () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Motion preference instance; the default applies and saves the choice globally.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;form&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The id of a form to belong to, when the segmented control isn't inside that form.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;name&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The name the value submits under. Without one, the segmented control submits nothing.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;orientation&#x22;,&#x22;type&#x22;:&#x22;\&#x22;horizontal\&#x22; | \&#x22;vertical\&#x22;&#x22;,&#x22;full&#x22;:&#x22;SegmentedControlOrientation&#x22;,&#x22;default&#x22;:&#x22;\&#x22;horizontal\&#x22;&#x22;,&#x22;description&#x22;:&#x22;Horizontal or vertical arrangement and keyboard navigation.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;disabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Disables changes to the selected style.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;loop&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;true&#x22;,&#x22;description&#x22;:&#x22;Wraps navigation between style options.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;readOnly&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Retains focus and browsing while preventing changes.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;required&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Requires a selected style when used in a form.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;controller&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ getValue: () => string | null; setValue: (value: string | null, details?: SegmentedControlChangeOptions) => boolean; focus: () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Checks items from anywhere. Create one with `createSegmentedControlController()`.&#x22;,&#x22;required&#x22;:false}]" />

## Hooks [#hooks]

### usePreference [#usepreference]

Call it inside the component to read and change its state.

## Keyboard [#keyboard]

| Key            | What it does                                                   |
| -------------- | -------------------------------------------------------------- |
| <kbd>← →</kbd> | In a preference switcher, moves to the previous or next value. |

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. More in [Accessibility](/docs/accessibility).

## Swap the import [#swap-the-import]

Already using UI SDK's preferences with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/preferences"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/preferences"
```

## Questions

### How does the animated Preferences for UI SDK move?

Stretch: A preference switcher's key stretches to the value you pick, as the motion style switcher's does between the four styles.

### Do I need Motion or Framer Motion for the animated Preferences?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/preferences` instead. It has the same parts and props as `@ui-sdk/react/preferences` and adds motion only.

### What happens to the Preferences when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
