# Animated List
A live list that animates rows arriving, leaving, and the rows they push aside.
Source page: https://dinachi.dev/docs/components/animated-list

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

## Usage
```tsx
import { useState } from "react"
import { AnimatedList, AnimatedListItem } from "@/components/ui/animated-list"

export function Notifications({ initial }: { initial: { id: string; title: string }[] }) {
  const [rows, setRows] = useState(initial)
  const [dismissed, setDismissed] = useState<string | null>(null)

  const dismiss = (id: string) => {
    setDismissed(id)
    setRows((current) => current.filter((row) => row.id !== id))
  }

  return (
    <AnimatedList dismissed={dismissed}>
      {rows.map((row) => (
        <AnimatedListItem key={row.id} itemKey={row.id}>
          {row.title}
          <button type="button" onClick={() => dismiss(row.id)}>
            Dismiss
          </button>
        </AnimatedListItem>
      ))}
    </AnimatedList>
  )
}
```

## Anatomy
```tsx
<AnimatedList>
  <AnimatedListItem />
</AnimatedList>
```
- `AnimatedList`: A `ul` that reconciles its rows with motion.
- `AnimatedListItem`: One row, an animated `li`.

## Examples

### Default
A feed whose rows enter, leave and make room for each other.
```tsx
import { AnimatedList, AnimatedListItem } from '@/components/ui/animated-list';

export function Example() {
  const [rows, setRows] = React.useState(SEED);
  const [dismissed, setDismissed] = React.useState<string | null>(null);

  const dismiss = (id: string) => {
    setDismissed(id);
    setRows((current) => current.filter((row) => row.id !== id));
  };

  return (
    <AnimatedList dismissed={dismissed} className="space-y-2">
      {rows.map((row) => (
        <AnimatedListItem key={row.id} itemKey={row.id}>
          <Row row={row} onDismiss={() => dismiss(row.id)} />
        </AnimatedListItem>
      ))}
    </AnimatedList>
  );
}
```

### Two exits
A row the reader closed leaves differently from one that was retracted.
```tsx
// The reader closed it: recorded in the same update that removes it.
const dismiss = (id: string) => {
  setDismissed(id);
  setRows((current) => current.filter((row) => row.id !== id));
};

// Removal the reader did not ask for: no `dismissed`, so it collapses in place.
const retract = (id: string) =>
  setRows((current) => current.filter((row) => row.id !== id));
```

### From below
A log grows downward, so its rows arrive from below.
```tsx
import { AnimatedList, AnimatedListItem } from '@/components/ui/animated-list';

export function Example() {
  return (
    <AnimatedList from="bottom" className="space-y-2">
      {rows.map((row) => (
        <AnimatedListItem key={row.id} itemKey={row.id}>
          <Row row={row} />
        </AnimatedListItem>
      ))}
    </AnimatedList>
  );
}
```

## Notes

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

### What animates
- A new row fades in from the `from` edge.
- A removed row leaves layout at once, so the gap closes immediately.
- Every other row springs to its new position.

### Dismissed rows
Pass the key of a row the reader closed as `dismissed`, in the same update that removes it. That row slides out sideways; other removals collapse in place.

```tsx
const dismiss = (id: string) => {
  setDismissed(id)
  setRows((current) => current.filter((row) => row.id !== id))
}
```

### When to use it
- A feed, inbox or activity stream that changes a row or two at a time while someone watches.
- For a list that only appears, use [Stagger List](/docs/components/stagger-list).
- Skip it when the whole list changes on every keystroke.

### Behaviour
- Nothing animates on first render.
- `AnimatedListItem` throws outside an `AnimatedList`.

## API reference

### AnimatedList
A `ul` that reconciles its rows with motion.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `from` | `"top" \| "bottom"` | `"top"` | The edge new rows arrive from. A feed that grows downward wants bottom. |
| `dismissed` | `string \| null` | `null` | The `itemKey` of the row the reader closed. Set it in the same update that removes the row. |
| `duration` | `number` | `0.3` | Seconds for each row's own animation. The reflow spring is scaled from it. |

### AnimatedListItem
One row, an animated `li`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `itemKey` | `string` | - | The same string as React's key, which a component cannot read back. Only needed with dismissed. |

## Accessibility
- Keeps ul and li semantics.
- Reduced motion drops the travel; rows still move to their new place in one frame.
- Changes are not announced. Use a live region if a new row matters.

## Source
`components/ui/animated-list/animated-list.tsx`
```tsx
"use client"

import * as React from "react"
import {
  AnimatePresence,
  motion,
  MotionConfigContext,
  useReducedMotion,
} from "motion/react"
import { cn } from "@/lib/utils"

/** `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 ?? false
}

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

const DEFAULT_DURATION = 0.3

interface AnimatedListContextValue {
  from: "top" | "bottom"
  duration: number
  reducedMotion: boolean
}

