Skip to content
Shaken UI
Sign in

Resizable

Save

Panels split by draggable hairline handles, horizontal or vertical, with min and max sizes, keyboard resizing, and optional saved layouts.

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

Preview

Resizable preview
Conversation

The invoice totals are off by a cent. Can you find out why?

Tax is rounded after summing line items. I changed it to round each line first and the failing test now passes.

src/invoices/tax.ts
export function invoiceTax(lines: Line[], rate: number) {
  return lines.reduce(
    (total, line) => total + roundCents(line.amount * rate),
    0,
  );
}
Terminal
$ pnpm test invoices
✓ 38 tests passed in 4.2s

Installation

npx @shakenui/cli add resizable

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

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

Usage

resizable-example.tsx
"use client";

import { useState } from "react";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/shaken/ui/resizable";

function PanelHeader({ title, size }: { title: string; size?: number }) {
  return (
    <div className="flex h-9 shrink-0 items-center justify-between border-b border-zinc-950/[0.07] px-3 dark:border-white/[0.08]">
      <span className="truncate text-xs font-medium text-zinc-500">{title}</span>
      {size !== undefined ? <span className="font-mono text-[11px] text-zinc-400 tabular-nums dark:text-zinc-600">{Math.round(size)}%</span> : null}
    </div>
  );
}

export default function ResizableExample() {
  const [outer, setOuter] = useState<number[]>([]);
  const [inner, setInner] = useState<number[]>([]);

  return (
    <div className="h-96 w-full max-w-3xl overflow-hidden rounded-xl border border-zinc-950/10 bg-white 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)]">
      <ResizablePanelGroup autoSaveId="example-workspace" onLayout={setOuter}>
        <ResizablePanel defaultSize={38} minSize={24} maxSize={60} className="flex flex-col">
          <PanelHeader title="Conversation" size={outer[0]} />
          <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-auto p-3 text-sm">
            <p className="m-0 max-w-[32ch] self-end rounded-lg border border-zinc-950/10 px-3 py-2 text-zinc-950 dark:border-white/15 dark:text-white">
              The invoice totals are off by a cent. Can you find out why?
            </p>
            <p className="m-0 leading-relaxed text-zinc-600 dark:text-zinc-400">
              Tax is rounded after summing line items. I changed it to round each line first and the failing test now passes.
            </p>
          </div>
        </ResizablePanel>
        <ResizableHandle withHandle aria-label="Resize conversation" />
        <ResizablePanel minSize={30}>
          <ResizablePanelGroup direction="vertical" autoSaveId="example-workspace-right" onLayout={setInner}>
            <ResizablePanel defaultSize={62} minSize={25} className="flex flex-col">
              <PanelHeader title="src/invoices/tax.ts" size={inner[0]} />
              <pre className="m-0 min-h-0 flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed text-zinc-700 dark:text-zinc-300">
                {`export function invoiceTax(lines: Line[], rate: number) {
  return lines.reduce(
    (total, line) => total + roundCents(line.amount * rate),
    0,
  );
}`}
              </pre>
            </ResizablePanel>
            <ResizableHandle aria-label="Resize terminal" />
            <ResizablePanel minSize={20} className="flex flex-col">
              <PanelHeader title="Terminal" size={inner[1]} />
              <div className="min-h-0 flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed text-zinc-500">
                <div>$ pnpm test invoices</div>
                <div className="text-emerald-600 dark:text-emerald-400">✓ 38 tests passed in 4.2s</div>
              </div>
            </ResizablePanel>
          </ResizablePanelGroup>
        </ResizablePanel>
      </ResizablePanelGroup>
    </div>
  );
}

API

