Resizable Panels
Horizontal or vertical split panes with pointer-captured drag handles, per-panel min/max sizes, collapsible panels that spring shut below a threshold, double-click reset, nestable layouts, and keyboard-resizable separators.
Preview
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/motion/resizable-panels
import {
animate,
type MotionValue,
motion,
motionValue,
useReducedMotion,
useTransform,
} from "motion/react";
import {
Children,
type KeyboardEvent,
type PointerEvent,
type ReactElement,
type ReactNode,
isValidElement,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { SPRING_LAYOUT } from "@/lib/ease";
import { capturePointer, releasePointer, TOUCH_GESTURE_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export type ResizableDirection = "horizontal" | "vertical";
export interface ResizablePanelProps {
/** Initial size in percent. Panels without one share what is left. */
defaultSize?: number;
/** Minimum size in percent while expanded. */
minSize?: number;
/** Maximum size in percent. */
maxSize?: number;
/** Snap shut when dragged below `collapseThreshold`. */
collapsible?: boolean;
/** Size in percent the panel rests at when collapsed. */
collapsedSize?: number;
/** Drag below this size (percent) to collapse. Defaults to half of `minSize`. */
collapseThreshold?: number;
/** Accessible name for the handle that resizes this panel (the handle after it). */
handleLabel?: string;
className?: string;
children?: ReactNode;
}
/**
* Declarative panel. `ResizablePanels` reads these props and renders the
* panel itself, so this component only renders when used on its own.
*/
export function ResizablePanel({ className, children }: ResizablePanelProps) {
return <div className={cn("min-h-0 min-w-0", className)}>{children}</div>;
}
export interface ResizablePanelsProps {
direction?: ResizableDirection;
/** Sizes in percent (controlled), one per panel, summing to 100. */
sizes?: number[];
/** Overrides each panel's `defaultSize`. */
defaultSizes?: number[];
onSizesChange?: (sizes: number[]) => void;
/** Show a grip pill on each handle. */
withHandle?: boolean;
className?: string;
/** `ResizablePanel` elements. Handles are inserted between them. */
children: ReactNode;
}
type PanelConfig = Required<
Pick<
ResizablePanelProps,
"minSize" | "maxSize" | "collapsible" | "collapsedSize" | "collapseThreshold"
>
> & {
defaultSize?: number;
handleLabel?: string;
className?: string;
children?: ReactNode;
};
const KEY_STEP = 2;
const KEY_STEP_LARGE = 10;
const EPSILON = 0.01;
const clamp = (value: number, min: number, max: number) =>
Math.min(max, Math.max(min, value));
const round = (value: number) => Math.round(value * 100) / 100;
function resolveDefaults(configs: PanelConfig[], override?: number[]) {
if (override && override.length === configs.length) return override;
const fixed = configs.reduce((sum, c) => sum + (c.defaultSize ?? 0), 0);
const free = configs.filter((c) => c.defaultSize === undefined).length;
const share = free ? Math.max(0, 100 - fixed) / free : 0;
return configs.map((c) => c.defaultSize ?? share);
}
function PanelFrame({
id,
size,
config,
collapsed,
}: {
id: string;
size: MotionValue<number>;
config: PanelConfig;
collapsed: boolean;
}) {
// Flex-grow proportional to the percentage: handles keep their pixel width
// and the panels split exactly what is left.
const flex = useTransform(size, (v) => `${Math.max(v, 0)} 1 0px`);
return (
<motion.div
id={id}
data-collapsed={collapsed || undefined}
inert={collapsed}
style={{ flex }}
className={cn("relative min-h-0 min-w-0 overflow-hidden", config.className)}
>
{config.children}
</motion.div>
);
}
export function ResizablePanels({
direction = "horizontal",
sizes: sizesProp,
defaultSizes,
onSizesChange,
withHandle = true,
className,
children,
}: ResizablePanelsProps) {
const reduce = useReducedMotion();
const baseId = useId();
const containerRef = useRef<HTMLDivElement>(null);
const horizontal = direction === "horizontal";
const configs = useMemo<PanelConfig[]>(
() =>
Children.toArray(children)
.filter((child): child is ReactElement<ResizablePanelProps> =>
isValidElement(child),
)
.map(({ props }) => {
const minSize = props.minSize ?? 10;
return {
defaultSize: props.defaultSize,
minSize,
maxSize: props.maxSize ?? 100,
collapsible: props.collapsible ?? false,
collapsedSize: props.collapsedSize ?? 0,
collapseThreshold:
props.collapseThreshold ??
((props.collapsedSize ?? 0) + minSize) / 2,
handleLabel: props.handleLabel,
className: props.className,
children: props.children,
};
}),
[children],
);
const [initial] = useState(() => resolveDefaults(configs, defaultSizes));
const [internal, setInternal] = useState(initial);
const controlled = sizesProp !== undefined;
const sizes = controlled ? sizesProp : internal;
// One motion value per panel drives layout; React state stays the source
// of truth for aria values. Created once per panel slot.
const motionSizes = useRef<MotionValue<number>[]>([]);
if (motionSizes.current.length !== configs.length) {
motionSizes.current = configs.map(
(_, i) => motionSizes.current[i] ?? motionValue(sizes[i] ?? 0),
);
}
const targets = useRef<number[]>([...sizes]);
const animateNext = useRef(new Set<number>());
useEffect(() => {
sizes.forEach((size, i) => {
const mv = motionSizes.current[i];
if (!mv || Math.abs((targets.current[i] ?? -1) - size) < EPSILON) return;
targets.current[i] = size;
if (animateNext.current.has(i) && !reduce) {
animate(mv, size, SPRING_LAYOUT);
} else {
mv.stop();
mv.set(size);
}
});
animateNext.current.clear();
}, [sizes, reduce]);
const commit = useCallback(
(next: number[], animated: number[] = []) => {
for (const i of animated) animateNext.current.add(i);
const rounded = next.map(round);
if (!controlled) setInternal(rounded);
onSizesChange?.(rounded);
},
[controlled, onSizesChange],
);
const isCollapsed = useCallback(
(i: number, value = sizes[i] ?? 0) => {
const config = configs[i];
return Boolean(
config?.collapsible && value <= config.collapsedSize + EPSILON,
);
},
[configs, sizes],
);
/**
* Resolve a requested size for panel `i` against the pair (i, i + 1):
* clamps to min/max on both sides and snaps collapsible panels shut below
* their threshold.
*/
const resolvePair = useCallback(
(base: number[], i: number, requested: number) => {
const a = configs[i];
const b = configs[i + 1];
if (!a || !b) return base;
const total = (base[i] ?? 0) + (base[i + 1] ?? 0);
const settle = (config: PanelConfig, raw: number) => {
if (raw < config.minSize) {
if (config.collapsible && raw < config.collapseThreshold) {
return config.collapsedSize;
}
return config.minSize;
}
return Math.min(raw, config.maxSize);
};
let nextA = settle(a, clamp(requested, 0, total));
let nextB = settle(b, total - nextA);
nextA = total - nextB;
// If B's limits pushed A out of its own range, re-settle A and give B the rest.
if (nextA > a.maxSize || (nextA < a.minSize && !isCollapsedFor(a, nextA))) {
nextA = settle(a, nextA);
nextB = total - nextA;
}
const next = [...base];
next[i] = nextA;
next[i + 1] = nextB;
return next;
},
[configs],
);
const drag = useRef<{
index: number;
pointerId: number;
start: number;
length: number;
base: number[];
} | null>(null);
const onPointerDown = (event: PointerEvent<HTMLDivElement>, index: number) => {
if (event.button !== 0) return;
const rect = containerRef.current?.getBoundingClientRect();
if (!rect) return;
event.preventDefault();
event.currentTarget.focus();
capturePointer(event.currentTarget, event.pointerId);
drag.current = {
index,
pointerId: event.pointerId,
start: horizontal ? event.clientX : event.clientY,
length: horizontal ? rect.width : rect.height,
base: [...sizes],
};
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const state = drag.current;
if (!state || state.pointerId !== event.pointerId || !state.length) return;
const delta =
(((horizontal ? event.clientX : event.clientY) - state.start) /
state.length) *
100;
const next = resolvePair(
state.base,
state.index,
(state.base[state.index] ?? 0) + delta,
);
if (next.every((v, i) => Math.abs(v - (sizes[i] ?? 0)) < EPSILON)) return;
// Snaps animate only when the collapsed state flips relative to now.
const pair = [state.index, state.index + 1];
const flipped = pair.some((i) => isCollapsed(i, next[i]) !== isCollapsed(i));
commit(next, flipped ? pair : []);
};
const endDrag = (event: PointerEvent<HTMLDivElement>) => {
if (drag.current?.pointerId !== event.pointerId) return;
releasePointer(event.currentTarget, event.pointerId);
drag.current = null;
};
const resizeBy = (index: number, requested: number) => {
commit(resolvePair(sizes, index, requested), [index, index + 1]);
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>, index: number) => {
const config = configs[index];
if (!config) return;
const current = sizes[index] ?? 0;
const step = event.shiftKey ? KEY_STEP_LARGE : KEY_STEP;
const decrease = horizontal ? "ArrowLeft" : "ArrowUp";
const increase = horizontal ? "ArrowRight" : "ArrowDown";
switch (event.key) {
case decrease:
event.preventDefault();
// From the minimum, one more step snaps a collapsible panel shut.
resizeBy(
index,
config.collapsible && current - step < config.minSize
? config.collapsedSize
: current - step,
);
return;
case increase:
event.preventDefault();
resizeBy(
index,
isCollapsed(index) ? Math.max(config.minSize, current + step) : current + step,
);
return;
case "Home":
event.preventDefault();
resizeBy(index, config.collapsible ? config.collapsedSize : config.minSize);
return;
case "End":
event.preventDefault();
resizeBy(index, config.maxSize);
return;
case "Enter":
if (!config.collapsible) return;
event.preventDefault();
resizeBy(
index,
isCollapsed(index)
? (initial[index] ?? config.minSize) > config.collapsedSize
? (initial[index] ?? config.minSize)
: config.minSize
: config.collapsedSize,
);
return;
default:
return;
}
};
const resetAll = () => {
commit(
[...initial],
initial.map((_, i) => i),
);
};
const items: ReactNode[] = [];
configs.forEach((config, i) => {
const mv = motionSizes.current[i];
if (!mv) return;
const panelId = `${baseId}-panel-${i}`;
items.push(
<PanelFrame
key={panelId}
id={panelId}
size={mv}
config={config}
collapsed={isCollapsed(i)}
/>,
);
if (i < configs.length - 1) {
const value = Math.round(sizes[i] ?? 0);
items.push(
// biome-ignore lint/a11y/useSemanticElements: a focusable window splitter (WAI-ARIA) is a separator widget; <hr> cannot take focus or children.
<div
key={`${panelId}-handle`}
role="separator"
tabIndex={0}
aria-orientation={horizontal ? "vertical" : "horizontal"}
aria-controls={panelId}
aria-label={config.handleLabel ?? "Resize panels"}
aria-valuenow={value}
aria-valuemin={Math.round(
config.collapsible ? config.collapsedSize : config.minSize,
)}
aria-valuemax={Math.round(config.maxSize)}
onPointerDown={(event) => onPointerDown(event, i)}
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
onKeyDown={(event) => onKeyDown(event, i)}
onDoubleClick={resetAll}
className={cn(
"group/handle relative z-10 flex shrink-0 touch-none items-center justify-center bg-border outline-none",
TOUCH_GESTURE_CLASS,
horizontal
? "w-px cursor-col-resize before:absolute before:inset-y-0 before:-inset-x-1.5 before:content-['']"
: "h-px cursor-row-resize before:absolute before:inset-x-0 before:-inset-y-1.5 before:content-['']",
"transition-colors hover:bg-ring/60 focus-visible:bg-ring",
)}
>
{withHandle ? (
<span
aria-hidden
className={cn(
"pointer-events-none relative rounded-full border border-border-strong bg-background shadow-sm transition-transform duration-150",
"group-hover/handle:scale-110 group-focus-visible/handle:border-ring",
horizontal ? "h-6 w-1.5" : "h-1.5 w-6",
)}
/>
) : null}
</div>,
);
}
});
return (
<div
ref={containerRef}
data-direction={direction}
className={cn(
"flex h-full w-full overflow-hidden",
horizontal ? "flex-row" : "flex-col",
className,
)}
>
{items}
</div>
);
}
function isCollapsedFor(config: PanelConfig, value: number) {
return config.collapsible && value <= config.collapsedSize + EPSILON;
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
ResizablePanel
defaultSize?numberInitial size in percent. Panels without one share what is left.
—minSize?numberMinimum size in percent while expanded.
—maxSize?numberMaximum size in percent.
—collapsible?booleanSnap shut when dragged below `collapseThreshold`.
—collapsedSize?numberSize in percent the panel rests at when collapsed.
—collapseThreshold?numberDrag below this size (percent) to collapse. Defaults to half of `minSize`.
—handleLabel?stringAccessible name for the handle that resizes this panel (the handle after it).
—className?string—ResizablePanels
direction?"horizontal" | "vertical"horizontalsizes?number[]Sizes in percent (controlled), one per panel, summing to 100.
—defaultSizes?number[]Overrides each panel's `defaultSize`.
—onSizesChange?((sizes: number[]) => void)—withHandle?booleanShow a grip pill on each handle.
trueclassName?string—childrenReactNode`ResizablePanel` elements. Handles are inserted between them.
—Updated