# sweepPage

> A page that turns behind a wave of colour: the page leans in towards where the wave will come from while the work runs and is struck further in when it is done, a wave crosses the screen, bending and blurring the page as it passes and leaving its colour on the edges, and the next page is there behind it. You choose where it comes from and what it is coloured with.

```tsx
import { HugeiconsIcon } from '@hugeicons/react'
import { ArrowUp02Icon } from '@hugeicons/core-free-icons'
import { useState } from 'react'

import { GlassActionButton } from '@/components/liquid-glass'

// The wave's four colours, from the back of it to its front: deep, vivid, light, pale.
const GREEN = ['#009646', '#35ba00', '#8ceb5a', '#c4ff78']

const COLS = 13
const ROWS = 7

/** 1 around the middle of the grid, falling to 0 at its edge. */
const fade = (col: number, row: number) => {
  const distance = Math.hypot((col - (COLS - 1) / 2) / (COLS / 2), (row - (ROWS - 1) / 2) / (ROWS / 2))
  return Math.min(1, Math.max(0, (1 - distance) / 0.45))
}

// Press it: the page leans in towards the button while the payment runs and is struck further in
// when it is done; the button lands its success (the glass swells and turns green, a check draws
// itself in) and a wave of colour opens from under it over the whole screen, with the next page
// behind it.
// The button is a GlassActionButton with `sweep`: its own action is the work the page waits on (a
// timer stands in for the request here) and `change` is what turns the page. It runs inside a
// view transition, so the new page has to be there when it returns: the button flushes the update.
// `from: 'center'` is a ring out of the button; leave it out for a wave from the top of the screen.
// `colors` makes the wave green, as the button turns: that green is the button's own class, read
// from its `data-state`. `icon` is the droplet's arrow, pointing up here.
// The button takes no second press until the turn is over: the sweep sees to that. Where nothing
// can play (reduced motion, no WebGL, no view transitions) the page just turns.
// Behind the button, only the Press demo's fine grid on the page's own colour, centred on it:
// plain DOM, every cell draws its own top and left line, fainter towards the edge.
export default function Demo() {
  const [paid, setPaid] = useState(false)
  // Changed to hand the button back: its droplet splits off again and the label morphs back.
  const [order, setOrder] = useState(0)
  return (
    <div className="relative isolate flex h-[22rem] w-full max-w-xl flex-col items-center justify-center gap-6 text-center">
      <div aria-hidden className="absolute top-1/2 left-1/2 -z-10 grid -translate-x-1/2 -translate-y-1/2 grid-cols-[repeat(13,40px)]">
        {Array.from({ length: COLS * ROWS }, (_, i) => (
          <span key={i} className="relative size-10" style={{ opacity: fade(i % COLS, Math.floor(i / COLS)) }}>
            <span className="absolute inset-x-0 top-0 h-px bg-black/10 dark:bg-white/10" />
            <span className="absolute inset-y-0 left-0 w-px bg-black/10 dark:bg-white/10" />
          </span>
        ))}
      </div>
      {/* As tall above the button as below it, so the button stays in the middle of the grid. */}
      <p className="flex h-10 items-end text-4xl font-semibold tracking-tight text-neutral-900 tabular-nums dark:text-white">{paid ? 'Paid' : '$48.00'}</p>
      <GlassActionButton
        resetKey={order}
        size="lg"
        material="tinted"
        className="bg-neutral-900 text-white transition-colors duration-300 data-[state=success]:bg-[#30d158] data-[state=success]:text-neutral-950 dark:bg-white dark:text-neutral-900 dark:data-[state=success]:bg-[#30d158] dark:data-[state=success]:text-neutral-950"
        pendingLabel="Paying"
        successLabel="Paid"
        onAction={() => new Promise((done) => setTimeout(done, 600))}
        icon={<HugeiconsIcon icon={ArrowUp02Icon} strokeWidth={2} />}
        sweep={{ from: 'center', colors: GREEN, change: () => setPaid(true) }}
      >
        Pay now
      </GlassActionButton>
      <p className="h-10 text-sm text-neutral-600 dark:text-neutral-400">
        {paid ? (
          <button
            type="button"
            onClick={() => {
              setPaid(false)
              setOrder((n) => n + 1)
            }}
            className="cursor-pointer underline underline-offset-4 hover:text-neutral-900 dark:hover:text-white"
          >
            Back to the order
          </button>
        ) : (
          'Two tickets, Friday at 20:00'
        )}
      </p>
    </div>
  )
}
```