PropTypeDefaultDescription
ResizablePanelGroup direction"horizontal" | "vertical""horizontal"Side by side, or stacked.
ResizablePanelGroup autoSaveIdstring—Saves sizes to localStorage under this id and restores them before the first paint on the next visit.
ResizablePanelGroup onLayout(sizes: number[]) => void—Called with panel sizes in percent whenever they change.
ResizablePanelGroup keyboardStepnumber5Percent moved per arrow key press; Shift + arrow moves 1%.
ResizablePanel defaultSize / minSize / maxSizenumbernone / 0 / 100Sizes in percent of the group. Panels without defaultSize share what is left.
ResizableHandle withHandlebooleanfalseShows a small grip on the hairline.
ResizableHandle aria-labelstring"Resize panels"Name of the separator, for example "Resize conversation".

Accessibility

  • Each handle is a focusable role="separator" with aria-orientation, aria-valuenow (the preceding panel's size in percent), aria-valuemin, aria-valuemax, and aria-controls pointing at that panel.
  • Arrow keys along the group's axis resize by 5% (Shift for 1%), Home and End jump to the panel's minimum and maximum, and Enter collapses the panel to its minimum and restores it on the next press.
  • Keyboard resizing and dragging change sizes immediately, without animation, so the layout tracks the input exactly.
  • Handles have a 13px hit area around the 1px hairline, a resize cursor, and a sky focus ring; they brighten on hover and while dragged.
  • Pointer capture keeps a drag working when the pointer leaves the handle, and text selection is suspended while dragging.

Files

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

  • src/components/shaken/ui/resizable.tsxresizable
  • npm packages: noneReact and Tailwind CSS v4 required

Source

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

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

import {
  Children,
  type ComponentProps,
  createContext,
  isValidElement,
  type KeyboardEvent,
  type PointerEvent,
  useContext,
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
} from "react";

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

export type ResizableDirection = "horizontal" | "vertical";

interface PanelConstraints {
  id: string;
  defaultSize: number | undefined;
  minSize: number;
  maxSize: number;
}

interface GroupContextValue {
  direction: ResizableDirection;
  sizes: number[];
  panels: PanelConstraints[];
  draggingHandle: number | null;
  keyboardStep: number;
  startDrag: (handle: number, event: PointerEvent<HTMLElement>) => void;
  moveDrag: (event: PointerEvent<HTMLElement>) => void;
  endDrag: (event: PointerEvent<HTMLElement>) => void;
  resizeTo: (handle: number, size: number) => void;
}

const GroupContext = createContext<GroupContextValue | null>(null);
/** Index of a panel among panels, or of a handle among handles, assigned by the group. */
const PositionContext = createContext(-1);

function useGroup(part: string) {
  const context = useContext(GroupContext);
  if (!context) throw new Error(`${part} must be a direct child of ResizablePanelGroup.`);
  return context;
}

/** Fills in sizes that were not given by sharing what is left equally, then scales the total to 100. */
function initialSizes(panels: PanelConstraints[]) {
  const given = panels.reduce((sum, panel) => sum + (panel.defaultSize ?? 0), 0);
  const open = panels.filter((panel) => panel.defaultSize === undefined).length;
  const share = open > 0 ? Math.max(0, 100 - given) / open : 0;
  const raw = panels.map((panel) => panel.defaultSize ?? share);
  const total = raw.reduce((sum, size) => sum + size, 0) || 1;
  return raw.map((size) => (size / total) * 100);
}

/** Moves the boundary after panel `index` by `delta` percent, clamped so both neighbours stay within their limits. */
function shift(sizes: number[], panels: PanelConstraints[], index: number, delta: number) {
  const a = panels[index];
  const b = panels[index + 1];
  const sizeA = sizes[index];
  const sizeB = sizes[index + 1];
  if (!a || !b || sizeA === undefined || sizeB === undefined) return sizes;
  const lower = Math.max(a.minSize - sizeA, sizeB - b.maxSize);
  const upper = Math.min(a.maxSize - sizeA, sizeB - b.minSize);
  const applied = Math.min(Math.max(delta, lower), upper);
  if (applied === 0) return sizes;
  const next = [...sizes];
  next[index] = sizeA + applied;
  next[index + 1] = sizeB - applied;
  return next;
}

const storageKey = (id: string) => `shaken-resizable:${id}`;

export interface ResizablePanelGroupProps extends ComponentProps<"div"> {
  /** `horizontal` lays panels side by side; `vertical` stacks them. */
  direction?: ResizableDirection;
  /** Saves the layout to localStorage under this id and restores it on the next visit. */
  autoSaveId?: string;
  /** Called with the panel sizes, in percent, whenever they change. */
  onLayout?: (sizes: number[]) => void;
  /** Percent moved by each arrow key press on a focused handle. Shift with an arrow moves 1%. */
  keyboardStep?: number;
}

/**
 * Lays out `ResizablePanel`s with `ResizableHandle`s between them. Panels and handles must be
 * direct children. Sizes are percentages of the space left after the handles; they follow the
 * pointer exactly while dragging and change in steps from the keyboard, without animation.
 */
export function ResizablePanelGroup({
  direction = "horizontal",
  autoSaveId,
  onLayout,
  keyboardStep = 5,
  className,
  children,
  ...props
}: ResizablePanelGroupProps) {
  const baseId = useId();
  const groupRef = useRef<HTMLDivElement>(null);

  const panels: PanelConstraints[] = [];
  let handleCount = 0;
  const content = Children.map(children, (child) => {
    if (!isValidElement(child)) return child;
    if (child.type === ResizablePanel) {
      const panel = child.props as ResizablePanelProps;
      const index = panels.length;
      panels.push({
        id: panel.id ?? `${baseId}panel-${index}`,
        defaultSize: panel.defaultSize,
        minSize: panel.minSize ?? 0,
        maxSize: panel.maxSize ?? 100,
      });
      return <PositionContext.Provider value={index}>{child}</PositionContext.Provider>;
    }
    if (child.type === ResizableHandle) {
      return <PositionContext.Provider value={handleCount++}>{child}</PositionContext.Provider>;
    }
    return child;
  });

  const [stored, setSizes] = useState<number[]>(() => initialSizes(panels));
  // If panels are added or removed, start again from their default sizes.
  const sizes = stored.length === panels.length ? stored : initialSizes(panels);
  const [draggingHandle, setDraggingHandle] = useState<number | null>(null);
  const drag = useRef<{ handle: number; pointerId: number; start: number; base: number[]; space: number } | null>(null);
  const latest = useRef(sizes);
  latest.current = sizes;

  // Restore a saved layout before the first paint, so the panels do not jump.
  useLayoutEffect(() => {
    if (!autoSaveId) return;
    try {
      const saved = JSON.parse(window.localStorage.getItem(storageKey(autoSaveId)) ?? "null") as unknown;
      if (Array.isArray(saved) && saved.length === panels.length && saved.every((size) => typeof size === "number")) {
        setSizes(saved);
      }
    } catch {
      // Storage can be unavailable (private mode, blocked cookies); fall back to the defaults.
    }
  }, [autoSaveId]);

  // Saved only after the person resizes (drag end or a key press), never on mount, so a restore
  // can not be overwritten by the default layout.
  const persist = (next: number[]) => {
    if (!autoSaveId) return;
    try {
      window.localStorage.setItem(storageKey(autoSaveId), JSON.stringify(next.map((size) => Math.round(size * 100) / 100)));
    } catch {
      // Ignore storage failures; the layout still works for this visit.
    }
  };

  const onLayoutRef = useRef(onLayout);
  onLayoutRef.current = onLayout;
  const sizesKey = sizes.map((size) => size.toFixed(3)).join(",");
  useEffect(() => {
    onLayoutRef.current?.(latest.current);
  }, [sizesKey]);

  const axis = (event: { clientX: number; clientY: number }) => (direction === "horizontal" ? event.clientX : event.clientY);

  const value: GroupContextValue = {
    direction,
    sizes,
    panels,
    draggingHandle,
    keyboardStep,
    startDrag(handle, event) {
      const group = groupRef.current;
      if (!group || event.button !== 0) return;
      event.preventDefault();
      event.currentTarget.setPointerCapture(event.pointerId);
      const rect = group.getBoundingClientRect();
      const handles = group.querySelectorAll<HTMLElement>(":scope > [data-slot=resizable-handle]");
      const handleSpace = [...handles].reduce((sum, el) => sum + (direction === "horizontal" ? el.offsetWidth : el.offsetHeight), 0);
      const space = (direction === "horizontal" ? rect.width : rect.height) - handleSpace;
      drag.current = { handle, pointerId: event.pointerId, start: axis(event), base: sizes, space: Math.max(space, 1) };
      setDraggingHandle(handle);
      document.documentElement.style.setProperty("cursor", direction === "horizontal" ? "col-resize" : "row-resize");
      document.documentElement.style.setProperty("user-select", "none");
    },
    moveDrag(event) {
      const current = drag.current;
      if (!current || current.pointerId !== event.pointerId) return;
      const delta = ((axis(event) - current.start) / current.space) * 100;
      setSizes(shift(current.base, panels, current.handle, delta));
    },
    endDrag(event) {
      const current = drag.current;
      if (!current || current.pointerId !== event.pointerId) return;
      drag.current = null;
      setDraggingHandle(null);
      persist(latest.current);
      document.documentElement.style.removeProperty("cursor");
      document.documentElement.style.removeProperty("user-select");
    },
    resizeTo(handle, size) {
      setSizes((previous) => {
        const base = previous.length === panels.length ? previous : sizes;
        const next = shift(base, panels, handle, size - (base[handle] ?? 0));
        persist(next);
        return next;
      });
    },
  };

  return (
    <GroupContext.Provider value={value}>
      <div
        ref={groupRef}
        data-direction={direction}
        data-dragging={draggingHandle !== null || undefined}
        className={cx("flex h-full w-full min-w-0 overflow-hidden", direction === "vertical" && "flex-col", className)}
        {...props}
      >
        {content}
      </div>
    </GroupContext.Provider>
  );
}

export interface ResizablePanelProps extends ComponentProps<"div"> {
  /** Starting size in percent. Panels without one share the remaining space equally. */
  defaultSize?: number;
  /** Smallest size in percent the panel can be dragged to. */
  minSize?: number;
  /** Largest size in percent the panel can be dragged to. */
  maxSize?: number;
}

/** A region of the group. Its content scrolls or clips on its own; add `overflow-auto` for scrolling content. */
export function ResizablePanel({ defaultSize: _defaultSize, minSize: _minSize, maxSize: _maxSize, className, style, ...props }: ResizablePanelProps) {
  const group = useGroup("ResizablePanel");
  const index = useContext(PositionContext);
  const size = group.sizes[index] ?? 0;
  const panel = group.panels[index];
  return (
    <div
      data-slot="resizable-panel"
      id={panel?.id}
      data-at-min={(panel && size <= panel.minSize + 0.01) || undefined}
      className={cx("relative min-h-0 min-w-0 overflow-hidden", className)}
      style={{ ...style, flex: `${size} 1 0px` }}
      {...props}
    />
  );
}

export interface ResizableHandleProps extends ComponentProps<"div"> {
  /** Shows a small grip on the hairline so the handle is easy to find at rest. */
  withHandle?: boolean;
  /** Accessible name. Name what it resizes, for example "Resize sidebar". */
  "aria-label"?: string;
}

/**
 * The divider between two panels: a 1px hairline with a 13px hit area. Drag it, or focus it and
 * use the arrow keys (Shift for 1% steps), Home and End for the limits, and Enter to collapse the
 * panel before it to its minimum and restore it again. It brightens on hover and while dragged.
 */
export function ResizableHandle({
  withHandle = false,
  "aria-label": label = "Resize panels",
  className,
  onKeyDown,
  ...props
}: ResizableHandleProps) {
  const group = useGroup("ResizableHandle");
  const index = useContext(PositionContext);
  const before = group.panels[index];
  const size = group.sizes[index] ?? 0;
  const restoreSize = useRef<number | null>(null);
  const horizontal = group.direction === "horizontal";
  const dragging = group.draggingHandle === index;

  function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    onKeyDown?.(event);
    if (event.defaultPrevented || !before) return;
    const step = event.shiftKey ? 1 : group.keyboardStep;
    const back = horizontal ? "ArrowLeft" : "ArrowUp";
    const forward = horizontal ? "ArrowRight" : "ArrowDown";
    let target: number | null = null;
    if (event.key === back) target = size - step;
    else if (event.key === forward) target = size + step;
    else if (event.key === "Home") target = before.minSize;
    else if (event.key === "End") target = before.maxSize;
    else if (event.key === "Enter") {
      if (restoreSize.current !== null && size <= before.minSize + 0.01) {
        target = restoreSize.current;
        restoreSize.current = null;
      } else {
        restoreSize.current = size;
        target = before.minSize;
      }
    }
    if (target === null) return;
    event.preventDefault();
    group.resizeTo(index, target);
  }

  return (
    <div
      role="separator"
      tabIndex={0}
      aria-label={label}
      aria-orientation={horizontal ? "vertical" : "horizontal"}
      aria-controls={before?.id}
      aria-valuenow={Math.round(size)}
      aria-valuemin={before?.minSize ?? 0}
      aria-valuemax={before?.maxSize ?? 100}
      data-slot="resizable-handle"
      data-dragging={dragging || undefined}
      className={cx(
        "group/handle relative z-10 flex shrink-0 touch-none items-center justify-center select-none",
        "bg-zinc-950/10 dark:bg-white/10",
        "transition-[background-color] duration-150 ease-out motion-reduce:transition-none",
        "hover:bg-zinc-950/30 data-[dragging]:bg-zinc-950/45 dark:hover:bg-white/30 dark:data-[dragging]:bg-white/50",
        "focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-500",
        // The 1px line gets a 13px invisible hit area.
        "after:absolute after:content-['']",
        horizontal
          ? "w-px cursor-col-resize after:inset-y-0 after:-inset-x-1.5"
          : "h-px cursor-row-resize after:inset-x-0 after:-inset-y-1.5",
        className,
      )}
      onPointerDown={(event) => group.startDrag(index, event)}
      onPointerMove={group.moveDrag}
      onPointerUp={group.endDrag}
      onPointerCancel={group.endDrag}
      onLostPointerCapture={group.endDrag}
      onKeyDown={handleKeyDown}
      {...props}
    >
      {withHandle ? (
        <span
          aria-hidden="true"
          className={cx(
            "relative z-10 flex items-center justify-center gap-0.5 rounded-full border bg-white",
            "border-zinc-950/15 shadow-[0_1px_2px_rgb(0_0_0/0.06)] dark:border-white/20 dark:bg-black dark:shadow-none",
            "transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
            "group-hover/handle:border-zinc-950/30 group-data-[dragging]/handle:border-zinc-950/45",
            "dark:group-hover/handle:border-white/35 dark:group-data-[dragging]/handle:border-white/50",
            "group-focus-visible/handle:border-sky-500 dark:group-focus-visible/handle:border-sky-500",
            horizontal ? "h-6 w-2.5 flex-col" : "h-2.5 w-6",
          )}
        >
          <span className="size-0.5 rounded-full bg-zinc-400 dark:bg-zinc-500" />
          <span className="size-0.5 rounded-full bg-zinc-400 dark:bg-zinc-500" />
          <span className="size-0.5 rounded-full bg-zinc-400 dark:bg-zinc-500" />
        </span>
      ) : null}
    </div>
  );
}