Getting Started
Components
Special Effects
Animations
Text Animations
Backgrounds
A frame-based 2D grid animation primitive with active/inactive cell states.
motion-sv
components
<script lang="ts"> import { onMount } from "svelte"; import { motion, AnimatePresence } from "motion-sv"; import { MotionGrid, MotionGridCells } from "#lib/components/magic/motion-grid/index.js"; import { motionGridStateOrder, motionGridStates, type MotionGridStateKey, } from "./state-frames";
let stateIndex = $state(0);
let currentStateKey = $derived.by(() => { return motionGridStateOrder[stateIndex] ?? ("importing" as MotionGridStateKey); });
let currentState = $derived(motionGridStates[currentStateKey]);
onMount(() => { const interval = setInterval(() => { stateIndex = (stateIndex + 1) % motionGridStateOrder.length; }, 3000);
return () => clearInterval(interval); });</script>
<motion.button layout whileHover={{ scale: 1.05 }} whilePress={{ scale: 0.95 }} class="bg-primary relative inline-flex h-11 items-center justify-center gap-x-3 px-3"> <motion.div layout="preserve-aspect"> <MotionGrid gridSize={[5, 5]} frames={currentState.frames} class="w-fit gap-0.5"> <MotionGridCells class="aspect-square size-[3px] rounded-full bg-white/20 data-[active=true]:bg-white/70 dark:bg-black/20 dark:data-[active=true]:bg-black/70" /> </MotionGrid> </motion.div>
<div class="absolute top-1/2 left-[46px] -translate-y-1/2"> <AnimatePresence mode="wait"> {#key currentState.label} <motion.span layout="preserve-aspect" class="text-primary-foreground inline-block text-sm font-medium" initial={{ opacity: 0, y: -12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: 12 }} transition={{ duration: 0.25, ease: "easeOut" }} > {currentState.label} </motion.span> {/key} </AnimatePresence> </div>
<span class="invisible opacity-0" aria-hidden={true}>{currentState.label}</span></motion.button>Installation
pnpm dlx shadcn-svelte@latest add https://sv-animations.vercel.app/r/motion-grid.json
Install dependencies
Install the required packages for this component:
pnpm add motion-sv
Copy the Source Code
Copy and paste the following code into your project:
motion-grid.svelte
<script lang="ts"> import { motion } from "motion-sv"; import { setMotionGridContext } from "./use-motion-grid-context.svelte"; import type { MotionGridCellMotionProps, MotionGridProps } from "./types";
type StyleValue = MotionGridCellMotionProps["style"];
function mergeStyles(baseStyle: StyleValue, userStyle: StyleValue): StyleValue { return { ...(baseStyle ?? {}), ...(userStyle ?? {}), }; }
function withRefProp<T extends Record<string, unknown>>(props: T) { return Object.defineProperty(props, "ref", { enumerable: true, configurable: true, get: () => ref, set: (value) => { ref = value as HTMLDivElement | null; }, }) as T & { ref: HTMLDivElement | null }; }
let { ref = $bindable(null), gridSize, frames, duration = 200, animate = true, child, children, ...restProps }: MotionGridProps = $props();
let index = $state(0);
let cols = $derived(gridSize[0]); let rows = $derived(gridSize[1]);
setMotionGridContext({ animate: () => { return animate; }, index: () => { return index; }, cols: () => { return cols; }, rows: () => { return rows; }, frames: () => { return frames; }, duration: () => { return duration; }, });
$effect(() => { frames; index = 0; });
$effect(() => { if (frames.length === 0) { index = 0; return; }
if (index >= frames.length) { index = 0; } });
$effect(() => { if (!animate || frames.length === 0) return;
let interval = setInterval(() => { index = (index + 1) % frames.length; }, duration);
return () => clearInterval(interval); });
let baseStyle = $derived({ display: "grid", gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gridAutoRows: "1fr", });
let mergedProps = $derived.by(() => { let style = mergeStyles(baseStyle, restProps.style as StyleValue); return withRefProp({ ...restProps, "data-animate": animate, style, }) as MotionGridCellMotionProps; });</script>
{#if child} {@render child({ props: mergedProps })}{:else} <motion.div bind:ref {...mergedProps}> {@render children?.()} </motion.div>{/if} motion-grid-cells.svelte
<script lang="ts"> import { motion } from "motion-sv"; import { cn } from "#lib/utils.js"; import { useMotionGridContext } from "./use-motion-grid-context.svelte"; import type { MotionGridCellMotionProps, MotionGridCellsProps } from "./types";
type StyleValue = MotionGridCellMotionProps["style"];
function mergeStyles(baseStyle: StyleValue, variantStyle: StyleValue): StyleValue { return { ...(baseStyle ?? {}), ...(variantStyle ?? {}), }; }
let { activeProps, inactiveProps, ...props }: MotionGridCellsProps = $props();
let context = useMotionGridContext(); let cellRef = $state<HTMLDivElement | null>(null);
let animate = $derived(context.animate()); let index = $derived(context.index()); let cols = $derived(context.cols()); let rows = $derived(context.rows()); let frames = $derived(context.frames()); let duration = $derived(context.duration()); let transitionDuration = $derived(duration / 1000);
let active = $derived.by(() => { return new Set<number>(frames[index]?.map(([x, y]) => y * cols + x) ?? []); });
let totalCells = $derived(cols * rows);
let baseClass = $derived(props.class); let baseStyle = $derived(props.style as StyleValue); let baseProps = $derived.by(() => { const { class: _class, style: _style, ref: _ref, ...rest } = props; return rest; });</script>
{#each Array.from({ length: totalCells }) as _, i (i)} {@const isActive = active.has(i)} {@const variantProps = (isActive ? activeProps : inactiveProps) ?? {}} {@const variantClass = variantProps.class} {@const variantStyle = variantProps.style} {@const mergedClass = cn(baseClass, variantClass)} {@const mergedStyle = mergeStyles(baseStyle, variantStyle as StyleValue)} {@const { ref: _variantRef, ...variantRestProps } = variantProps} {@const restVariantProps = { ...variantRestProps, class: mergedClass, style: mergedStyle }}
<motion.div bind:ref={cellRef} data-active={isActive} data-animate={animate} transition={{ duration: transitionDuration, ease: "easeInOut" }} {...baseProps} {...restVariantProps} />{/each} use-motion-grid-context.svelte.ts
import { getContext, setContext } from "svelte";import type { MotionGridContextType } from "./types";
const MOTION_GRID_CONTEXT_KEY = Symbol("motion-grid-context");
export function setMotionGridContext(value: MotionGridContextType): MotionGridContextType { setContext(MOTION_GRID_CONTEXT_KEY, value); return value;}
export function useMotionGridContext(): MotionGridContextType { const context = getContext<MotionGridContextType>(MOTION_GRID_CONTEXT_KEY); if (!context) { throw new Error("MotionGridCells must be used within a MotionGrid provider"); } return context;} types.ts
import type { MotionHTMLAttributes } from "motion-sv";import type { MotionProps } from "motion-sv";import type { Snippet } from "svelte";
export type FrameDot = [number, number];export type Frame = FrameDot[];export type Frames = Frame[];
export type MotionGridContextType = { index: () => number; cols: () => number; rows: () => number; frames: () => Frames; duration: () => number; animate: () => boolean;};
export type MotionGridCellMotionProps = Omit<MotionProps, "children"> & MotionHTMLAttributes<"div">;
export type MotionGridProps = Omit<MotionProps, "children" | "animate"> & MotionHTMLAttributes<"div"> & { gridSize: [number, number]; frames: Frames; duration?: number; animate?: boolean; child?: Snippet<[{ props: MotionGridCellMotionProps }]>; children?: Snippet; };
export type MotionGridCellsProps = Omit<MotionProps, "children"> & MotionHTMLAttributes<"div"> & { activeProps?: MotionGridCellMotionProps; inactiveProps?: MotionGridCellMotionProps; }; index.ts
export { default as MotionGrid } from "./motion-grid.svelte";export { default as MotionGridCells } from "./motion-grid-cells.svelte";
export type { FrameDot, Frame, Frames, MotionGridContextType, MotionGridCellMotionProps, MotionGridProps, MotionGridCellsProps,} from "./types";Folder Structure
Folder Structure
src/└── lib/ └── components/ └── magic/ └── motion-grid/ ├── motion-grid.svelte ├── motion-grid-cells.svelte ├── use-motion-grid-context.svelte.ts ├── types.ts └── index.tsInstall and integrate the Svelte component documented below.https://sv-animations.vercel.app/magic/docs/components/motion-grid/llms.txt
Follow the guide's installation and usage instructions.Match the project's existing structure, imports, and styles.Keep changes scoped to the component and verify it works.Reply with a short bullet list of completed changes.Usage
<script lang="ts"> import { MotionGrid, MotionGridCells, type Frames } from "#lib/components/magic/motion-grid/index.js";
const frames: Frames = [ [[0, 0], [1, 1]], [[1, 0], [0, 1]], ];</script>
<MotionGrid gridSize={[2, 2]} {frames} class="w-12 gap-1"> <MotionGridCells class="aspect-square rounded-full bg-muted data-[active=true]:bg-primary" /></MotionGrid>Examples
Manual State Switcher
Importing
manual-state-switcher.svelte
<script lang="ts"> import { MotionGrid, MotionGridCells } from "$lib/components/magic/motion-grid/index.js"; import { motionGridStateOrder, motionGridStates, type MotionGridStateKey, } from "./state-frames";
let selected: MotionGridStateKey = "importing";</script>
<div class="space-y-4"> <div class="flex flex-wrap gap-2"> {#each motionGridStateOrder as key} <button type="button" class="cursor-pointer rounded-md border px-2.5 py-1 text-xs transition-colors" class:bg-primary={selected === key} class:text-primary-foreground={selected === key} class:bg-background={selected !== key} onclick={() => (selected = key)} > {motionGridStates[key].label} </button> {/each} </div>
<div class="flex items-center gap-3"> <MotionGrid gridSize={[5, 5]} frames={motionGridStates[selected].frames} class="gap-1"> <MotionGridCells class="bg-muted data-[active=true]:bg-foreground size-2.5 rounded-full" activeProps={{ animate: { scale: 1.1 } }} /> </MotionGrid>
<span class="text-sm font-medium">{motionGridStates[selected].label}</span> </div></div>Custom Cell Props
Use activeProps and inactiveProps to style and animate cell states without
changing frame data.
custom-cell-props.svelte
<script lang="ts"> import { MotionGrid, MotionGridCells } from "$lib/components/magic/motion-grid/index.js"; import { motionGridStates } from "./state-frames";</script>
<div class="flex items-center gap-4"> <MotionGrid gridSize={[5, 5]} frames={motionGridStates.searching.frames} duration={220} class="gap-1" > <MotionGridCells class="size-2.5 rounded-sm border" activeProps={{ class: "border-emerald-300/70 bg-emerald-400 shadow-[0_0_10px_rgba(52,211,153,0.65)]", animate: { scale: [1, 1.2, 1], opacity: [0.8, 1, 0.8] }, }} inactiveProps={{ class: "border-muted-foreground/30 bg-muted/40", animate: { opacity: 0.4, scale: 0.9 }, }} /> </MotionGrid>
<p class="text-muted-foreground max-w-sm text-sm"> Use <code>activeProps</code> and <code>inactiveProps</code> to style and animate cell states without changing frame data. </p></div>Child Render Prop
This uses the child render-prop to customize the outer wrapper.
child-render-prop.svelte
<script lang="ts"> import { motion } from "motion-sv"; import { cn } from "$lib/utils.js"; import { MotionGrid, MotionGridCells, type MotionGridCellMotionProps, } from "$lib/components/magic/motion-grid/index.js"; import { motionGridStates } from "./state-frames";</script>
{#snippet gridChild({ props }: { props: MotionGridCellMotionProps })} <motion.div {...props} class={cn( "from-background to-muted/30 rounded-lg border bg-gradient-to-br p-2 shadow-sm", props.class )} > <MotionGridCells class="bg-foreground/15 data-[active=true]:bg-foreground/90 size-2 rounded-full" /> </motion.div>{/snippet}
<div class="flex items-center gap-4"> <MotionGrid gridSize={[5, 5]} frames={motionGridStates.syncing.frames} duration={180} class="gap-1" child={gridChild} /> <p class="text-muted-foreground text-sm"> This uses the <code>child</code> render-prop to customize the outer wrapper. </p></div>Props
Motion Grid
Grid container that provides frame state and layout context.
| Name | Type | Default | Description |
|---|---|---|---|
gridSize | [number, number] | required | Grid dimensions as [columns, rows]. |
frames | Frames | required | Frame sequence of active [x, y] cells. |
duration | number | 200 | Frame interval in milliseconds. |
animate | boolean | true | Toggles automatic frame cycling. |
child | Snippet<[ { props: MotionGridCellMotionProps } ]> | - | Render-prop wrapper for custom root rendering. |
class | ClassValue | "" | Additional classes for the grid root. |
Motion Grid Cells
Renders all cells and applies active/inactive presentation.
| Name | Type | Default | Description |
|---|---|---|---|
activeProps | MotionGridCellMotionProps | - | Props merged into active cells. |
inactiveProps | MotionGridCellMotionProps | - | Props merged into inactive cells. |
class | ClassValue | "" | Base class applied to all cells. |