**Use it for**

- The one step that changes everything on the screen: signing in, paying, opening the product from its landing page.
- A page that has to wait for something first (a route that loads, a request): the lean is the wait, and the band leaves when it is over.
- The end of a Slide to Confirm: the page starts leaning in while the thumb is still being pulled (`pullPage`).

**Not for**

- Every link and every tab: it takes the whole screen for two seconds. Ordinary navigation just navigates.
- Something that changes a part of the page: a Dialog, a Popover or an Accordion opens where it is.
- News nobody asked for: that is Toast. Its page leans in the same way, and stays the same page.

```bash
npx shadcn@latest add https://liquidglass.onemorethink.dev/r/sweep.json
```

> Sweep needs no package and is not a React component: it is a function you call. The turn is a view transition (the View Transitions API), and the band and the lean are drawn with WebGL. Where one of them is missing, or with reduced motion on, `sweepPage` plays nothing and returns `false`: turn the page yourself, as the examples do. It brings its own CSS, added to the page on the first sweep.

## Usage

```tsx
import { GlassButton } from '@/components/liquid-glass'
import { sweepFrom, sweepPage } from '@/components/liquid-glass/glass-sweep'

function open(button: Element) {
  const work = router.preloadRoute({ to: '/app' })      // what the page waits on
  const change = () => router.navigate({ to: '/app' })  // what turns it
  // false: nothing plays here (reduced motion, no WebGL, no view transitions).
  if (!sweepPage({ ...sweepFrom(button), work, change })) work.then(change)
}

<GlassButton onClick={(event) => open(event.currentTarget)}>Open the app</GlassButton>
```

`sweepFrom(control)` gives the sweep what it needs from the control that was pressed: the point the page leans in towards, which is where the band will come from (the place on that side of the screen in line with the control, or the control itself for a ring), and the control itself, which is left as it is while the page leans in. `work` is a promise the page waits on. The page leans in for as long as it takes, a second and a half at the least, and is struck further in when it settles. Then `change` runs, inside a view transition: whatever it does (a navigation, a state update flushed with `flushSync`), the new page has to be there when it returns or resolves. The band crosses, with the old page still ahead of it and the new one behind, and a ripple leaves the control through the old page. The new page takes presses as soon as the band's front has left the screen, and a press, a scroll or a key ends the turn at once. One sweep plays at a time, and what was pressed takes no second press until the turn is over (it is `inert` for that long). A `work` that fails lets the page go without turning it.

## Where it comes from, and its colours

`from` is where the band comes from: `top` (the default), `bottom`, `left` or `right` send a band across the screen from that side, its ends trailing its middle; `center` opens a ring from under the control instead: the band is drawn around the control, never over it, and the control stays in front until the ring has left it behind. The page leans in towards the same place the band comes from, so the bend and the light are one thing. `colors` is four colours of your own, as hex; `null` is the kit's own palette (cyan, blue, indigo, purple). A band given colours is a front with a wake: a pale line at the front, the brightest colour right behind it, and a wake that deepens towards where it came from, with specks of light in it. The four are read from the back of the wake to its front: deep, vivid, light, pale. Give them to one call, or set them once for the whole app on `SWEEP`, the object every sweep reads its defaults from. Choose below and play it: a set fills the four colours, and each of the four can be changed. What you see is what the call under the button gives you.

### Choose a side and four colours, then play it

