Skip to content
Shaken UI
Sign in

View Stack

Save

Multi-step panels for a popover, dialog, or card that push and pop with a short blurred slide while the height eases to the new view.

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

Preview

View Stack preview

Share run

deploy-preview-482

Installation

npx @shakenui/cli add view-stack

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

npx @shakenui/cli add view-stack --dry-run

Usage

view-stack-example.tsx
"use client";

import { useState } from "react";
import { View, ViewLink, ViewStack, useViewStack } from "@/components/shaken/ui/view-stack";

const accessOptions = [
  { value: "invited", label: "Only invited people", hint: "Nobody else can open it" },
  { value: "workspace", label: "Anyone in Northwind", hint: "Members can view and comment" },
  { value: "link", label: "Anyone with the link", hint: "No sign-in needed to view" },
];

const formats = ["JSON", "Markdown", "OpenTelemetry"];

function Check() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4 text-zinc-950 dark:text-white">
      <path d="M3.5 8.5 6.5 11.5 12.5 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

const optionRow =
  "-mx-2 flex cursor-default items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 dark:hover:bg-white/[0.06]";

/** Choosing an option goes back to the previous view, where the new value shows. */
function Options({
  options,
  value,
  onChange,
}: {
  options: { value: string; label: string; hint?: string }[];
  value: string;
  onChange: (value: string) => void;
}) {
  const { pop } = useViewStack();
  return (
    <div className="grid">
      {options.map((option) => (
        <button
          key={option.value}
          type="button"
          aria-pressed={option.value === value}
          onClick={() => {
            onChange(option.value);
            pop();
          }}
          className={optionRow}
        >
          <span className="grid min-w-0 flex-1">
            <span className="text-sm text-zinc-950 dark:text-white">{option.label}</span>
            {option.hint ? <span className="text-xs text-zinc-500">{option.hint}</span> : null}
          </span>
          {option.value === value ? <Check /> : null}
        </button>
      ))}
    </div>
  );
}

export default function ViewStackExample() {
  const [access, setAccess] = useState("workspace");
  const [format, setFormat] = useState("JSON");
  const [toolOutputs, setToolOutputs] = useState(true);
  const accessLabel = accessOptions.find((option) => option.value === access)?.label ?? "";

  return (
    <div className="w-full max-w-72 rounded-xl border border-zinc-950/10 bg-white p-4 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)]">
      <ViewStack>
        <View name="share" title="Share run" description="deploy-preview-482">
          <div className="grid">
            <ViewLink to="access" meta={access === "workspace" ? "Workspace" : access === "link" ? "Public" : "Invited"}>
              Link access
            </ViewLink>
            <ViewLink to="export" meta={format}>
              Export trace
            </ViewLink>
          </div>
        </View>
        <View name="access" title="Link access" description={accessLabel}>
          <Options options={accessOptions} value={access} onChange={setAccess} />
        </View>
        <View name="export" title="Export trace">
          <div className="grid">
            <ViewLink to="format" meta={format}>
              Format
            </ViewLink>
            <button type="button" aria-pressed={toolOutputs} onClick={() => setToolOutputs((value) => !value)} className={optionRow}>
              <span className="flex-1 text-sm text-zinc-700 dark:text-zinc-300">Include tool outputs</span>
              {toolOutputs ? <Check /> : null}
            </button>
          </div>
          <button
            type="button"
            className="inline-flex h-8 items-center justify-center rounded-lg bg-zinc-950 px-3 text-sm font-medium text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] transition-colors duration-150 ease-out hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:bg-white dark:text-black dark:hover:bg-zinc-200"
          >
            Download {format}
          </button>
        </View>
        <View name="format" title="Format">
          <Options options={formats.map((value) => ({ value, label: value }))} value={format} onChange={setFormat} />
        </View>
      </ViewStack>
    </div>
  );
}

States

Every state, rendered from local fixture data.

View Stack states

API

PropTypeDefaultDescription
childrenView elements—ViewStack: the views. The first is the root unless initialView names another.
initialViewstring—ViewStack: name of the view to start on.
onStackChange(stack: string[]) => void—ViewStack: called with the open view names after each push and pop.
backLabelstring"Back to <previous title>"ViewStack: accessible name of the Back button.
namestring—View: unique name used by push and ViewLink to.
title / descriptionReactNode—View: heading and supporting text. Focus moves to the heading when the view opens.
tostring—ViewLink: the view to open.
icon / metaReactNode—ViewLink: a 16px icon before the label, and trailing text such as the current value.
useViewStack(){ push, pop, reset, current, depth, stack }—Hook for any element inside a view, for example to go back after picking an option.

