Skip to content
Thrum

Resizable panels

Panes split by lines that a reader drags, or moves with the keyboard: a sidebar beside an editor, a result under a query. A panel can collapse to nothing or to a rail. For a sidebar that only opens and closes, a sheet or a collapsible is simpler.

Install

npx shadcn@latest add https://thrumui.dev/r/resizable-panels.json

Adds components/ui/resizable-panels.tsx and components/ui/resizable-panels-layout.ts. Nothing else in your project changes.

import { fitPanel } from "@/components/ui/resizable-panels-layout";

Automatically installs icon grip-vertical from the icon set.

Props

PropTypeDefaultDescription
ResizablePanelGroup: direction"horizontal" | "vertical"Default "horizontal"horizontal puts the panels side by side, vertical stacks them. The group fills its container; give it a height.
ResizablePanelGroup: onLayout(sizes: number[]) => void–Called with every panel's size in percent after each drag step, key press or collapse. The group stores nothing itself: save this to restore a layout.
ResizablePanelGroup: soundbooleanDefault truePlay a tick when a panel collapses or opens again, if the visitor has sound on.
ResizablePanel: defaultSizenumber–Size in percent at first. Panels without one share what is left equally, and the sizes are scaled to add up to 100.
ResizablePanel: minSizenumberDefault 0Smallest size in percent while open.
ResizablePanel: maxSizenumberDefault 100Largest size in percent.
ResizablePanel: collapsiblebooleanDefault falseSnap shut when dragged below half of minSize, and open again when dragged past it. Enter on the handle before it toggles it.
ResizablePanel: collapsedSizenumberDefault 0Size in percent when collapsed. At 0 the panel leaves the tab order; above 0 it stays as a rail.
ResizableHandle: withHandlebooleanDefault falseDraw a grip in the middle of the line, so it reads as something to drag.
ResizableHandle: disabledbooleanDefault falseThe handle ignores the pointer and the keys and leaves the tab order.
ResizableHandle: aria-labelstringDefault "Resize"The handle's name. Say which panel it resizes: "Resize files".
classNamestring–On every part: extra classes, merged last.

Motion and sound

Motion

  • Panels follow the pointer and the keys at once, with no animation, so the line stays under the pointer.
  • The line takes the ring colour over 150 ms on hover, while dragging and on focus. Reduced motion: at once.

Sound

  • A tick when a panel collapses and when it opens again, by drag or by key. Plain resizing is silent.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • It follows the WAI-ARIA window splitter pattern. Each handle is a focusable separator with aria-valuenow, aria-valuemin and aria-valuemax giving the size of the panel before it in percent, and aria-controls pointing at that panel.
  • Name every handle with aria-label, saying which panel it resizes. The default name is Resize.
  • The line is 1 pixel, but the pointer target around it is 25 pixels wide. The grip keeps 3 to 1 contrast against the page; without it, the line is the theme's border colour.
  • A panel collapsed to 0 is inert: its content leaves the tab order and the accessibility tree.
  • Panels and handles go directly inside the group, alternating, so it can read their order.
KeysAction
TabFocus the next handle, after any controls in the panel before it.
← / →In a horizontal group: move the handle by 2% of the group. In right-to-left text the keys follow the direction of reading.
↑ / ↓In a vertical group: move the handle by 2% of the group.
Home / EndMove the handle as far as the two panels allow. Home collapses a collapsible panel before it.
EnterCollapse the panel before the handle, or open it again to its last size. When that panel cannot collapse, the one after it does.

Source

components/ui/resizable-panels.tsx
"use client";

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

import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { GripVerticalIcon } from "@/components/icons/grip-vertical";
import { initialSizes, isCollapsed, moveHandle, type PanelLimits } from "@/components/ui/resizable-panels-layout";

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

export type ResizablePanelGroupProps = ComponentProps<"div"> & {
  /** `horizontal` puts the panels side by side, `vertical` stacks them. */
  direction?: ResizableDirection;
  /** Called with every panel's size in percent after a drag step, a key press or a collapse. Save it to restore the layout later. */
  onLayout?: (sizes: number[]) => void;
  /** Play a tick when a panel collapses or opens again, if the visitor has sound on. */
  sound?: boolean;
};

