Explore the index
Browse components
InputstableReactResizeObserverCSS

Liquid Segmented Control

A selection surface with a little momentum.

Control size

Use arrow keys, Home or End. Watch the shelf reflow as density changes.

A real browser viewport. Scroll within the preview when the sample needs more space. Configuration stays in sync between sizes.

01What it does

A radiogroup segmented control whose selection surface is measured from the chosen label, glides between slots and gains a few pixels toward the direction of travel. Keyboard selection and focus move together.

In this previewA reading-room density switcher. Compact removes excerpts and avatars, comfortable shows a balanced row, and spacious reveals notes and more generous spacing. The selected option can be disabled from the preview controls.

Design decisions

The surface is measured from the selected button, not built as equal fractions. Labels of different lengths receive an honest pill.

The stretch is capped at 18px and only lasts for the first 190ms of travel. It reads as weight, not as a rubber band.

The control and the content share a single state value; changing density actually changes the sample interface's spacing and information, not just the control decoration.

02Install

Registry install

registry:component

Run this in a React project with components.json. The component and its stylesheet land in components/lab/liquid-segmented/.

npx shadcn@latest add https://lab.tanishk.me/r/liquid-segmented.json

Files included

2
  • components/lab/liquid-segmented/liquid-segmented.tsxcomponent
  • components/lab/liquid-segmented/liquid-segmented.cssstyles

Manual install: copy each file into the same folder and preserve its relative imports. Open the source

03Usage

liquid-segmented.usage.tsx
"use client";
import { useState } from "react";
import { LiquidSegmented } from "@/components/lab/liquid-segmented/liquid-segmented";

export function DensityControl() {
const [density, setDensity] = useState("comfortable");
return (
<LiquidSegmented
label="Layout density"
value={density}
onChange={setDensity}
options={[
{ value: "compact", label: "Compact" },
{ value: "comfortable", label: "Comfortable" },
{ value: "spacious", label: "Spacious" },
]}
/>
);
}

04Props

Props accepted by Liquid Segmented Control
PropTypeDefaultNotes
options{ value: string; label: string; disabled?: boolean }[]—The choices, in visual order.
valuestring—Controlled selected value.
onChange(value: string) => void—Called when the selection changes by click or keyboard.
labelstring—Accessible name for the radiogroup.
size"sm" | "md""md"Control height and label scale.
stretchbooleantrueAllow the brief directional stretch during travel.
classNamestring—Forwarded to the root for local layout.

05Accessibility

  • Exposes a labelled radiogroup with radio roles, aria-checked and a roving tab stop on the current option.
  • Arrow keys move selection and focus together; Home and End reach the first and last enabled options; disabled options are skipped.
  • The moving surface is decorative. Text contrast and the focus ring do not depend on its position.
  • The selection state is announced by the radio semantics, not by colour or motion.
  • The stretch and glide are removed under reduced motion; the surface changes position instantly.

06Source

2 files, 302 lines. The combined copy is a reference; save each file separately for use.

components/lab/liquid-segmented/liquid-segmented.tsx— press enter to show or hide the source
tsx
"use client";

import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type KeyboardEvent,
} from "react";
import "./liquid-segmented.css";

export type SegmentedOption = {
value: string;
label: string;
disabled?: boolean;
};

export type LiquidSegmentedProps = {
options: SegmentedOption[];
value: string;
onChange: (value: string) => void;
/** Accessible group name. */
label: string;
size?: "sm" | "md";
/** Let the surface stretch briefly in the direction of travel. */
stretch?: boolean;
className?: string;
};