```tsx
import { useRef, useState } from 'react'
import { flushSync } from 'react-dom'

import { GlassButton, GlassTabs } from '@/components/liquid-glass'
import { sweepFrom, sweepPage, type SweepFrom, type SweepLook } from '@/components/liquid-glass/glass-sweep'

// Sets of four to start from, each read from the back of the band's wake to its front.
// `null` is the kit's own palette.
const SETS: { name: string; colors: string[] | null }[] = [
  { name: 'Kit', colors: null },
  { name: 'Green', colors: ['#0d4d1e', '#3fae2a', '#86d44a', '#e4f5dc'] },
  { name: 'Ocean', colors: ['#18c8ff', '#2f6bff', '#5b3dff', '#19e0c4'] },
  { name: 'Sunset', colors: ['#ffc233', '#ff7a2f', '#ff3d6e', '#b45cff'] },
  { name: 'Candy', colors: ['#ff5ac8', '#ffc233', '#30d5ff', '#8a5cff'] },
  { name: 'Mono', colors: ['#f0f0f5', '#b9bcc8', '#f0f0f5', '#8f93a3'] },
]
/** What the four fields show while the kit's palette is on: its own colours, near enough. */
const KIT = ['#35d6f2', '#2f7dff', '#5a4bff', '#9a4dff']
const same = (a: string[] | null, b: string[] | null) => (a && b ? a.join() === b.join() : a === b)

const COLS = 13
const ROWS = 9

/** 1 around the middle of the grid, falling to 0 at its edge. */
const fade = (col: number, row: number) => {
  const distance = Math.hypot((col - (COLS - 1) / 2) / (COLS / 2), (row - (ROWS - 1) / 2) / (ROWS / 2))
  return Math.min(1, Math.max(0, (1 - distance) / 0.45))
}

// Choose what crosses the screen, where it comes from and what it is coloured with, then play it:
// what you see is what `look`, `from` and `colors` give you. Wave bends and blurs the page as it
// passes and leaves its colour on the edges; Band is the band of colour that came before it. A side of the screen sends a band across it; Button
// (`center`) opens a ring from under the button, and the page leans in towards the same place the
// band comes from. A set fills the four colours, and each of the
// four can be changed: a band given colours is a front with a wake, and reads them from the back
// of the wake to its front (deep, vivid, light, pale). Kit is the kit's own palette
// (`colors: null`), a crest with no wake.
// The line under the button is the call as it stands, ready to copy.
// Behind the button, only the Press demo's fine grid on the page's own colour, centred on it:
// plain DOM, every cell draws its own top and left line, fainter towards the edge.
export default function Demo() {
  const [look, setLook] = useState<SweepLook>('wave')
  const [from, setFrom] = useState<SweepFrom>('top')
  const [colors, setColors] = useState(SETS[2].colors)
  const [turned, setTurned] = useState(false)
  const turning = useRef(false)

  const play = (button: Element) => {
    if (turning.current) return
    turning.current = true
    const work = new Promise((done) => setTimeout(done, 300))
    const change = () => {
      turning.current = false
      flushSync(() => setTurned((was) => !was))
    }
    if (!sweepPage({ ...sweepFrom(button, from), look, colors, work, change })) work.then(change)
  }

  return (
    // Three rows, the outer two as tall as each other: the button stays in the middle of the grid.
    <div className="relative isolate grid h-[27rem] w-full max-w-xl grid-rows-[1fr_auto_1fr] justify-items-center text-neutral-900 dark:text-white">
      <div aria-hidden className="absolute top-1/2 left-1/2 -z-10 grid -translate-x-1/2 -translate-y-1/2 grid-cols-[repeat(13,40px)]">
        {Array.from({ length: COLS * ROWS }, (_, i) => (
          <span key={i} className="relative size-10" style={{ opacity: fade(i % COLS, Math.floor(i / COLS)) }}>
            <span className="absolute inset-x-0 top-0 h-px bg-black/10 dark:bg-white/10" />
            <span className="absolute inset-y-0 left-0 w-px bg-black/10 dark:bg-white/10" />
          </span>
        ))}
      </div>
      <div className="flex flex-col items-center justify-end gap-3 pb-6">
        <GlassTabs
          aria-label="What crosses the screen"
          size="sm"
          value={look}
          onValueChange={setLook}
          options={[
            { value: 'wave', label: 'Wave' },
            { value: 'band', label: 'Band' },
          ]}
        />
        <GlassTabs
          aria-label="Where the band comes from"
          size="sm"
          value={from}
          onValueChange={setFrom}
          options={[
            { value: 'top', label: 'Top' },
            { value: 'bottom', label: 'Bottom' },
            { value: 'left', label: 'Left' },
            { value: 'right', label: 'Right' },
            { value: 'center', label: 'Button' },
          ]}
        />
        <div role="group" aria-label="Colours" className="flex max-w-[13rem] flex-wrap justify-center gap-1 sm:max-w-none">
          {SETS.map((set) => {
            const on = same(colors, set.colors)
            return (
              <button
                key={set.name}
                type="button"
                aria-pressed={on}
                onClick={() => setColors(set.colors)}
                className={`h-7 rounded-full px-3 text-xs font-medium transition-colors ${on ? 'bg-neutral-900 text-white dark:bg-white dark:text-neutral-900' : 'bg-black/[0.05] text-neutral-600 hover:text-neutral-900 dark:bg-white/[0.08] dark:text-neutral-400 dark:hover:text-white'}`}
              >
                {set.name}
              </button>
            )
          })}
        </div>
        {/* The four colours of the band, from the back of its wake to its front. Each can be changed. */}
        <div className="flex h-9 items-center gap-2">
          {(colors ?? KIT).map((color, i) => (
            <input
              key={i}
              type="color"
              aria-label={`Colour ${i + 1}`}
              value={color}
              onChange={(event) => setColors((colors ?? KIT).map((was, j) => (j === i ? event.target.value : was)))}
              className="size-9 cursor-pointer rounded-full border-0 bg-transparent p-0 [&::-moz-color-swatch]:rounded-full [&::-moz-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-full [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0"
            />
          ))}
        </div>
      </div>
      <GlassButton size="lg" onClick={(event) => play(event.currentTarget)}>
        {turned ? 'Play it back' : 'Play'}
      </GlassButton>
      <div className="flex flex-col items-center gap-3 px-4 pt-6 text-center">
        <p className="text-sm font-medium">{turned ? 'Page two' : 'Page one'}</p>
        <code className="max-w-full font-mono text-xs break-words text-neutral-600 dark:text-neutral-400">
          sweepPage({'{'} ...sweepFrom(button, '{from}'), look: '{look}', colors: {colors ? `['${colors.join("', '")}']` : 'null'}, work, change {'}'})
        </code>
      </div>
    </div>
  )
}
```