export type ResizablePanelProps = ComponentProps<"div"> & {
  /** Size in percent at first. Panels without one share what is left equally. */
  defaultSize?: number;
  /** Smallest size in percent while open. */
  minSize?: number;
  /** Largest size in percent. */
  maxSize?: number;
  /** Snap shut when dragged below half of `minSize`, and toggle with Enter on the handle before it. */
  collapsible?: boolean;
  /** Size in percent when collapsed: 0 hides it, a few percent leaves a rail. */
  collapsedSize?: number;
};

export type ResizableHandleProps = Omit<ComponentProps<"div">, "children"> & {
  /** Draw a small grip in the middle of the line, so it reads as something to drag. */
  withHandle?: boolean;
  /** The handle ignores the pointer and the keyboard, and leaves the tab order. */
  disabled?: boolean;
};

type Group = {
  direction: ResizableDirection;
  sizes: number[];
  limits: PanelLimits[];
  ids: string[];
  setDragging: (dragging: boolean) => void;
  update: (next: number[]) => void;
  restore: (index: number) => number;
  element: () => HTMLDivElement | null;
};

const GroupContext = createContext<Group | null>(null);
/** Each child's position: the panel's own index, or for a handle the index of the panel before it. */
const Slot = createContext(0);

const STEP = 2;

const useGroup = () => {
  const group = useContext(GroupContext);
  if (!group) throw new Error("Resizable panels and handles go inside a ResizablePanelGroup.");
  return group;
};

function limitsOf(props: ResizablePanelProps): PanelLimits {
  return { minSize: props.minSize ?? 0, maxSize: props.maxSize ?? 100, collapsible: Boolean(props.collapsible), collapsedSize: props.collapsedSize ?? 0 };
}

/**
 * Panes split by handles that a reader drags, or moves with the keyboard: a sidebar beside an editor, a preview under
 * a query. It follows the WAI-ARIA window splitter pattern. `ResizablePanel` and `ResizableHandle` go directly inside,
 * alternating. Sizes live in the group; it keeps nothing between visits, so save what `onLayout` reports if you need to.
 */
export function ResizablePanelGroup({ direction = "horizontal", onLayout, sound = true, className, children, ...props }: ResizablePanelGroupProps) {
  const id = useId();
  const ref = useRef<HTMLDivElement>(null);
  const restoreTo = useRef<number[]>([]);
  const [dragging, setDragging] = useState(false);

  // Read the panels' settings from the children, in order. A handle belongs to the panel before it.
  const panels: ResizablePanelProps[] = [];
  const slotted = Children.toArray(children).map((child, i) => {
    const panel = isValidElement<ResizablePanelProps>(child) && child.type === ResizablePanel;
    if (panel) panels.push(child.props);
    return (
      <Slot key={isValidElement(child) && child.key !== null ? child.key : i} value={panel ? panels.length - 1 : Math.max(0, panels.length - 1)}>
        {child}
      </Slot>
    );
  });
  const limits = panels.map(limitsOf);
  const defaults = panels.map((panel) => panel.defaultSize);
  const [state, setState] = useState(() => initialSizes(defaults));
  // A different number of panels starts from their defaults again.
  const sizes = state.length === panels.length ? state : initialSizes(defaults);

  const update = (next: number[]) => {
    if (next.every((size, i) => size === sizes[i])) return;
    let changed = false;
    next.forEach((size, i) => {
      const was = isCollapsed(sizes[i], limits[i]);
      if (was === isCollapsed(size, limits[i])) return;
      changed = true;
      if (!was) restoreTo.current[i] = sizes[i];
    });
    if (changed && sound) play("tick");
    setState(next);
    onLayout?.(next);
  };

  const group: Group = {
    direction,
    sizes,
    limits,
    ids: panels.map((panel, i) => panel.id ?? `${id}-panel-${i}`),
    setDragging,
    update,
    // The size before the last collapse, or the default, but never less than the minimum.
    restore: (index) => Math.max(limits[index].minSize, restoreTo.current[index] ?? defaults[index] ?? limits[index].minSize),
    element: () => ref.current,
  };

  return (
    <GroupContext value={group}>
      <div
        ref={ref}
        data-slot="resizable-panels"
        data-surface="panel"
        data-orientation={direction}
        data-dragging={dragging || undefined}
        className={cn(
          "flex size-full min-h-0 min-w-0 overflow-hidden rounded-lg border bg-card text-card-foreground",
          direction === "vertical" && "flex-col",
          dragging && (direction === "vertical" ? "cursor-row-resize select-none" : "cursor-col-resize select-none"),
          className,
        )}
        {...props}
      >
        {slotted}
      </div>
    </GroupContext>
  );
}

