# Compare Slider
Two aligned layers split by a movable divider.
Source page: https://dinachi.dev/docs/components/compare-slider

## Installation
```bash
npx @dinachi/cli@latest add compare-slider
```
Adds to your project:
- `components/ui/compare-slider/compare-slider.tsx`
- `components/ui/compare-slider/index.ts`
Installs:
- `motion` ^12.23.6

## Usage
```tsx
import { CompareSlider } from "@/components/ui/compare-slider"

export function Retouch() {
  return (
    <CompareSlider
      label="Compare the two revisions"
      before={<img src="/before.jpg" alt="Before retouching" />}
      after={<img src="/after.jpg" alt="After retouching" />}
    />
  )
}
```

## Examples

### Default
Drag the divider, or focus it and use the arrow keys.
```tsx
import { CompareSlider } from '@/components/ui/compare-slider';

export function Example() {
  return (
    <CompareSlider
      label="Compare the two revisions"
      before={<img src="/before.jpg" alt="Before retouching" />}
      after={<img src="/after.jpg" alt="After retouching" />}
    />
  );
}
```

### Panel drag
Press anywhere to jump the divider there.
```tsx
import { CompareSlider } from '@/components/ui/compare-slider';

export function Example() {
  // Both sides are images, so there is nothing to click and a 2px handle is a
  // needlessly small target.
  return (
    <CompareSlider
      drag="panel"
      label="Compare the two revisions"
      before={<img src="/before.jpg" alt="Before retouching" />}
      after={<img src="/after.jpg" alt="After retouching" />}
    />
  );
}
```

### Live content
Both layers stay interactive while the handle drags.
```tsx
import { CompareSlider } from '@/components/ui/compare-slider';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <CompareSlider
      label="Compare the two plans"
      before={<CurrentPlan />}
      after={
        <ProposedPlan>
          <Button onClick={upgrade}>Upgrade</Button>
        </ProposedPlan>
      }
    />
  );
}
```

## Notes

### Motion tier
Needs [motion](https://motion.dev). `add --all` skips it; install with `add --motion` or by name.

### Drag modes
- `handle` (default): only the divider starts a drag; both layers stay interactive. Use when either side is real UI.
- `panel`: pressing anywhere jumps the divider there and makes both layers inert. Use when both sides are images.

### When to use it
- Before and after photos, design diffs, a map with a layer toggled.
- Both layers must share the same frame, position and size.
- For two unaligned things, use side-by-side panels.

### Behaviour
- A pointer drag tracks 1:1 with no easing.
- A keyboard step animates over 100ms; a held arrow key moves continuously.
- Grabbing the handle keeps the grab offset. In `panel` mode the divider jumps to the press.
- A second pointer mid-drag is ignored until the first lifts.
- `onPositionChange` runs only when the rounded position changes.

## API reference
Props marked **agent** change what an agent reads or may do.

### CompareSlider
The panel, both layers and the handle.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `before` | `ReactNode` | - | The layer left of the divider. |
| `after` | `ReactNode` | - | The layer right of the divider. |
| `defaultPosition` | `number` | `50` | Starting divider position, 0 to 100. |
| `onPositionChange` **agent** | `(position, details) => void` | - | Runs on release, each key step and for agents. `details.cancel()` puts the divider back. |
| `step` | `number` | `2` | Percentage points per arrow key. Shift moves five times as far. |
| `drag` | `"handle" \| "panel"` | `"handle"` | What starts a drag. `handle` keeps both layers interactive. |
| `label` **agent** | `string` | `"Compare position"` | Accessible name for the handle. Also the name the agent reads. |
| `stickyHandle` | `boolean` | `false` | Keeps the knob mid-viewport. Use when the panel is taller than the screen. |
| `disabled` **agent** | `boolean` | `false` | Ignores drags and keys, dims the panel and blocks agents. |

## Agent
Inside an `AgentProvider`, Compare Slider appears in `agent.snapshot()` as `slider`.
Reads:
- `label`: The `label` prop, the handle's aria-label.
- `value`: The divider position, a whole number from 0 to 100.
- `min / max`: Always 0 and 100.
- `disabled`: True when the slider is disabled.
Actions:
- `setValue(70)`: Moves the divider. Rounds the input; refuses non-numbers and out-of-range values.
An agent's move runs through `onPositionChange` with `details.reason` set to `imperative-action`. `isAgentChange(details)` is true for it, and `details.cancel()` refuses it; the divider stays and the agent is told the app refused. A disabled slider refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "Compare the two revisions", action: "setValue", args: [70] }],
})
```

## Accessibility
- The handle is a slider with min, max, live valuenow and a percentage valuetext.
- The announced value updates on key press and stays current during a drag.
- Give it a `label` naming what is compared; the default describes only the control.
- Disabled, the handle leaves the tab order and gets aria-disabled.
- Reduced motion applies each keyboard step immediately.
### Keyboard
| Keys | Does |
| --- | --- |
| `←` / `↓` | Moves the divider left by one step |
| `→` / `↑` | Moves the divider right by one step |
| `Shift` / `Arrow` | Moves five steps at once |
| `Home` / `End` | Jumps to either end |

## Source
`components/ui/compare-slider/compare-slider.tsx`
```tsx
"use client"

