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.jsonInstall dependencies:
$ pnpm add motionAdd the utility function for class merging:
lib/utils.ts
tsx
1import { ClassValue, clsx } from "clsx";2import { twMerge } from "tailwind-merge";3 4export function cn(...inputs: ClassValue[]) {5 return twMerge(clsx(inputs));6}
Copy the component code into your project:
tsx
1"use client";2 3import React, { Children, useEffect, useRef, useState } from "react";4import {5 animate,6 motion,7 useMotionValue,8 useReducedMotion,9 useTransform,10} from "motion/react";11import { cn } from "@/lib/utils";12 13export type SplitPaneProps = {14 children: [React.ReactNode, React.ReactNode];15 defaultRatio?: number;16 minRatio?: number;17 maxRatio?: number;18 direction?: "horizontal" | "vertical";19 /** Let the first panel collapse to zero when dragged well past its minimum. */20 collapsible?: boolean;21 /** Fires when a resize settles — persist it to restore the layout later. */22 onRatioChange?: (ratio: number) => void;23 className?: string;24};25 26const SPRING = { type: "spring" as const, bounce: 0, duration: 0.3 };27const STEP = 0.05;28 29function clamp(n: number, lo: number, hi: number) {30 return Math.min(hi, Math.max(lo, n));31}32 33/** Ratio-space rubber band: resistance grows the further past the limit. */34function rubberband(over: number, dimension = 0.2, constant = 0.55) {35 return (over * dimension * constant) / (dimension + constant * over);36}37 38export function SplitPane({39 children,40 defaultRatio: defaultRatioProp = 0.5,41 minRatio: minRatioProp = 0.2,42 maxRatio: maxRatioProp = 0.8,43 direction = "horizontal",44 collapsible = false,45 onRatioChange,46 className,47}: SplitPaneProps) {48 const minRatio = clamp(Number.isFinite(minRatioProp) ? minRatioProp : 0.2, 0, 0.98);49 const maxRatio = clamp(50 Number.isFinite(maxRatioProp) ? maxRatioProp : 0.8,51 minRatio + 0.02,52 1,53 );54 const initialRatio = clamp(55 Number.isFinite(defaultRatioProp) ? defaultRatioProp : 0.5,56 minRatio,57 maxRatio,58 );59 const isH = direction === "horizontal";60 const reduce = useReducedMotion();61 const rootRef = useRef<HTMLDivElement>(null);62 const [a, b] = Children.toArray(children);63 64 // The ratio lives in a motion value: dragging writes straight to the DOM65 // without re-rendering React on every pointer move.66 const ratio = useMotionValue(initialRatio);67 const basis = useTransform(ratio, (r) => `${Math.max(0, r) * 100}%`);68 const [ariaNow, setAriaNow] = useState(Math.round(initialRatio * 100));69 const [collapsed, setCollapsed] = useState(false);70 const [dragging, setDragging] = useState(false);71 // Last open ratio, so un-collapsing returns where you left off.72 const restoreTo = useRef(initialRatio);73 74 useEffect(75 () =>76 ratio.on("change", (r) => {77 const pct = Math.round(clamp(r, 0, 1) * 100);78 setAriaNow((prev) => (prev === pct ? prev : pct));79 }),80 [ratio],81 );82 83 const settle = (target: number, velocity = 0) => {84 const isCollapsed = target === 0;85 setCollapsed(isCollapsed);86 if (!isCollapsed) restoreTo.current = target;87 if (reduce) ratio.set(target);88 else animate(ratio, target, { ...SPRING, velocity });89 onRatioChange?.(target);90 };91 92 /* ── Drag ─────────────────────────────────────────────── */93 94 const grab = useRef({ offset: 0, pointerId: -1 });95 const samples = useRef<{ t: number; r: number }[]>([]);96 97 const rawFromPointer = (e: { clientX: number; clientY: number }) => {98 const rect = rootRef.current?.getBoundingClientRect();99 if (!rect) return ratio.get();100 const extent = (isH ? rect.width : rect.height) - 1;101 const pos = (isH ? e.clientX - rect.left : e.clientY - rect.top) - grab.current.offset;102 return extent > 0 ? pos / extent : ratio.get();103 };104 105 const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {106 if (!e.isPrimary || e.button !== 0) return;107 e.preventDefault();108 ratio.stop();109 // Keep the grab point under the pointer instead of snapping the divider to it.110 const handle = e.currentTarget.getBoundingClientRect();111 const center = isH ? handle.left + handle.width / 2 : handle.top + handle.height / 2;112 grab.current = {113 offset: (isH ? e.clientX : e.clientY) - center,114 pointerId: e.pointerId,115 };116 samples.current = [{ t: performance.now(), r: ratio.get() }];117 setDragging(true);118 try {119 e.currentTarget.setPointerCapture(e.pointerId);120 } catch {121 /* pointer already gone — the drag still ends on pointerup */122 }123 };124 125 const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {126 if (e.pointerId !== grab.current.pointerId) return;127 const raw = rawFromPointer(e);128 let next = raw;129 if (raw < minRatio) {130 // Past the minimum a collapsible panel follows further, then gives way.131 next = minRatio - rubberband(minRatio - raw, collapsible ? minRatio : 0.2);132 } else if (raw > maxRatio) {133 next = maxRatio + rubberband(raw - maxRatio);134 }135 ratio.set(next);136 samples.current.push({ t: performance.now(), r: next });137 if (samples.current.length > 5) samples.current.shift();138 if (collapsed && raw > minRatio * 0.5) setCollapsed(false);139 };140 141 const endDrag = (e: React.PointerEvent<HTMLDivElement>) => {142 if (e.pointerId !== grab.current.pointerId) return;143 grab.current.pointerId = -1;144 setDragging(false);145 const s = samples.current;146 const dt = s.length > 1 ? (s[s.length - 1].t - s[0].t) / 1000 : 0;147 const v = dt > 0 ? (s[s.length - 1].r - s[0].r) / dt : 0;148 const raw = rawFromPointer(e);149 if (collapsible && (raw < minRatio * 0.5 || (raw < minRatio && v < -1.2))) {150 settle(0, v);151 return;152 }153 settle(clamp(ratio.get(), minRatio, maxRatio), v);154 };155 156 // While dragging, the cursor and text selection stay locked page-wide.157 useEffect(() => {158 if (!dragging) return;159 const { style } = document.body;160 const prev = { cursor: style.cursor, userSelect: style.userSelect };161 style.cursor = isH ? "col-resize" : "row-resize";162 style.userSelect = "none";163 return () => {164 style.cursor = prev.cursor;165 style.userSelect = prev.userSelect;166 };167 }, [dragging, isH]);168 169 const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {170 const back = isH ? "ArrowLeft" : "ArrowUp";171 const fwd = isH ? "ArrowRight" : "ArrowDown";172 const step = e.shiftKey ? STEP * 3 : STEP;173 const current = collapsed ? 0 : ratio.get();174 let target: number | null = null;175 if (e.key === back) target = collapsed ? 0 : Math.max(minRatio, current - step);176 else if (e.key === fwd) target = collapsed ? minRatio : Math.min(maxRatio, current + step);177 else if (e.key === "Home") target = collapsible ? 0 : minRatio;178 else if (e.key === "End") target = maxRatio;179 else if (e.key === "Enter") target = collapsible && !collapsed ? 0 : collapsed ? restoreTo.current : initialRatio;180 if (target === null) return;181 e.preventDefault();182 settle(target);183 };184 185 const onDoubleClick = () => settle(collapsed ? restoreTo.current : initialRatio);186 187 return (188 <div189 ref={rootRef}190 className={cn(191 "flex min-h-[12rem] w-full overflow-hidden rounded-[var(--radius-md)] border border-(--color-rule) bg-(--color-paper)",192 isH ? "flex-row" : "flex-col",193 className,194 )}195 >196 <motion.div197 style={{ flexBasis: basis }}198 inert={collapsed || undefined}199 className="min-h-0 min-w-0 shrink-0 grow-0 overflow-auto"200 >201 {a}202 </motion.div>203 204 <div className={cn("relative z-10 shrink-0 bg-(--color-rule)", isH ? "w-px" : "h-px")}>205 <div206 role="separator"207 tabIndex={0}208 aria-label="Resize panels"209 aria-orientation={isH ? "vertical" : "horizontal"}210 aria-valuemin={collapsible ? 0 : Math.round(minRatio * 100)}211 aria-valuemax={Math.round(maxRatio * 100)}212 aria-valuenow={ariaNow}213 data-dragging={dragging || undefined}214 onPointerDown={onPointerDown}215 onPointerMove={onPointerMove}216 onPointerUp={endDrag}217 onPointerCancel={endDrag}218 onKeyDown={onKeyDown}219 onDoubleClick={onDoubleClick}220 className={cn(221 "group absolute touch-none outline-none",222 isH223 ? "inset-y-0 left-1/2 w-3 -translate-x-1/2 cursor-col-resize"224 : "inset-x-0 top-1/2 h-3 -translate-y-1/2 cursor-row-resize",225 )}226 >227 {/* Line highlight: grows in on hover, stays lit while dragging */}228 <span229 aria-hidden230 className={cn(231 "absolute bg-(--color-ink)/0 transition-[background-color,transform] duration-150 ease-out",232 "group-hover:bg-(--color-ink)/25 group-data-[dragging]:bg-(--color-ink)/45 group-focus-visible:bg-(--color-focus)",233 isH234 ? "inset-y-0 left-1/2 w-[2px] -translate-x-1/2"235 : "inset-x-0 top-1/2 h-[2px] -translate-y-1/2",236 )}237 />238 {/* Grip */}239 <span240 aria-hidden241 className={cn(242 "absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full",243 "border border-(--color-rule) bg-(--color-paper) shadow-[0_1px_3px_rgba(0,0,0,0.08)]",244 "flex items-center justify-center gap-[3px] transition-transform duration-150 ease-out",245 "group-hover:scale-110 group-data-[dragging]:scale-110",246 isH ? "h-8 w-3 flex-col" : "h-3 w-8 flex-row",247 )}248 >249 {[0, 1, 2].map((i) => (250 <span key={i} className="size-[2px] rounded-full bg-(--color-neutral)" />251 ))}252 </span>253 </div>254 </div>255 256 <div className="min-h-0 min-w-0 flex-1 overflow-auto">{b}</div>257 </div>258 );259}
Adjust import paths according to your folder structure.
Basic Usage
tsx
1import { SplitPane } from "@/components/ui/split-pane";2 3<SplitPane defaultRatio={0.4} minRatio={0.25} maxRatio={0.7}>4 {[<Sidebar key="a" />, <Main key="b" />]}5</SplitPane>
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| children | [ReactNode, ReactNode] | Yes | — | Left/top and right/bottom panels. |
| defaultRatio | number | No | 0.5 | Initial first-panel fraction. |
| minRatio | number | No | 0.2 | Minimum first-panel fraction. |
| maxRatio | number | No | 0.8 | Maximum first-panel fraction. |
| collapsible | boolean | No | false | First panel collapses to zero when dragged well past its minimum (or with Enter / Home). |
| onRatioChange | (ratio: number) => void | No | — | Fires when a resize settles. Persist it to restore the layout. |
| direction | "horizontal" | "vertical" | No | "horizontal" | Split axis. |
Best Practices
- Pass exactly two children as a tuple/array.
- Persist the value from
onRatioChangeif the layout should survive navigation, and pass it back asdefaultRatio. - Prefer horizontal for master–detail; vertical for stacked editors.