/** What the group reads off its panels. These are settings, not attributes, so they stay off the element. */
const PANEL_SETTINGS = ["defaultSize", "minSize", "maxSize", "collapsible", "collapsedSize", "id"] as const;

/** One pane. Its size is a share of the group; its content scrolls or clips inside it. */
export function ResizablePanel({ className, style, ...rest }: ResizablePanelProps) {
  const props: Record<string, unknown> = { ...rest };
  for (const key of PANEL_SETTINGS) delete props[key];
  const group = useGroup();
  const index = useContext(Slot);
  const size = group.sizes[index] ?? 0;
  const collapsed = isCollapsed(size, group.limits[index]);
  return (
    <div
      id={group.ids[index]}
      data-slot="resizable-panel"
      data-collapsed={collapsed || undefined}
      // A panel shut to nothing leaves the tab order and the accessibility tree.
      inert={size === 0 || undefined}
      className={cn("min-h-0 min-w-0 shrink grow-0 overflow-hidden", className)}
      style={{ flexBasis: `${size}%`, ...style }}
      {...props}
    />
  );
}

/** The line between two panels. Drag it, or focus it and use the arrow keys, Home, End and Enter. */
export function ResizableHandle({ withHandle = false, disabled = false, className, "aria-label": ariaLabel = "Resize", ...props }: ResizableHandleProps) {
  const group = useGroup();
  const index = useContext(Slot);
  const drag = useRef<{ start: number; length: number; sizes: number[]; flip: number } | null>(null);
  const [active, setActive] = useState(false);
  const horizontal = group.direction === "horizontal";
  const before = group.limits[index];
  const after = group.limits[index + 1];
  if (!before || !after) return null;

  const position = (event: PointerEvent) => (horizontal ? event.clientX : event.clientY);
  const rtl = () => {
    const element = group.element();
    return horizontal && element !== null && getComputedStyle(element).direction === "rtl";
  };

  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
    const element = group.element();
    if (disabled || event.button !== 0 || !element) return;
    event.preventDefault();
    event.currentTarget.setPointerCapture(event.pointerId);
    event.currentTarget.focus();
    const box = element.getBoundingClientRect();
    drag.current = { start: position(event), length: horizontal ? box.width : box.height, sizes: group.sizes, flip: rtl() ? -1 : 1 };
    group.setDragging(true);
    setActive(true);
  };
  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
    const start = drag.current;
    if (!start || start.length === 0) return;
    const delta = ((position(event) - start.start) / start.length) * 100 * start.flip;
    group.update(moveHandle(start.sizes, group.limits, index, delta));
  };
  const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
    if (!drag.current) return;
    drag.current = null;
    if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
    group.setDragging(false);
    setActive(false);
  };

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (disabled) return;
    const sizes = group.sizes;
    const flip = rtl() ? -1 : 1;
    const keys: Record<string, number> = horizontal ? { ArrowLeft: -STEP * flip, ArrowRight: STEP * flip } : { ArrowUp: -STEP, ArrowDown: STEP };
    let delta: number | null = null;
    if (event.key in keys) {
      delta = keys[event.key];
      // A collapsed panel opens straight to its minimum: a 2 percent step would only snap it shut again.
      if (delta > 0 && isCollapsed(sizes[index], before)) delta = before.minSize - sizes[index];
      if (delta < 0 && isCollapsed(sizes[index + 1], after)) delta = sizes[index + 1] - after.minSize;
    } else if (event.key === "Home") delta = -100;
    else if (event.key === "End") delta = 100;
    else if (event.key === "Enter") {
      // The window splitter pattern: Enter collapses the panel before the handle, and restores it. Failing that, the one after.
      if (before.collapsible) delta = (isCollapsed(sizes[index], before) ? group.restore(index) : before.collapsedSize) - sizes[index];
      else if (after.collapsible) delta = sizes[index + 1] - (isCollapsed(sizes[index + 1], after) ? group.restore(index + 1) : after.collapsedSize);
    }
    if (delta === null) return;
    event.preventDefault();
    group.update(moveHandle(sizes, group.limits, index, delta));
  };

  return (
    <div
      role="separator"
      data-slot="resizable-handle"
      data-disabled={disabled || undefined}
      data-dragging={active || undefined}
      tabIndex={disabled ? -1 : 0}
      aria-label={ariaLabel}
      aria-controls={group.ids[index]}
      // The line runs across the direction the panels are laid out in.
      aria-orientation={horizontal ? "vertical" : "horizontal"}
      aria-valuenow={Math.round(group.sizes[index])}
      aria-valuemin={before.collapsible ? before.collapsedSize : before.minSize}
      aria-valuemax={before.maxSize}
      aria-disabled={disabled || undefined}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerUp}
      onKeyDown={onKeyDown}
      className={cn(
        "relative flex shrink-0 touch-none items-center justify-center bg-foreground/15 outline-none",
        "transition-[background-color] duration-150 ease-out hover:bg-ring data-dragging:bg-ring motion-reduce:transition-none",
        "focus-visible:bg-ring focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
        // The line is 1 pixel; the pointer target around it is 25.
        "after:absolute after:content-['']",
        horizontal ? "w-px cursor-col-resize after:-inset-x-3 after:inset-y-0" : "h-px cursor-row-resize after:-inset-y-3 after:inset-x-0",
        "data-disabled:cursor-default data-disabled:hover:bg-foreground/15",
        className,
      )}
      {...props}
    >
      {withHandle && (
        <span className={cn("z-10 grid place-items-center rounded-sm border border-foreground/20 bg-card text-foreground/75", horizontal ? "h-6 w-3.5" : "h-3.5 w-6")}>
          <GripVerticalIcon size={12} className={horizontal ? undefined : "rotate-90"} />
        </span>
      )}
    </div>
  );
}
components/ui/resizable-panels-layout.ts
// The arithmetic of resizable panels, kept free of React so it can be tested on its own.
// Sizes are percentages of the group and always add up to 100.