import * as React from "react"
import {
  animate,
  motion,
  MotionConfigContext,
  useMotionTemplate,
  useMotionValue,
  useReducedMotion,
  useTransform,
} from "motion/react"
import { cn } from "@/lib/utils"
import { changeAsAgent, useAgentControl } from "@/components/ui/agent"

/** `useReducedMotion` reads the OS setting only, and only at mount. Also honour an
 *  app-level `<MotionConfig reducedMotion>`, so a user preference in the host app
 *  reaches this component. */
function useReducedMotionConfig() {
  const config = React.useContext(MotionConfigContext)
  const prefersReduced = useReducedMotion()
  if (config.reducedMotion === "always") return true
  if (config.reducedMotion === "never") return false
  return prefersReduced
}

const EASE_OUT: [number, number, number, number] = [0.23, 1, 0.32, 1]

/** Runs a consumer's handler ahead of the component's own, so passing one adds
 *  behaviour instead of replacing it. */
function compose<E>(
  theirs: ((event: E) => void) | undefined,
  ours: (event: E) => void
) {
  return (event: E) => {
    theirs?.(event)
    ours(event)
  }
}

const clamp = (n: number) => Math.min(100, Math.max(0, n))

/** What moved the divider. Cancel one from `onPositionChange` and the divider goes back. */
export interface CompareSliderChangeDetails {
  reason: "drag" | "keyboard" | "imperative-action"
  isCanceled: boolean
  cancel: () => void
}

function personChange(reason: "drag" | "keyboard"): CompareSliderChangeDetails {
  const details: CompareSliderChangeDetails = {
    reason,
    isCanceled: false,
    cancel: () => {
      details.isCanceled = true
    },
  }
  return details
}

/** A position an agent sent, rounded, or what is wrong with it. */
function agentPosition(wanted: unknown): number | string {
  const n = Number(wanted)
  if (wanted === "" || wanted === null || !Number.isFinite(n)) return `"${String(wanted)}" is not a number.`
  if (n < 0 || n > 100) return `${n} is out of range: 0 to 100.`
  return Math.round(n)
}

/** The classes a sticky handle changes. */
const stickyClasses = (sticky: boolean) =>
  sticky
    ? // A panel taller than the screen still has to scroll vertically, so only the
      // horizontal axis is claimed there. `overflow: clip` still trims to the radius but
      // does not open a scrollport, which `overflow: hidden` does, and a sticky knob
      // resolves against the nearest scrollport, so `hidden` would pin it to a box that
      // never scrolls.
      { touch: "touch-pan-y", overflow: "overflow-clip" }
    : { touch: "touch-none", overflow: "overflow-hidden" }

/** Panel and handle attributes: locked, or focusable. */
const lockAttrs = (disabled: boolean) =>
  disabled
    ? { panel: { "data-disabled": "" }, handle: { tabIndex: -1, "aria-disabled": true } }
    : { panel: {}, handle: { tabIndex: 0 } }

/** An agent's position, or the message saying why it cannot have it. */
const placeAsAgent = (next: number | string, place: (next: number, details: CompareSliderChangeDetails) => void) =>
  typeof next === "string" ? next : changeAsAgent(place, next)