Accessibility

  • Pushing a view moves focus to its heading; going back returns focus to the control that opened the view.
  • Escape goes back one view and stops there, so a surrounding Popover or Dialog stays open; on the root view Escape is left to them.
  • The Back button is a labeled button ("Back to Share run") that is removed from the tab order on the root view.
  • Views below the top of the stack stay mounted, keeping their state, but are inert and hidden, so focus and screen readers only reach the current view.
  • With reduced motion preferred, views swap and the height changes instantly.

Files

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

  • src/components/shaken/ui/view-stack.tsxview-stack
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/view-stack/0.1.0.json.

ui/view-stack.tsxShow
ui/view-stack.tsx
"use client";

import { AnimatePresence, animate, motion, useReducedMotion, type AnimationPlaybackControls, type Variants } from "motion/react";
import {
  Children,
  type ComponentProps,
  createContext,
  isValidElement,
  type ReactElement,
  type ReactNode,
  useCallback,
  useContext,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";

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

const ease = [0.23, 1, 0.32, 1] as const;

/** Reduced-motion preference, read only after hydration so server and client render the same markup first. */
function useReducedMotionAfterMount() {
  const reduce = useReducedMotion();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  return mounted && reduce === true;
}

interface StackContextValue {
  /** Names of the open views, root first. */
  stack: string[];
  /** The view on top. */
  current: string;
  /** 0 on the root view. */
  depth: number;
  /** Opens a view on top of the current one. */
  push: (name: string) => void;
  /** Goes back one view. Does nothing on the root view. */
  pop: () => void;
  /** Goes back to the root view. */
  reset: () => void;
}

const StackContext = createContext<StackContextValue | null>(null);
const FrameContext = createContext<{ index: number }>({ index: 0 });

/** Reads and drives the nearest ViewStack: `push`, `pop`, `reset`, the `current` view and the `depth`. */
export function useViewStack() {
  const context = useContext(StackContext);
  if (!context) throw new Error("useViewStack must be used inside a ViewStack.");
  return context;
}

export interface ViewProps extends Omit<ComponentProps<"div">, "title"> {
  /** Unique name, used by `push` and ViewLink `to`. */
  name: string;
  /** Heading of the view. Focus moves here when the view opens, and the Back button names it. */
  title?: ReactNode;
  /** Supporting text under the heading. */
  description?: ReactNode;
}

/** One page of a ViewStack. Only the views on the stack are mounted. */
export function View({ name: _name, title, description, className, children, ...props }: ViewProps) {
  const { index } = useContext(FrameContext);
  return (
    <div className={cx("grid gap-3", className)} {...props}>
      {title || description ? (
        <div className={cx("grid min-h-7 content-center gap-0.5", index > 0 && "pl-7")}>
          {title ? (
            <h2 tabIndex={-1} data-view-heading="" className="text-sm leading-5 font-semibold text-zinc-950 outline-none dark:text-white">
              {title}
            </h2>
          ) : null}
          {description ? <p className="text-sm leading-5 text-zinc-600 dark:text-zinc-400">{description}</p> : null}
        </div>
      ) : null}
      {children}
    </div>
  );
}

export interface ViewLinkProps extends ComponentProps<"button"> {
  /** Name of the view to open. */
  to: string;
  /** A 16px icon before the label. */
  icon?: ReactNode;
  /** Trailing secondary text, such as the current value of a setting. */
  meta?: ReactNode;
}

/** A row that opens another view, with a chevron that nudges toward where the next view comes from. */
export function ViewLink({ to, icon, meta, className, children, onClick, type = "button", ...props }: ViewLinkProps) {
  const { push } = useViewStack();
  return (
    <button
      type={type}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) push(to);
      }}
      className={cx(
        "group/view-link -mx-2 flex h-9 cursor-default items-center gap-2.5 rounded-lg px-2 text-left text-sm text-zinc-700 select-none dark:text-zinc-300",
        "transition-colors duration-150 ease-out motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
        "[&_svg]:size-4 [&_svg]:shrink-0",
        className,
      )}
      {...props}
    >
      {icon ? (
        <span className="flex text-zinc-500 group-hover/view-link:text-zinc-950 dark:group-hover/view-link:text-white">{icon}</span>
      ) : null}
      <span className="min-w-0 flex-1 truncate">{children}</span>
      {meta ? <span className="truncate text-xs text-zinc-500">{meta}</span> : null}
      <svg
        aria-hidden="true"
        viewBox="0 0 16 16"
        fill="none"
        className="text-zinc-400 transition-transform duration-150 ease-out group-hover/view-link:translate-x-0.5 motion-reduce:transition-none dark:text-zinc-500"
      >
        <path d="m6 4 4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </button>
  );
}