```tsx
import { SWEEP, sweepFrom, sweepPage } from '@/components/liquid-glass/glass-sweep'

// From the back of the wake to its front: deep, vivid, light, pale.
const GREEN = ['#0d4d1e', '#3fae2a', '#86d44a', '#e4f5dc']

// For one call:
sweepPage({ ...sweepFrom(button, 'left'), colors: GREEN, work, change })

// Or once, for every sweep in the app:
SWEEP.from = 'left'
SWEEP.colors = GREEN
```

## After a slide

A Slide to Confirm is pulled before it is confirmed, and the page can lean in with the pull: `pullPage(slider)` draws the page in a little as the thumb goes, and takes it back with the thumb when it is let go early. The `sweepPage` that the slide's `onConfirm` calls carries on from where the slide left the page. Give it the slide itself, the element with `role="slider"`. A box around the slide marked `data-sweep-keep` is what the page leans in around, instead of the track alone: a held thumb's shadow falls outside the track, and the picture of the page would cut it off there. Something above the control that moves by itself (a marquee) is marked `data-sweep-above`, and the lean stops short of it.

```tsx
import { useEffect, useRef } from 'react'

import { GlassSlideToConfirm } from '@/components/liquid-glass'
import { pullPage, sweepFrom, sweepPage } from '@/components/liquid-glass/glass-sweep'

const slide = useRef<HTMLDivElement>(null)
const slider = () => slide.current?.querySelector('[role="slider"]')

// The page leans in as the thumb is pulled. What it returns stops it.
useEffect(() => {
  const control = slider()
  if (control) return pullPage(control)
}, [])

const open = () => {
  const work = router.preloadRoute({ to: '/app' })
  const change = () => router.navigate({ to: '/app' })
  const control = slider()
  if (!control || !sweepPage({ ...sweepFrom(control), work, change })) work.then(change)
  return work  // the slide shows its spinner until then
}

// Room for the thumb's shadow: the page leans in around this box.
<div ref={slide} data-sweep-keep="" className="rounded-[80px] px-8 pt-3 pb-16">
  <GlassSlideToConfirm onConfirm={open}>Slide to open</GlassSlideToConfirm>
</div>
```

