# Animated Motion Style for UI SDK (/docs/components/motion-style)

Switch the whole set between Calm, Springy, Snappy and Playful motion with one setting.

```tsx title="example.tsx"
import { Button } from "@/components/keyframery/button"
import { createMotionStyle, MotionStyle, MotionStyleSwitcher } from "@/components/keyframery/motion-style"
import { Switch } from "@/components/keyframery/switch"
import { Tabs, TabsList, TabsTab } from "@/components/keyframery/tabs"

/* In the lab the style stays inside this demo: a scoped preference, not saved, so the rest of the
   page keeps the style picked in the header. In an app, use `motionStyle` (the default), which
   goes on <html>. */
const demoMotion = createMotionStyle({ global: false, storageKey: null })

const item = (n: number) => `[aria-label="Motion style"] [data-slot="segmented-control-item"]:nth-of-type(${n})`

export default function MotionStyleDemo() {
  return (
    <MotionStyle preference={demoMotion}>
      <div className="flex w-[380px] flex-col items-center gap-5">
        <MotionStyleSwitcher preference={demoMotion} />
        <div className="w-full 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)]">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-[15px] font-semibold tracking-tight">Focus hours</div>
              <div className="mt-0.5 text-[12px] text-muted-foreground">Silence notifications while you work</div>
            </div>
            <Switch aria-label="Focus hours" />
          </div>
          <Tabs defaultValue="today" className="mt-5">
            <TabsList aria-label="Schedule">
              <TabsTab value="today">Today</TabsTab>
              <TabsTab value="weekdays">Weekdays</TabsTab>
              <TabsTab value="always">Every day</TabsTab>
            </TabsList>
          </Tabs>
          <div className="mt-5 flex justify-end gap-2">
            <Button variant="ghost">Cancel</Button>
            <Button variant="primary">Save</Button>
          </div>
        </div>
      </div>
    </MotionStyle>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/motion-style
```

This adds `components/keyframery/motion-style.tsx` and its primitive, `components/keyframery/primitives/motion-style.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import { MotionStyleSwitcher } from "@/components/keyframery/motion-style"
```

The parts and props are the same as UI SDK's `preferences`. For every prop, see the [UI SDK preferences reference](https://ui-sdk.dev/docs/components/preferences).

## What moves [#what-moves]

| Move        | What you see                                          |
| ----------- | ----------------------------------------------------- |
| **Stretch** | The switcher's key stretches between the four styles. |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## 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/motion-style"
```

## Parts [#parts]

The finished component exports one part:

`MotionStyleSwitcher`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the motion style moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/motion-style.tsx**

```tsx
"use client"

/* Styled motion style switcher: a segmented control whose key stretches between the four styles.
   It mounts MotionStyle itself, so dropping it anywhere applies the choice to <html>. */

import * as React from "react"

import {
  MotionStyle,
  motionStyle,
  type MotionStylePreference,
  motionStyles,
  type MotionStyleValue,
  usePreference,
} from "@/components/keyframery/primitives/motion-style"
import { SegmentedControl, SegmentedControlItem } from "@/components/keyframery/segmented-control"

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

function MotionStyleSwitcher({
  preference = motionStyle,
  "aria-label": ariaLabel = "Motion style",
  ...props
}: Omit<React.ComponentProps<typeof SegmentedControl>, "value" | "defaultValue" | "onValueChange" | "children"> & {
  preference?: MotionStylePreference
}) {
  const { value } = usePreference(preference)
  return (
    <MotionStyle preference={preference}>
      <SegmentedControl
        aria-label={ariaLabel}
        value={value}
        onValueChange={(next, details) => {
          if (next) preference.set(next as MotionStyleValue, { reason: "press", event: details.event })
        }}
        {...props}
      >
        {motionStyles.map((style) => (
          <SegmentedControlItem key={style} value={style}>
            {labels[style]}
          </SegmentedControlItem>
        ))}
      </SegmentedControl>
    </MotionStyle>
  )
}

export { createMotionStyle, MotionStyle, motionStyle, motionStyles, type MotionStyleValue } from "@/components/keyframery/primitives/motion-style"
export { MotionStyleSwitcher }
```

**components/keyframery/primitives/motion-style.tsx**

```tsx
"use client"

/* Keyframery's four motion styles, on top of `@ui-sdk/react/preferences`.

   Every Keyframery duration is written as calc(Nms * var(--kf-speed, 1)) and every 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 the preference: 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 }
```

## Questions

### How does the animated Motion Style for UI SDK move?

Stretch: The switcher's key stretches between the four styles.

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

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/motion-style` instead. It has the same parts and props as `@ui-sdk/react/preferences` and adds motion only.

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

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