/**
* LIQUID SEGMENTED CONTROL
*
* A radiogroup with one physical selection surface. The surface is
* measured from the chosen option and glides between slots; during a
* change it gains a few pixels toward the direction of travel and
* settles back. Arrow keys move selection and focus together, disabled
* options are skipped, and the roving tab stop always points at the
* current choice.
*/
export function LiquidSegmented({
options,
value,
onChange,
label,
size = "md",
stretch = true,
className,
}: LiquidSegmentedProps) {
const rootRef = useRef<HTMLDivElement>(null);
const buttonRefs = useRef(new Map<string, HTMLButtonElement>());
const [indicator, setIndicator] = useState({ x: 0, width: 0, ready: false });
const [give, setGive] = useState({ amount: 0, direction: 1 });
const giveTimer = useRef<number | null>(null);
const usable = options.filter((option) => !option.disabled);
const activeValue = options.some(
(option) => option.value === value && !option.disabled,
)
? value
: (usable[0]?.value ?? "");
const selected = options.find((option) => option.value === activeValue);

const measure = useCallback(() => {
const root = rootRef.current;
const button = buttonRefs.current.get(activeValue);
if (!root || !button) return;
setIndicator({
x: button.offsetLeft,
width: button.offsetWidth,
ready: true,
});
}, [activeValue]);

useLayoutEffect(() => {
measure();
const root = rootRef.current;
if (!root || typeof ResizeObserver !== "function") return;
const observer = new ResizeObserver(measure);
observer.observe(root);
for (const button of buttonRefs.current.values()) observer.observe(button);
return () => observer.disconnect();
}, [measure]);

useEffect(() => {
const onResize = () => measure();
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, [measure]);

const choose = (next: string, current: string) => {
const from = options.findIndex((option) => option.value === current);
const to = options.findIndex((option) => option.value === next);
if (stretch && from !== -1 && to !== -1 && from !== to) {
const amount = Math.min(18, Math.abs(to - from) * 5);
setGive({ amount, direction: to > from ? 1 : -1 });
if (giveTimer.current !== null) window.clearTimeout(giveTimer.current);
giveTimer.current = window.setTimeout(() => {
setGive({ amount: 0, direction: 1 });
giveTimer.current = null;
}, 190);
}
onChange(next);
};

useEffect(
() => () => {
if (giveTimer.current !== null) window.clearTimeout(giveTimer.current);
},
[],
);

const move = (
event: KeyboardEvent<HTMLButtonElement>,
direction: 1 | -1,
) => {
event.preventDefault();
const usable = options.filter((option) => !option.disabled);
if (!usable.length) return;
const current = usable.findIndex(
(option) => option.value === selected?.value,
);
const next = usable[(current + direction + usable.length) % usable.length];
choose(next.value, selected?.value ?? value);
buttonRefs.current.get(next.value)?.focus();
};

const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
if (event.key === "ArrowRight" || event.key === "ArrowDown")
move(event, 1);
else if (event.key === "ArrowLeft" || event.key === "ArrowUp")
move(event, -1);
else if (event.key === "Home") {
event.preventDefault();
const first = options.find((option) => !option.disabled);
if (first) {
choose(first.value, selected?.value ?? value);
buttonRefs.current.get(first.value)?.focus();
}
} else if (event.key === "End") {
event.preventDefault();
const last = [...options].reverse().find((option) => !option.disabled);
if (last) {
choose(last.value, selected?.value ?? value);
buttonRefs.current.get(last.value)?.focus();
}
}
};

const width = indicator.width + give.amount;
const x =
indicator.x -
(give.amount && give.direction < 0 ? give.amount : 0);

return (
<div
ref={rootRef}
className={`ls-root${className ? ` ${className}` : ""}`}
role="radiogroup"
aria-label={label}
data-size={size}
>
<span
className="ls-indicator"
aria-hidden="true"
data-ready={indicator.ready ? "true" : "false"}
style={{ width, transform: `translate3d(${x}px, 0, 0)` }}
/>
{options.map((option) => {
const checked = option.value === activeValue;
return (
<button
key={option.value}
ref={(node) => {
if (node) buttonRefs.current.set(option.value, node);
else buttonRefs.current.delete(option.value);
}}
type="button"
role="radio"
aria-checked={checked}
disabled={option.disabled}
tabIndex={checked ? 0 : -1}
className="ls-option"
onClick={() => choose(option.value, activeValue)}
onKeyDown={onKeyDown}
>
{option.label}
</button>
);
})}
</div>
);
}
components/lab/liquid-segmented/liquid-segmented.css— press enter to show or hide the source
css
.ls-root {
--ls-ink: #24211c;
--ls-muted: #625d55;
--ls-line: rgba(36, 33, 28, 0.13);
--ls-surface: #f6f3ea;
--ls-pill: #e6d5ae;
--ls-pill-ink: #24211c;
--ls-focus: #b04a2e;
--ls-ease: cubic-bezier(0.16, 1, 0.3, 1);
position: relative;
display: inline-flex;
align-items: stretch;
gap: 2px;
min-width: 0;
max-width: 100%;
padding: 3px;
border: 1px solid var(--ls-line);
border-radius: 999px;
background: var(--ls-surface);
color: var(--ls-ink);
font: inherit;
overflow-x: auto;
scrollbar-width: none;
isolation: isolate;
}

.ls-root::-webkit-scrollbar {
display: none;
}

.ls-indicator {
position: absolute;
top: 3px;
bottom: 3px;
left: 0;
z-index: -1;
border-radius: 999px;
background: var(--ls-pill);
box-shadow: inset 0 0 0 1px rgba(36, 33, 28, 0.08);
opacity: 0;
pointer-events: none;
transition:
transform 380ms var(--ls-ease),
width 380ms var(--ls-ease),
opacity 120ms linear;
will-change: transform, width;
}

.ls-indicator[data-ready="true"] {
opacity: 1;
}

.ls-option {
position: relative;
z-index: 1;
flex: 0 0 auto;
min-height: 34px;
padding: 6px 16px;
border: 0;
border-radius: 999px;
background: transparent;
color: var(--ls-muted);
font: inherit;
font-size: 0.8125rem;
font-weight: 550;
letter-spacing: -0.004em;
white-space: nowrap;
cursor: pointer;
transition: color 190ms var(--ls-ease);
}

.ls-root[data-size="sm"] .ls-option {
min-height: 28px;
padding: 3px 12px;
font-size: 0.75rem;
}

.ls-option:hover:not(:disabled) {
color: var(--ls-ink);
}

.ls-option[aria-checked="true"] {
color: var(--ls-pill-ink);
}

.ls-option:disabled {
opacity: 0.38;
cursor: not-allowed;
}

.ls-option:focus-visible {
outline: 2px solid var(--ls-focus);
outline-offset: 2px;
}

@media (max-width: 400px) {
.ls-option {
padding-inline: 12px;
font-size: 0.75rem;
}
}

@media (prefers-reduced-motion: reduce) {
.ls-indicator,
.ls-option {
transition-duration: 0.01ms;
}
}