## The numbers

What crosses the screen is a wave (`SWEEP.look`, `'wave'`): it bends and blurs the page along its front, throws particles ahead and leaves its colour on the edges of the screen, and the new page is the page itself right behind it. It is Jakub Antalik's Distortion Waves (libraries.dev/waves, MIT), its two files taken whole into the kit (`glass-wave-model.ts`, `glass-wave-renderer.ts`); its own numbers go in `SWEEP.wave`, over the defaults of its type, and `SWEEP.letGo` is how long the page takes to let go as it leaves. `look: 'band'` is the band that came before it, and where there is no WebGL2 the band plays in its place. Everything else about the turn is a number on `SWEEP`, read as each sweep begins: how long the page leans in (`gather`), how far in it waits and how far the blow takes it (`hold`, `strike`), the ripple that leaves the control (`ripple`, `rippleRun`), how long the page takes to let go and the band to cross (`release`, `run`), how narrow and how curved the band is (`tight`, `curve`), its brightness on a light page and on a dark one (`brightness`, `dim`), the wake a band with colours of its own leaves, the line at its front and the specks of light in it (`wake`, `line`, `dots`; with `wake` at 0 that band is a crest like the palette's, its four colours run into one another), and how far a slide draws the page in (`drag`). Each is described in `glass-sweep.ts`. They are tuned together: change one at a time, and leave them alone if the turn already looks right. The motion is ported from glimm (glimm.dev, MIT); what was taken and what is different is written at the top of the file.

## A turn of its own

One turn in an app can differ from the rest without touching `SWEEP`: `tune` takes any of its numbers for that call alone. This site's theme switch is such a turn. It is glimm's "Toggle the theme" (glimm.dev/demos/theme, MIT), with that demo's numbers: the page leans in all the way in 620 ms with nothing to wait on, the theme changes, and a narrower band takes 2.7 s to come down, with the new theme behind it. A `hold` that is no less than `strike` leaves nothing for a blow: the page then softens and the band comes up to strength with the lean itself. Two numbers exist for a turn like this one, and are off by default. `soft` lets the old page run into the new one under the band (in half-widths of the band, either side of its crest; 0 cuts the old page along the crest), which a turn between a light page and a dark one needs: a cut shows as a line there. `dusk` darkens the rest of the page a little while it leans in. `palette` is the cosine palette the band reads when `colors` is `null`.

```tsx
import { sweepFrom, sweepPage } from '@/components/liquid-glass/glass-sweep'

// glimm's theme demo: a quick lean with no blow, a narrow band, a soft edge.
const TURN = { gather: 620, hold: 1, strike: 1, snap: 440, release: 220, run: 2700, tight: 28, curve: 0.12, alpha: 1.1, brightness: 1.15, dim: 1.15, swell: 0.15, tones: 0, soft: 1.2, dusk: 0.09 }

function turnTheme(next: 'light' | 'dark', button: Element) {
  const change = () => document.documentElement.setAttribute('data-theme', next)
  if (!sweepPage({ ...sweepFrom(button, 'top'), tune: TURN, work: Promise.resolve(), change })) change()
}
```

