Snappy resizable panels
Most people have one width they like for a sidebar. They drag it back there again and again, but never to the exact same pixel. This sidebar learns that width and snaps to it. The chart above the window shows how.1
Remembering where the edge was left
Every time you let go, the width is saved as a mark. We never land on the same width twice, so we can't just count widths. Instead, each mark adds a small hill. Marks that land close together stack into a bigger hill.
Weighing newer drags more
Your preferred width can change. So newer marks count more than older ones. Every five drags, a mark's weight halves. A new habit takes over within a few drags.
Age is counted in drags, not days. If you don't touch the sidebar for a week, it still remembers your width.
Choosing the snap point
The snap point is the top of the tallest hill. It only shows up once about three recent drags agree. One random drag is never enough.
Once it's set, the snap point stays put. It only moves if the tallest hill ends up outside the snap zone. Otherwise it would shift a pixel with every drag.
Snapping and fine-tuning
When you drag close to the snap point, the edge sticks to it. Your cursor keeps moving, but the edge stays. If you let go there, the mark is saved at the snap point.





The catch is that you can't reach the widths right next to the snap point. So if you pause there for a moment, the snap lets go. Now the edge follows your cursor again, without jumping. Arrow keys never snap.
The hook
All of this is one hook, useSnapPoint, for version 4 of react-resizable-panels. Pass it the panel's id, and spread snap.group onto the Group.
12345678910111213import { Group, Panel, Separator } from "react-resizable-panels";import { useSnapPoint } from "./use-snap-point";
export function Layout() { const snap = useSnapPoint({ panel: "sidebar" }); return ( <Group {...snap.group}> <Panel id="sidebar" defaultSize="25%" minSize="15%" maxSize="40%" /> <Separator /> <Panel id="main" /> </Group> );}Sizes are in pixels. The snap zone is 10px on each side by default. Nothing is saved between visits. To keep it, store samples and pass them back as initial.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useGroupRef, type Layout, type LayoutChangedMeta } from "react-resizable-panels";import { DEFAULTS, favourite, record, type Sample, type Tuning } from "./favourite";
type Options = Partial<Tuning> & { /** The id of the Panel whose size is learned. */ panel: string; /** A history to start from, such as one you saved. */ initial?: Sample[]; /** How long the hand has to rest in the snap zone before the snap lets go, in ms. */ dwellMs?: number; /** * How many units one percent of the group is. Left out, sizes are in * pixels, measured from the group. Set it to work in units of your own. */ perPercent?: number; orientation?: "horizontal" | "vertical";};
/** * A learned snap point for one panel of a react-resizable-panels Group (v4). * * It remembers where the panel's edge is let go, finds the size those * let-gos agree on, and holds the edge there while it's dragged close by. * If the hand rests in the snap zone, the snap lets go, so every size * inside the zone can still be reached. Keyboard resizing never snaps. * * const snap = useSnapPoint({ panel: "sidebar" }); * <Group {...snap.group}> … </Group> * * Nothing is saved. To keep the habit between visits, store `samples` * yourself and pass them back as `initial`. */export function useSnapPoint({ panel, initial, dwellMs = 300, perPercent, orientation = "horizontal", ...rest }: Options) { const { spread, halfLife, minWeight, snap, correctionMs, keep } = { ...DEFAULTS, ...rest }; const tuning = useMemo( () => ({ spread, halfLife, minWeight, snap, correctionMs, keep }), [spread, halfLife, minWeight, snap, correctionMs, keep], );
const groupRef = useGroupRef(); const elementRef = useRef<HTMLDivElement | null>(null); const [samples, setSamples] = useState<Sample[]>(initial ?? []); const [width, setWidth] = useState<number | null>(null); // Set when a drag snaps. It stays set through fine-tuning and the let-go, // and goes once the edge leaves the zone (checked at render, below). const [held, setHeld] = useState(false); const point = useMemo(() => favourite(samples, tuning), [samples, tuning]);
// What the handlers read. They run outside render, on the library's events. const now = useRef({ point, tuning, panel, perPercent, orientation, dwellMs }); useEffect(() => { now.current = { point, tuning, panel, perPercent, orientation, dwellMs }; });
// Where the hand is, before any snap. const hand = useRef(0); // Where the edge really is: the snap point while held, the hand otherwise. // This is what a let-go records. const edge = useRef(0); const holding = useRef(false); // Set once the snap has let go: the edge then follows the hand from the // snap point, with no jump, until the drag ends. const free = useRef<{ from: number } | null>(null); const dwell = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const still = useRef(0); // A pointer is down, so a resize is a drag and not the keyboard. const dragging = useRef(false); const placing = useRef(false); // A size this hook just set. The library reports it back, sometimes a // frame later; that report isn't the hand. const echo = useRef<number | null>(null);
useEffect(() => { const down = () => (dragging.current = true); const up = () => { dragging.current = false; free.current = null; clearTimeout(dwell.current); }; window.addEventListener("pointerdown", down, true); window.addEventListener("pointerup", up); window.addEventListener("pointercancel", up); return () => { window.removeEventListener("pointerdown", down, true); window.removeEventListener("pointerup", up); window.removeEventListener("pointercancel", up); clearTimeout(dwell.current); }; }, []);
/** Units per percent of the group. */ const scale = useCallback(() => { const { perPercent, orientation } = now.current; if (perPercent) return perPercent; const box = elementRef.current?.getBoundingClientRect(); return (box ? (orientation === "horizontal" ? box.width : box.height) : 100) / 100; }, []);
/** Sets the panel to `to`, taking the difference from the panel next to it. Returns where it landed. */ const place = useCallback( (layout: Layout, to: number) => { const { panel } = now.current; const ids = Object.keys(layout); const i = ids.indexOf(panel); const beside = ids[i + 1] ?? ids[i - 1]; const share = to / scale(); placing.current = true; const applied = groupRef.current?.setLayout({ ...layout, [panel]: share, [beside]: layout[beside] - (share - layout[panel]), }); placing.current = false; const landed = (applied?.[panel] ?? share) * scale(); echo.current = landed; edge.current = landed; setWidth(landed); return landed; }, [groupRef, scale], );
const onLayoutChange = useCallback( (layout: Layout) => { const { point, tuning, panel, dwellMs } = now.current; const w = layout[panel] * scale(); if (placing.current) return; if (echo.current !== null && Math.abs(w - echo.current) < 0.01) { echo.current = null; return; } echo.current = null; hand.current = w;
// Fine-tuning: the edge follows the hand from where the snap let go. if (free.current && point) return void place(layout, point.width + (w - free.current.from));
const was = holding.current; holding.current = dragging.current && !!point && Math.abs(w - point.width) <= tuning.snap; if (holding.current) setHeld(true); if (!holding.current) { clearTimeout(dwell.current); edge.current = w; return setWidth(w); } // A pause in the zone lets go of the snap. Moving starts the wait again. if (!was || Math.abs(w - still.current) > tuning.snap / 6) { still.current = w; clearTimeout(dwell.current); dwell.current = setTimeout(() => { if (!dragging.current || !holding.current) return; free.current = { from: hand.current }; holding.current = false; }, dwellMs); } place(layout, point!.width); }, [place, scale], );
const onLayoutChanged = useCallback((_: Layout, meta: LayoutChangedMeta) => { if (!meta.isUserInteraction) return; setSamples((cur) => record(cur, Math.round(edge.current), Date.now(), now.current.tuning)); }, []);
/** Replaces the history, and optionally moves the panel to `to`. */ const reset = useCallback( (next: Sample[] = [], to?: number) => { setSamples(next); setHeld(false); const layout = groupRef.current?.getLayout(); if (to !== undefined && layout) place(layout, to); }, [groupRef, place], );
const inZone = point !== null && width !== null && Math.abs(width - point.width) <= tuning.snap; if (held && !inZone) setHeld(false);
return { /** Spread onto the Group. */ group: { groupRef, elementRef, onLayoutChange, onLayoutChanged }, /** The learned size, or null while there isn't one yet. */ snapPoint: point?.width ?? null, /** How much weight is behind the snap point. */ support: point?.support ?? 0, /** The let-gos so far. Save these to keep the habit between visits. */ samples, /** The panel's size right now, or null before the first resize. */ width, /** True from the moment a drag snaps until the edge leaves the snap zone, through fine-tuning and the let-go. */ held: held && inZone, reset, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110/** * Finding the size someone keeps coming back to. * * Every time they let go of a panel's edge, that size is one sample. A * sample is a vote, but not an equal one: newer votes count more (habits * change), and votes that land near each other add up. So each sample is * spread into a small bell, scaled by how recent it is, the bells are summed * into one curve, and the favourite is the top of the highest hill. A hill * has to carry enough weight before it counts, so one stray drag never * becomes a snap point. * * Plain functions with no React in them, so they run anywhere. */
/** One let-go: the panel's width (its height in a vertical group), and when. */export type Sample = { width: number; at: number };
export type Tuning = { /** How wide one sample's bell is. Let-gos within about this much of each other agree. */ spread: number; /** After this many newer let-gos, a sample counts half as much. */ halfLife: number; /** How much weight a hill needs (about this many recent, agreeing let-gos) before it's a snap point. */ minWeight: number; /** Within this much of the favourite, the edge holds at it. */ snap: number; /** A let-go this soon after the last one is a correction of it, not a new vote. */ correctionMs: number; /** How many let-gos to keep. Older ones weigh almost nothing by then. */ keep: number;};
/** In pixels. */export const DEFAULTS: Tuning = { spread: 8, halfLife: 5, minWeight: 2.5, snap: 10, correctionMs: 2000, keep: 40 };
/** The newest sample weighs 1; each older one weighs less, halving every `halfLife`. */export function weights(samples: Sample[], halfLife: number) { const n = samples.length; return samples.map((_, i) => 0.5 ** ((n - 1 - i) / halfLife));}
/** The summed curve at `width`. `w` is each sample's weight. */export function density(samples: Sample[], w: number[], width: number, spread: number) { let sum = 0; for (let i = 0; i < samples.length; i++) { const d = width - samples[i].width; sum += w[i] * Math.exp(-(d * d) / (2 * spread * spread)); } return sum;}
/** The weight of the samples within two spreads of `width`. */function support(samples: Sample[], w: number[], width: number, spread: number) { return samples.reduce((s, smp, i) => (Math.abs(smp.width - width) <= 2 * spread ? s + w[i] : s), 0);}
/** The top of the tallest hill. It always lies between the smallest and largest sample. */function peak(samples: Sample[], t: Tuning) { const w = weights(samples, t.halfLife); const from = Math.floor(Math.min(...samples.map((s) => s.width))); const to = Math.ceil(Math.max(...samples.map((s) => s.width))); let best = from; let top = -1; for (let x = from; x <= to; x++) { const d = density(samples, w, x, t.spread); if (d > top) { top = d; best = x; } } return { width: best, support: support(samples, w, best, t.spread) };}
/** * The favourite, or null while no hill is tall enough. * * It's sticky. Every new let-go nudges the top of the hill a little, because * the bells overlap, but one let-go near the edge of the snap zone shouldn't * move a size someone has stopped at a hundred times. So while the top of * the tallest hill stays inside the favourite's snap zone, the favourite * stays exactly where it is; it moves only when the tallest hill is clearly * somewhere else. The history is replayed in order to find it, so the same * history always gives the same answer. */export function favourite(samples: Sample[], t: Tuning = DEFAULTS) { let current: { width: number; support: number } | null = null; for (let n = 1; n <= samples.length; n++) { const seen = samples.slice(0, n); const p = peak(seen, t); if (p.support < t.minWeight) { current = null; } else if (current && Math.abs(p.width - current.width) <= t.snap) { current = { width: current.width, support: support(seen, weights(seen, t.halfLife), current.width, t.spread) }; } else { current = p; } } return current;}
/** * Adds a let-go to the history: replaces the last sample if it came right * after it (they were still adjusting), otherwise appends. */export function record(samples: Sample[], width: number, at: number, t: Tuning = DEFAULTS) { const last = samples[samples.length - 1]; const corrected = last && at - last.at < t.correctionMs; const next = corrected ? [...samples.slice(0, -1), { width, at }] : [...samples, { width, at }]; return next.slice(-t.keep);}Footnotes
-
The notes window is inspired by a pin on Pinterest. ↩