export interface CompareSliderProps
  extends Omit<React.ComponentProps<"div">, "children" | "onChange"> {
  /** Content shown on the left of the divider. */
  before: React.ReactNode
  /** Content shown on the right of the divider. */
  after: React.ReactNode
  /** Starting divider position, 0–100. */
  defaultPosition?: number
  /** Percentage points moved per arrow key press. */
  step?: number
  /** What starts a drag.
   *
   *  `"handle"` — the default — limits dragging to the divider, leaving both layers
   *  live: buttons take clicks, text takes selection, links take focus.
   *
   *  `"panel"` treats the whole surface as the control, so pressing anywhere jumps
   *  the divider there. Reach for it when the panes are images, where there is
   *  nothing to click and a thin handle is a needlessly small target — but note that
   *  it makes both layers inert, which reads as a bug on anything interactive. */
  drag?: "panel" | "handle"
  /** Accessible name for the divider handle. */
  label?: string
  /** Keep the knob at the vertical middle of the viewport instead of the middle of
   *  the panel. Set this when the panel is taller than the screen, or the knob spends
   *  most of the page off-screen. */
  stickyHandle?: boolean
  /** Stops the divider from moving. */
  disabled?: boolean
  /** Fired on release and on each keyboard step. Cancel `details` to put the divider back. */
  onPositionChange?: (position: number, details: CompareSliderChangeDetails) => void
}

/**
 * Drag a divider to compare two layers.
 *
 * A pointer drag tracks 1:1 with no easing — that is direct manipulation, and any
 * smoothing there reads as lag. A keyboard step is the opposite case: one press moves
 * the divider a fixed slice of the panel in a single frame, which strobes rather than
 * moves, so each step is carried over 100ms instead. The tween retargets from wherever
 * the divider currently is, so a held arrow key composes into one continuous travel
 * rather than a queue of restarts.
 *
 * Position lives in a motion value, so dragging never triggers a React render.
 * Component state is synced on release and on each keyboard step, where it feeds
 * `aria-valuenow` — that sync is deliberately immediate on a key press, so the
 * announced value is never waiting on the pixels to arrive. A drag writes the same two
 * attributes straight to the node, which keeps the reported value current without
 * putting a render in the middle of a gesture.
 */