export interface ViewStackProps extends Omit<ComponentProps<"div">, "children"> {
  /** View elements. The first one is the root unless `initialView` names another. */
  children: ReactNode;
  /** Name of the view to start on. */
  initialView?: string;
  /** Called with the names of the open views after every push and pop. */
  onStackChange?: (stack: string[]) => void;
  /** Accessible name of the Back button. Defaults to "Back to <previous title>" when that title is text. */
  backLabel?: string;
}

// Push: the new view comes in from 14px right while the old one drifts 10px left; both blur a
// little so the direction reads without a long slide. Pop mirrors it.
const frameVariants: Variants = {
  enter: (direction: number) => ({ x: direction > 0 ? 14 : -10, opacity: 0, filter: "blur(4px)" }),
  current: { x: 0, opacity: 1, filter: "blur(0px)", visibility: "visible", transition: { duration: 0.28, ease } },
  covered: { x: -10, opacity: 0, filter: "blur(4px)", transition: { duration: 0.2, ease }, transitionEnd: { visibility: "hidden" } },
  exit: { x: 14, opacity: 0, filter: "blur(4px)", transition: { duration: 0.2, ease } },
};

const stillVariants: Variants = {
  enter: { opacity: 0 },
  current: { opacity: 1, visibility: "visible", transition: { duration: 0 } },
  covered: { opacity: 0, transition: { duration: 0 }, transitionEnd: { visibility: "hidden" } },
  exit: { opacity: 0, transition: { duration: 0 } },
};

/**
 * Multi-step panels for a popover, dialog or card. Views push and pop with a short blurred slide,
 * the container height eases to the new view, a Back button fades in past the root, focus moves
 * to the new view's heading, and Escape or Back goes back one view (Escape on the root view is
 * left to the surrounding popover or dialog).
 */
