Skip to content
Browse documentation

A multi-segment allocation track. Drag dividers to rebalance constrained percentages with zero initial jump.

Used forTraffic splitsBudget allocationResource quotasRevenue and payout splits

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/ratio-balancer

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/ratio-balancer.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Traffic splits

    Divide traffic between variants of a test or a rollout.

  • Budget allocation

    Split a budget between channels or teams.

  • Resource quotas

    Share compute or storage across projects in cloud settings.

  • Revenue and payout splits

    Divide earnings between collaborators.

What it handles for you

Dividing 100% between several things is awkward with separate number fields that never add up. This is one bar with draggable dividers, where the total is always 100%.

Instead of wiring uplinked sliderspercentage inputs that must sum to 100normalisation logica minimum share ruletouch target sizing
  1. Always 100%

    On release every ratio is normalised to whole numbers that add up to 100.

  2. Drag the dividers

    Moving a divider rebalances the two segments beside it. It tracks your finger one to one, with no jump at the start.

  3. A minimum share

    No segment can drop below minRatio, 5% by default.

  4. Numbers that roll

    The percentages roll to their settled totals when you let go.

  5. Commit when done

    onValueChange fires while dragging, and onValueCommit fires on release or a keyboard change.

  6. Keyboard and screen readers

    Dividers take focus, Left and Right nudge by 1% (5% with Shift), and each divider reports its value.

Overview

Distribute a shared 100% budget among multiple competing categories. Thin hairline dividers glide between segments with 1:1 physical tracking, numbers roll to settled totals, and expanded touch targets make dragging effortless on mobile and desktop. Built with pure flex-grow transitions, zero animation libraries, and zero shadows.

States

rebalance
Dragging a divider updates adjacent segment flex-grow styles and DOM text nodes directly.
settle
Releasing the pointer normalizes all ratios to 100% and rolls final percentage digits via NumberRoll.
keyboard
Dividers accept focus; Left and Right arrow keys nudge allocations by 1% (or 5% with Shift).

Usage

usage.tsx
import { RatioBalancer } from "@/components/ratio-balancer";<RatioBalancer  label="Compute allocation"  defaultSegments={[    { id: "eval", label: "Evaluation", ratio: 45 },    { id: "batch", label: "Batch tasks", ratio: 35 },    { id: "dev", label: "Dev testing", ratio: 20 },  ]}  onValueCommit={setRatios}/>

Works with

Allocate resource quotas in cloud settings

Use RatioBalancer to configure server cluster allocation or team spend limits. It maintains total conservation (always 100%) with fluid responsive drag.

example.tsx
"use client";import { useState } from "react";import { RatioBalancer, type RatioSegment } from "@/components/ratio-balancer";export function QuotaManager() {  const [segments, setSegments] = useState<RatioSegment[]>([    { id: "gpu", label: "GPU Clusters", ratio: 60 },    { id: "cpu", label: "General CPU", ratio: 25 },    { id: "storage", label: "NVMe Cache", ratio: 15 },  ]);  return (    <div className="rounded-2xl border border-border bg-card p-6">      <RatioBalancer        label="Cluster resources"        segments={segments}        onValueCommit={(ratios) => {          setSegments(prev => prev.map((s, i) => ({ ...s, ratio: ratios[i] })));        }}      />    </div>  );}

Props

label
string
Accessible heading displayed above the allocation bar.
segments / defaultSegments
RatioSegment[]
Array of segment objects with id, label, and ratio (summing to 100).
minRatio= 5
number
Minimum allowed percentage for any segment during drag.
disabled= false
boolean
Disables all divider dragging.
onValueChange
(ratios: number[]) => void
Fired during divider movement with immediate ratio updates.
onValueCommit
(ratios: number[]) => void
Fired upon pointer release or keyboard adjustment with clean normalized integers.

Accessibility and motion

  • Dividers act as semantic separators with vertical orientation and aria-valuenow.
  • Delta-based drag ensures 1:1 finger tracking without initial jumping on touch devices.
  • Segments maintain pure DOM styles during drag; React state updates occur only on commit.
  • Reduced motion removes flex-grow easing transitions and rolls digits in place.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll.

Source

