Many elements at once
A Wardic element carries its own animation: its values, its springs, and the work of starting and stepping them. A few dozen on a page cost little. For hundreds or thousands of like elements moving on the same keys, such as a grid's tiles, a long list or a chart's points, createBatch animates them as one Batch. Every member's values, speeds and targets are kept together, and each frame steps them all in one run. Changing a thousand members' targets costs about a twentieth of changing them one at a time, and each frame about half (measured).
A grid that shuffles
import { createBatch, stagger } from "@wardic/solid"
import { createSignal, For, isPending, onSettled } from "solid-js"
import { framesPerSecond } from "../frames.ts"
const COLUMNS = 40
const STEP = 7
const TILES: ReadonlyArray<number> = Array.from({ length: 1000 }, (_, id) => id)
/** The `i`th place in the grid. */
const placeOf = (i: number) => ({ x: (i % COLUMNS) * STEP, y: Math.floor(i / COLUMNS) * STEP })
const shuffled = (ids: ReadonlyArray<number>): ReadonlyArray<number> => {
const out = [...ids]
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[out[i], out[j]] = [out[j], out[i]]
}
return out
}
/** A thousand tiles in one Batch: each order sends every tile to its new place in one change. */
export default function Tiles() {
const [order, setOrder] = createSignal(TILES)
const [fps, setFps] = createSignal<number>()
onSettled(() => framesPerSecond(setFps))
// Keyed by tile, so a new order moves each tile from where it is, at the speed it has.
const tiles = createBatch({
each: order,
key: (id) => id,
initial: (_, i) => ({ ...placeOf(i), scale: 0, opacity: 0 }),
animate: (_, i) => ({ ...placeOf(i), scale: 1, opacity: 1 }),
// stagger() counts the tiles a change moves.
transition: { type: "spring", visualDuration: 0.6, bounce: 0.2, delay: stagger(0.0004) },
})
const sorted = () => order() === TILES
return (
<div class="sample-stack">
<button class="sample-button" onClick={() => setOrder(sorted() ? shuffled(TILES) : TILES)}>
{sorted() ? "Shuffle" : "Sort"}
</button>
<div class="sample-tiles">
<For each={TILES}>{(id) => <div class="sample-tile" {...tiles.member(id, { style: { background: `hsl(${190 + id * 0.15} 60% 62%)` } })} />}</For>
</div>
<p class="sample-note">
1,000 tiles · {isPending(() => tiles.settled()) ? "Moving…" : "Ready"} · {fps() ?? "–"} fps
</p>
</div>
)
}import { createBatch, stagger } from "@wardic/solid/v1"
import { createSignal, For, onCleanup, onMount } from "solid-js"
import { framesPerSecond } from "../frames.ts"
const COLUMNS = 40
const STEP = 7
const TILES: ReadonlyArray<number> = Array.from({ length: 1000 }, (_, id) => id)
/** The `i`th place in the grid. */
const placeOf = (i: number) => ({ x: (i % COLUMNS) * STEP, y: Math.floor(i / COLUMNS) * STEP })
const shuffled = (ids: ReadonlyArray<number>): ReadonlyArray<number> => {
const out = [...ids]
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[out[i], out[j]] = [out[j], out[i]]
}
return out
}
/** A thousand tiles in one Batch: each order sends every tile to its new place in one change. */
export default function Tiles() {
const [order, setOrder] = createSignal(TILES)
const [moving, setMoving] = createSignal(false)
const [fps, setFps] = createSignal<number>()
onMount(() => onCleanup(framesPerSecond(setFps)))
// Keyed by tile, so a new order moves each tile from where it is, at the speed it has.
const tiles = createBatch({
each: order,
key: (id) => id,
initial: (_, i) => ({ ...placeOf(i), scale: 0, opacity: 0 }),
animate: (_, i) => ({ ...placeOf(i), scale: 1, opacity: 1 }),
// stagger() counts the tiles a change moves.
transition: { type: "spring", visualDuration: 0.6, bounce: 0.2, delay: stagger(0.0004) },
onAnimationStart: () => setMoving(true),
onAnimationComplete: () => setMoving(false),
})
const sorted = () => order() === TILES
return (
<div class="sample-stack">
<button class="sample-button" onClick={() => setOrder(sorted() ? shuffled(TILES) : TILES)}>
{sorted() ? "Shuffle" : "Sort"}
</button>
<div class="sample-tiles">
<For each={TILES}>{(id) => <div class="sample-tile" {...tiles.member(id, { style: { background: `hsl(${190 + id * 0.15} 60% 62%)` } })} />}</For>
</div>
<p class="sample-note">
1,000 tiles · {moving() ? "Moving…" : "Ready"} · {fps() ?? "–"} fps
</p>
</div>
)
}import { animate } from "motion/react"
import { useEffect, useRef, useState } from "react"
import { framesPerSecond } from "../frames.ts"
const COLUMNS = 40
const STEP = 7
const TILES: ReadonlyArray<number> = Array.from({ length: 1000 }, (_, id) => id)
/** The `i`th place in the grid. */
const placeOf = (i: number) => ({ x: (i % COLUMNS) * STEP, y: Math.floor(i / COLUMNS) * STEP })
const shuffled = (ids: ReadonlyArray<number>): ReadonlyArray<number> => {
const out = [...ids]
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[out[i], out[j]] = [out[j], out[i]]
}
return out
}
const SPRING = { type: "spring", visualDuration: 0.6, bounce: 0.2 } as const
/** A thousand tiles: each order sends every tile to its new place, an animation per tile. */
export default function Tiles() {
const tiles = useRef<Array<HTMLDivElement | null>>([])
const entered = useRef(false)
const runs = useRef(0)
const [order, setOrder] = useState(TILES)
const [moving, setMoving] = useState(false)
const [fps, setFps] = useState<number>()
useEffect(() => framesPerSecond(setFps), [])
// Motion has no Batch: each tile runs on its own, staggered by its place.
useEffect(() => {
const run = ++runs.current
setMoving(true)
const moves = order.map((id, i) => {
const tile = tiles.current[id]
if (tile === null || tile === undefined) return undefined
const { x, y } = placeOf(i)
// Its entrance, from nothing at its place; after it, from where it is.
const to = entered.current ? { x, y } : { x: [x, x], y: [y, y], scale: [0, 1], opacity: [0, 1] }
return animate(tile, to, { ...SPRING, delay: i * 0.0004 })
})
entered.current = true
Promise.all(moves).then(() => {
if (run === runs.current) setMoving(false)
})
}, [order])
const sorted = order === TILES
return (
<div className="sample-stack">
<button className="sample-button" onClick={() => setOrder(sorted ? shuffled(TILES) : TILES)}>
{sorted ? "Shuffle" : "Sort"}
</button>
<div className="sample-tiles">
{TILES.map((id) => (
<div
key={id}
className="sample-tile"
ref={(tile) => {
tiles.current[id] = tile
}}
style={{ background: `hsl(${190 + id * 0.15} 60% 62%)`, opacity: 0 }}
/>
))}
</div>
<p className="sample-note">
1,000 tiles · {moving ? "Moving…" : "Ready"} · {fps ?? "–"} fps
</p>
</div>
)
}- One Batch for the grid, keyed by tile:
eachis the order, andkeyeach tile's id.animate(tile, i)gives a tile its place from its index in the order now, so a new order turns every tile toward its new place in one change, each from where it is and at the speed it has. Press Sort while they're still on their way and each one changes course without stopping. tiles.member(id, { style })is a tile's handle, spread onto its element. Give the element's ownstyleto the handle, not beside it: the Batch drawstransformandopacityover the rest.- The tiles render once.
<For each={TILES}>makes the thousand elements, and a new order changes only what the Batch reads. stagger()counts the tiles a change moves, so the wave runs through the ones that go somewhere.- "Moving…" and "Ready" come from the Batch's landings: on Solid 2
tiles.settled(), pending while any tile moves; on Solid 1onAnimationStartandonAnimationComplete. The frame rate is the page's own readout, the frames it drew in each second (site/samples/frames.ts).
The demo's Mosaic and Lines turn the same tiles to Wardic's mark, a tile to each of its cells, or shrunk and turned along its strokes: each drawing is one change of the Batch's targets, as a shuffle is. Shuffle and Sort work in them too: a tile's cell is its place in the order, and its colour its own, so a shuffled mark is scrambled until Sort puts it back together. They're the demo's alone (demo.tsx).
Motion has no Batch. Its tab runs the same grid through animate(), a call per tile, as createAnimate would.
Sierpiński's triangle, at scale
import { createBatch } from "@wardic/solid"
import { createSignal, For, isPending, onSettled } from "solid-js"
import { framesPerSecond } from "../frames.ts"
import { colorOf, DEPTH, HEIGHT, LEAVES, leafAt, WIDTH } from "./triangle.ts"
const LEAF_INDICES: ReadonlyArray<number> = Array.from({ length: LEAVES }, (_, i) => i)
export const SPRING = { type: "spring", visualDuration: 0.5, bounce: 0.25 } as const
/** Sierpiński's triangle in 2,187 leaves, one Batch: a new depth moves every leaf in one change. */
export default function Sierpinski() {
const [depth, setDepth] = createSignal(0)
const [fps, setFps] = createSignal<number>()
// Its entrance climbs a level every 0.7 s, to 5, until the slider takes over.
let climb: ReturnType<typeof setInterval> | undefined
onSettled(() => {
let steps = 0
climb = setInterval(() => {
steps++
setDepth(steps)
if (steps === 5) clearInterval(climb)
}, 700)
const stopFrames = framesPerSecond(setFps)
return () => {
clearInterval(climb)
stopFrames()
}
})
const leaves = createBatch({
count: LEAVES,
initial: false,
animate: (i) => leafAt(i, depth()),
transition: SPRING,
})
return (
<div class="sample-stack">
<div class="sample-sierpinski" style={{ width: `${WIDTH}px`, height: `${HEIGHT}px` }}>
<For each={LEAF_INDICES}>{(i) => <div class="sample-leaf" {...leaves.at(i, { style: { color: colorOf(i) } })} />}</For>
</div>
<label class="sample-range">
Depth {depth()} · {(3 ** depth()).toLocaleString("en")} triangles
<input
type="range"
min="0"
max={DEPTH}
value={depth()}
onInput={(event) => {
clearInterval(climb)
setDepth(event.currentTarget.valueAsNumber)
}}
/>
</label>
<p class="sample-note">
{LEAVES.toLocaleString("en")} elements · {isPending(() => leaves.settled()) ? "Moving…" : "Ready"} · {fps() ?? "–"} fps
</p>
</div>
)
}import { createBatch } from "@wardic/solid/v1"
import { createSignal, For, onCleanup, onMount } from "solid-js"
import { framesPerSecond } from "../frames.ts"
import { colorOf, DEPTH, HEIGHT, LEAVES, leafAt, WIDTH } from "./triangle.ts"
const LEAF_INDICES: ReadonlyArray<number> = Array.from({ length: LEAVES }, (_, i) => i)
const SPRING = { type: "spring", visualDuration: 0.5, bounce: 0.25 } as const
/** Sierpiński's triangle in 2,187 leaves, one Batch: a new depth moves every leaf in one change. */
export default function Sierpinski() {
const [depth, setDepth] = createSignal(0)
const [moving, setMoving] = createSignal(false)
const [fps, setFps] = createSignal<number>()
// Its entrance climbs a level every 0.7 s, to 5, until the slider takes over.
let climb: ReturnType<typeof setInterval> | undefined
onMount(() => {
let steps = 0
climb = setInterval(() => {
steps++
setDepth(steps)
if (steps === 5) clearInterval(climb)
}, 700)
onCleanup(framesPerSecond(setFps))
})
onCleanup(() => clearInterval(climb))
const leaves = createBatch({
count: LEAVES,
initial: false,
animate: (i) => leafAt(i, depth()),
transition: SPRING,
onAnimationStart: () => setMoving(true),
onAnimationComplete: () => setMoving(false),
})
return (
<div class="sample-stack">
<div class="sample-sierpinski" style={{ width: `${WIDTH}px`, height: `${HEIGHT}px` }}>
<For each={LEAF_INDICES}>{(i) => <div class="sample-leaf" {...leaves.at(i, { style: { color: colorOf(i) } })} />}</For>
</div>
<label class="sample-range">
Depth {depth()} · {(3 ** depth()).toLocaleString("en")} triangles
<input
type="range"
min="0"
max={DEPTH}
value={depth()}
onInput={(event) => {
clearInterval(climb)
setDepth(event.currentTarget.valueAsNumber)
}}
/>
</label>
<p class="sample-note">
{LEAVES.toLocaleString("en")} elements · {moving() ? "Moving…" : "Ready"} · {fps() ?? "–"} fps
</p>
</div>
)
}import { domAnimation, LazyMotion } from "motion/react"
import * as m from "motion/react-m"
import { useEffect, useRef, useState } from "react"
import { framesPerSecond } from "../frames.ts"
import { colorOf, DEPTH, HEIGHT, LEAVES, leafAt, WIDTH } from "./triangle.ts"
const LEAF_INDICES: ReadonlyArray<number> = Array.from({ length: LEAVES }, (_, i) => i)
const SPRING = { type: "spring", visualDuration: 0.5, bounce: 0.25 } as const
/** Sierpiński's triangle in 2,187 leaves, a motion.div each: a new depth retargets every one. */
export default function Sierpinski() {
const [depth, setDepth] = useState(0)
const [moving, setMoving] = useState(false)
const [fps, setFps] = useState<number>()
const climb = useRef<ReturnType<typeof setInterval>>(undefined)
// The leaves on their way: a retarget starts a leaf again without completing it, so each counts once.
const running = useRef(new Set<number>())
const started = (i: number) => {
if (running.current.size === 0) setMoving(true)
running.current.add(i)
}
const landed = (i: number) => {
running.current.delete(i)
if (running.current.size === 0) setMoving(false)
}
// Its entrance climbs a level every 0.7 s, to 5, until the slider takes over.
useEffect(() => {
let steps = 0
climb.current = setInterval(() => {
steps++
setDepth(steps)
if (steps === 5) clearInterval(climb.current)
}, 700)
const stopFrames = framesPerSecond(setFps)
return () => {
clearInterval(climb.current)
stopFrames()
}
}, [])
return (
<LazyMotion features={domAnimation}>
<div className="sample-stack">
<div className="sample-sierpinski" style={{ width: WIDTH, height: HEIGHT }}>
{LEAF_INDICES.map((i) => (
<m.div
key={i}
className="sample-leaf"
style={{ color: colorOf(i) }}
initial={false}
animate={leafAt(i, depth)}
transition={SPRING}
onAnimationStart={() => started(i)}
onAnimationComplete={() => landed(i)}
/>
))}
</div>
<label className="sample-range">
Depth {depth} · {(3 ** depth).toLocaleString("en")} triangles
<input
type="range"
min="0"
max={DEPTH}
value={depth}
onChange={(event) => {
clearInterval(climb.current)
setDepth(event.currentTarget.valueAsNumber)
}}
/>
</label>
<p className="sample-note">
{LEAVES.toLocaleString("en")} elements · {moving ? "Moving…" : "Ready"} · {fps ?? "–"} fps
</p>
</div>
</LazyMotion>
)
}Its 2,187 leaves are always mounted, one Batch by index (count), and at depth d they cover 3 ** d triangles, 243 at depth 5. Each leaf has an address, its number in base 3: at each level a 0 takes its triangle's top half, a 1 its bottom-left and a 2 its bottom-right. At depth d, a leaf sits on its ancestor d levels down, so the leaves sharing one cover it as one triangle:
// triangle.ts
export const leafAt = (i: number, depth: number): { x: number; y: number; scale: number } => {
let x = 0
let y = 0
let scale = 1
let leavesUnder = LEAVES
for (let level = 0; level < depth; level++) {
leavesUnder /= 3
const half = HALVES[Math.floor(i / leavesUnder) % 3]
x += half.x * scale * WIDTH
y += half.y * scale * HEIGHT
scale /= 2
}
return { x, y, scale }
}Its sizes, HALVES (each half's top-left corner as a share of its triangle) and the colours are in triangle.ts.
The slider changes the depth, and animate: (i) => leafAt(i, depth()) turns every leaf toward its new place in one change. Drag it back and forth and the leaves carry their speed through each turn. "A ward each" runs the same triangle with a Wardic element per leaf: compare the frame rate while it moves.
Hover and press
import { createBatch } from "@wardic/solid"
import { createEffect, createSignal, For } from "solid-js"
const COLUMNS = 12
const STEP = 24
const SWATCHES: ReadonlyArray<number> = Array.from({ length: 120 }, (_, i) => i)
const colX = (i: number) => (i % COLUMNS) * STEP
const rowY = (i: number) => Math.floor(i / COLUMNS) * STEP
/** Swatch `i`'s hue, across the aurora. */
const hueOf = (i: number) => Math.round(150 + i * 1.75)
/** A swatch's scale near the hovered one: 1.25 on it, less with each cell away, 1 from three cells. */
const scaleNear = (i: number, hovered: number | undefined) => {
if (hovered === undefined) return 1
const cells = Math.hypot((i % COLUMNS) - (hovered % COLUMNS), Math.floor(i / COLUMNS) - Math.floor(hovered / COLUMNS))
return 1 + 0.25 * Math.max(0, 1 - cells / 3)
}
/** A palette of 120 swatches in one Batch: the hovered one lifts, its neighbours grow with it, a press shrinks it, a tap picks it. */
export default function Palette() {
const [picked, setPicked] = createSignal<number>()
const [hovered, setHovered] = createSignal<number>()
const swatches = createBatch({
count: SWATCHES.length,
initial: false,
// Every swatch scales by its distance from the hovered one: a new hover is one change for all 120.
animate: (i) => ({ x: colX(i), y: rowY(i), scale: scaleNear(i, hovered()) }),
// The hovered one lifts from its own row: a function, since `y` is where a swatch sits.
whileHover: (i) => ({ y: rowY(i) - 3 }),
whileTap: { scale: 0.9 },
})
// Every swatch's hover and tap, heard from one set of listeners.
createEffect(swatches.when("hoverStart"), ({ i }) => {
setHovered(i)
})
createEffect(swatches.when("tap"), ({ i }) => {
setPicked(hueOf(i))
})
return (
<div class="sample-stack">
<div class="sample-palette" onPointerLeave={() => setHovered(undefined)}>
<For each={SWATCHES}>
{(i) => (
<button
class="sample-swatch"
aria-label={`Hue ${hueOf(i)}°`}
aria-pressed={picked() === hueOf(i) ? "true" : "false"}
{...swatches.at(i, { style: { background: `hsl(${hueOf(i)} 60% 62%)` } })}
/>
)}
</For>
</div>
<p class="sample-note">{picked() === undefined ? "Tap a swatch" : `Picked: hue ${picked()}°`}</p>
</div>
)
}import { createBatch } from "@wardic/solid/v1"
import { createSignal, For } from "solid-js"
const COLUMNS = 12
const STEP = 24
const SWATCHES: ReadonlyArray<number> = Array.from({ length: 120 }, (_, i) => i)
const colX = (i: number) => (i % COLUMNS) * STEP
const rowY = (i: number) => Math.floor(i / COLUMNS) * STEP
/** Swatch `i`'s hue, across the aurora. */
const hueOf = (i: number) => Math.round(150 + i * 1.75)
/** A swatch's scale near the hovered one: 1.25 on it, less with each cell away, 1 from three cells. */
const scaleNear = (i: number, hovered: number | undefined) => {
if (hovered === undefined) return 1
const cells = Math.hypot((i % COLUMNS) - (hovered % COLUMNS), Math.floor(i / COLUMNS) - Math.floor(hovered / COLUMNS))
return 1 + 0.25 * Math.max(0, 1 - cells / 3)
}
/** A palette of 120 swatches in one Batch: the hovered one lifts, its neighbours grow with it, a press shrinks it, a tap picks it. */
export default function Palette() {
const [picked, setPicked] = createSignal<number>()
const [hovered, setHovered] = createSignal<number>()
const swatches = createBatch({
count: SWATCHES.length,
initial: false,
// Every swatch scales by its distance from the hovered one: a new hover is one change for all 120.
animate: (i) => ({ x: colX(i), y: rowY(i), scale: scaleNear(i, hovered()) }),
// The hovered one lifts from its own row: a function, since `y` is where a swatch sits.
whileHover: (i) => ({ y: rowY(i) - 3 }),
whileTap: { scale: 0.9 },
// Every swatch's hover and tap, heard from one set of listeners.
onHoverStart: (_, { i }) => setHovered(i),
onTap: (_, { i }) => setPicked(hueOf(i)),
})
return (
<div class="sample-stack">
<div class="sample-palette" onPointerLeave={() => setHovered(undefined)}>
<For each={SWATCHES}>
{(i) => (
<button
class="sample-swatch"
aria-label={`Hue ${hueOf(i)}°`}
aria-pressed={picked() === hueOf(i) ? "true" : "false"}
{...swatches.at(i, { style: { background: `hsl(${hueOf(i)} 60% 62%)` } })}
/>
)}
</For>
</div>
<p class="sample-note">{picked() === undefined ? "Tap a swatch" : `Picked: hue ${picked()}°`}</p>
</div>
)
}import { domAnimation, LazyMotion } from "motion/react"
import * as m from "motion/react-m"
import { useState } from "react"
const COLUMNS = 12
const STEP = 24
const SWATCHES: ReadonlyArray<number> = Array.from({ length: 120 }, (_, i) => i)
const colX = (i: number) => (i % COLUMNS) * STEP
const rowY = (i: number) => Math.floor(i / COLUMNS) * STEP
/** Swatch `i`'s hue, across the aurora. */
const hueOf = (i: number) => Math.round(150 + i * 1.75)
/** A swatch's scale near the hovered one: 1.25 on it, less with each cell away, 1 from three cells. */
const scaleNear = (i: number, hovered: number | undefined) => {
if (hovered === undefined) return 1
const cells = Math.hypot((i % COLUMNS) - (hovered % COLUMNS), Math.floor(i / COLUMNS) - Math.floor(hovered / COLUMNS))
return 1 + 0.25 * Math.max(0, 1 - cells / 3)
}
/** A palette of 120 swatches: the hovered one lifts, its neighbours grow with it, a press shrinks it, a tap picks it. */
export default function Palette() {
const [picked, setPicked] = useState<number>()
const [hovered, setHovered] = useState<number>()
return (
<LazyMotion features={domAnimation}>
<div className="sample-stack">
<div className="sample-palette" onPointerLeave={() => setHovered(undefined)}>
{/* Each swatch listens for itself, and each scales by its distance from the hovered one. */}
{SWATCHES.map((i) => (
<m.button
key={i}
className="sample-swatch"
aria-label={`Hue ${hueOf(i)}°`}
aria-pressed={picked === hueOf(i)}
style={{ x: colX(i), background: `hsl(${hueOf(i)} 60% 62%)` }}
initial={false}
animate={{ y: rowY(i), scale: scaleNear(i, hovered) }}
whileHover={{ y: rowY(i) - 3 }}
whileTap={{ scale: 0.9 }}
onHoverStart={() => setHovered(i)}
onTap={() => setPicked(hueOf(i))}
/>
))}
</div>
<p className="sample-note">{picked === undefined ? "Tap a swatch" : `Picked: hue ${picked}°`}</p>
</div>
</LazyMotion>
)
}whileHoverandwhileTapmove a member while the pointer is over it and while it's pressed, as a Wardic element's do. A press that ends with the pointer still over it goes back to the hover's values.- Here
whileHoverlifts the hovered swatch from its own row: a function of its index, since a swatch'syis where it sits, and values would send every swatch to one row. A function's keys must be keys the Batch already has. Given as values, a gesture's keys join the Batch's, and go back to where they were as it ends. - Its neighbours grow with it.
hoverStartputs the hovered swatch in a signal, andanimatescales every swatch by its distance from it: 1.25 on it, less with each cell away. A new hover is one change for all 120, and leaving the palette clears it. - The tap tells you which member:
swatches.when("tap")'s on Solid 2,onTap's{ i }on Solid 1, withitemtoo when keyed. Each swatch is a<button>, so Enter and Space press it; a member that isn't focusable is giventabindex="0". - One set of listeners on the window hears every swatch, however many there are, where each of Motion's 120 buttons listens for itself. The gesture code loads with the first Batch that needs it.
Items that come and go
import { createBatch, stagger } from "@wardic/solid"
import { Presence } from "@wardic/solid/hooks"
import { createMemo, createSignal, For } from "solid-js"
type Kind = "Fruit" | "Veg" | "Herbs"
const FRUIT = ["Apple", "Pear", "Plum", "Fig", "Kiwi", "Lime", "Lemon", "Mango", "Peach", "Cherry", "Grape", "Melon", "Apricot", "Banana", "Orange", "Quince", "Date", "Guava", "Prune", "Lychee", "Olive", "Raisin", "Medlar", "Sloe", "Yuzu", "Citron", "Ackee", "Feijoa", "Jujube", "Durian", "Loquat", "Cassis", "Nashi", "Sapote"]
const VEG = ["Leek", "Kale", "Okra", "Pea", "Bean", "Beet", "Carrot", "Celery", "Chard", "Corn", "Cress", "Onion", "Potato", "Radish", "Squash", "Turnip", "Swede", "Yam", "Taro", "Endive", "Garlic", "Shallot", "Chili", "Pepper", "Fava", "Lentil", "Rocket", "Yucca", "Tatsoi", "Gourd", "Sprout", "Daikon", "Jicama", "Salsify"]
const HERBS = ["Basil", "Bay", "Chive", "Dill", "Fennel", "Lovage", "Anise", "Mint", "Borage", "Parsley", "Savory", "Sage", "Sorrel", "Hyssop", "Thyme", "Chervil", "Clove", "Rue", "Tansy", "Yarrow", "Catnip", "Mace", "Tulsi", "Cassia", "Perilla", "Shiso", "Hops", "Myrtle", "Cumin", "Nettle", "Sumac", "Ajwain", "Cicely", "Ginger"]
/** 102 items, the kinds mixed. */
export const PRODUCE = FRUIT.flatMap((_, k) => [
{ name: FRUIT[k], kind: "Fruit" as Kind },
{ name: VEG[k], kind: "Veg" as Kind },
{ name: HERBS[k], kind: "Herbs" as Kind },
])
export const FILTERS = ["All", "Fruit", "Veg", "Herbs"] as const
const COLUMNS = 6
/** The `i`th place in the grid. */
const placeOf = (i: number) => ({ x: (i % COLUMNS) * 48, y: Math.floor(i / COLUMNS) * 30 })
/** A pantry filtered by kind: the items filtered out play their exit, the rest move to their new places. */
export default function Pantry() {
const [filter, setFilter] = createSignal<(typeof FILTERS)[number]>("All")
const shown = createMemo(() => PRODUCE.filter((item) => filter() === "All" || item.kind === filter()))
const items = createBatch({
each: shown,
key: "name",
initial: (_, i) => ({ ...placeOf(i), scale: 0.6, opacity: 0 }),
animate: (_, i) => ({ ...placeOf(i), scale: 1, opacity: 1 }),
transition: { type: "spring", visualDuration: 0.45, bounce: 0.2 },
// stagger() counts the items leaving together.
exit: { scale: 0.6, opacity: 0, transition: { duration: 0.2, delay: stagger(0.007) } },
})
return (
<div class="sample-stack">
<div class="sample-tabs sample-filters" role="group" aria-label="Show">
<For each={FILTERS}>
{(name) => (
<button class="sample-tab" aria-pressed={filter() === name ? "true" : "false"} onClick={() => setFilter(name)}>
{name}
</button>
)}
</For>
</div>
<div class="sample-pantry">
{/* A leaving item's element stays until its exit lands. */}
<Presence>
<For each={shown()}>
{(item) => (
<div class="sample-produce" data-kind={item.kind} {...items.member(item.name)}>
{item.name}
</div>
)}
</For>
</Presence>
</div>
<p class="sample-note">
{shown().length} of {PRODUCE.length}
</p>
</div>
)
}import { AnimatePresence, createBatch, stagger } from "@wardic/solid/v1"
import { createMemo, createSignal, For } from "solid-js"
type Kind = "Fruit" | "Veg" | "Herbs"
const FRUIT = ["Apple", "Pear", "Plum", "Fig", "Kiwi", "Lime", "Lemon", "Mango", "Peach", "Cherry", "Grape", "Melon", "Apricot", "Banana", "Orange", "Quince", "Date", "Guava", "Prune", "Lychee", "Olive", "Raisin", "Medlar", "Sloe", "Yuzu", "Citron", "Ackee", "Feijoa", "Jujube", "Durian", "Loquat", "Cassis", "Nashi", "Sapote"]
const VEG = ["Leek", "Kale", "Okra", "Pea", "Bean", "Beet", "Carrot", "Celery", "Chard", "Corn", "Cress", "Onion", "Potato", "Radish", "Squash", "Turnip", "Swede", "Yam", "Taro", "Endive", "Garlic", "Shallot", "Chili", "Pepper", "Fava", "Lentil", "Rocket", "Yucca", "Tatsoi", "Gourd", "Sprout", "Daikon", "Jicama", "Salsify"]
const HERBS = ["Basil", "Bay", "Chive", "Dill", "Fennel", "Lovage", "Anise", "Mint", "Borage", "Parsley", "Savory", "Sage", "Sorrel", "Hyssop", "Thyme", "Chervil", "Clove", "Rue", "Tansy", "Yarrow", "Catnip", "Mace", "Tulsi", "Cassia", "Perilla", "Shiso", "Hops", "Myrtle", "Cumin", "Nettle", "Sumac", "Ajwain", "Cicely", "Ginger"]
/** 102 items, the kinds mixed. */
const PRODUCE = FRUIT.flatMap((_, k) => [
{ name: FRUIT[k], kind: "Fruit" as Kind },
{ name: VEG[k], kind: "Veg" as Kind },
{ name: HERBS[k], kind: "Herbs" as Kind },
])
const FILTERS = ["All", "Fruit", "Veg", "Herbs"] as const
const COLUMNS = 6
/** The `i`th place in the grid. */
const placeOf = (i: number) => ({ x: (i % COLUMNS) * 48, y: Math.floor(i / COLUMNS) * 30 })
/** A pantry filtered by kind: the items filtered out play their exit, the rest move to their new places. */
export default function Pantry() {
const [filter, setFilter] = createSignal<(typeof FILTERS)[number]>("All")
const shown = createMemo(() => PRODUCE.filter((item) => filter() === "All" || item.kind === filter()))
const items = createBatch({
each: shown,
key: "name",
initial: (_, i) => ({ ...placeOf(i), scale: 0.6, opacity: 0 }),
animate: (_, i) => ({ ...placeOf(i), scale: 1, opacity: 1 }),
transition: { type: "spring", visualDuration: 0.45, bounce: 0.2 },
// stagger() counts the items leaving together.
exit: { scale: 0.6, opacity: 0, transition: { duration: 0.2, delay: stagger(0.007) } },
})
return (
<div class="sample-stack">
<div class="sample-tabs sample-filters" role="group" aria-label="Show">
<For each={FILTERS}>
{(name) => (
<button class="sample-tab" aria-pressed={filter() === name ? "true" : "false"} onClick={() => setFilter(name)}>
{name}
</button>
)}
</For>
</div>
<div class="sample-pantry">
{/* A leaving item's element stays until its exit lands. */}
<AnimatePresence>
<For each={shown()}>
{(item) => (
<div class="sample-produce" data-kind={item.kind} {...items.member(item.name)}>
{item.name}
</div>
)}
</For>
</AnimatePresence>
</div>
<p class="sample-note">
{shown().length} of {PRODUCE.length}
</p>
</div>
)
}import { AnimatePresence, domMax, LazyMotion } from "motion/react"
import * as m from "motion/react-m"
import { useState } from "react"
type Kind = "Fruit" | "Veg" | "Herbs"
const FRUIT = ["Apple", "Pear", "Plum", "Fig", "Kiwi", "Lime", "Lemon", "Mango", "Peach", "Cherry", "Grape", "Melon", "Apricot", "Banana", "Orange", "Quince", "Date", "Guava", "Prune", "Lychee", "Olive", "Raisin", "Medlar", "Sloe", "Yuzu", "Citron", "Ackee", "Feijoa", "Jujube", "Durian", "Loquat", "Cassis", "Nashi", "Sapote"]
const VEG = ["Leek", "Kale", "Okra", "Pea", "Bean", "Beet", "Carrot", "Celery", "Chard", "Corn", "Cress", "Onion", "Potato", "Radish", "Squash", "Turnip", "Swede", "Yam", "Taro", "Endive", "Garlic", "Shallot", "Chili", "Pepper", "Fava", "Lentil", "Rocket", "Yucca", "Tatsoi", "Gourd", "Sprout", "Daikon", "Jicama", "Salsify"]
const HERBS = ["Basil", "Bay", "Chive", "Dill", "Fennel", "Lovage", "Anise", "Mint", "Borage", "Parsley", "Savory", "Sage", "Sorrel", "Hyssop", "Thyme", "Chervil", "Clove", "Rue", "Tansy", "Yarrow", "Catnip", "Mace", "Tulsi", "Cassia", "Perilla", "Shiso", "Hops", "Myrtle", "Cumin", "Nettle", "Sumac", "Ajwain", "Cicely", "Ginger"]
/** 102 items, the kinds mixed. */
const PRODUCE = FRUIT.flatMap((_, k) => [
{ name: FRUIT[k], kind: "Fruit" as Kind },
{ name: VEG[k], kind: "Veg" as Kind },
{ name: HERBS[k], kind: "Herbs" as Kind },
])
const FILTERS = ["All", "Fruit", "Veg", "Herbs"] as const
const SPRING = { type: "spring", visualDuration: 0.45, bounce: 0.2 } as const
/** A pantry filtered by kind: the items filtered out play their exit, the rest move to their new places. */
export default function Pantry() {
const [filter, setFilter] = useState<(typeof FILTERS)[number]>("All")
const shown = PRODUCE.filter((item) => filter === "All" || item.kind === filter)
return (
// The rest close the gap with `layout`, so this page brings `domMax`, Motion's layout and drag, itself.
<LazyMotion features={domMax}>
<div className="sample-stack">
<div className="sample-tabs sample-filters" role="group" aria-label="Show">
{FILTERS.map((name) => (
<button key={name} className="sample-tab" aria-pressed={filter === name} onClick={() => setFilter(name)}>
{name}
</button>
))}
</div>
<div className="sample-pantry-grid">
{/* popLayout takes a leaving item out of the grid at once, so the rest move as it goes. */}
<AnimatePresence mode="popLayout">
{shown.map((item) => (
<m.div
key={item.name}
className="sample-produce"
data-kind={item.kind}
layout
initial={{ scale: 0.6, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.6, opacity: 0, transition: { duration: 0.2 } }}
transition={SPRING}
>
{item.name}
</m.div>
))}
</AnimatePresence>
</div>
<p className="sample-note">
{shown.length} of {PRODUCE.length}
</p>
</div>
</LazyMotion>
)
}- Keyed by name, its
eachis the filtered list. Filter an item out and it leaves the list, and the rest turn toward their new places in the same change: each one's place is its index, so they need nolayout. - Under
<Presence>(Solid 1's<AnimatePresence>), a leaving item plays itsexitbefore its element goes.stagger()in the exit's transition counts the items leaving together. - An item back enters from
initial. Switch filters before an exit lands and the items coming back turn around where they are, at the speed they have, their old elements gone at once. - Motion's tab gives every item
layout, and its presencemode="popLayout", so a leaving item gives up its place in the grid as it fades.
The demo's 612 items run the same pantry at six times its size, each item six times in a scroller, with the frame rate: two thirds of them leave at a filter, their exits staggered across the same half second. It's the demo's alone (demo.tsx).
Inside an <svg>
import { createBatch, stagger } from "@wardic/solid"
import { Presence } from "@wardic/solid/hooks"
import { createMemo, createSignal, For } from "solid-js"
type Series = "Teal" | "Blue" | "Purple"
const SERIES: ReadonlyArray<{ readonly name: Series; readonly x: number; readonly y: number }> = [
{ name: "Teal", x: 100, y: 75 },
{ name: "Blue", x: 210, y: 65 },
{ name: "Purple", x: 160, y: 120 },
]
const PER_SERIES = 60
/** 180 points, 60 a series, each series a disc of points around its centre, from the middle out. */
const POINTS = SERIES.flatMap((series, s) =>
Array.from({ length: PER_SERIES }, (_, k) => {
const out = Math.sqrt((k + 0.5) / PER_SERIES)
return { id: s * PER_SERIES + k, series: series.name, x: series.x + out * 48 * Math.cos(k * 2.4), y: series.y + out * 40 * Math.sin(k * 2.4) }
}),
)
const FILTERS = ["All", "Teal", "Blue", "Purple"] as const
/** A scatter plot filtered by series: each point an SVG circle, the ones filtered out shrinking away. */
export default function Scatter() {
const [filter, setFilter] = createSignal<(typeof FILTERS)[number]>("All")
const shown = createMemo(() => POINTS.filter((point) => filter() === "All" || point.series === filter()))
const points = createBatch({
each: shown,
key: "id",
initial: { scale: 0, opacity: 0 },
animate: () => ({ scale: 1, opacity: 1 }),
whileHover: { scale: 1.8 },
// stagger() counts the points entering together, and in `exit`, the points leaving together.
transition: { type: "spring", visualDuration: 0.4, bounce: 0.35, delay: stagger(0.003) },
exit: { scale: 0, opacity: 0, transition: { duration: 0.2, delay: stagger(0.003) } },
})
return (
<div class="sample-stack">
<div class="sample-tabs sample-filters" role="group" aria-label="Show">
<For each={FILTERS}>
{(name) => (
<button class="sample-tab" aria-pressed={filter() === name ? "true" : "false"} onClick={() => setFilter(name)}>
{name}
</button>
)}
</For>
</div>
<svg class="sample-plot" viewBox="0 0 320 180" role="img" aria-label={`A scatter plot of ${shown().length} points`}>
{/* A leaving point's circle stays until its exit lands. */}
<Presence>
<For each={shown()}>
{(point) => <circle class="sample-scatter-point" data-series={point.series} cx={point.x} cy={point.y} r="4" {...points.member(point.id)} />}
</For>
</Presence>
</svg>
<p class="sample-note">
{shown().length} of {POINTS.length}
</p>
</div>
)
}import { AnimatePresence, createBatch, stagger } from "@wardic/solid/v1"
import { createMemo, createSignal, For } from "solid-js"
type Series = "Teal" | "Blue" | "Purple"
const SERIES: ReadonlyArray<{ readonly name: Series; readonly x: number; readonly y: number }> = [
{ name: "Teal", x: 100, y: 75 },
{ name: "Blue", x: 210, y: 65 },
{ name: "Purple", x: 160, y: 120 },
]
const PER_SERIES = 60
/** 180 points, 60 a series, each series a disc of points around its centre, from the middle out. */
const POINTS = SERIES.flatMap((series, s) =>
Array.from({ length: PER_SERIES }, (_, k) => {
const out = Math.sqrt((k + 0.5) / PER_SERIES)
return { id: s * PER_SERIES + k, series: series.name, x: series.x + out * 48 * Math.cos(k * 2.4), y: series.y + out * 40 * Math.sin(k * 2.4) }
}),
)
const FILTERS = ["All", "Teal", "Blue", "Purple"] as const
/** A scatter plot filtered by series: each point an SVG circle, the ones filtered out shrinking away. */
export default function Scatter() {
const [filter, setFilter] = createSignal<(typeof FILTERS)[number]>("All")
const shown = createMemo(() => POINTS.filter((point) => filter() === "All" || point.series === filter()))
const points = createBatch({
each: shown,
key: "id",
initial: { scale: 0, opacity: 0 },
animate: () => ({ scale: 1, opacity: 1 }),
whileHover: { scale: 1.8 },
// stagger() counts the points entering together, and in `exit`, the points leaving together.
transition: { type: "spring", visualDuration: 0.4, bounce: 0.35, delay: stagger(0.003) },
exit: { scale: 0, opacity: 0, transition: { duration: 0.2, delay: stagger(0.003) } },
})
return (
<div class="sample-stack">
<div class="sample-tabs sample-filters" role="group" aria-label="Show">
<For each={FILTERS}>
{(name) => (
<button class="sample-tab" aria-pressed={filter() === name ? "true" : "false"} onClick={() => setFilter(name)}>
{name}
</button>
)}
</For>
</div>
<svg class="sample-plot" viewBox="0 0 320 180" role="img" aria-label={`A scatter plot of ${shown().length} points`}>
{/* A leaving point's circle stays until its exit lands. */}
<AnimatePresence>
<For each={shown()}>
{(point) => <circle class="sample-scatter-point" data-series={point.series} cx={point.x} cy={point.y} r="4" {...points.member(point.id)} />}
</For>
</AnimatePresence>
</svg>
<p class="sample-note">
{shown().length} of {POINTS.length}
</p>
</div>
)
}import { AnimatePresence, domAnimation, LazyMotion } from "motion/react"
import * as m from "motion/react-m"
import { useState } from "react"
type Series = "Teal" | "Blue" | "Purple"
const SERIES: ReadonlyArray<{ readonly name: Series; readonly x: number; readonly y: number }> = [
{ name: "Teal", x: 100, y: 75 },
{ name: "Blue", x: 210, y: 65 },
{ name: "Purple", x: 160, y: 120 },
]
const PER_SERIES = 60
/** 180 points, 60 a series, each series a disc of points around its centre, from the middle out. */
const POINTS = SERIES.flatMap((series, s) =>
Array.from({ length: PER_SERIES }, (_, k) => {
const out = Math.sqrt((k + 0.5) / PER_SERIES)
return { id: s * PER_SERIES + k, series: series.name, x: series.x + out * 48 * Math.cos(k * 2.4), y: series.y + out * 40 * Math.sin(k * 2.4) }
}),
)
const FILTERS = ["All", "Teal", "Blue", "Purple"] as const
/** A scatter plot filtered by series: each point an SVG circle, the ones filtered out shrinking away. */
export default function Scatter() {
const [filter, setFilter] = useState<(typeof FILTERS)[number]>("All")
const shown = POINTS.filter((point) => filter === "All" || point.series === filter)
return (
<LazyMotion features={domAnimation}>
<div className="sample-stack">
<div className="sample-tabs sample-filters" role="group" aria-label="Show">
{FILTERS.map((name) => (
<button key={name} className="sample-tab" aria-pressed={filter === name} onClick={() => setFilter(name)}>
{name}
</button>
))}
</div>
<svg className="sample-plot" viewBox="0 0 320 180" role="img" aria-label={`A scatter plot of ${shown.length} points`}>
{/* A leaving point's circle stays until its exit lands. Each point is its own animation, its delay its index. */}
<AnimatePresence>
{shown.map((point, i) => (
<m.circle
key={point.id}
className="sample-scatter-point"
data-series={point.series}
cx={point.x}
cy={point.y}
r={4}
initial={{ scale: 0, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
whileHover={{ scale: 1.8 }}
exit={{ scale: 0, opacity: 0, transition: { duration: 0.2 } }}
transition={{ type: "spring", visualDuration: 0.4, bounce: 0.35, delay: i * 0.003 }}
/>
))}
</AnimatePresence>
</svg>
<p className="sample-note">
{shown.length} of {POINTS.length}
</p>
</div>
</LazyMotion>
)
}- A member can be an SVG element. Each point here is a
<circle>, placed by its owncxandcy, and the Batch animates itsscaleandopacity. A member scales and turns about its own centre, as an HTML one does. - Under
<Presence>(Solid 1's<AnimatePresence>), a point filtered out shrinks away before its circle goes, as an HTML member does. stagger()counts both ways: intransition, the points entering together; in the exit's, the points leaving together. Motion's tab has no stagger for its leavers: each point's exit is its own animation, so it gives the entering ones a delay by index.
What else a Batch does
Each of these is on createBatch's page:
- Landings. Pending while anything moves, then how many members set off. Its landings.
- From code.
animate(grid, …)with Playback controls, a member's own call, and a Batch as a sequence's Segment. Animating it from code. - One member that does more. A Wardic element on a member's element drags, or runs variants or a hover of its own, and hands its keys back to the Batch once it's done. A Wardic element as a member.
- Server rendering. Each member renders its start, so a hydrated page doesn't jump, and with
appear: trueits entrance plays from the first paint, before the JavaScript. Server rendering.
A list the reader puts in order is a Batch too: Reorder.BatchGroup places thousands of items of one size and keeps Reorder's drag, keyboard and announcements.
Its limits
- Its keys are the transforms and
opacity, as numbers:pxfor a move, degrees for a turn, unitless for a scale. A colour, a size or any other style is a Wardic element's. - Every member has the same keys, the Batch's: the ones its first targets and starts give, joined by the keys of an
exit,whileHoverorwhileTapgiven as values. A keyed Batch can takekeysup front instead. A key a lateranimategives is an error. - A member has no variants, drag or layout of its own. Make its element a Wardic element for variants or a drag, as above. Layout animations aren't a member's: its Wardic element can't have
layoutorlayoutId.
In the storefront
The storefront's examples that show it, live and with their code:
- A glaze library of 288 swatches: Filter the studio's glazes by family, sort them by colour or shuffle them: every swatch moves to its new place in one change, in a wave.
- Search the studio's archive, 600 pieces: Type to search 600 pieces from forty years of firings: the ones that stop matching leave together, and the rest close up in one change.
- The studio's year, as a chart: Each of the 288 glazes a point: switch the measure and every point moves in one wave; pick a family and the rest shrink away.