Overview

Two panels and a hairline divider with a wide, invisible hit area. The ratio lives in a motion value, so dragging writes straight to the DOM without re-rendering. The grab point stays under the pointer (no jump), the cursor is locked page-wide while dragging, and past min/max the divider rubber-bands, then springs back into bounds with your release velocity. A collapsible first panel gives way when dragged well past its minimum. Double-click resets; arrows nudge (Shift for bigger steps), Home/End jump to the limits, Enter collapses and restores.


Installation

Use the CLI to install the component automatically:

$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/split-pane.json

Install dependencies:

$ pnpm add motion

Add the utility function for class merging:

lib/utils.ts
tsx
import { ClassValue, clsx } from "clsx";import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {  return twMerge(clsx(inputs));}

Copy the component code into your project:

components/ui/split-pane.tsx
tsx
"use client";
import React, { Children, useEffect, useRef, useState } from "react";import {  animate,  motion,  useMotionValue,  useReducedMotion,  useTransform,} from "motion/react";import { cn } from "@/lib/utils";
export type SplitPaneProps = {  children: [React.ReactNode, React.ReactNode];  defaultRatio?: number;  minRatio?: number;  maxRatio?: number;  direction?: "horizontal" | "vertical";  /** Let the first panel collapse to zero when dragged well past its minimum. */  collapsible?: boolean;  /** Fires when a resize settles — persist it to restore the layout later. */  onRatioChange?: (ratio: number) => void;  className?: string;};
const SPRING = { type: "spring" as const, bounce: 0, duration: 0.3 };const STEP = 0.05;
function clamp(n: number, lo: number, hi: number) {  return Math.min(hi, Math.max(lo, n));}
/** Ratio-space rubber band: resistance grows the further past the limit. */function rubberband(over: number, dimension = 0.2, constant = 0.55) {  return (over * dimension * constant) / (dimension + constant * over);}
export function SplitPane({  children,  defaultRatio: defaultRatioProp = 0.5,  minRatio: minRatioProp = 0.2,  maxRatio: maxRatioProp = 0.8,  direction = "horizontal",  collapsible = false,  onRatioChange,  className,}: SplitPaneProps) {  const minRatio = clamp(Number.isFinite(minRatioProp) ? minRatioProp : 0.2, 0, 0.98);  const maxRatio = clamp(    Number.isFinite(maxRatioProp) ? maxRatioProp : 0.8,    minRatio + 0.02,    1,  );  const initialRatio = clamp(    Number.isFinite(defaultRatioProp) ? defaultRatioProp : 0.5,    minRatio,    maxRatio,  );  const isH = direction === "horizontal";  const reduce = useReducedMotion();  const rootRef = useRef<HTMLDivElement>(null);  const [a, b] = Children.toArray(children);
  // The ratio lives in a motion value: dragging writes straight to the DOM  // without re-rendering React on every pointer move.  const ratio = useMotionValue(initialRatio);  const basis = useTransform(ratio, (r) => `${Math.max(0, r) * 100}%`);  const [ariaNow, setAriaNow] = useState(Math.round(initialRatio * 100));  const [collapsed, setCollapsed] = useState(false);  const [dragging, setDragging] = useState(false);  // Last open ratio, so un-collapsing returns where you left off.  const restoreTo = useRef(initialRatio);
  useEffect(    () =>      ratio.on("change", (r) => {        const pct = Math.round(clamp(r, 0, 1) * 100);        setAriaNow((prev) => (prev === pct ? prev : pct));      }),    [ratio],  );
  const settle = (target: number, velocity = 0) => {    const isCollapsed = target === 0;    setCollapsed(isCollapsed);    if (!isCollapsed) restoreTo.current = target;    if (reduce) ratio.set(target);    else animate(ratio, target, { ...SPRING, velocity });    onRatioChange?.(target);  };
  /* ── Drag ─────────────────────────────────────────────── */
  const grab = useRef({ offset: 0, pointerId: -1 });  const samples = useRef<{ t: number; r: number }[]>([]);
  const rawFromPointer = (e: { clientX: number; clientY: number }) => {    const rect = rootRef.current?.getBoundingClientRect();    if (!rect) return ratio.get();    const extent = (isH ? rect.width : rect.height) - 1;    const pos = (isH ? e.clientX - rect.left : e.clientY - rect.top) - grab.current.offset;    return extent > 0 ? pos / extent : ratio.get();  };
  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {    if (!e.isPrimary || e.button !== 0) return;    e.preventDefault();    ratio.stop();    // Keep the grab point under the pointer instead of snapping the divider to it.    const handle = e.currentTarget.getBoundingClientRect();    const center = isH ? handle.left + handle.width / 2 : handle.top + handle.height / 2;    grab.current = {      offset: (isH ? e.clientX : e.clientY) - center,      pointerId: e.pointerId,    };    samples.current = [{ t: performance.now(), r: ratio.get() }];    setDragging(true);    try {      e.currentTarget.setPointerCapture(e.pointerId);    } catch {      /* pointer already gone — the drag still ends on pointerup */    }  };
  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {    if (e.pointerId !== grab.current.pointerId) return;    const raw = rawFromPointer(e);    let next = raw;    if (raw < minRatio) {      // Past the minimum a collapsible panel follows further, then gives way.      next = minRatio - rubberband(minRatio - raw, collapsible ? minRatio : 0.2);    } else if (raw > maxRatio) {      next = maxRatio + rubberband(raw - maxRatio);    }    ratio.set(next);    samples.current.push({ t: performance.now(), r: next });    if (samples.current.length > 5) samples.current.shift();    if (collapsed && raw > minRatio * 0.5) setCollapsed(false);  };
  const endDrag = (e: React.PointerEvent<HTMLDivElement>) => {    if (e.pointerId !== grab.current.pointerId) return;    grab.current.pointerId = -1;    setDragging(false);    const s = samples.current;    const dt = s.length > 1 ? (s[s.length - 1].t - s[0].t) / 1000 : 0;    const v = dt > 0 ? (s[s.length - 1].r - s[0].r) / dt : 0;    const raw = rawFromPointer(e);    if (collapsible && (raw < minRatio * 0.5 || (raw < minRatio && v < -1.2))) {      settle(0, v);      return;    }    settle(clamp(ratio.get(), minRatio, maxRatio), v);  };
  // While dragging, the cursor and text selection stay locked page-wide.  useEffect(() => {    if (!dragging) return;    const { style } = document.body;    const prev = { cursor: style.cursor, userSelect: style.userSelect };    style.cursor = isH ? "col-resize" : "row-resize";    style.userSelect = "none";    return () => {      style.cursor = prev.cursor;      style.userSelect = prev.userSelect;    };  }, [dragging, isH]);
  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {    const back = isH ? "ArrowLeft" : "ArrowUp";    const fwd = isH ? "ArrowRight" : "ArrowDown";    const step = e.shiftKey ? STEP * 3 : STEP;    const current = collapsed ? 0 : ratio.get();    let target: number | null = null;    if (e.key === back) target = collapsed ? 0 : Math.max(minRatio, current - step);    else if (e.key === fwd) target = collapsed ? minRatio : Math.min(maxRatio, current + step);    else if (e.key === "Home") target = collapsible ? 0 : minRatio;    else if (e.key === "End") target = maxRatio;    else if (e.key === "Enter") target = collapsible && !collapsed ? 0 : collapsed ? restoreTo.current : initialRatio;    if (target === null) return;    e.preventDefault();    settle(target);  };
  const onDoubleClick = () => settle(collapsed ? restoreTo.current : initialRatio);
  return (    <div      ref={rootRef}      className={cn(        "flex min-h-[12rem] w-full overflow-hidden rounded-[var(--radius-md)] border border-(--color-rule) bg-(--color-paper)",        isH ? "flex-row" : "flex-col",        className,      )}    >      <motion.div        style={{ flexBasis: basis }}        inert={collapsed || undefined}        className="min-h-0 min-w-0 shrink-0 grow-0 overflow-auto"      >        {a}      </motion.div>
      <div className={cn("relative z-10 shrink-0 bg-(--color-rule)", isH ? "w-px" : "h-px")}>        <div          role="separator"          tabIndex={0}          aria-label="Resize panels"          aria-orientation={isH ? "vertical" : "horizontal"}          aria-valuemin={collapsible ? 0 : Math.round(minRatio * 100)}          aria-valuemax={Math.round(maxRatio * 100)}          aria-valuenow={ariaNow}          data-dragging={dragging || undefined}          onPointerDown={onPointerDown}          onPointerMove={onPointerMove}          onPointerUp={endDrag}          onPointerCancel={endDrag}          onKeyDown={onKeyDown}          onDoubleClick={onDoubleClick}          className={cn(            "group absolute touch-none outline-none",            isH              ? "inset-y-0 left-1/2 w-3 -translate-x-1/2 cursor-col-resize"              : "inset-x-0 top-1/2 h-3 -translate-y-1/2 cursor-row-resize",          )}        >          {/* Line highlight: grows in on hover, stays lit while dragging */}          <span            aria-hidden            className={cn(              "absolute bg-(--color-ink)/0 transition-[background-color,transform] duration-150 ease-out",              "group-hover:bg-(--color-ink)/25 group-data-[dragging]:bg-(--color-ink)/45 group-focus-visible:bg-(--color-focus)",              isH                ? "inset-y-0 left-1/2 w-[2px] -translate-x-1/2"                : "inset-x-0 top-1/2 h-[2px] -translate-y-1/2",            )}          />          {/* Grip */}          <span            aria-hidden            className={cn(              "absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full",              "border border-(--color-rule) bg-(--color-paper) shadow-[0_1px_3px_rgba(0,0,0,0.08)]",              "flex items-center justify-center gap-[3px] transition-transform duration-150 ease-out",              "group-hover:scale-110 group-data-[dragging]:scale-110",              isH ? "h-8 w-3 flex-col" : "h-3 w-8 flex-row",            )}          >            {[0, 1, 2].map((i) => (              <span key={i} className="size-[2px] rounded-full bg-(--color-neutral)" />            ))}          </span>        </div>      </div>
      <div className="min-h-0 min-w-0 flex-1 overflow-auto">{b}</div>    </div>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { SplitPane } from "@/components/ui/split-pane";
<SplitPane defaultRatio={0.4} minRatio={0.25} maxRatio={0.7}>  {[<Sidebar key="a" />, <Main key="b" />]}</SplitPane>

Props

PropTypeRequiredDefaultDescription
children[ReactNode, ReactNode]Yes—Left/top and right/bottom panels.
defaultRationumberNo0.5Initial first-panel fraction.
minRationumberNo0.2Minimum first-panel fraction.
maxRationumberNo0.8Maximum first-panel fraction.
collapsiblebooleanNofalseFirst panel collapses to zero when dragged well past its minimum (or with Enter / Home).
onRatioChange(ratio: number) => voidNo—Fires when a resize settles. Persist it to restore the layout.
direction"horizontal" | "vertical"No"horizontal"Split axis.

Best Practices

  1. Pass exactly two children as a tuple/array.
  2. Persist the value from onRatioChange if the layout should survive navigation, and pass it back as defaultRatio.
  3. Prefer horizontal for master–detail; vertical for stacked editors.