# Motion

> Source: https://design.nanatec.co.ke/guides/motion/
> How Nana UI moves. Duration, easing and distance roles named by intent, shared keyframes, reduced motion that keeps the fade, and optional GSAP and Lenis.

Motion in Nana UI is slow enough to follow and never makes anyone wait.
Every component reads the same small set of roles from `@nana-tec/ui-motion`,
so a menu, a toast and a dialog move as one system, in the web components, in
React and in Svelte.

```bash
npm install @nana-tec/ui-motion
```

`@nana-tec/ui-themes/base` already imports the motion stylesheet. If you load
the theme, the roles are already on the page.

## Roles, not numbers

A component asks for `enter` or `state`, never for `420ms`. Press **Play** to
compare them side by side, and slow them down to see the shape of each one.

**Duration roles**

```css
.panel {
  transition:
    background-color var(--nana-motion-state) var(--nana-motion-ease-state),
    transform var(--nana-motion-move) var(--nana-motion-ease-move);
}

.panel[data-open] {
animation: nana-rise-in var(--nana-motion-overlay) var(--nana-motion-ease-enter) both;
}

.panel[data-closing] {
animation: nana-sink-out var(--nana-motion-overlay-exit) var(--nana-motion-ease-exit) both;
}
```

Closing always takes three quarters of the opening time: whatever arrived
gently leaves promptly. Retune a role once and every component follows:

```css
:root {
  --nana-motion-enter: 360ms;
  --nana-motion-overlay: 600ms;
}
```

## Four curves

Each curve has one job. Things arriving glide in and settle slowly, things
leaving pick up speed as they go, and things that move from rest to rest ease
at both ends.

**Easing roles**

```ts
import { easings, patterns } from "@nana-tec/ui-motion/core";

easings.enter;
patterns.overlay;
```

| Easing                     | Used for                                       |
| -------------------------- | ---------------------------------------------- |
| `--nana-motion-ease-state` | Colour, border, shadow and opacity changes     |
| `--nana-motion-ease-enter` | Popovers, menus, toasts, dialogs appearing     |
| `--nana-motion-ease-exit`  | The same, leaving                              |
| `--nana-motion-ease-move`  | Indicators, carets, expanding panels, progress |

## Entrances

Elements travel a few pixels and settle, without bouncing or overshooting.
Click a tile to replay it, change the distance, or turn on reduced motion to
see what people who ask for less movement get: the same fade, with no travel.

**enter() and exit()**

```ts
import { enter, exit, finished } from "@nana-tec/ui-motion";

enter(panel, { entrance: "fade-up", distance: "md" });

await finished(exit(panel, { pattern: "overlayExit" }));
panel.remove();
```

On phones every distance is smaller: 2, 8 and 16 pixels instead of 4, 12 and 24.

## Text reveals

Headings come in line by line, rising from behind their own edge. Words suit
short paragraphs, where whole lines would feel heavy. Characters are for a
single word or a short title, never for body copy.

**revealText()**

```ts
import { revealText } from "@nana-tec/ui-motion";

const stop = revealText(document.querySelectorAll(".hero h1, .hero p"), {
by: "lines",
mask: true,
trigger: "scroll",
});
```

### Choosing a split

| Split   | Use it for                                        | Avoid it for                      |
| ------- | ------------------------------------------------- | --------------------------------- |
| `lines` | Headlines and hero statements                     | Text that reflows while it plays  |
| `words` | Short paragraphs, subtitles, a lead under a title | Anything longer than a few lines  |
| `chars` | One word or a short title                         | Body copy, buttons, labels, links |

Reveal one heading and the line beneath it, not every paragraph on the page.
Body copy that animates as it arrives slows reading down.

### Options

| Option       | Values                    | Default                          | Does                                                  |
| ------------ | ------------------------- | -------------------------------- | ----------------------------------------------------- |
| `by`         | `lines`, `words`, `chars` | `lines`                          | What each piece is                                    |
| `mask`       | `true`, `false`           | `true`                           | Rise from behind the line's own edge, or fade up      |
| `trigger`    | `load`, `scroll`          | `load`                           | Play at once, or when the text scrolls into view      |
| `step`       | milliseconds              | 90 for lines, 35 words, 18 chars | The gap between pieces                                |
| `delay`      | milliseconds              | `0`                              | Added before the first piece                          |
| `pattern`    | any pattern               | `enter`                          | The duration and curve of each piece                  |
| `threshold`  | 0 to 1                    | `0.2`                            | How much must be visible before a scroll reveal plays |
| `rootMargin` | CSS margin                | `0px 0px -10% 0px`               | Shrinks or grows the area that counts as in view      |

`revealText` returns a cleanup that stops every animation and restores the
original markup.

