Resizable
Panels side by side or one above another with a pen line between each pair to drag. Arrow keys work too. No library.
One
Two
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
export default function ResizableDemo() {
return (
<ResizablePanelGroup framed seed="rz-demo-frame" direction="horizontal" className="h-48 w-full max-w-md" aria-label="Two panels">
<ResizablePanel defaultSize={50} minSize={20}>
<div className="flex h-full items-center justify-center p-6 text-lg font-bold">One</div>
</ResizablePanel>
<ResizableHandle seed="rz-demo" aria-label="Resize the panels" />
<ResizablePanel defaultSize={50} minSize={20}>
<div className="flex h-full items-center justify-center p-6 text-lg font-bold">Two</div>
</ResizablePanel>
</ResizablePanelGroup>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ resizable"use client";
import { createContext, useCallback, useContext, useId, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type CSSProperties, type KeyboardEvent, type PointerEvent, type RefObject } from "react";
import { cn } from "@/lib/utils";
import { penStyle, useInkSeed, usePen, type Pen } from "@/hooks/use-ink-box";
import { InkSvg, Stroke } from "@/lib/ink";
import { InkOutline } from "@/lib/ink-outline";
import { dotStroke, ruleStroke, verticalStroke } from "@/lib/ink-sketch";
// Panels side by side (or one above another) with a handle between each pair
// to drag. Sizes are percentages of the group and always add up to 100; drag
// a handle, or focus it and use the arrow keys, Home and End. Panels and
// handles tell their group they are there, in the order they mount, so they
// can be put in it from anywhere, server components included.
type Direction = "horizontal" | "vertical";
type Item = { id: string; kind: "panel" | "handle"; defaultSize?: number; minSize: number; maxSize: number };
type GroupContext = {
direction: Direction;
items: Item[];
/** Every panel's size, as a percentage. */
sizes: Record<string, number>;
/** A panel or handle has mounted: it takes the next place in the group. Returns how to take it out again. */
register: (id: string, kind: Item["kind"]) => () => void;
/** Its sizes, which can change without it losing its place. */
update: (id: string, patch: Partial<Item>) => void;
/** Moves the boundary after panel `index` to `to` percent, starting from `from`. */
drag: (index: number, to: number, from: Record<string, number>) => void;
group: RefObject<HTMLDivElement | null>;
};
const GroupCtx = createContext<GroupContext | null>(null);
/** Sizes for the panels: the ones given, and the rest sharing what remains. */
function initialSizes(panels: Item[]) {
const given = panels.reduce((sum, p) => sum + (p.defaultSize ?? 0), 0);
const free = panels.filter((p) => p.defaultSize === undefined).length;
const each = free ? Math.max(0, 100 - given) / free : 0;
const raw = panels.map((p) => p.defaultSize ?? each);
const total = raw.reduce((a, b) => a + b, 0) || 1;
return Object.fromEntries(panels.map((p, i) => [p.id, (raw[i] / total) * 100]));
}
/**
* A row (or column) of panels with a drag handle between each. Put
* ResizablePanel and ResizableHandle in it, alternating.
*/
function ResizablePanelGroup({
direction = "horizontal",
onLayout,
framed = false,
seed,
roughness,
passes,
radius,
corners,
draw,
weight,
speed,
className,
children,
...props
}: ComponentProps<"div"> &
Pick<Pen, "roughness" | "passes" | "radius" | "corners" | "draw" | "weight" | "speed"> & {
direction?: Direction;
/** Called with every panel's size as they change. */
onLayout?: (sizes: number[]) => void;
/** Pencil a box round the whole group. */
framed?: boolean;
seed?: string | number;
}) {
const pen = usePen({ roughness, passes, radius, corners, draw, weight, speed });
const group = useRef<HTMLDivElement>(null);
const [items, setItems] = useState<Item[]>([]);
// What a drag has set; used for as long as it still names every panel.
const [dragged, setDragged] = useState<Record<string, number> | null>(null);
const panels = useMemo(() => items.filter((item) => item.kind === "panel"), [items]);
const sizes = useMemo(() => {
if (dragged && panels.length === Object.keys(dragged).length && panels.every((p) => p.id in dragged)) return dragged;
return initialSizes(panels);
}, [dragged, panels]);
const register = useCallback((id: string, kind: Item["kind"]) => {
setItems((all) => [...all, { id, kind, minSize: 0, maxSize: 100 }]);
return () => setItems((all) => all.filter((other) => other.id !== id));
}, []);
const update = useCallback((id: string, patch: Partial<Item>) => setItems((all) => all.map((item) => (item.id === id ? { ...item, ...patch } : item))), []);
const drag = useCallback(
(index: number, to: number, from: Record<string, number>) => {
const left = panels[index];
const right = panels[index + 1];
if (!left || !right) return;
const pair = from[left.id] + from[right.id];
const lo = Math.max(left.minSize, pair - right.maxSize);
const hi = Math.min(left.maxSize, pair - right.minSize);
const size = Math.min(Math.max(to, lo), Math.max(lo, hi));
const next = { ...from, [left.id]: size, [right.id]: pair - size };
setDragged(next);
onLayout?.(panels.map((p) => next[p.id]));
},
[panels, onLayout],
);
const context = useMemo<GroupContext>(() => ({ direction, items, sizes, register, update, drag, group }), [direction, items, sizes, register, update, drag]);
return (
<GroupCtx value={context}>
<div ref={group} data-slot="resizable-panel-group" data-direction={direction} className={cn("flex h-full w-full data-[direction=vertical]:flex-col", framed && "relative isolate", className)} {...props}>
{framed && <InkOutline pen={pen} seed={seed} estimate={[448, 192]} maxRadius={12} className="-z-10 text-ink-line" />}
{children}
</div>
</GroupCtx>
);
}
type PanelProps = ComponentProps<"div"> & {
/** Starting size, a percentage of the group. Panels without one share what is left. */
defaultSize?: number;
/** Smallest and largest, as percentages. */
minSize?: number;
maxSize?: number;
};
/** One panel of the group. Its content is whatever you put in it. */
function ResizablePanel({ defaultSize, minSize = 0, maxSize = 100, className, style, ...props }: PanelProps) {
const context = useContext(GroupCtx);
const id = useId();
const register = context?.register;
const update = context?.update;
useLayoutEffect(() => register?.(id, "panel"), [register, id]);
useLayoutEffect(() => update?.(id, { defaultSize, minSize, maxSize }), [update, id, defaultSize, minSize, maxSize]);
// Until it has registered (the server, the first paint) it takes the size it was given.
const grow = context?.sizes[id] ?? defaultSize ?? 1;
return <div data-slot="resizable-panel" className={cn("relative min-h-0 min-w-0 overflow-auto", className)} style={{ flexBasis: 0, flexGrow: grow, flexShrink: 1, ...style } as CSSProperties} {...props} />;
}
/**
* The line between two panels, wandering a little the way a pen rule does.
* Drag it, or focus it and press the arrow keys (Shift for bigger steps),
* Home and End to send it as far as it goes. `withHandle` adds a grip.
*/
function ResizableHandle({
withHandle = false,
className,
seed,
roughness,
draw,
weight,
speed,
...props
}: Omit<ComponentProps<"div">, "children"> & { withHandle?: boolean; seed?: string | number } & Pick<Pen, "roughness" | "draw" | "weight" | "speed">) {
const context = useContext(GroupCtx);
const pen = usePen({ roughness, draw, weight, speed });
const s = useInkSeed(seed);
const id = useId();
const [active, setActive] = useState(false);
const drawing = useRef<{ from: Record<string, number>; start: number; length: number } | null>(null);
const vertical = context?.direction === "vertical";
const d = useMemo(() => (vertical ? ruleStroke(s, 700) : verticalStroke(s, 700)), [s, vertical]);
const register = context?.register;
useLayoutEffect(() => register?.(id, "handle"), [register, id]);
if (!context) return null;
const { items, sizes, drag, group } = context;
const panels = items.filter((item) => item.kind === "panel");
// The panel before this handle: how many panels registered before it, less one.
const at = items.slice(0, items.findIndex((item) => item.id === id)).filter((item) => item.kind === "panel").length - 1;
const left = panels[at];
const right = panels[at + 1];
const registered = at >= 0 && !!left && !!right;
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
const box = group.current?.getBoundingClientRect();
if (!box) return;
event.currentTarget.setPointerCapture(event.pointerId);
drawing.current = { from: { ...sizes }, start: vertical ? event.clientY : event.clientX, length: vertical ? box.height : box.width };
setActive(true);
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const state = drawing.current;
if (!state || !registered) return;
const rtl = !vertical && getComputedStyle(group.current!).direction === "rtl";
const delta = (((vertical ? event.clientY : event.clientX) - state.start) / state.length) * 100 * (rtl ? -1 : 1);
drag(at, state.from[left.id] + delta, state.from);
};
const end = (event: PointerEvent<HTMLDivElement>) => {
drawing.current = null;
setActive(false);
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!registered) return;
const [less, more] = vertical ? ["ArrowUp", "ArrowDown"] : ["ArrowLeft", "ArrowRight"];
const step = event.shiftKey ? 10 : 2;
let to: number | undefined;
if (event.key === less) to = sizes[left.id] - step;
else if (event.key === more) to = sizes[left.id] + step;
else if (event.key === "Home") to = left.minSize;
else if (event.key === "End") to = left.maxSize;
if (to === undefined) return;
event.preventDefault();
drag(at, to, sizes);
};
return (
<div
role="separator"
tabIndex={0}
aria-orientation={vertical ? "horizontal" : "vertical"}
aria-valuenow={registered ? Math.round(sizes[left.id]) : undefined}
aria-valuemin={0}
aria-valuemax={100}
data-slot="resizable-handle"
data-direction={context.direction}
data-active={active ? "" : undefined}
className={cn(
"relative flex shrink-0 touch-none items-center justify-center text-ink-4 transition-colors outline-none select-none hover:text-ink-2 data-active:text-ink",
"focus-visible:text-ink focus-visible:outline-solid focus-visible:outline-[1.5px] focus-visible:outline-offset-2 focus-visible:outline-ring",
vertical ? "h-px w-full cursor-row-resize" : "h-full w-px cursor-col-resize",
// A wide hit area around the thin line.
"after:absolute after:content-['']",
vertical ? "after:inset-x-0 after:-inset-y-1.5" : "after:inset-y-0 after:-inset-x-1.5",
className,
)}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={end}
onPointerCancel={end}
onKeyDown={onKeyDown}
{...props}
>
<InkSvg box={vertical ? [0, -1, 700, 4] : [-1, 0, 4, 700]} stretch className={vertical ? "inset-x-0 -top-0.5 h-1 w-full" : "inset-y-0 -left-0.5 h-full w-1"} style={penStyle(pen)}>
<Stroke d={d} draw={pen.draw ?? "auto"} duration={700} width={1.2} className="[vector-effect:non-scaling-stroke]" />
</InkSvg>
{withHandle && <Grip vertical={!!vertical} seed={s} pen={pen} />}
</div>
);
}
/** A little boxed grip of three dots on the line. */
function Grip({ vertical, seed, pen }: { vertical: boolean; seed: number; pen: Pen }) {
const dots = useMemo(() => [0, 1, 2].map((i) => dotStroke(seed + 7 + i, 0.9)), [seed]);
return (
<div className={cn("relative z-10 flex items-center justify-center bg-popover", vertical ? "h-4 w-7" : "h-7 w-4")}>
<InkOutline pen={{ ...pen, passes: 1, corners: "joined" }} estimate={vertical ? [28, 16] : [16, 28]} pad={3} className="text-ink-3" />
<InkSvg box={[0, 0, 12, 12]} className={cn("relative size-3", vertical && "rotate-90")}>
{dots.map((path, i) => (
<g key={i} transform={`translate(6 ${2.5 + i * 3.5})`}>
<Stroke d={path} width={1.6} />
</g>
))}
</InkSvg>
</div>
);
}
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };Usage
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable"
<ResizablePanelGroup direction="horizontal">
<ResizablePanel defaultSize={50}>One</ResizablePanel>
<ResizableHandle />
<ResizablePanel defaultSize={50}>Two</ResizablePanel>
</ResizablePanelGroup>Examples
Vertical
Panels one above another.
Header
Content
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
export default function ResizableVertical() {
return (
<ResizablePanelGroup framed seed="rz-vert-frame" direction="vertical" className="h-64 w-full max-w-md" aria-label="Two panels, one above the other">
<ResizablePanel defaultSize={30} minSize={15}>
<div className="flex h-full items-center justify-center p-6 text-lg font-bold">Header</div>
</ResizablePanel>
<ResizableHandle seed="rzv" aria-label="Resize the panels" />
<ResizablePanel defaultSize={70} minSize={20}>
<div className="flex h-full items-center justify-center p-6 text-lg font-bold">Content</div>
</ResizablePanel>
</ResizablePanelGroup>
);
}With a grip
A boxed grip on the handle, and a group nested inside a panel.
Pages
Canvas
Notes
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
export default function ResizableHandleExample() {
return (
<ResizablePanelGroup framed seed="rz-handle-frame" direction="horizontal" className="h-64 w-full max-w-xl" aria-label="Notebook layout">
<ResizablePanel defaultSize={25} minSize={15} maxSize={40}>
<div className="flex h-full items-center justify-center p-4 text-lg font-bold">Pages</div>
</ResizablePanel>
<ResizableHandle withHandle seed="rzh-a" aria-label="Resize the page list" />
<ResizablePanel defaultSize={75}>
<ResizablePanelGroup direction="vertical">
<ResizablePanel defaultSize={65} minSize={25}>
<div className="flex h-full items-center justify-center p-4 text-lg font-bold">Canvas</div>
</ResizablePanel>
<ResizableHandle withHandle seed="rzh-b" aria-label="Resize the notes" />
<ResizablePanel defaultSize={35} minSize={15}>
<div className="flex h-full items-center justify-center p-4 text-lg font-bold">Notes</div>
</ResizablePanel>
</ResizablePanelGroup>
</ResizablePanel>
</ResizablePanelGroup>
);
}API reference
- ResizablePanelGroup directiondefault
"horizontal" "horizontal" | "vertical"Which way the panels run. Give the group a height.
- ResizablePanelGroup frameddefault
false booleanPencils a box round the whole group.
- ResizablePanelGroup onLayout
(sizes: number[]) => voidCalled with every panel's size, as percentages, as a handle moves.
- ResizablePanel defaultSize / minSize / maxSize
numberPercentages of the group. Panels without a defaultSize share what's left.
- ResizableHandle withHandledefault
false booleanAdds a boxed grip on the line.
- ResizableHandle keys
Arrow keys, Shift, Home, EndFocus the handle: arrows move it 2%, with Shift 10%; Home and End send it as far as the panels allow.
- seed
string | numberPins the drawing.
Pen settings
The drawing also takes draw, roughness, weight and speed, as props or from the nearest InkProvider. What each one does.