export function ViewStack({ children, initialView, onStackChange, backLabel, className, ...props }: ViewStackProps) {
  const views = useMemo(() => {
    const map = new Map<string, ReactElement<ViewProps>>();
    Children.forEach(children, (child) => {
      if (isValidElement<ViewProps>(child) && typeof child.props.name === "string") map.set(child.props.name, child);
    });
    return map;
  }, [children]);

  const rootName = initialView ?? views.keys().next().value ?? "";
  const [stack, setStack] = useState<string[]>([rootName]);
  const [direction, setDirection] = useState(1);
  const reduceMotion = useReducedMotionAfterMount();

  const rootRef = useRef<HTMLDivElement>(null);
  const viewportRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const fromHeight = useRef<number | null>(null);
  const heightAnimation = useRef<AnimationPlaybackControls | null>(null);
  // The control that opened each view, so going back returns focus to it.
  const openers = useRef<(HTMLElement | null)[]>([]);
  const navigated = useRef<"push" | "pop" | null>(null);

  const change = useCallback((next: (stack: string[]) => string[], kind: "push" | "pop") => {
    setStack((previous) => {
      const updated = next(previous);
      if (updated === previous) return previous;
      if (viewportRef.current) fromHeight.current = viewportRef.current.getBoundingClientRect().height;
      navigated.current = kind;
      return updated;
    });
    setDirection(kind === "push" ? 1 : -1);
  }, []);

  const pendingOpener = useRef<HTMLElement | null>(null);
  const push = useCallback(
    (name: string) => {
      pendingOpener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
      change((previous) => (previous[previous.length - 1] === name ? previous : [...previous, name]), "push");
    },
    [change],
  );
  const pop = useCallback(() => change((previous) => (previous.length > 1 ? previous.slice(0, -1) : previous), "pop"), [change]);
  const reset = useCallback(() => change((previous) => (previous.length > 1 ? previous.slice(0, 1) : previous), "pop"), [change]);

  const depth = stack.length - 1;
  const current = stack[depth] ?? rootName;

  useEffect(() => {
    if (navigated.current) onStackChange?.(stack);
    // Only report changes the user made, not the first render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stack]);

  // After a push or pop: animate the height from the old view to the new one, then move focus.
  useLayoutEffect(() => {
    const kind = navigated.current;
    if (!kind) return;
    navigated.current = null;

    const viewport = viewportRef.current;
    const content = contentRef.current;
    const from = fromHeight.current;
    fromHeight.current = null;
    if (viewport && content && from != null && !reduceMotion) {
      heightAnimation.current?.stop();
      const to = content.getBoundingClientRect().height;
      if (Math.abs(to - from) > 0.5) {
        const controls = animate(viewport, { height: [from, to] }, { duration: 0.3, ease });
        heightAnimation.current = controls;
        // Back to auto height so content that grows inside a view is never clipped.
        void controls.then(() => {
          if (heightAnimation.current === controls) viewport.style.height = "";
        });
      } else {
        viewport.style.height = "";
      }
    }

    const frame = content?.querySelector<HTMLElement>("[data-view-frame][data-current]");
    // A view coming back from under the stack is still hidden from its covered state; show it now
    // so it can take focus before its animation starts.
    if (frame) frame.style.visibility = "visible";
    let target: HTMLElement | null = null;
    if (kind === "push") {
      openers.current.push(pendingOpener.current);
      pendingOpener.current = null;
    } else {
      while (openers.current.length > stack.length - 1) target = openers.current.pop() ?? null;
      if (target && (!target.isConnected || !rootRef.current?.contains(target))) target = null;
    }
    target ??= frame?.querySelector<HTMLElement>("[data-view-heading]") ?? frame ?? null;
    target?.focus({ preventScroll: true });
  }, [stack, reduceMotion]);

  // Escape goes back one view and stops there, so the popover or dialog around it stays open.
  // A native listener on the root runs before listeners on the document.
  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape" || event.defaultPrevented || stack.length < 2) return;
      event.preventDefault();
      event.stopPropagation();
      pop();
    };
    root.addEventListener("keydown", onKeyDown);
    return () => root.removeEventListener("keydown", onKeyDown);
  }, [stack.length, pop]);

  const previousTitle = depth > 0 ? views.get(stack[depth - 1] ?? "")?.props.title : undefined;
  const back = backLabel ?? (typeof previousTitle === "string" ? `Back to ${previousTitle}` : "Back");
  const context = useMemo<StackContextValue>(
    () => ({ stack, current, depth, push, pop, reset }),
    [stack, current, depth, push, pop, reset],
  );
  const variants = reduceMotion ? stillVariants : frameVariants;

  return (
    <StackContext.Provider value={context}>
      <div ref={rootRef} data-depth={depth} className={cx("relative", className)} {...props}>
        <button
          type="button"
          aria-label={back}
          tabIndex={depth > 0 ? 0 : -1}
          aria-hidden={depth > 0 ? undefined : true}
          onClick={pop}
          className={cx(
            "absolute top-0 -left-1.5 z-10 flex size-7 cursor-default items-center justify-center rounded-lg text-zinc-500",
            "transition-[opacity,translate,background-color,color] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
            "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
            "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
            depth > 0 ? "translate-x-0 opacity-100" : "pointer-events-none translate-x-1 opacity-0",
          )}
        >
          <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
            <path d="m10 4-4 4 4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        {/* Clips only vertically, so the blurred edge of a sliding view is not cut at the sides. */}
        <div ref={viewportRef} className="relative overflow-x-visible overflow-y-clip">
          <div ref={contentRef} className="relative">
            <AnimatePresence initial={false} custom={direction} mode="popLayout">
              {stack.map((name, index) => {
                const isCurrent = index === depth;
                return (
                  <motion.div
                    key={`${index}:${name}`}
                    data-view-frame=""
                    data-current={isCurrent ? "" : undefined}
                    custom={direction}
                    variants={variants}
                    initial="enter"
                    animate={isCurrent ? "current" : "covered"}
                    exit="exit"
                    inert={!isCurrent}
                    tabIndex={-1}
                    className={cx("outline-none", !isCurrent && "absolute inset-x-0 top-0")}
                  >
                    <FrameContext.Provider value={{ index }}>{views.get(name) ?? null}</FrameContext.Provider>
                  </motion.div>
                );
              })}
            </AnimatePresence>
          </div>
        </div>
      </div>
    </StackContext.Provider>
  );
}