export type PanelLimits = {
  /** Smallest size in percent while open. */
  minSize: number;
  /** Largest size in percent. */
  maxSize: number;
  /** Whether the panel snaps shut when dragged below half its minimum. */
  collapsible: boolean;
  /** Size in percent when collapsed. */
  collapsedSize: number;
};

const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));

/** A size the panel may take: inside its limits, or its collapsed size when it is dragged below half its minimum. */
export function fitPanel(size: number, limits: PanelLimits): number {
  if (limits.collapsible && size < limits.minSize) return size < (limits.minSize + limits.collapsedSize) / 2 ? limits.collapsedSize : limits.minSize;
  return clamp(size, limits.minSize, limits.maxSize);
}

/** Whether a panel is at its collapsed size. */
export function isCollapsed(size: number, limits: PanelLimits): boolean {
  return limits.collapsible && Math.abs(size - limits.collapsedSize) < 0.01;
}

/**
 * The sizes after the handle between panel `index` and panel `index + 1` moves by `delta` percent.
 * Only those two panels change, and their sum stays the same. Each keeps its limits; when both cannot, the one after wins.
 */
// Moves only the two adjacent panels beside a handle; pushing further across neighbours would require a cascade.
export function moveHandle(sizes: readonly number[], limits: readonly PanelLimits[], index: number, delta: number): number[] {
  const before = index;
  const after = index + 1;
  if (after >= sizes.length) return [...sizes];
  const pair = sizes[before] + sizes[after];
  const first = fitPanel(sizes[before] + delta, limits[before]);
  const second = fitPanel(pair - first, limits[after]);
  const next = [...sizes];
  next[before] = round(pair - second);
  next[after] = round(second);
  return next;
}

/**
 * The starting sizes: each panel's `defaultSize`, and an equal share of what is left for the panels without one.
 * The result is scaled to add up to exactly 100.
 */
export function initialSizes(defaults: readonly (number | undefined)[]): number[] {
  if (defaults.length === 0) return [];
  const given = defaults.reduce<number>((sum, size) => sum + (size ?? 0), 0);
  const open = defaults.filter((size) => size === undefined).length;
  const share = open ? Math.max(0, 100 - given) / open : 0;
  const raw = defaults.map((size) => size ?? share);
  const total = raw.reduce((sum, size) => sum + size, 0) || 1;
  return raw.map((size) => round((size / total) * 100));
}

/** Two decimals: enough for a pixel on a 10 000 pixel wide group, and stable in the markup. */
function round(value: number): number {
  return Math.round(value * 100) / 100;
}

Files and dependencies

Adds
components/ui/resizable-panels.tsxcomponents/ui/resizable-panels-layout.ts
Packages
None
Brings along
Sound engine
Icons
grip-vertical

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor