dxbh-uiGitHub

Page States

Empty, error and loading states that share one shell. The retry action is a render prop so it can be your own button, and the skeleton shimmer is a linear, transform-only sweep that stops under reduced motion.

Preview
Loading items

Install

npx shadcn@latest add @dxbh-ui/page-states

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { useState } from "react";
import { Inbox } from "lucide-react";
import { EmptyState, ErrorState, LoadingState } from "@/components/ui/page-states/page-states";

const states = ["loading", "empty", "error"] as const;
type State = (typeof states)[number];

export default function PageStatesDemo() {
  const [state, setState] = useState<State>("loading");
  const [retrying, setRetrying] = useState(false);

  const retry = () => {
    setRetrying(true);
    setTimeout(() => {
      setRetrying(false);
      setState("loading");
    }, 900);
  };

  return (
    <div className="flex w-full max-w-md flex-col gap-4">
      <div role="group" aria-label="State" className="flex gap-1 self-center rounded-lg bg-muted p-1 text-sm">
        {states.map((s) => (
          <button
            key={s}
            type="button"
            aria-pressed={state === s}
            onClick={() => setState(s)}
            className="cursor-pointer rounded-md px-3 py-1 capitalize text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/50 aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm"
          >
            {s}
          </button>
        ))}
      </div>
      {state === "loading" ? <LoadingState label="Loading items" /> : null}
      {state === "empty" ? (
        <EmptyState
          icon={<Inbox />}
          title="Nothing here yet"
          description="Items you add will show up in this list."
          action={
            <button type="button" className="h-9 cursor-pointer rounded-md border px-3 text-sm font-medium transition-transform duration-(--duration-press) ease-out active:scale-[0.97]">
              Add an item
            </button>
          }
        />
      ) : null}
      {state === "error" ? (
        <ErrorState message="We couldn't load this list. Check your connection and try again." onRetry={retry} retrying={retrying} />
      ) : null}
    </div>
  );
}

Props

PropTypeDefault
EmptyState.title*

The one-line headline.

ReactNode—
EmptyState.action

One call to action: your own button or link.

ReactNode—
icon / description / compact

Decorative icon, supporting line, and tighter padding (both states).

ReactNode / ReactNode / boolean—
ErrorState.onRetry

Shows a retry action when set.

() => void—
ErrorState.retrying

Disables the action and spins its icon.

booleanfalse
ErrorState.renderAction

Render the retry with your own button: spread the props onto it.

(props: RetryActionProps) => ReactNode—
LoadingState.rows

Placeholder rows when no children are given.

number3
LoadingState.label

Announced to screen readers.

string"Loading"

Polish

  • No shadcn Button dependency: ErrorState renders a plain button with a 0.97 press, or hands its props to renderAction for your own.
  • Error and loading regions announce politely through role=status; the retry button reports aria-busy while it runs.
  • States fade in with @starting-style instead of tw-animate-css keyframes. Opacity only, so reduced motion keeps it.
  • Skeleton shimmer is linear, moves by transform rather than background-position, and stops under reduced motion (the flat block stays).
  • The retry spinner stops under reduced motion.
  • Serif heading and product copy replaced with neutral defaults from the shadcn palette.

Source

page-states.tsx
"use client";

import { useEffect, useRef, type HTMLAttributes, type ReactNode } from "react";
import { RefreshCw } from "lucide-react";
import { cn } from "@/lib/utils";
import { useReducedMotion } from "@/hooks/use-reduced-motion";

// One shell for empty and error states. It fades in through @starting-style,
// so a state that replaces content arrives without a jump; opacity only, so
// reduced motion keeps it.
const shell =
  "flex flex-col items-center gap-3 rounded-xl bg-muted/40 px-6 py-16 text-center ring-1 ring-foreground/5 transition-opacity duration-(--duration-modal,240ms) ease-out starting:opacity-0";

function Mark({ children }: { children: ReactNode }) {
  return (
    <span
      aria-hidden="true"
      className="flex size-11 items-center justify-center rounded-full bg-background text-muted-foreground ring-1 ring-foreground/5 [&_svg:not([class*='size-'])]:size-5"
    >
      {children}
    </span>
  );
}

export type EmptyStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
  title: ReactNode;
  description?: ReactNode;
  /** Decorative icon above the title. */
  icon?: ReactNode;
  /** One call to action: your own button or link. */
  action?: ReactNode;
  /** Less padding, for a section inside a page. */
  compact?: boolean;
};

/** Icon, title, one line, one action: the single empty-state pattern. */
export function EmptyState({ title, description, icon, action, compact, className, ...props }: EmptyStateProps) {
  return (
    <div className={cn(shell, compact && "py-10", className)} {...props}>
      {icon ? <Mark>{icon}</Mark> : null}
      <p className="text-lg font-semibold text-balance">{title}</p>
      {description ? <p className="max-w-md text-sm text-pretty text-muted-foreground">{description}</p> : null}
      {action ? <div className="mt-1">{action}</div> : null}
    </div>
  );
}

/** What `renderAction` receives: spread it onto your own button. */
export type RetryActionProps = {
  type: "button";
  onClick: () => void;
  disabled: boolean;
  "aria-busy": boolean;
  children: ReactNode;
};

export type ErrorStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
  title?: ReactNode;
  message?: ReactNode;
  icon?: ReactNode;
  /** Shows a retry action when set. */
  onRetry?: () => void;
  /** Disables the action and spins its icon while a retry runs. */
  retrying?: boolean;
  retryLabel?: string;
  /** Render the retry action with your own button component. */
  renderAction?: (props: RetryActionProps) => ReactNode;
  compact?: boolean;
};

/**
 * Something failed to load. Announced politely when it appears, with an
 * optional retry that you can render with your own button.
 */
export function ErrorState({
  title = "Something went wrong",
  message,
  icon,
  onRetry,
  retrying = false,
  retryLabel = "Try again",
  renderAction,
  compact,
  className,
  ...props
}: ErrorStateProps) {
  const action: RetryActionProps | null = onRetry
    ? {
        type: "button",
        onClick: onRetry,
        disabled: retrying,
        "aria-busy": retrying,
        children: (
          <>
            <RefreshCw
              aria-hidden="true"
              className={cn("size-4", retrying && "animate-spin motion-reduce:animate-none")}
            />
            {retryLabel}
          </>
        ),
      }
    : null;

  return (
    <div role="status" aria-live="polite" className={cn(shell, compact && "py-10", className)} {...props}>
      {icon ? <Mark>{icon}</Mark> : null}
      <p className="text-lg font-semibold text-balance">{title}</p>
      {message ? <p className="max-w-md text-sm text-pretty text-muted-foreground">{message}</p> : null}
      {action ? (
        <div className="mt-1">
          {renderAction ? (
            renderAction(action)
          ) : (
            <button
              {...action}
              className={cn(
                "inline-flex h-10 cursor-pointer items-center gap-2 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground outline-none select-none",
                "transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97]",
                "focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-60",
              )}
            />
          )}
        </div>
      ) : null}
    </div>
  );
}

export type SkeletonProps = HTMLAttributes<HTMLDivElement>;

/**
 * A placeholder block with a linear shimmer. The highlight moves by
 * transform only, and stops (leaving the flat block) under reduced motion.
 */
export function Skeleton({ className, ...props }: SkeletonProps) {
  const sheen = useRef<HTMLSpanElement>(null);
  const reduced = useReducedMotion();

  useEffect(() => {
    const el = sheen.current;
    if (!el || reduced || typeof el.animate !== "function") return;
    const animation = el.animate(
      [{ transform: "translateX(-100%)" }, { transform: "translateX(100%)" }],
      { duration: 1600, iterations: Infinity, easing: "linear" },
    );
    return () => animation.cancel();
  }, [reduced]);

  return (
    <div
      aria-hidden="true"
      data-slot="skeleton"
      className={cn("relative isolate overflow-hidden rounded-md bg-muted", className)}
      {...props}
    >
      <span
        ref={sheen}
        className={cn(
          "absolute inset-0 -translate-x-full bg-linear-to-r from-transparent via-foreground/5 to-transparent",
          reduced && "hidden",
        )}
      />
    </div>
  );
}

export type LoadingStateProps = HTMLAttributes<HTMLDivElement> & {
  /** Announced to screen readers while the skeleton shows. */
  label?: string;
  /** How many placeholder rows. */
  rows?: number;
  /** Your own skeleton layout instead of the rows. */
  children?: ReactNode;
};

/** A labelled loading region: rows of skeletons, or your own layout. */
export function LoadingState({ label = "Loading", rows = 3, children, className, ...props }: LoadingStateProps) {
  return (
    <div role="status" aria-live="polite" aria-busy="true" className={cn("flex flex-col gap-3", className)} {...props}>
      <span className="sr-only">{label}</span>
      {children ??
        Array.from({ length: rows }, (_, i) => (
          <div key={i} className="flex items-center gap-3">
            <Skeleton className="size-10 shrink-0 rounded-full" />
            <div className="flex flex-1 flex-col gap-2">
              <Skeleton className="h-3.5" style={{ width: `${70 - ((i * 17) % 30)}%` }} />
              <Skeleton className="h-3 w-2/5" />
            </div>
          </div>
        ))}
    </div>
  );
}

Extracted from Kanshelf/web/src/components/kanshelf/page-states.tsx at e889ab6, Kanshelf/web/src/components/ui/skeleton.tsx at e889ab6.