Skip to content
Shaken UI
Sign in

Skeleton

Save

Loading placeholders for text lines, avatars, and cards, swept by one shared light that holds still under reduced motion.

Category
Feedback
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Skeleton preview

Team members

Loading team members
Loading usage

Installation

npx @shakenui/cli add skeleton

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add skeleton --dry-run

Usage

skeleton-example.tsx
"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/shaken/ui/button";
import { Skeleton, SkeletonAvatar, SkeletonCard, SkeletonGroup } from "@/components/shaken/ui/skeleton";

const members = [
  { name: "Priya Raman", email: "priya@northwind.dev", role: "Owner" },
  { name: "Tomás Ibarra", email: "tomas@northwind.dev", role: "Admin" },
  { name: "Mei Chen", email: "mei@northwind.dev", role: "Member" },
];

export default function SkeletonExample() {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!loading) return;
    const timer = setTimeout(() => setLoading(false), 2600);
    return () => clearTimeout(timer);
  }, [loading]);

  return (
    <div className="grid w-full max-w-2xl gap-4">
      <div className="flex items-center justify-between gap-3">
        <p className="text-sm font-medium text-zinc-950 dark:text-white">Team members</p>
        <Button size="sm" variant="secondary" onClick={() => setLoading(true)}>
          Reload
        </Button>
      </div>

      <div className="grid items-start gap-4 md:grid-cols-[minmax(0,1fr)_15rem]">
        <div className="rounded-xl border border-zinc-950/10 dark:border-white/10">
          {loading ? (
            <SkeletonGroup label="Loading team members" className="divide-y divide-zinc-950/[0.07] dark:divide-white/[0.08]">
              {members.map((member) => (
                <div key={member.email} className="flex items-center gap-3 px-4 py-3">
                  <SkeletonAvatar />
                  <div className="grid flex-1 gap-1.5">
                    <Skeleton className="h-3 w-28 rounded-[4px]" />
                    <Skeleton className="h-2.5 w-40 max-w-full rounded-[4px]" />
                  </div>
                  <Skeleton className="h-5.5 w-16 rounded-md" />
                </div>
              ))}
            </SkeletonGroup>
          ) : (
            <ul className="divide-y divide-zinc-950/[0.07] dark:divide-white/[0.08]">
              {members.map((member) => (
                <li key={member.email} className="flex items-center gap-3 px-4 py-3">
                  <span className="flex size-8 items-center justify-center rounded-full border border-zinc-950/10 text-xs font-medium text-zinc-600 dark:border-white/12 dark:text-zinc-300">
                    {member.name
                      .split(" ")
                      .map((part) => part[0])
                      .join("")}
                  </span>
                  <div className="grid min-w-0 flex-1">
                    <span className="truncate text-sm font-medium text-zinc-950 dark:text-white">{member.name}</span>
                    <span className="truncate text-xs text-zinc-500">{member.email}</span>
                  </div>
                  <span className="inline-flex h-5.5 items-center rounded-md border border-zinc-950/10 px-2 text-xs font-medium text-zinc-700 dark:border-white/15 dark:text-zinc-300">
                    {member.role}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </div>

        {loading ? (
          <SkeletonGroup label="Loading usage">
            <SkeletonCard lines={2} />
          </SkeletonGroup>
        ) : (
          <div className="grid gap-4 rounded-xl border border-zinc-950/10 p-5 dark:border-white/10">
            <div className="flex items-center gap-3">
              <span className="flex size-8 items-center justify-center rounded-full bg-zinc-950 text-xs font-semibold text-white dark:bg-white dark:text-black">
                N
              </span>
              <div className="grid">
                <span className="text-sm font-medium text-zinc-950 dark:text-white">Northwind</span>
                <span className="text-xs text-zinc-500">Team plan</span>
              </div>
            </div>
            <p className="text-sm leading-5 text-zinc-600 dark:text-zinc-400">
              3 of 10 seats used. Billing renews on December 1.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
shimmerbooleantrueRuns the shared light sweep on Skeleton, SkeletonText, SkeletonAvatar, and SkeletonCard. Off, the blocks are still tints. Always still under reduced motion.
SkeletonText linesnumber3Number of text lines. Each row is one line-height tall, so the real text replaces it without a layout jump.
SkeletonText lastLineWidthstring"62%"Width of the last line, so the block reads as a paragraph.
SkeletonText size"xs" | "sm" | "base""sm"Text size the lines stand in for; sets row height (16, 20, or 24px).
SkeletonAvatar size / shape"sm" | "md" | "lg" / "circle" | "square""md" / "circle"24, 32, or 40px; circle for people, square for workspace or app icons.
SkeletonCard media / linesboolean / numberfalse / 2Adds a 16:9 media block above the text, and sets the number of body lines.
SkeletonGroup labelReactNode"Loading"What is loading. The group sets aria-busy="true" and announces this once through a polite status message.

Accessibility

  • Every placeholder block is aria-hidden, so screen readers never hear a run of empty shapes.
  • SkeletonGroup sets aria-busy="true" on the loading region and announces its label once through a visually hidden role="status" message.
  • When the data arrives, render the real content in place of the group (or remove aria-busy from your own container) so the finished region is read.
  • The sweep is a transform-only Web Animation that is never started under prefers-reduced-motion (and stops if the setting changes); the blocks then show as still tints.
  • Text rows match real line heights, so content replacing the placeholders does not shift the layout.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/skeleton.tsxskeleton
  • Also installs button@0.2.1registry dependency
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/skeleton/0.1.0.json.

ui/skeleton.tsxShow
ui/skeleton.tsx
"use client";

import { type ComponentProps, type ReactNode, useEffect, useRef } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/*
 * One light passes over every skeleton on the page together. Each block's highlight is moved
 * in viewport coordinates and all animations share one start time, so blocks of any width and
 * position read as a single sweep instead of many out-of-step shimmers. It is a transform-only
 * Web Animation (compositor driven), with a rest between passes so it stays quiet.
 * Under reduced motion there is no sweep: the blocks are still tints.
 */

const PERIOD = 2400;
/** Share of the period spent travelling; the rest is a pause before the next pass. */
const TRAVEL = 0.6;

function useSweep(enabled: boolean) {
  const ref = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const band = ref.current;
    const host = band?.parentElement;
    if (!enabled || !band || !host || typeof band.animate !== "function") return;

    const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
    let animation: Animation | undefined;

    const start = () => {
      animation?.cancel();
      animation = undefined;
      if (motion.matches) return;
      const left = host.getBoundingClientRect().left;
      const width = band.offsetWidth;
      const from = -width - left;
      const to = window.innerWidth - left;
      animation = band.animate(
        [
          { transform: `translateX(${from}px)`, offset: 0, easing: "cubic-bezier(0.45, 0, 0.55, 1)" },
          { transform: `translateX(${to}px)`, offset: TRAVEL },
          { transform: `translateX(${to}px)`, offset: 1 },
        ],
        { duration: PERIOD, iterations: Infinity },
      );
      // Same phase for every skeleton, measured from the document timeline's origin.
      animation.startTime = 0;
    };

    let resizeTimer: ReturnType<typeof setTimeout> | undefined;
    const onResize = () => {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(start, 150);
    };

    start();
    motion.addEventListener("change", start);
    window.addEventListener("resize", onResize);
    return () => {
      animation?.cancel();
      clearTimeout(resizeTimer);
      motion.removeEventListener("change", start);
      window.removeEventListener("resize", onResize);
    };
  }, [enabled]);

  return ref;
}

export interface SkeletonProps extends ComponentProps<"div"> {
  /** Runs the shared light sweep. Off, the block is a still tint. Always still with reduced motion. */
  shimmer?: boolean;
}

/**
 * A placeholder block. Size and shape it with classes (`h-4 w-32`, `size-10 rounded-full`).
 * It is aria-hidden: announce loading once on the container with `SkeletonGroup` or `aria-busy`.
 */
export function Skeleton({ shimmer = true, className, children, ...props }: SkeletonProps) {
  const band = useSweep(shimmer);
  return (
    <div
      aria-hidden="true"
      data-slot="skeleton"
      className={cx(
        "relative isolate shrink-0 overflow-hidden bg-zinc-950/[0.06] dark:bg-white/[0.07]",
        // Default radius only when the caller sets none, so `rounded-full` and friends always win.
        !/(^|\s)rounded/.test(className ?? "") && "rounded-md",
        className,
      )}
      {...props}
    >
      {shimmer ? (
        <span
          ref={band}
          // Parked off the left edge until the sweep starts (the animation drives `transform`).
          style={{ transform: "translateX(-100%)" }}
          className={cx(
            "pointer-events-none absolute inset-y-0 left-0 w-48 motion-reduce:hidden",
            "bg-linear-to-r from-transparent via-white/70 to-transparent dark:via-white/[0.07]",
          )}
        />
      ) : null}
      {children}
    </div>
  );
}

export interface SkeletonTextProps extends Omit<ComponentProps<"div">, "children"> {
  /** Number of lines. */
  lines?: number;
  /** Width of the last line, so the block reads as a paragraph. Any CSS length. */
  lastLineWidth?: string;
  /** Text size the lines stand in for; sets the row height so the layout does not jump on load. */
  size?: "xs" | "sm" | "base";
  shimmer?: boolean;
}

const lineRows = {
  xs: { row: "h-4", bar: "h-2" },
  sm: { row: "h-5", bar: "h-2.5" },
  base: { row: "h-6", bar: "h-3" },
} as const;

/** Lines of text. Each row is one line-height tall, so swapping in the real text keeps the layout. */
export function SkeletonText({ lines = 3, lastLineWidth = "62%", size = "sm", shimmer = true, className, ...props }: SkeletonTextProps) {
  const rows = lineRows[size];
  return (
    <div aria-hidden="true" className={cx("grid w-full", className)} {...props}>
      {Array.from({ length: lines }, (_, i) => (
        <div key={i} className={cx("flex items-center", rows.row)}>
          <Skeleton
            shimmer={shimmer}
            className={cx("rounded-[4px]", rows.bar)}
            style={{ width: i === lines - 1 && lines > 1 ? lastLineWidth : "100%" }}
          />
        </div>
      ))}
    </div>
  );
}

const avatarSizes = { sm: "size-6", md: "size-8", lg: "size-10" } as const;

export interface SkeletonAvatarProps extends SkeletonProps {
  /** 24, 32, or 40px. */
  size?: keyof typeof avatarSizes;
  /** `circle` for people, `square` for workspace or app icons. */
  shape?: "circle" | "square";
}

export function SkeletonAvatar({ size = "md", shape = "circle", className, ...props }: SkeletonAvatarProps) {
  return (
    <Skeleton className={cx(avatarSizes[size], shape === "circle" ? "rounded-full" : "rounded-lg", className)} {...props} />
  );
}

export interface SkeletonCardProps extends Omit<ComponentProps<"div">, "children"> {
  /** Shows a media block (an image or chart) above the text. */
  media?: boolean;
  /** Lines of body text. */
  lines?: number;
  shimmer?: boolean;
}

/** A card-shaped placeholder: avatar and title row, optional media, body lines, on the container surface. */
export function SkeletonCard({ media = false, lines = 2, shimmer = true, className, ...props }: SkeletonCardProps) {
  return (
    <div
      aria-hidden="true"
      className={cx(
        "grid gap-4 rounded-xl border border-zinc-950/10 bg-white p-5 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      <div className="flex items-center gap-3">
        <SkeletonAvatar shimmer={shimmer} />
        <div className="grid flex-1 gap-2">
          <Skeleton shimmer={shimmer} className="h-3 w-2/5 rounded-[4px]" />
          <Skeleton shimmer={shimmer} className="h-2.5 w-1/4 rounded-[4px]" />
        </div>
      </div>
      {media ? <Skeleton shimmer={shimmer} className="aspect-[16/9] w-full rounded-lg" /> : null}
      <SkeletonText lines={lines} shimmer={shimmer} />
    </div>
  );
}

export interface SkeletonGroupProps extends ComponentProps<"div"> {
  /** What is loading, announced once to screen readers ("Loading deployments"). */
  label?: ReactNode;
}

/**
 * Wraps placeholders for one loading region. It sets `aria-busy="true"` and announces `label`
 * once through a polite status message; the skeletons inside stay silent.
 *
 * When the data arrives, render the real content instead of the group (or drop `aria-busy`
 * on your own container) so assistive technology reads the finished region.
 */
export function SkeletonGroup({ label = "Loading", className, children, ...props }: SkeletonGroupProps) {
  return (
    <div aria-busy="true" className={className} {...props}>
      <span role="status" className="sr-only">
        {label}
      </span>
      {children}
    </div>
  );
}