const AnimatedListContext = React.createContext<AnimatedListContextValue | null>(null)

export interface AnimatedListProps extends React.ComponentProps<"ul"> {
  /** Which edge new rows arrive from. The direction of travel is a claim about where a
   *  row came from, so a feed that grows downward should not have its rows rising. */
  from?: "top" | "bottom"
  /**
   * The key of the row the reader closed themselves, if any.
   *
   * A row the reader dismissed and a row the server retracted are the same removal to
   * React and two different events to the reader, so they leave differently: the first
   * slides out towards the control that was just pressed, the second collapses in place.
   *
   * Set it in the same update that removes the row. By the time the row is leaving it is
   * already gone from the list, so nothing captured at render can still say why — this
   * value rides `AnimatePresence`'s `custom`, which is the one channel motion re-reads
   * when it resolves an exit. Leave it unset and every removal collapses in place.
   */
  dismissed?: string | null
  /** Seconds for each row's own animation. The reflow spring is scaled from it. */
  duration?: number
}

/**
 * A list whose contents change under the reader.
 *
 * Entering and leaving are the easy half. The case that decides whether a live list feels
 * built or assembled is the third one: the row that neither entered nor left but had to
 * move because something above it did. That movement is FLIP — motion measures both
 * positions across the commit and animates the difference — so a row that shifts up reads
 * as *displaced* rather than as having been repainted somewhere else.
 *
 * `mode="popLayout"` is what makes entrances, exits and displacement cooperate. An exiting
 * row is pulled out of layout flow immediately and animated on top of it, so the rows
 * below start closing the gap on the same frame the row starts leaving instead of waiting
 * for it to finish.
 *
 * Reduced motion drops the travel but not the reflow. Rows still have to end up in the
 * right place; they just get there in one frame.
 */
const AnimatedList = React.forwardRef<HTMLUListElement, AnimatedListProps>(
  (
    { from = "top", dismissed = null, duration, className, children, ...props },
    ref
  ) => {
    const reducedMotion = useReducedMotionConfig()
    const seconds = duration ?? DEFAULT_DURATION

    const context = React.useMemo(
      () => ({ from, duration: seconds, reducedMotion }),
      [from, seconds, reducedMotion]
    )

    return (
      <AnimatedListContext.Provider value={context}>
        <ul ref={ref} className={cn("list-none", className)} data-slot="animated-list" {...props}>
          <AnimatePresence mode="popLayout" initial={false} custom={dismissed}>
            {children}
          </AnimatePresence>
        </ul>
      </AnimatedListContext.Provider>
    )
  }
)
AnimatedList.displayName = "AnimatedList"

export interface AnimatedListItemProps
  extends React.ComponentProps<typeof motion.li> {
  /** The same string given to React's `key`, which a component cannot read back. Only
   *  needed if the list is using `dismissed`. */
  itemKey?: string
}

const AnimatedListItem = React.forwardRef<HTMLLIElement, AnimatedListItemProps>(
  ({ itemKey, className, children, ...props }, ref) => {
    const context = React.useContext(AnimatedListContext)

    if (!context) {
      throw new Error("AnimatedListItem must be used within an AnimatedList")
    }

    const { from, duration, reducedMotion } = context

    // `x`, `y` and `scale` rather than the full transform strings the rest of the tier
    // prefers. Those keep motion off the main thread, but `layout` builds the element's
    // transform out of these very values plus its own projection delta — hand it a
    // `transform` string and the two write over each other.
    const variants = {
      exit: (closedByReader: string | null) => {
        if (reducedMotion) return { opacity: 0, x: 0, scale: 1 }
        return closedByReader != null && closedByReader === itemKey
          ? { opacity: 0, x: 24, scale: 0.97 }
          : { opacity: 0, x: 0, scale: 0.94 }
      },
    }

    return (
      <motion.li
        ref={ref}
        layout
        className={cn(className)}
        // Every key `animate` sets appears in every branch. Dropping one under reduced
        // motion does not disable it — it animates it from `undefined`.
        initial={
          reducedMotion
            ? { opacity: 0, x: 0, y: 0, scale: 1 }
            : { opacity: 0, x: 0, y: from === "top" ? -12 : 12, scale: 0.97 }
        }
        animate={{ opacity: 1, x: 0, y: 0, scale: 1 }}
        variants={variants}
        exit="exit"
        transition={{
          layout: reducedMotion
            ? { duration: 0 }
            : { type: "spring", bounce: 0.15, duration: duration * 1.4 },
          // Opacity stays on a fixed clock so a row is never left half-visible waiting
          // for a spring to settle.
          default: { duration: reducedMotion ? 0.2 : duration, ease: EASE_OUT },
        }}
        data-slot="animated-list-item"
        {...props}
      >
        {children}
      </motion.li>
    )
  }
)
AnimatedListItem.displayName = "AnimatedListItem"

export { AnimatedList, AnimatedListItem }
```