## API reference

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `sweepPage(options)` | `(options) => boolean` | — | Turns the page behind a band. Returns `false` when nothing plays (reduced motion, no WebGL, no view transitions, a hidden page, or a sweep already on the screen): `change` is not called then. |
| `work` | `Promise<unknown>` | — | What the page waits on. It leans in for as long as this takes (`SWEEP.gather` ms at the least), and the band leaves when it settles. If it rejects, the page is let go and nothing turns. |
| `change` | `() => unknown` | — | Turns the page. It runs inside the view transition, so what it returns is waited for, 200 ms at most: a page that takes longer is not held under a still picture, and the band runs over it once it is there. |
| `from` | `'top' \| 'bottom' \| 'left' \| 'right' \| 'center'` | `SWEEP.from (top)` | Where the band comes from: a side of the screen, or `center`, a ring that opens from `at`, from under the control. |
| `colors` | `string[] \| null` | `SWEEP.colors (null)` | Four colours of your own (hex), read from the back of the band's wake to its front: deep, vivid, light, pale. `null` is the kit's palette. |
| `at` | `{ x: number; y: number }` | — | The point of the viewport the page leans in towards, in CSS px. `sweepFrom` gives where the band comes from: the place on that side of the screen in line with the control, or the control's middle for `center`. |
| `keep` | `Element` | — | The element that was pressed: it is left as it is, live, while the page leans in around it, and takes no press until the turn is over. `sweepFrom` gives the control, or the box around it marked `data-sweep-keep`. |
| `under` | `Element` | `keep` | What a ring (`center`) comes out from under: the band is drawn around it, and it stays in front until the ring has left it behind. `sweepFrom` gives the control itself. |
| `span` | `number` | — | How far the lean reaches, in CSS px. Default: the shorter side of the screen. `sweepFrom` stops it short of anything above the control marked `data-sweep-above`. |
| `above` | `number` | — | A line of the viewport the lean does not reach above, in CSS px from its top: what runs by itself up there (a marquee) is left alone. `sweepFrom` gives the bottom of anything above the control marked `data-sweep-above`. |
| `look` | `'wave' \| 'band'` | `SWEEP.look (wave)` | What crosses the screen: `wave`, which bends and blurs the page as it passes, or `band`, the band of colour that came before it: a crest in the kit's palette, a front with a wake in your colours (Mono among the sets of the example above). |
| `tune` | `Partial<typeof SWEEP>` | — | Numbers of `SWEEP` for this turn alone (see "A turn of its own"). `from` and `colors` win over it. |
| `sweepFrom(control, from?)` | `(Element, from?) => { at, keep, under, span, above, from }` | — | What a sweep from a control is given, ready to spread into `sweepPage`. The point is where the band comes from: on a side, the place of that side in line with the control; with `center`, the control's middle, or for a slide the far end of its track, where the slide ended. |
| `pullPage(slider, from?)` | `(Element, from?) => () => void` | — | The page leans in as a slide is pulled, before its sweep; `slider` is the element with `role="slider"`. Returns what stops it. |
| `warmSweep(control?, from?)` | `(Element?, from?) => () => void` | — | Makes what the first sweep needs ahead of it, while the page is idle: the lean's picture of the page and the shaders of the lean and of the wave. Made as they are first needed, they are made in the middle of the gesture, and the first turn drops frames a repeat does not. `pullPage` calls it by itself, `SWEEP.warm` ms after it is called (0: never); call it yourself for a sweep that starts from a button. Returns what stops it. |
| `SWEEP` | `object` | — | The defaults every sweep reads as it begins: `from`, `colors`, and the numbers of the turn (see above). |

Source: https://liquidglass.onemorethink.dev/docs/sweep