### Splitting by hand

`splitText` does only the splitting, for when you animate the pieces yourself:

```ts
import { splitText } from "@nana-tec/ui-motion";

const split = splitText(headline, { by: "words", mask: true });

split.pieces;
split.lines;
split.revert();
```

| Returns  | What it is                                       |
| -------- | ------------------------------------------------ |
| `pieces` | The word or character elements, in reading order |
| `lines`  | How many lines the text sits on                  |
| `revert` | Puts the original markup back                    |

Every piece carries `--i`, its position, and every word carries `--line`, the
line it sits on, so CSS can time a cascade on its own. Words are
`.nana-split-word`, characters `.nana-split-char`, and masks
`.nana-split-mask`.

### Driving it from CSS

Split once and add `nana-text-reveal` from `utilities.css`.
`--nana-text-step` sets the gap between pieces:

```html
<h1 class="headline">Property work, handled with care</h1>

<script type="module">
  import { splitText } from "@nana-tec/ui-motion";

  const headline = document.querySelector(".headline");
  splitText(headline, { by: "words" });
  headline.classList.add("nana-text-reveal");
</script>

<style>
  .headline {
    --nana-text-step: 50ms;
  }
</style>
```

### Accessibility

- **It still reads as text.** Inline markup such as `<em>` and links stays in
  place. Split into characters, each word keeps a hidden whole-word copy for
  screen readers and hides the letters from them, so nothing is spelled out.
- **Lines break where they will finally sit.** Splitting waits for web fonts to
  load, and the markup is restored once the reveal ends, so copy, search and
  translation work on plain text.
- **Reduced motion never splits.** The text fades in as one block, or is simply
  shown when the reveal was waiting for a scroll. The CSS path falls back to a
  fade too.
- **Long cascades stay short.** However many pieces there are, the whole run
  finishes within 600ms.

## Stagger

A cascade should read as one gesture. Keep the whole run under about half a
second, and use a smaller step as the list grows.

**stagger()**

```ts
import { stagger } from "@nana-tec/ui-motion";

stagger(list.children, { entrance: "fade-up", distance: "sm", step: 40 });
```

## Overlays

Dialogs and drawers use the overlay role, the slowest of the set. Closing plays
the exit before the native `<dialog>` closes, including when you press Escape.

**Dialog and drawer**

```html
<nana-dialog id="archive" aria-label="Archive unit">
  <nana-dialog-header>Archive unit 4B?</nana-dialog-header>
  <nana-dialog-body>It rises in and settles away.</nana-dialog-body>
</nana-dialog>
<nana-button onclick="archive.show()">Open dialog</nana-button>

<style>
  nana-dialog {
    --nana-motion-overlay: 600ms;
  }
</style>
```

## In the components

The components don't keep timings of their own. Each one reads a role from the
package, and the keyframes come from the same source, so retuning a role
retunes every component that uses it.

| Role                       | Components                                                                        |
| -------------------------- | --------------------------------------------------------------------------------- |
| `press`                    | Every pressable surface: buttons, icon buttons, interactive cards                 |
| `state`                    | Hover, focus and selected colours everywhere                                      |
| `move`                     | Tab indicator, Switch, Radio, Rating, Progress Bar and Ring, Details, Split Panel |
| `enter` / `exit`           | Popup, Popover, Hover Card, Tooltip, Menu, Menubar, Tab Panel, Toaster            |
| `overlay` / `overlay-exit` | Dialog, Drawer, File Viewer                                                       |
| `ambient` / `spin`         | Skeleton and Carousel shimmer, the loading spinner in Button, Input and Tree      |

The web components load the keyframes into each shadow root, only when the
Nana theme is on. Headless, they don't animate and nothing waits on an
animation. In React and Svelte the same roles reach Tailwind as
`duration-(--nana-motion-move)`, `ease-enter` and `animate-rise-in`.

## Scroll reveals with GSAP

For scroll-driven scenes, parallax and timelines, install GSAP and import the
`gsap` entry. It registers Nana's exact curves with GSAP, so a GSAP tween and a
CSS transition on the same page land the same way. Scroll these panels in and
out of view.

**scrollReveal()**

```ts
import { scrollReveal, createTimeline, timing } from "@nana-tec/ui-motion/gsap";

const stop = scrollReveal(".feature", { entrance: "fade-up", step: 80 });

const hero = createTimeline((tl, reduced) => {
tl.from(".hero h1", { autoAlpha: 0, y: reduced ? 0 : 24, ...timing("enter") })
.from(".hero p", { autoAlpha: 0, ...timing("enter") }, "-=0.25");
});
```