'use client';/* ───────────────────────────────────────────────────────── * RATIO BALANCER: constrained multi-segment resource allocator * *   track      a single 1px hairline bar dividing 100% across *              segments; each segment expands or shrinks with *              flex-grow *   dividers   tactile hairline divider grips; delta-based drag *              ensures 1:1 finger tracking with zero initial *              jump on mobile and desktop *   numbers    percentage readouts roll in place via NumberRoll *              upon release; DOM text updates immediately while *              dragging *   touch      expanded 36px touch targets allow effortless finger *              dragging on phones * * Dividers are accessible separators with ArrowLeft/Right keys. * ───────────────────────────────────────────────────────── */import * as React from 'react';import { NumberRoll } from './number-roll';import { INTERACTION_FOCUS, useInteractionReducedMotion } from './ui-interaction-motion';import { normalizeRatios, type RatioSegment, useRatioBalancer } from './use-ratio-balancer';export type { RatioSegment };export interface RatioBalancerProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {  label?: string;  segments?: RatioSegment[];  defaultSegments?: RatioSegment[];  minRatio?: number;  disabled?: boolean;  onValueChange?: (ratios: number[]) => void;  onValueCommit?: (ratios: number[]) => void;}const DEFAULT_SEGMENTS: RatioSegment[] = [  { id: 'inference', label: 'Inference', ratio: 50 },  { id: 'training', label: 'Training', ratio: 30 },  { id: 'cache', label: 'Cache & KV', ratio: 20 },];const COLORS = [  'bg-primary/10 text-primary border-primary/25',  'bg-foreground/5 text-foreground border-foreground/15',  'bg-muted text-muted-foreground border-border',  'bg-accent text-accent-foreground border-border',  'bg-primary/5 text-foreground border-primary/20',];export function RatioBalancer({  label,  segments: controlledSegments,  defaultSegments = DEFAULT_SEGMENTS,  minRatio = 5,  disabled = false,  onValueChange,  onValueCommit,  className = '',  ...props}: RatioBalancerProps) {  const reduced = useInteractionReducedMotion();  const [internalSegments, setInternalSegments] = React.useState<RatioSegment[]>(defaultSegments);  const segments = controlledSegments ?? internalSegments;  const currentRatios = React.useMemo(() => normalizeRatios(segments.map((s) => s.ratio)), [segments]);  const handleChange = React.useCallback(    (nextRatios: number[]) => {      onValueChange?.(nextRatios);    },    [onValueChange]  );  const handleCommit = React.useCallback(    (nextRatios: number[]) => {      if (!controlledSegments) {        setInternalSegments((prev) =>          prev.map((seg, i) => ({            ...seg,            ratio: nextRatios[i] ?? seg.ratio,          }))        );      }      onValueCommit?.(nextRatios);    },    [controlledSegments, onValueCommit]  );  const balancer = useRatioBalancer({    segments,    minRatio,    disabled,    reduced,    onChange: handleChange,    onCommit: handleCommit,  });  return (    <div      {...props}      role="region"      aria-label={label ?? 'Resource ratio balancer'}      className={`relative flex w-full max-w-xl select-none flex-col text-foreground ${className}`}    >      {/* Label and Total */}      {label && (        <div className="mb-3 flex items-center justify-between text-[12px] font-medium text-muted-foreground">          <span>{label}</span>          <span className="font-mono text-[11px] tabular-nums text-muted-foreground/80">100% TOTAL</span>        </div>      )}      {/* Main Bar Track (Hairline borders only, zero heavy shadows) */}      <div        ref={(el) => balancer.attachTrack(el)}        className="relative flex h-14 w-full overflow-hidden rounded-[14px] border border-border bg-surface p-1"      >        {segments.map((seg, i) => {          const colorClass = COLORS[i % COLORS.length];          const isLast = i === segments.length - 1;          const ratio = currentRatios[i] ?? seg.ratio;          return (            <React.Fragment key={seg.id}>              {/* Segment Cell */}              <div                ref={(el) => balancer.attachSegment(i, el)}                className={`relative flex min-w-[42px] flex-col justify-between overflow-hidden rounded-[10px] border px-2.5 py-1.5 transition-[flex-grow] will-change-[flex-grow] ${colorClass}`}                style={{ flexGrow: ratio }}              >                <div className="flex items-center justify-between">                  <span className="truncate text-[11px] font-medium tracking-tight">{seg.label}</span>                </div>                <div className="flex items-baseline justify-between">                  <span                    ref={(el) => balancer.attachReadout(i, el)}                    style={{ display: balancer.activeDivider !== null ? 'inline' : 'none' }}                    className="font-mono text-[13px] font-medium tabular-nums"                  >                    {Math.round(ratio)}%                  </span>                  <span                    style={{ display: balancer.activeDivider !== null ? 'none' : 'inline' }}                    className="font-mono text-[13px] font-medium tabular-nums"                  >                    <NumberRoll value={Math.round(ratio)} suffix="%" duration={380} />                  </span>                </div>              </div>              {/* Divider Grip (Expanded 36px touch hit area for mobile fingers) */}              {!isLast && (                <div className="relative z-10 flex w-3 shrink-0 items-center justify-center">                  <button                    ref={(el) => balancer.attachDivider(i, el)}                    {...balancer.getDividerProps(i)}                    type="button"                    role="separator"                    disabled={disabled}                    aria-orientation="vertical"                    aria-label={`Adjust split between ${seg.label} and ${segments[i + 1]?.label}`}                    style={{ touchAction: 'none' }}                    className={`group relative -inset-y-1 flex h-full w-3 cursor-ew-resize items-center justify-center touch-none select-none rounded before:absolute before:-inset-x-3.5 before:inset-y-0 before:content-[''] disabled:cursor-default disabled:opacity-40 ${INTERACTION_FOCUS}`}                  >                    <span className="h-6 w-0.5 rounded-full bg-border transition-colors group-hover:bg-primary group-focus-visible:bg-primary" />                  </button>                </div>              )}            </React.Fragment>          );        })}      </div>      {/* Legend & Breakdown */}      <div className="mt-3 flex flex-wrap items-center justify-between gap-2 text-[11px] text-muted-foreground">        <span className="flex items-center gap-1.5">          <span className="size-1.5 rounded-full bg-primary" />          <span>Drag dividers to reallocate percentages.</span>        </span>        <div className="flex items-center gap-3">          {segments.map((seg) => (            <span key={seg.id} className="flex items-center gap-1 font-mono text-[10px] tabular-nums">              <span>{seg.label}:</span>              <span className="font-semibold text-foreground">                {Math.round(currentRatios[segments.indexOf(seg)] ?? seg.ratio)}%              </span>            </span>          ))}        </div>      </div>    </div>  );}

Registry item: /r/ratio-balancer.json