const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
  (
    {
      before,
      after,
      defaultPosition = 50,
      step = 2,
      drag = "handle",
      label = "Compare position",
      stickyHandle = false,
      disabled = false,
      onPositionChange,
      className,
      ...props
    },
    ref
  ) => {
    const containerRef = React.useRef<HTMLDivElement>(null)
    React.useImperativeHandle(ref, () => containerRef.current as HTMLDivElement)

    const reducedMotion = useReducedMotionConfig()
    const position = useMotionValue(clamp(defaultPosition))
    const [announced, setAnnounced] = React.useState(clamp(defaultPosition))
    // Where the divider is headed. Stepping off the motion value instead would sample
    // a step still in flight, so each key repeat would advance by less than a full step.
    const settled = React.useRef(clamp(defaultPosition))
    const stepAnimation = React.useRef<ReturnType<typeof animate> | null>(null)
    // The pointer that owns the gesture. A second finger arriving mid-drag would
    // measure its own grab offset and jump the divider under the first one, so every
    // other pointer is ignored until this one lifts.
    const activePointer = React.useRef<number | null>(null)
    // How far the pointer sat from the divider when the drag began. Grabbing a handle
    // should not teleport it under your finger; pressing the panel should.
    const grabOffset = React.useRef(0)

    React.useEffect(() => () => stepAnimation.current?.stop(), [])

    const remainder = useTransform(position, (p) => 100 - p)
    const clipPath = useMotionTemplate`inset(0% ${remainder}% 0% 0%)`
    // A percentage translate resolves against the element's own width, so a track the
    // full width of the panel converts the position straight into a transform. `left`
    // would say the same thing as a layout property recomputed on every frame of a
    // drag, where this is composited.
    const track = useMotionTemplate`translateX(${position}%)`

    const handleRef = React.useRef<HTMLDivElement>(null)

    /**
     * The two attributes a slider is read through, written to the node rather than
     * through state. React owns them on every render; between renders a drag keeps them
     * current itself, so what assistive tech reports mid-gesture is where the divider
     * actually is rather than where it was when the finger landed.
     */
    const announceNow = React.useCallback((value: number) => {
      const node = handleRef.current
      if (!node) return
      node.setAttribute("aria-valuenow", String(value))
      node.setAttribute("aria-valuetext", `${value}%`)
    }, [])

    const setFromClientX = React.useCallback(
      (clientX: number) => {
        const rect = containerRef.current?.getBoundingClientRect()
        if (!rect || rect.width === 0) return
        const x = clientX - grabOffset.current - rect.left
        const next = clamp((x / rect.width) * 100)
        settled.current = next
        position.set(next)
        announceNow(Math.round(next))
      },
      [position, announceNow]
    )

    // The last value handed to `onPositionChange`. Plenty of gestures end where they
    // began: clicking a handle without dragging it, or stepping into either end. A
    // change event for an unchanged value is noise the caller has to filter.
    const emitted = React.useRef(clamp(defaultPosition))

    /** Reports the change, and says whether it stands. A canceled one leaves the old value announced. */
    const emit = React.useCallback(
      (next: number, details: CompareSliderChangeDetails) => {
        if (next !== emitted.current) onPositionChange?.(next, details)
        const stands = !details.isCanceled
        if (stands) emitted.current = next
        setAnnounced(emitted.current)
        announceNow(emitted.current)
        return stands
      },
      [onPositionChange, announceNow]
    )

    const moveTo = React.useCallback(
      (next: number) => {
        stepAnimation.current?.stop()
        settled.current = next
        if (reducedMotion) {
          position.set(next)
          return
        }
        stepAnimation.current = animate(position, next, {
          duration: 0.1,
          ease: EASE_OUT,
        })
      },
      [position, reducedMotion]
    )

    const commit = React.useCallback(() => {
      if (!emit(Math.round(position.get()), personChange("drag"))) moveTo(emitted.current)
    }, [position, emit, moveTo])

    /** Moves the divider to `next` unless the app cancels the change. */
    const place = React.useCallback(
      (next: number, details: CompareSliderChangeDetails) => {
        if (emit(Math.round(next), details)) moveTo(next)
      },
      [emit, moveTo]
    )

    const stepBy = React.useCallback(
      (delta: number) => place(clamp(settled.current + delta), personChange("keyboard")),
      [place]
    )

    useAgentControl(() => ({
      kind: "slider",
      element: handleRef.current,
      value: emitted.current,
      min: 0,
      max: 100,
      disabled,
      actions: {
        setValue: (wanted: unknown) => placeAsAgent(agentPosition(wanted), place),
      },
    }))

    const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (disabled) return
      const large = event.shiftKey ? 5 : 1
      switch (event.key) {
        case "ArrowLeft":
        case "ArrowDown":
          event.preventDefault()
          stepBy(-step * large)
          break
        case "ArrowRight":
        case "ArrowUp":
          event.preventDefault()
          stepBy(step * large)
          break
        case "Home":
          event.preventDefault()
          stepBy(-100)
          break
        case "End":
          event.preventDefault()
          stepBy(100)
          break
        default:
          break
      }
    }

    const lock = lockAttrs(disabled)
    const onHandle = drag === "handle"
    const { touch, overflow } = stickyClasses(stickyHandle)

    const endDrag = (event: React.PointerEvent<HTMLDivElement>) => {
      if (event.pointerId !== activePointer.current) return
      activePointer.current = null
      grabOffset.current = 0
      commit()
    }

    const dragHandlers = {
      onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => {
        if (disabled || activePointer.current !== null) return
        const rect = containerRef.current?.getBoundingClientRect()
        if (!rect || rect.width === 0) return
        // A step still in flight has to be dropped here rather than left to finish,
        // or it would keep writing over the pointer for the rest of its 100ms. The
        // grab offset is then measured against where the divider actually is on
        // screen, not where that step was headed.
        stepAnimation.current?.stop()
        grabOffset.current = onHandle
          ? event.clientX - (rect.left + (rect.width * position.get()) / 100)
          : 0
        activePointer.current = event.pointerId
        event.currentTarget.setPointerCapture(event.pointerId)
        setFromClientX(event.clientX)
      },
      onPointerMove: (event: React.PointerEvent<HTMLDivElement>) => {
        if (event.pointerId === activePointer.current) setFromClientX(event.clientX)
      },
      onPointerUp: endDrag,
      onPointerCancel: endDrag,
      // Capture can be lost without a `pointerup` — the drag has to end there too, or
      // the divider stays bound to a pointer that is no longer down.
      onLostPointerCapture: endDrag,
    }

    // Spread after the consumer's props, and composed rather than assigned: their
    // handler still runs, but it cannot take the drag's place. A slider whose pointer
    // handlers were quietly overwritten still looks interactive and is not.
    const panelHandlers = onHandle
      ? {}
      : {
          onPointerDown: compose(props.onPointerDown, dragHandlers.onPointerDown),
          onPointerMove: compose(props.onPointerMove, dragHandlers.onPointerMove),
          onPointerUp: compose(props.onPointerUp, dragHandlers.onPointerUp),
          onPointerCancel: compose(
            props.onPointerCancel,
            dragHandlers.onPointerCancel
          ),
          onLostPointerCapture: compose(
            props.onLostPointerCapture,
            dragHandlers.onLostPointerCapture
          ),
        }

    return (
      <div
        ref={containerRef}
        className={cn(
          "relative isolate w-full rounded-lg",
          // Only claim selection and touch gestures where the drag actually starts.
          // In handle mode the layers stay live, so taking either off the container
          // would break selecting text and scrolling the page under it.
          onHandle ? "select-auto" : cn("select-none", touch),
          overflow,
          "data-[disabled]:opacity-50",
          className
        )}
        data-slot="compare-slider"
        {...lock.panel}
        {...props}
        {...panelHandlers}
      >
        {/* `after` is the base layer and `before` is clipped over it, because the clip
            runs from the left edge to the divider — so whichever layer is clipped is
            the one on the left.

            Both layers isolate. Without it neither one owns a stacking context, so a
            `z-10` anywhere inside the base layer competes directly with the clipped
            layer above it and paints straight through the clip — invisible with two
            images, immediately obvious the moment either side is real UI. */}
        <div className="relative isolate">{after}</div>

        <motion.div style={{ clipPath }} className="absolute inset-0 isolate">
          {before}
        </motion.div>

        {/* The track spans the panel and carries the transform; it stays inert so the
            layers underneath keep their clicks, and only the strip inside it takes the
            pointer. */}
        <motion.div
          style={{ transform: track }}
          className="pointer-events-none absolute inset-0 z-10"
        >
          <div
            ref={handleRef}
            role="slider"
            {...lock.handle}
            onKeyDown={handleKeyDown}
            aria-label={label}
            aria-valuemin={0}
            aria-valuemax={100}
            aria-valuenow={announced}
            // Without this a reader announces a bare "62". `aria-label` says what is
            // being compared; this supplies the unit.
            aria-valuetext={`${announced}%`}
            aria-orientation="horizontal"
            {...(onHandle ? dragHandlers : {})}
            className={cn(
              "pointer-events-auto absolute inset-y-0 left-0 w-0.5 -translate-x-1/2 cursor-ew-resize bg-background",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
              // A 2px line is not a grab target. The pseudo-element widens the hit area
              // to a comfortable strip without widening the line you can see.
              onHandle &&
                cn(
                  touch,
                  "select-none before:absolute before:inset-y-0 before:-left-2.5 before:-right-2.5 before:content-['']"
                )
            )}
          >
            <span
              aria-hidden
              className={cn(
                "flex h-7 w-7 items-center justify-center rounded-full bg-background text-foreground shadow-md",
                stickyHandle
                  ? // The divider is 2px wide, so the knob's flow position starts 1px
                    // left of centre and has to be pulled back by the rest of its half.
                    // The top margin only decides where it rests before anything has
                    // scrolled — without it the knob would start pinned to the very top
                    // edge of the panel, which reads as broken.
                    "sticky top-[50vh] -ml-[13px] mt-[30vh]"
                  : "absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"
              )}
            >
              <svg
                className="h-3.5 w-3.5"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth={2}
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <polyline points="15 18 9 12 15 6" transform="translate(-3 0)" />
                <polyline points="9 18 15 12 9 6" transform="translate(3 0)" />
              </svg>
            </span>
          </div>
        </motion.div>
      </div>
    )
  }
)
CompareSlider.displayName = "CompareSlider"

export { CompareSlider }
```