Text works the same way. `textReveal` splits and reveals on scroll, and with
`scrub` each word lights up as it reaches the middle of the screen and dims
again on the way back, so a long statement reads at the pace of the scroll.

**textReveal({ scrub: true })**

```ts
import { textReveal } from "@nana-tec/ui-motion/gsap";

textReveal(".manifesto", { scrub: true, start: "top 75%", end: "bottom 40%" });
textReveal(".hero h1", { by: "lines" });
```

| Option    | Values                    | Default                          | Does                                            |
| --------- | ------------------------- | -------------------------------- | ----------------------------------------------- |
| `by`      | `lines`, `words`, `chars` | `lines`, or `words` with `scrub` | What each piece is                              |
| `mask`    | `true`, `false`           | `true`, or `false` with `scrub`  | Rise from behind an edge, or fade up            |
| `scrub`   | `true`, `false`           | `false`                          | Tie each word's brightness to the scroll        |
| `dim`     | 0 to 1                    | `0.18`                           | How faint words are before they light up        |
| `start`   | ScrollTrigger position    | `top 85%`, or `top 80%` scrubbed | When the reveal begins                          |
| `end`     | ScrollTrigger position    | `bottom 45%`                     | Where a scrub finishes                          |
| `step`    | milliseconds              | as `revealText`                  | The gap between pieces                          |
| `pattern` | any pattern               | `enter`                          | The duration and curve of each piece            |
| `scope`   | an element                | the document                     | Limits selector strings to one part of the page |

Under reduced motion `textReveal` doesn't split and the text is shown as it is.
Keep a scrub to one statement per page, because it asks the reader to scroll at
its pace.

Everything is built inside `gsap.matchMedia`, so it rebuilds when the motion
preference changes and returns a cleanup that restores every element.

## Liquid selection

`liquid()` moves one indicator between the items of a group. It squashes as it
leaves, stretches past the target and settles on the spring ease, so a tab,
segment or filter seems to flow into place rather than slide. It watches
`aria-selected`, `aria-pressed`, `aria-checked`, `aria-current` and
`data-state`, so it follows whatever already marks the active item.

**liquid()**

```html
<link rel="stylesheet" href="@nana-tec/ui-motion/utilities.css" />

<div role="tablist" data-nana-liquid>
  <span data-nana-liquid-indicator></span>
  <button role="tab" aria-selected="true" data-nana-liquid-item>Day</button>
  <button role="tab" aria-selected="false" data-nana-liquid-item>Week</button>
</div>

<script type="module">
  import { liquid } from "@nana-tec/ui-motion/dom";
  const stop = liquid(document.querySelector("[data-nana-liquid]"));
</script>
```

The indicator only changes its `clip-path`, never its box, so it can't overflow
a scrolling container. A move that starts mid-flight picks up from where the
indicator is. `--nana-liquid-radius` sets its corners, defaulting to
`--nana-radius-full`. Under reduced motion it jumps straight to the new item.

## Smooth scrolling with Lenis

Lenis eases wheel and touch input toward its target. The sample runs it inside
a scroll area. Turn it off to compare with native scrolling.

**createSmoothScroll()**

```ts
import "@nana-tec/ui-motion/scroll.css";
import { createSmoothScroll } from "@nana-tec/ui-motion/scroll";
import { gsapScrollDriver } from "@nana-tec/ui-motion/gsap";

const scroll = createSmoothScroll({ driver: gsapScrollDriver() });

scroll.scrollTo("#pricing");
dialog.addEventListener("nana-open", scroll.stop);
dialog.addEventListener("nana-close", scroll.start);
```

Under reduced motion Lenis isn't created at all, and the browser scrolls
natively.

### Scroll CSS

`scroll.css` holds the rules Lenis expects, smooth native anchor scrolling, and
a scroll area with a quiet scrollbar:

```css
@import "@nana-tec/ui-motion/scroll.css";

:root {
  --nana-scroll-offset: 4.5rem;
}
```

| Class or variable                                  | Effect                                                     |
| -------------------------------------------------- | ---------------------------------------------------------- |
| `--nana-scroll-offset`                             | Keeps anchors and focused targets clear of a sticky header |
| `.nana-scroll-area`                                | Contained overscroll, stable gutter, a thin scrollbar      |
| `.nana-scroll-fade`                                | Fades content in and out at the top and bottom edges       |
| `.nana-scroll-snap`                                | Children snap gently into place                            |
| `--nana-scrollbar-thumb`, `--nana-scrollbar-track` | Scrollbar colours                                          |

Native smooth scrolling turns itself off under reduced motion and whenever
Lenis is running, so the two never fight.

## Reduced motion

When someone asks for reduced motion, distances become zero and scales become
one, but fades stay. A dialog still fades in, so a change on screen is never
silent. It just stops moving.
