@kellanjs/use-resizable
v0.1.0
Published
Headless React hooks for resizable UI: sidebars, drawers, floating windows, split panes, IDE layouts and grids.
Maintainers
Readme
@kellanjs/use-resizable
Headless React hooks for resizable UI: sidebars, drawers, images, floating windows, split panes, IDE layouts and grids.
The hooks hand you props to spread onto your own elements. You own the markup and every pixel of styling; the library owns sizes, limits, snapping, dragging, keyboard control and persistence.
- React 18 or later; for its types, TypeScript 5.4 or later.
- No CSS to import and no wrapper components: every element is yours.
npm install @kellanjs/use-resizableThe examples style with Tailwind classes; any CSS works the same way.
Contents
- Quick start
- Concepts
useResizable, a guideuseResizableLayout, a guide- How a layout shares space
- Content while it resizes
- Persistence
- Motion
- Styling
- Accessibility
- Performance
- Recipes
- Building blocks
- Reference
- Pitfalls
Quick start
One element: a sidebar
useResizable resizes one element whose size is its own. Spread
getElementProps() onto the element and getHandleProps(edge) onto each handle
you drag:
import { useResizable } from "@kellanjs/use-resizable";
export function AppFrame() {
const sidebar = useResizable({
anchor: "start", // the left edge stays still (the right, right to left)
width: {
defaultSize: "16rem",
minSize: "12rem",
maxSize: ["28rem", "50%"], // 28rem, or half the container if smaller
},
persist: { key: "sidebar" }, // saved to localStorage
});
return (
<div className="flex h-screen">
<aside {...sidebar.getElementProps()} className="relative border-e">
<nav className="p-4">Navigation</nav>
<div
{...sidebar.getHandleProps("end")}
aria-label="Resize sidebar"
className="absolute inset-y-0 -end-1 w-2 hover:bg-blue-500/40"
/>
</aside>
<main className="min-w-0 flex-1 p-4">Main content</main>
</div>
);
}The handle is an ordinary element you place and style; the library makes it draggable, focusable (arrow keys resize) and announced as a separator. The main area beside the sidebar is plain flexbox: it takes what the sidebar leaves.
Elements sharing space: a split
useResizableLayout resizes elements that share one space, so one grows by
taking from its neighbours. Describe the layout as data, then spread props onto
a group's element, its children and the separators between them:
import { useResizableLayout } from "@kellanjs/use-resizable";
export function Editor() {
const editor = useResizableLayout({
layout: {
id: "editor",
direction: "row",
children: [
{ id: "files", defaultSize: 240, minSize: 160 },
{ id: "code", minSize: 320 }, // no defaultSize: takes the rest
{ id: "preview", defaultSize: "30%", minSize: 200 },
],
},
persist: { key: "editor" },
});
return (
<div {...editor.getGroupProps("editor")} className="h-screen">
<nav {...editor.getElementProps("files")}>Files</nav>
<div
{...editor.getSeparatorProps("files", "code")}
aria-label="Resize files"
className="w-px bg-neutral-300"
/>
<main {...editor.getElementProps("code")}>Code</main>
<div
{...editor.getSeparatorProps("code", "preview", { primary: "after" })}
aria-label="Resize preview"
className="w-px bg-neutral-300"
/>
<section {...editor.getElementProps("preview")}>Preview</section>
</div>
);
}Here the layout is a single group, its root (id: "editor"); a layout with
groups inside it calls getGroupProps once per group (see
Groups in groups).
A separator's size is the room it takes, so a 1px line is a 1px target; A
separator gives it a wider hit area that takes no room.
primary: "after" makes the second separator about the preview (its value, its
keys, its label), as it's the preview that a user resizes there.
From here, the guides build on these two:
useResizable and
useResizableLayout. How a layout shares
space has every rule for complex layouts, and
Reference every option with its type and default.
Concepts
Two hooks
| Hook | Use it for | You drag |
| -------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| useResizable | One element whose size is its own: a sidebar, a drawer, an image, a chat widget. | handles, which drive its free edges and corners |
| useResizableLayout | Elements sharing one space, in rows and columns: an editor split, an IDE layout, a grid. | separators, which sit between the children of a group |
The difference is where the space comes from. A resizable sidebar grows into whatever is next to it, and the page reflows. An element in a layout grows by taking space from its neighbours, so the layout resolves them together: if one hits its minimum, the next gives way; if one snaps to a smaller stop, the other side takes the space.
Terms
- An element is something resized that you put content in, in either hook: a sidebar, or one pane of a layout.
- A handle is any element you drag to change a resizable: an edge handle, a corner handle, or a floating element's move handle. It's your own element, placed and styled as you like.
- A handle's edge is the part of the element it drives (
"right", or a corner like"top-left", which drives two edges), not where the handle sits. - A layout is what one
useResizableLayoutcoordinates: elements in groups, each group a row or a column of children. A child is an element, another group, or a grid; the layout's root is the top group (or a grid). Every group, grid and element has anid. - A grid lays its children out in columns and rows at once: its columns and rows are tracks that resize like a group's children, and its children are cells placed on them, spanning one or more.
- A separator sits between two neighbouring children of a group (or two neighbouring tracks of a grid). Dragged like a handle, whatever one side gains, the other loses. It's your own element: the library connects it to its two neighbours, not to a place on screen.
- A line is the boundary between two neighbours that a drag moves. Usually one separator draws it; a grid line that a spanning cell cuts is drawn by several, its segments, which move and light up together.
- A junction drags several separators at once, the way a corner handle drives two edges. You render it where they cross.
- A stop is a named size (a point, like a rail) or range of sizes (a range, like open) that a dimension or a layout child rests in. A dimension or a child with its stops is a track, and so is a grid's column or row.
- Stepping down is a layout child moving to a smaller stop on its own,
because its group's minimums don't fit, and back up once they do (
yieldTo). - A fill is a layout element that takes whatever space its siblings leave,
instead of having a size of its own (
fill). - Zero is the library's word for a size of 0 (
hideAtZero,data-zero), so it can't be confused with your stop names, likeclosed. - The content size is the size an element's content is laid out at, which
can differ from the element's own while it resizes (
contentSize; see Content while it resizes).
The same ideas in both hooks
The two hooks name the same ideas the same way where they can:
| Idea | useResizable | useResizableLayout |
| ---------------------------- | -------------------------------------- | ------------------------------------------ |
| What's resized | getElementProps() | getElementProps(id), getGroupProps(id) |
| Its content (optional) | getContentProps() | getContentProps(id) |
| A layer clipping it | getClipProps() | getClipProps(id) |
| What it sits in | its container (containerRef) | the root group, getGroupProps(rootId) |
| What you drag | getHandleProps(edge) | getSeparatorProps(before, after) |
| Two at once | a corner, getHandleProps("top-left") | getJunctionProps([[a, b], [c, d]]) |
| Live state | width, height | getChild(id), elements |
| Its stop, and the one before | width.stop, width.previousStop | getChild(id).stop, .previousStop |
| Where this change began | width.fromStop | getChild(id).fromStop |
| Content to show for the stop | width.contentStop | getChild(id).contentStop |
| Stepped down to fit, from | — | getChild(id).yieldedFrom |
| Move to a stop | setStop("rail") | setStop(id, "rail") |
| Back to the defaults | reset(), reset("width") | reset(), reset(id) |
| Being dragged | dragging: an edge, or "move" | dragging: [{ before, after }] |
| Transitioning | animating, data-animating | animating, data-animating |
| At zero | data-zero | data-zero |
| Reached from elsewhere | createResizableRemote() | createLayoutRemote() |
Sizes
Anywhere a size (or a floating element's position) is accepted, it can be:
| Value | Meaning |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| 240 | Pixels. |
| "240px" | Pixels. |
| "16rem" | Root ems. Follows the root font size, even if it changes. |
| "25%" | For useResizable, a percentage of the container, along the same dimension. In a layout, a percentage of the space the group's children share. |
| "25vw" | A percentage of the viewport's width (vh: its height), as in CSS. Follows the window as it resizes. |
Sizes can't be negative (a floating element's position can). The type is
SizeValue.
Lists of limits. minSize and maxSize (and a range's min and max)
also take a list, and every entry applies, so the tightest wins:
maxSize: ["28rem", "50%"] means "28rem, or half the container if that's
smaller", like CSS min(28rem, 50%). The type is SizeBound.
When limits conflict. When a minimum and maximum disagree
(minSize: "17.5rem" with maxSize: "90%" in a narrow container), the minimum
wins, as in CSS: the element's content stays usable, and it can be wider than
what it sits in. wins: "max" lets the maximum win instead, so what's beside it
stays usable:
width: { minSize: "17.5rem", maxSize: ["32.5rem", "90%"], wins: "max" }wins is per dimension (or layout child, or grid track) and covers all its
ranges. It applies to limits from outside it too: the container's room with
confine, an aspect ratio's, and what a nested group's children need.
Whole boxes. A size is the element's whole box, padding and border included.
For useResizable, getElementProps sets box-sizing: border-box on what it
sizes (your style can say otherwise, but its stops and its room in a container
then leave the padding and border out). A layout's sizes are whole boxes
whatever box-sizing its children use: it allows for content-box itself.
Kept as given. A size you give (a default, or setSize) is kept as you gave
it until the user resizes: a % width stays a percentage, so it follows the
container as the window resizes. A drag or a key sets it in pixels. (A layout's
children keep their share of the group's space either way.)
In a layout, a child's sizes are along its group's direction: its width in a
row, its height in a column. How % limits behave in nested groups is in %
limits in nested groups.
Stops
Without stops, a dimension or layout child is one range, from minSize to
maxSize. With stops, it's a set of named places it can be: single sizes
(points), or ranges of sizes.
width: {
defaultSize: "16rem",
stops: {
closed: { size: 0, onlyByName: true },
rail: "3.5rem",
open: { min: "12rem", max: ["28rem", "50%"] },
},
}| Stop | Written as |
| ----- | ------------------------------------------------------------------ |
| point | a size, "3.5rem", or { size: "3.5rem" } with options beside it |
| range | { min, max }; min defaults to 0, max to unbounded |
The names are yours: there's no built-in "collapsed" or "expanded". width.stop
(or a layout child's stop) names the stop it's in, typed from your options,
and data-width-stop / data-stop expose it to CSS. Whether rail means
"collapsed", "compact" or something else is your app's call. Without named
stops, stop is null. stops and minSize/maxSize can't be combined: give
the range in stops its own min and max.
Each stop takes options (pull, onlyByName, endsDrag, elastic), listed in
Stop options and explained below.
Where a size lands
Drags, arrow keys and setSize all ask for a size, and the stops decide where
it lands:
- Inside a stop, it stays as asked: in a range, the size follows the pointer.
- In a gap between stops, it goes to the nearer side, dividing the gap
halfway.
pull(default 1) moves the dividing point: withrail: { size: "3.5rem", pull: 3 }, the rail claims three quarters of each gap beside it, so leaving it takes a longer drag. - Beyond every stop, it stops at the nearest one (with an elastic stretch past a range's end while dragging).
onlyByName: truestops are never landed on by a drag, the arrow keys orsetSize. Only naming them reaches them (setStop,toggle, or Enter whenenterTogglesnames one), for states a button should reach but a drag shouldn't, like closed.endsDrag: truestops end the drag when it lands in them (or passes through them, however fast the pointer moves), as if the pointer had been released: the move into the stop animates, and the rest of the gesture is ignored until the next press. For gestures that should play out on their own, like a drawer closing:closed: { size: 0, endsDrag: true }. A range with it goes to the size it has there, assetStopwould, rather than where the pointer was (just past its edge), so a drawer pulled open (endsDragon its open range) opens as a toggle would. Dragging out of the stop works as usual.
Elastic stretch. While dragging, a size can stretch a little past a stop's
edge, with resistance, and spring back on release. By default ranges stretch at
their ends and points stay crisp. A stop's own elastic option changes where
that happens: true or false for both ways, or "larger" / "smaller" for
one. With rail: { size: "3.5rem", elastic: "larger" } the rail gives a little
when pulled open, but not when pushed smaller (where, if the only stop below is
an onlyByName one, nothing would happen); elastic: false on a range makes
its ends hard. A stretch is resistance: it happens where the pointer has gone
past a stop's edge (a rail pulled open, a maximum pushed, a minimum pushed on
the way back). Where a drag snaps across a gap to a stop the pointer hasn't
reached yet, the pointer is short of it, and it sits at that stop's edge
(opening from a rail lands at exactly the minimum).
[!NOTE] Two options are called
elastic. A stop'selasticsays where a stretch happens (which ways, at that stop). The hook'selasticoption says how a stretch feels (how far and how stiff, andafterSnap), or turns stretching off entirely; see Motion.
Order and overlaps. The order stops are written in doesn't matter. They're
resolved and sorted by size after measuring, which matters when some are % and
some rem: their order can change with the window. Stops may overlap. While the
size is inside the current stop, it stays in that stop; otherwise it's in the
narrowest stop containing it. So a point inside a range (say half: "50%"
inside open) is passed over by drags and reached with setStop("half").
Moving between stops
setStop("rail")goes to a point, or to a range at the size it last had there. Each range remembers its own size.toggle("rail")goes torail, or if it's already there, back: to the stop it came from if that's a larger one, so hiding a sidebar from its rail and showing it again comes back to the rail; otherwise to the last range it was in. (Where it came from is where it last rested, not a stop a drag passed through.)- In
useResizable, without a dimension, both act on every dimension with a stop of that name, so a width and a height that share one (sayminimised) move together. A toggle then decides once: back only if both are at the stop, otherwise both go to it. Pass a dimension to act on just one, as intoggle("minimised", "height"). - Enter on a focused handle or separator toggles a stop too: by default the
smallest stop a drag can reach (when there's more than one), or the one
enterTogglesnames (falsefor none). See Accessibility. defaultStop: "rail"starts there. Without it, a track starts whereverdefaultSizelands (a layout child without either starts in its roomiest stop). Give named stops adefaultStopfor exact server HTML: until it knows which stopdefaultSizelands in, the CSS before measuring is justdefaultSize.defaultSizeis optional when there's adefaultStop. A range the track hasn't been in then starts at its minimum, and toggling back with no range to return to goes to the roomiest stop.setStopwith a name that isn't one of the stops throws (and is a type error).
useResizable, a guide
Every option is in useResizable options, with its
type and default; what the hook returns is in What useResizable
returns.
Anchors and handles
The anchor says which part of the element stays still while it resizes, named
like CSS background-position. It decides which handles there are. With both
width and height:
| Anchor | Stays still | Handles |
| ---------------- | --------------------------------- | ---------------------------------------------- |
| "left" | the left edge, centred vertically | right, top, bottom, both right corners |
| "top" | the top edge, centred across | left, right, bottom, both bottom corners |
| "top-left" | the top-left corner | right, bottom, bottom-right |
| "bottom-right" | the bottom-right corner | left, top, top-left |
| "center" | the centre | all four edges and corners |
| "none" | nothing: the element is floating | all eight, plus a move handle |
The other sides and corners ("right", "bottom", "top-right",
"bottom-left") work the same way.
- Only dimensions you configure are resizable. A sidebar (
anchor: "left") with onlywidthgets only itsrighthandle, and a drawer (anchor: "bottom") with onlyheight, onlytop. handlesoffers fewer than the anchor allows: corners only on an image, say (then a corner takes the keyboard; see Accessibility), orhandles: []for an element only your code resizes.- Reading direction. The sides can go by reading direction, as layouts do:
"start"and"end", and corners like"top-start"and"bottom-end". They're the left and right in a left-to-right page, and the other way round in a right-to-left one, by the element's CSSdirection. A sidebar withanchor: "start"stays at the start either way. Thehandlesoption andgetHandlePropstake the same names (getHandleProps("end")), while the returnedhandleslist, anddata-handle, give the physical edges, so styles written forleftandrightkeep working. - When the direction is read. When the element mounts, each time its container is measured, and when a handle is pressed. Before it mounts, it's left to right, as on the server, which can't know: so a right-to-left page hydrates the server's HTML as it is, and the handles move to their side as it mounts, before anything's painted.
[!IMPORTANT] The anchor describes your CSS layout; it doesn't create it. A centred image needs CSS that centres it and
anchor: "top"or"center", so the library knows each pixel of drag should grow both sides (twice the size change). Centre it with flex or grid (align-self: centerin a column) rather thanmargin: auto: pulled past its max, the element is briefly wider than its container, and auto margins then align it left, so the stretch shows only on the right.
Handles. A handle is any element you spread getHandleProps(edge) onto,
where edge is the part of the element it drives (an edge, or a corner), not
where it sits. Usually it sits on that edge, inside the element, but it can be
anywhere: a drag moves the edge by however far the pointer moves. You place it,
size it and style it. The usual placement is centred on its edge or corner,
absolutely positioned in the element (which then needs position: relative, or
any other positioning), with a bigger hit area on a touch screen. Render one per
entry of handles to offer them all:
import { type HandleEdge, useResizable } from "@kellanjs/use-resizable";
const PLACEMENT: Record<HandleEdge, string> = {
left: "inset-y-0 left-0 w-2 pointer-coarse:w-6 -translate-x-1/2",
right: "inset-y-0 right-0 w-2 pointer-coarse:w-6 translate-x-1/2",
top: "inset-x-0 top-0 h-2 pointer-coarse:h-6 -translate-y-1/2",
bottom: "inset-x-0 bottom-0 h-2 pointer-coarse:h-6 translate-y-1/2",
"top-left": "top-0 left-0 z-10 size-3 pointer-coarse:size-8 -translate-1/2",
"top-right":
"top-0 right-0 z-10 size-3 pointer-coarse:size-8 translate-x-1/2 -translate-y-1/2",
"bottom-left":
"bottom-0 left-0 z-10 size-3 pointer-coarse:size-8 -translate-x-1/2 translate-y-1/2",
"bottom-right":
"bottom-0 right-0 z-10 size-3 pointer-coarse:size-8 translate-1/2",
};
export function Box() {
const box = useResizable({
anchor: "top-left",
width: { defaultSize: 320, minSize: 160 },
height: { defaultSize: 200, minSize: 120 },
});
return (
<div {...box.getElementProps()} className="relative border">
Content
{box.handles.map((edge) => (
<div
key={edge}
{...box.getHandleProps(edge)}
aria-label={`Resize box (${edge})`}
className={`absolute ${PLACEMENT[edge]} hover:bg-blue-500/40`}
/>
))}
</div>
);
}- Corners go above edges (
z-10), so where they overlap, the corner wins. pointer-coarse:(or@media (pointer: coarse)) gives fingers a bigger target, from the first render.- When the element goes to zero against its container's edge, a handle centred
on that edge is half cut off if the container clips. The handle has
data-zerothen, so it can move to the open side (see Bottom drawer). It's set as a change to zero begins, so move it with the change's timing (--resizable-duration,--resizable-easing), or it jumps out before the element closes. - Don't put
overflow: hiddenon the element: it would clip handles that hang over its edge. Clip an inner wrapper instead (see Pitfalls). - A handle in Building blocks is the same placement as plain CSS.
A sidebar or a drawer
The quick start is a complete sidebar. The parts that matter:
- The container.
%sizes are of the element's container: its parent, unlesscontainerRefpoints elsewhere. The main area beside it is yours (flexbox, say); the library only sizes the sidebar. - Limits.
minSizeandmaxSizemake one range. With stops instead, the sidebar can rest at a rail, or close. - Your code.
sidebar.setSize({ width: "20rem" })lands like a drag would (inside the range, or at the nearest stop), and before the container is measured it waits for it.sidebar.reset()goes back to the defaults;reset("width"), just the width. - Its state.
sidebar.widthhas thesizein pixels (nulluntil measured), thestopit's in, thestopsin pixels, and the content fields (Content while it resizes). The type knows which dimensions you configured, sosidebar.width.sizeneeds no?.. To size something to a stop before anything is measured (a rail's icon column), share the CSS length with the options instead.
A drawer is the same thing turned round: anchor: "bottom" with only height,
so its handle is top. Stops like
{ closed: 0, open: { min: 96, max: "80%" } } let it close; Bottom
drawer is the complete recipe, including where its handle goes
at zero.
A rail: stops on a sidebar
A rail is a stop: a point the sidebar rests at, between closed and open.
width: {
defaultSize: "16rem",
defaultStop: "open",
stops: {
closed: { size: 0, onlyByName: true }, // a button closes it; a drag can't
rail: { size: "3.5rem", endsDrag: true },
open: { min: "12rem", max: ["28rem", "50%"] },
},
}Dragging narrower than the open range snaps to the rail at the gap's halfway
point; endsDrag makes reaching the rail end the drag, as if released, so the
collapse plays out on its own instead of following the pointer. toggle("rail")
and toggle("closed") are the buttons. Show the rail's content by
width.contentStop, not width.stop (which changes as a change begins, so the
open content would vanish as the closing starts): see Deciding what to
show. Sidebar with an icon
rail is the complete recipe.
A stop, or a range's minimum? Make the rail a stop when it's a state of its
own: sizes between it and the open range aren't places to rest (a drag there
snaps to one or the other), stop and contentStop name it, and the open
content keeps its open size while the rail shows. When the narrowest size is
just small rather than different (a pane that can be dragged as narrow as you
like, down to its minimum), leave it the open range's minimum, and to show
something there, compare contentSize with the minimum (see Deciding what to
show).
Floating and confined
With anchor: "none" the element is floating: it has a position as well as a
size, and a move handle.
- Its position is
x,yfrom the container's top-left, inside its border, and may be negative. Like an absolutely positioned element's, its position and%sizes are of the container's padding box. It starts atdefaultPosition(default{ x: 0, y: 0 }), andsetPosition({ x, y })moves it. - Its styles. It gets
position: absolute,leftandtop, so its container needs a positioning of its own (position: relative). - The move handle is
getMoveHandleProps(), spread onto a title bar, say. It takes arrow keys too: give it a label that says so. - Resizing from an edge or corner keeps the opposite side still.
confine: "container" keeps it inside its container:
- It's never bigger than the container, unless its minimum is: as in CSS, the
minimum wins, unless
wins: "max"(see Sizes). - It's shown inside the container whatever moved it: a drag, the keyboard,
setSize,setPosition, or the container shrinking. A width or height you size yourself (with CSS, or its content) counts as drawn: the element is measured for it. - Resized from an edge, it can't reach a stop whose smallest size is bigger than
the room on that side (a point, or a range's minimum): a drag (or a key; Enter
by default goes no further than the room either) stops on one that fits,
rather than show the stop at a size it isn't, or past the edge.
setStopstill goes there, moving the element inside, and so does Enter to the stopenterTogglesnames. - An elastic stretch gives at the element's own limits, but not at the container's edge.
- The position you set is kept, so it goes back there when there's room again: resizing it doesn't change it, unless the resize moved it (from the left or top) or it was shown somewhere else to fit (then it stays where it was seen).
defaultPosition and confine need anchor: "none" (anything else throws).
Floating window is the complete recipe.
Aspect ratio
aspectRatio: 16 / 9 (width ÷ height) locks the ratio. Only the width is
stored, and CSS aspect-ratio sizes the height:
- Height handles still work: they drive the width through the ratio.
heighttakes onlyminSizeandmaxSize, which become width limits through the ratio.setSize({ height })sizes the width through the ratio, in pixels (a height invhdoesn't stay relative as a width); given both, the width is used.- The height's stops are the width's:
setStop(stop, "height")goes to the width's stop.
A corner can only move along its path (the line from the anchor out through the
corner), and cornerDrag says how it follows the pointer:
"nearest"(the default): it goes to the point on that path nearest the pointer. This feels smooth in every direction, but off the path the corner trails the pointer."axis": it stays on the pointer along whichever axis you pull further (pulls in opposite directions offset each other). Use it when people line an edge up with something exactly, as in design tools. The cost is unevenness: near the start of a drag, wobble one way is ignored and the other way counts.
Image in a document is the complete recipe.
useResizableLayout, a guide
Every option is in useResizableLayout options
and the tables after it (groups, children, grids, tracks, cells), with their
types and defaults; what the hook returns is in What useResizableLayout
returns. The rules for how children share
space are in How a layout shares space.
A row or column
import { useResizableLayout } from "@kellanjs/use-resizable";
import { Fragment } from "react";
export function Editor() {
const editor = useResizableLayout({
layout: {
id: "editor",
direction: "row",
children: [
{
id: "files",
defaultSize: 240,
defaultStop: "open",
stops: { closed: 0, open: { min: 180 } },
},
{ id: "code", minSize: 320 },
{ id: "preview", defaultSize: "30%", minSize: 200 },
],
},
});
return (
<div {...editor.getGroupProps("editor")} className="h-full">
{editor.elements.map((element, index) => (
<Fragment key={element.id}>
{index > 0 && (
<div
{...editor.getSeparatorProps(
editor.elements[index - 1].id,
element.id,
)}
// About the child before it (see Accessibility).
aria-label={`Resize ${editor.elements[index - 1].id}`}
className="relative w-px bg-neutral-700"
>
{/* A wider area to grab, 4px past the line on each side. */}
<span className="absolute -inset-x-1 inset-y-0" />
</div>
)}
<section {...editor.getElementProps(element.id)}>
{element.id}
</section>
</Fragment>
))}
</div>
);
}The layout. layout is the root group: its id, its direction ("row"
lays children out left to right; "column", top to bottom), its children, and
optionally refuseOverflow (see Overflow).
Nested groups take the same. Every id must be unique in the layout, and not
empty.
Sizes are along the group's direction. A child's defaultSize, minSize,
maxSize and stops are its width in a row and its height in a column. Across
the group, every child is as big as the group (flexbox stretches it). So in a
column inside a row, minSize is a height; the column's own minSize, as a
child of the row, is a width.
Children without a defaultSize share whatever space is left. One child
must be able to take the space the others leave: see rule
1.
Separators, gaps and padding. Separators can be any size, and gaps, padding and borders are fine, on groups and on children: the layout measures what its children actually got, and each child's own padding and border are part of its size. One limit comes from CSS: nothing renders smaller than its own padding and border, so a child that goes to zero (or to a rail narrower than its padding) should pad an inner wrapper instead. (Its siblings are drawn smaller by that much, and their content laid out so.)
Right to left. In a right-to-left page (direction: rtl, or dir="rtl" on
any ancestor), a row lays its children out from the right, and drags and arrow
keys follow the screen: moving a separator right grows the child on its right,
whichever it is in the options. Each row's direction is read from the page when
a drag or key press starts.
A separator's hit area. A separator sits in the layout between two children,
so flexbox places it. Being in the layout, its size is the room it takes: a 1px
line is a 1px target. To make it easier to grab without taking more room, give
it a wider child, as above (it overlaps its neighbours' edges, so it goes above
them: the separator relative, and a z-index on the wider child if they're
positioned; see Junctions for why not on the separator). Each
separator has data-direction (its group's), so one component can draw both
kinds: data-[direction=row]:w-px data-[direction=column]:h-px. A
separator in Building blocks does all of this in plain CSS.
Live state. Both hooks re-render with the live sizes during a drag (see
Performance). editor.getChild("files") has its size, stop,
stops and content fields; editor.elements lists every element in reading
order. To follow every change without re-rendering (or outside React), subscribe
to the controller: editor.controller.subscribe(listener).
Dragging a separator
A drag (or an arrow key on a focused separator) moves the line between two neighbours: whatever one side gains, the other loses.
- Within their stops, the neighbours follow the pointer.
- A neighbour at the end of its stop, with another stop beyond it, stops there and snaps across the gap once the pointer passes the gap's dividing point (see Where a size lands), but only if the other side can take or give exactly that much.
- A neighbour with nothing beyond it lets the drag push on to the next
child, and the next (cascading). With
cascade: false, the separator stops there instead. - A neighbour snapping across a gap goes first. Opening a strip next to a pane just above its minimum: the strip opens once the pointer passes its own dividing point, the pane gives what it has down to its minimum, and the children beyond give the rest. From there the drag carries on as if it had started that way: the pane stops at its minimum, and collapses only when the pointer passes its dividing point in turn.
- Drags don't use
priority,growor stepping down: a drag moves the children beside it. (How children beside a fill move is in Fills.)
A drag never pushes a child below its minimum, and a separator that can't change anything either way is disabled for the moment (see What lights up).
The layout is data
layout is the source of truth, so a "dynamic" layout is just one that changes:
- Adding a child: it gets its
defaultSize(or a fair share) and the others make room, growing from 0 as they do; those that keep their size (keepSize) only once nothing else can. One coming back gets the size it had, the same way. If several join at once and don't all fit, they share what's short in proportion to their sizes. - Removing a child: the others take its space, at once. Its size is remembered, so it comes back the size it was.
- Reordering: sizes travel with the children.
Keep ids stable. They identify children across renders, reorders and saved layouts. Workspace of panes is the complete recipe.
Groups in groups
A child with its own direction and children is a group:
import { useResizableLayout } from "@kellanjs/use-resizable";
export function Ide() {
const ide = useResizableLayout({
layout: {
id: "ide",
direction: "row",
children: [
{ id: "files", defaultSize: 220, minSize: 160 },
{
id: "work",
direction: "column",
children: [
{ id: "editor", minSize: 200 }, // a height: work is a column
{
id: "terminal",
defaultSize: 160,
stops: { bar: "2rem", open: { min: 80 } },
},
],
},
],
},
});
return (
<div {...ide.getGroupProps("ide")} className="h-screen">
<nav {...ide.getElementProps("files")}>Files</nav>
<div
{...ide.getSeparatorProps("files", "work")}
aria-label="Resize files"
className="w-px bg-neutral-300"
/>
<div {...ide.getGroupProps("work")}>
<main {...ide.getElementProps("editor")}>Editor</main>
<div
{...ide.getSeparatorProps("editor", "terminal", { primary: "after" })}
aria-label="Resize terminal"
className="h-px bg-neutral-300"
/>
<section {...ide.getElementProps("terminal")}>Terminal</section>
</div>
</div>
);
}This is one layout, not two groups that don't know about each other. A nested
group is sized like any child of its parent (it takes the same size options:
defaultSize, stops, keepSize, yieldTo…), and it can't shrink below what
its own children need. Ids are typed from the options, nested ones included, and
so is each child's stops: a typo in getElementProps("edtor") or
setStop("terminal", "closd") is a type error. The callbacks get the same ids
(onDragStart's separators, valueText's id).
Rendering a tree. Written out like this, the markup mirrors the tree. When
the tree is data (the user can split and merge panes), render it recursively
with childrenOf(id), which lists a group's children, each
{ id, kind, previous }:
kindis"element","group"or"grid";previousis the child before it (nullfor the first), and the separator between them isgetSeparatorProps(previous, id).
import { type ResizableLayout } from "@kellanjs/use-resizable";
import { Fragment, type ReactNode } from "react";
export function renderGroup(workspace: ResizableLayout, id: string): ReactNode {
return (
<div {...workspace.getGroupProps(id)}>
{workspace.childrenOf(id).map((child) => (
<Fragment key={child.id}>
{child.previous && (
<div
{...workspace.getSeparatorProps(child.previous, child.id)}
aria-label={`Resize ${child.previous}`}
/>
)}
{child.kind === "element" ? (
<section {...workspace.getElementProps(child.id)}>
{child.id}
</section>
) : (
renderGroup(workspace, child.id)
)}
</Fragment>
))}
</div>
);
}Start it with the root's id. A grid's childrenOf lists its cells (each with
previous: null), and its lines come from separatorsOf: see Grids.
Keep the props' id: it's the element's DOM id, which separators point at
(aria-controls). To pass your own id to a component, use another name, like
paneId.
Grids
A grid lays its children out in columns and rows at once. (In a tree, the two
columns of a 2×2 layout each have their own row line; in a grid, a line runs
through the whole grid.) Its columns and rows are tracks, each sized like a
group's child, and its children are cells placed on them with column and
row (track ids), spanning columnSpan columns and rowSpan rows (1 each by
default):
import { useResizableLayout } from "@kellanjs/use-resizable";
const CELLS = ["chart", "stats", "table", "log"] as const;
export function Dashboard() {
const dashboard = useResizableLayout({
layout: {
id: "dashboard",
columns: [
{ id: "left", minSize: 160 },
{ id: "middle", minSize: 160 },
{
id: "right",
defaultSize: 260,
stops: { closed: 0, open: { min: 200 } },
},
],
rows: [{ id: "top" }, { id: "bottom" }],
children: [
{ id: "chart", column: "left", columnSpan: 2, row: "top" },
{ id: "stats", column: "right", row: "top", rowSpan: 2 },
{ id: "table", column: "left", row: "bottom" },
{ id: "log", column: "middle", row: "bottom" },
],
},
});
return (
<div {...dashboard.getGroupProps("dashboard")} className="h-screen">
{CELLS.map((id) => (
<section key={id} {...dashboard.getElementProps(id)}>
{id}
</section>
))}
{dashboard
.separatorsOf("dashboard")
.map(({ key, before, after, segment }) => (
<div
key={key}
{...dashboard.getSeparatorProps(before, after, { segment })}
aria-label={`Resize ${before}`}
className="separator"
/>
))}
{/* Where the line between middle and right crosses the row line. */}
<div
{...dashboard.getJunctionProps([
["middle", "right"],
["top", "bottom"],
])}
className="junction"
/>
</div>
);
}- Tracks take a child's size options (
defaultSize,minSize,maxSize,stops,defaultStop,enterToggles,wins,keepSize,priority,grow,yieldTo,locked,fill), along the grid's width for a column and its height for a row. A track is named by its id, like any child:setStop("right", "closed"),getChild("right")(its size, stop, stops and content size), keys, snapshots. - Cells have no size of their own (each is as big as the tracks it spans),
so they take no size options, and
getChildis for their tracks. A cell takesgetElementProps,getContentProps,getClipPropsandhideAtZero(hidden while it rests at 0 either way). Cells can't overlap, and a span can't run past the last track (both throw). - A cell's content size is its tracks' together: while any track it spans is in a range, what they show, so a cell spanning a track that closes reflows with its edge, as a child resized within its stop does; only while all of them close or open (or rest at points) is its content kept at theirs.
- Lines. A line runs between two neighbouring tracks, named like a
separator,
["left", "middle"], wherever no cell spans across it: above, the line between left and middle runs under the chart only. A cell spanning across a line in the middle cuts it in two. Each stretch is a segment, an element of its own:separatorsOf(id)lists them, each{ key, before, after, segment }(for a group, its separators, allsegment: 0), andgetSeparatorProps(before, after, { segment })places one. Grab any segment and the whole line moves; its segments light up together. - It's a CSS grid (
display: grid, its templates set by the library), with a track between each two of its tracks for the line there, as thick as the line's segments: a line takes room, as a separator does in a group. Cells, segments and junctions are placed for you, so their order in the markup doesn't matter, but for the tab order. - Junctions. A junction of one of its column lines and one of its row lines
places itself on their crossing (positioned absolutely in the grid, which is
position: relative), at no cost through drags and animations: give it a size, and it's centred there. Other junctions you place yourself (see Junctions). - Cells clip. Cells get
contain: sizeandoverflow: hidden: they're as big as their tracks whatever's in them (content larger than a cell spanning tracks would otherwise widen the lines between them). - Where a grid goes. A grid can be the layout's root, or a child of a group, sized in it like any child (with the same size options), and a change in its size passes to its tracks.
- A cell can be a group or a grid itself: give it
directionandchildren, orcolumns,rowsandchildren, as a group's child would, and render it withgetGroupProps(id). A change in its tracks' sizes passes to it, and a track can't be smaller than a cell of its own needs (its group's children, or its grid's tracks, that way). Across a cell spanning several tracks, that's not kept to: the tracks together could need to be bigger, which the library doesn't work out, so its content is clipped instead. - Gaps. A grid's gaps changing resize nothing the layout watches: it notices
a change of the grid's own
classorstyle, but one from an ancestor or a CSS variable shows at the grid's next resize.
Grid dashboard is the complete recipe, styled.
Junctions
Where separators cross, a junction drags them together, the way a corner
handle drives two edges. Like a corner, it's an element you render and place:
name the separators it drags (each [before, after], as for
getSeparatorProps), and put it where they cross. A separator only ever drags
itself; nothing is inferred from where things sit on screen.
<div
{...ide.getSeparatorProps("editor", "terminal", { primary: "after" })}
aria-label="Resize terminal"
className="relative h-px"
>
{/* The left end of this line, where the files separator crosses it. */}
<div
{...ide.getJunctionProps([
["files", "work"],
["editor", "terminal"],
])}
className="absolute top-1/2 left-0 z-30 size-3 -translate-1/2"
/>
</div>- Where it goes in the DOM is up to you. Inside one of its separators, like a corner inside its element, it moves with that line for free, through drags and animations alike: the separator is the one element already where the lines meet. Elsewhere, you place it yourself (from the children's sizes, which jump where the transition glides, or with CSS anchor positioning). In a grid, it places itself (see Grids).
- It gets the
movecursor when its separators run different ways, anddata-draggingwhile it's dragged (its separators get theirs too). - While a mouse or pen is over it, it and the separators it would drag get
data-hover(see What lights up). - Pointer-only, like a corner (
aria-hidden, out of the tab order): each separator it drags is reachable from the keyboard on its own. - Pressing it doesn't also start a drag of the separator it's inside.
- Mind stacking: it has to be above the hit areas of the separators it
crosses. A separator with a
z-indexis a stacking context of its own, so a junction'sz-indexinside it only counts within it; put thez-indexon the hit areas and junctions instead. In development, when a separator gets a press inside a junction's box (so something covers the junction there), the library warns. - Separators that move the same space can't be dragged together: two in one group, or in nested groups that run the same way (moving the outer one resizes the inner group). Only the first named moves, and in development it warns.
- Which separators meet where is yours to say, and can change. In two columns each divided in two, say, render one junction for the column line and both middle lines while the middle lines line up (compare their sizes), and one per middle line otherwise.
A junction in Building blocks has its CSS.
What lights up
:hover only applies to the element under the pointer, but a press can move
more than that: a junction drags several separators, and in a grid each line can
be several segments that move as one. So while a mouse or pen is over a
separator or junction, every separator a press there would drag gets
data-hover, and so does the junction itself: it's what data-dragging will be
once the pointer moves. Style those two instead of :hover, and the lines that
light up are the lines that will move:
<div
{...editor.getSeparatorProps("files", "code")}
aria-label="Resize files"
className="bg-white/10 data-[dragging]:bg-cyan-400 data-[hover]:bg-cyan-400/60"
/>A touch has no hover, so nothing is left lit after a tap.
A separator that can't change anything right now, either way (one with only
fixed sizes on one side and nothing beyond them to give, say, or beside a
"last" fill with no space) doesn't pretend to: no resize cursor, no
data-hover, and a press does nothing. Unless Enter can still take its child to
a stop (one only reachable by name, say), it's also aria-disabled (still
focusable, so focus doesn't jump around). Style [aria-disabled] to dim or hide
it; it comes back once it can. One that can push a child at its minimum along,
or collapse one, counts as able to move. A separator you disable (see Locking
and disabling) gets the same treatment, as does one
beside a locked child with nothing beyond it.
Separators beside a child at zero
A child at zero takes no room, but its separators stay: they sit where it was, against the group's edge or against another separator, and dragging one opens the child again. Whether that's wanted is yours to decide: keep them grabbable, or hide them.
data-zero on a separator says which neighbour is at zero: "before",
"after" or "both". Like an element's, it's about the size the layout is
going to (below half a pixel), so it's set as a change to zero begins and
cleared as one out of it begins, not when the line arrives: styles on it move
with the change, not after it. With "both", neither side has room to open
into; the separator may still move (pushing children beyond, with cascading), so
it isn't disabled (aria-disabled says when nothing can move), and where its
hit area goes is your choice.
Keeping them grabbable. Two lines in one place are two of your elements overlapping, and the one on top gets the press. The separator's CSS moves the hit area wholly onto the open side next to a child at zero, above its neighbours, so a separator against the group's edge or another line can still be pressed.
Two that lie together. Below, the preview is the last child of work, and
the outline comes after work. With both closed, the preview's line (at the end
of work) and the outline's (at the end of the row) are both at the right edge,
and both hit areas move onto the same side. Which lines meet there is your
layout's to know, as with junctions; the separators' data-zero says when. Step
one of them aside with --separator-offset, and give them labels (and, if you
like, visible grips) that say which is which, since they're in the same place:
import { useResizableLayout } from "@kellanjs/use-resizable";
const closable = { closed: 0, open: { min: 200 } };
export function Workbench() {
const ide = useResizableLayout({
layout: {
id: "ide",
direction: "row",
children: [
{
id: "work",
direction: "row",
children: [
{ id: "editor" },
{ id: "preview", defaultSize: 300, stops: closable },
],
},
{ id: "outline", defaultSize: 240, stops: closable },
],
},
});
const preview = ide.getSeparatorProps("editor", "preview", {
primary: "after",
});
const outline = ide.getSeparatorProps("work", "outline", {
primary: "after",
});
// Both closed: the preview's line lies on the outline's.
const stacked = !!preview["data-zero"] && !!outline["data-zero"];
return (
<div {...ide.getGroupProps("ide")} className="h-screen">
<div {...ide.getGroupProps("work")}>
<main {...ide.getElementProps("editor")}>Editor</main>
<div
{...preview}
aria-label="Resize preview"
className="separator"
data-stacked={stacked ? "" : undefined}
/>
<section {...ide.getElementProps("preview")}>Preview</section>
</div>
<div {...outline} aria-label="Resize outline" className="separator" />
<aside {...ide.getElementProps("outline")}>Outline</aside>
</div>
);
}/* A stacked separator takes the strip beyond its neighbour's, toward its
open side. Lines that lie together are often a line's thickness apart
(one at the end of a nested group, one just after it), so two reaches
leave no gap between the strips. */
.separator[data-stacked][data-zero="after"] {
--separator-offset: calc(-2 * var(--separator-reach));
}
.separator[data-stacked][data-zero="before"] {
--separator-offset: calc(2 * var(--separator-reach));
}Pressing just inside the edge then opens the outline, and a little further in, the preview; the highlight follows the offset, so hovering or focusing each shows where it is. They stay two tab stops, each labelled for its own child: they do different things. The library doesn't work out which lines lie together itself: that's a fact about where your layout puts things, nested groups and all, and how to present it is yours.
Hiding them. To make a closed child reopen only through your own controls, hide the separators beside it:
.separator[data-zero] {
visibility: hidden;
}visibility: hidden keeps the line's room and takes it out of the tab order and
the accessibility tree; not rendering it (or display: none) also gives up its
room, which nudges the layout by the line's thickness. Either way, it hides as
the closing begins (that's when data-zero is set). If the separator had focus,
move focus to whatever reopens the child. And hiding one separator doesn't stop
the child opening through its other one, a junction, or the keyboard on a
neighbour: disabledSeparators and locked (below) are the tools for that.
Locking and disabling
To keep the user from resizing one child, lock it; to keep them from moving one separator, disable it; to turn off every drag and key, disable the layout. All three are options, so they can follow your app's state (a "lock layout" toggle, say):
useResizableLayout({
layout: {
id: "editor",
direction: "row",
children: [
{ id: "files", defaultSize: 240, locked: filesLocked },
{ id: "code" },
{ id: "preview", defaultSize: "30%" },
],
},
disabledSeparators: previewLocked ? [["code", "preview"]] : [],
disabled: layoutLocked,
});locked: trueon a child keeps its size through drags and keys. A drag that reaches it pushes on past it to the children beyond (withcascade), so a separator beside it moves only if there's something beyond to give or take; with nothing, it's disabled. Your calls for its siblings (setStop,setSize) take room from it only if nothing else can give it, and a"last"fill takes space before it grows. Calls for it still move it, and when the window resizes, it keeps its share like any other child (addkeepSizeto keep its size then too).disabledSeparators(each[before, after], as forgetSeparatorProps): those separators don't move under a press or a key, and a junction drags only its others. Their neighbours can still change other ways: another separator's drag pushing on into them, the window, your code.disabled: trueon the layout: no separator or junction takes a press or a key. Separators arearia-disabled, out of the tab order, and without a resize cursor ordata-hover. Your calls (setStop,setSize,reset, …) still work, and so does fitting to the window.useResizabletakesdisabledtoo, with the same meaning for its handles and move handle.
How a layout shares space
The sizes in a layout are worked out together, in one of two ways:
- A drag or an arrow key moves one line, and only the children it pushes change (see Dragging a separator).
- A fit shares out a group's space among its children. It happens when the
space changes (the window or the container resizing, or an outer separator
resizing a nested group), when a call sizes a child (
setStop,toggle,setStops,setSize,reset(id)), when children are added or removed, and when the options change.
The rules below are for fits. Each fit starts from what's saved for each child, the stop chosen for it and its size in each range (what the user or your code last set), not from the sizes the last fit showed. So nothing is lent or owed: narrow the window and widen it again, and everything comes back where it was.
The rules, in short:
- Empty space. A group's children always fill it, so one of them must be able to take whatever the others leave; calls that would leave none are refused.
- Shrinking. When a group has less room, its
children give way in an order (fills, then children by
priority, then those that keep their size, then the one being sized), each down to its minimum. - Growing. Extra room goes in
proportion to size, or by
grow; children that keep their size take it last. - Stepping down. Once the minimums don't fit,
children with
yieldTostep down to smaller stops, one at a time in a set order, across nested groups as if they were one;keepSize: "yield-first"children keep their size until no one else can step down. - Overflow. If that still isn't enough,
the children are drawn smaller than their minimums, in proportion;
refuseOverflowmakes calls refuse to get there. - Protection. The child a call last changed steps down last, until the room around it shrinks; a child stepped down when a drag starts stays down after it.
%limits in nested groups are shares of the nested group's own space.
To find the option for a behaviour:
| You want | Use |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| A child that keeps its size when the window resizes, the others absorbing it | keepSize: true |
| A child that gives way before its siblings when room is short | a lower priority than theirs |
| A child that takes the extra room when the window widens | grow: 1 on it (and none on the others), or fill: "first" |
| Children that close, or go to a rail, when the window gets too narrow | yieldTo, with a smaller stop to step down to |
| A child that keeps its size until the others have stepped down | keepSize: "yield-first" |
| Children that may all sit at points, with spare room left empty | a fill: "last" element |
| Children kept centred | a fill element either side |
| Buttons that can't squeeze children below their minimums | refuseOverflow: true on the group
