Choice Cards
Cards to compare and pick, on real radio buttons or checkboxes, with a title, a line and an optional price. The picked card's ink border draws itself around it from the corner while a check draws in its mark. Pure CSS.
View codeTwo to five exclusive choices on real radio buttons. An ink pill slides to the one you pick, stretching on the way, and the labels turn white exactly at its edges.
With your AI
Say it to your AI. It gets the exact code below, not its best guess, and knows where it goes.
Add the Kodza Segmented Control to my page.
claude mcp add -t http kodza https://kodza.dev/api/mcp
<fieldset class="kodza-segmented">
<legend class="kodza-segmented__legend kodza-segmented__legend--hidden">Billing</legend>
<div class="kodza-segmented__track">
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="billing" value="monthly" checked>
<span class="kodza-segmented__label">Monthly</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="billing" value="annual">
<span class="kodza-segmented__label">Annual <span class="kodza-segmented__badge">−20%</span></span>
</label>
</div>
</fieldset>
<fieldset class="kodza-segmented kodza-segmented--icons">
<legend class="kodza-segmented__legend kodza-segmented__legend--hidden">View</legend>
<div class="kodza-segmented__track">
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="view" value="list" checked>
<span class="kodza-segmented__label">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" aria-hidden="true"><path d="M4 6.5h16M4 12h16M4 17.5h16"/></svg>
<span class="kodza-segmented__name">List</span>
</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="view" value="grid">
<span class="kodza-segmented__label">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5"/></svg>
<span class="kodza-segmented__name">Grid</span>
</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="view" value="board">
<span class="kodza-segmented__label">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="4" width="4.5" height="16" rx="1.5"/><rect x="9.75" y="4" width="4.5" height="11" rx="1.5"/><rect x="15.5" y="4" width="4.5" height="7" rx="1.5"/></svg>
<span class="kodza-segmented__name">Board</span>
</span>
</label>
</div>
</fieldset>
<fieldset class="kodza-segmented kodza-segmented--block">
<legend class="kodza-segmented__legend">Size</legend>
<div class="kodza-segmented__track">
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="size" value="xs">
<span class="kodza-segmented__label">XS</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="size" value="s">
<span class="kodza-segmented__label">S</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="size" value="m" checked>
<span class="kodza-segmented__label">M</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="size" value="l">
<span class="kodza-segmented__label">L</span>
</label>
<label class="kodza-segmented__option">
<input class="kodza-segmented__input" type="radio" name="size" value="xl" disabled>
<span class="kodza-segmented__label">XL</span>
</label>
</div>
</fieldset>
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Segmented Control
Two to five exclusive choices on real radio buttons, in one pill. An ink pill slides to the
option you pick, its front edge first and its back edge catching up, like a drop of ink, and
the labels turn white exactly at its edges. Arrow keys move the choice, like any radio group,
and the form gets the value as usual. Without the script, the chosen option simply fills
with ink.
--block fills the width with equal segments (sizes, a form), --icons shows icons only (the
names stay for screen readers), and a badge (−20%) can ride in a label.
Everything is tuned with the --kz-segmented-* variables; the stretch of the pill, with the
constants at the top of the script. */
.kodza-segmented {
--kz-segmented-bg: #ffffff;
--kz-segmented-fg: #0a0a0a;
--kz-segmented-muted: rgba(10, 10, 10, 0.58);
--kz-segmented-border: rgba(10, 10, 10, 0.1);
--kz-segmented-ink: #0a0a0a;
--kz-segmented-on-ink: #ffffff;
--kz-segmented-badge: rgba(10, 10, 10, 0.07); /* the badge on the track */
--kz-segmented-badge-on-ink: rgba(255, 255, 255, 0.2); /* the badge under the pill */
--kz-segmented-height: 44px; /* the whole pill; the options are 2 × --kz-segmented-pad shorter */
--kz-segmented-pad: 4px; /* the room around the ink pill */
--kz-segmented-width: var(--kz-field-width, 360px); /* --block: the width it fills, at most */
--kz-segmented-duration: 0.55s; /* the slide of the pill. 0s = no motion */
display: inline-block;
min-width: 0;
max-width: 100%;
margin: 0;
padding: 0;
border: 0;
color: var(--kz-segmented-fg);
}
.kodza-segmented__legend {
margin-bottom: 10px;
padding: 0;
font-family: var(--kz-font-label, var(--kz-font-mono, ui-monospace, "SF Mono", Menlo, monospace));
font-size: var(--kz-font-label-size, 12px);
font-weight: var(--kz-font-label-weight, inherit);
line-height: var(--kz-font-label-leading, inherit);
letter-spacing: var(--kz-font-label-tracking, inherit);
text-transform: var(--kz-font-label-case, inherit);
color: var(--kz-segmented-muted);
}
/* A name for screen readers only (a pricing toggle needs no visible title) */
.kodza-segmented__legend--hidden,
.kodza-segmented--icons .kodza-segmented__name {
position: absolute;
width: 1px;
height: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.kodza-segmented__track {
position: relative;
display: flex;
box-sizing: border-box;
max-width: 100%;
height: var(--kz-segmented-height);
padding: var(--kz-segmented-pad);
border-radius: var(--kz-radius-pill, 999px);
background: var(--kz-segmented-bg);
box-shadow: inset 0 0 0 1px var(--kz-segmented-border);
}
.kodza-segmented__option {
position: relative;
flex: 0 1 auto;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
min-width: 0;
height: 100%;
margin: 0;
padding: 0 16px;
border-radius: var(--kz-radius-pill, 999px);
cursor: pointer;
user-select: none;
-webkit-tap-highlight-color: transparent;
}
/* The state colours the text, not the option (the white copies hold their own) */
.kodza-segmented__option > .kodza-segmented__label {
color: var(--kz-segmented-muted);
transition: color calc(0.25s * var(--kz-motion-scale, 1)) ease;
}
/* The real radio covers its option: a click anywhere picks it */
.kodza-segmented__input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: inherit;
}
.kodza-segmented__label {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 15px);
font-weight: var(--kz-font-label-weight, 500);
line-height: 1;
letter-spacing: var(--kz-font-label-tracking, inherit);
text-transform: var(--kz-font-label-case, inherit);
white-space: nowrap;
}
.kodza-segmented__label svg {
display: block;
flex: none;
}
.kodza-segmented__badge {
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 7px;
border-radius: var(--kz-radius-pill, 999px);
background: var(--kz-segmented-badge);
color: var(--kz-segmented-fg);
font-size: var(--kz-font-label-size, 12px);
font-variant-numeric: tabular-nums;
letter-spacing: 0;
text-transform: none;
}
@media (hover: hover) {
.kodza-segmented__option:hover > .kodza-segmented__label {
color: var(--kz-segmented-fg);
}
}
.kodza-segmented__option:has(.kodza-segmented__input:checked) > .kodza-segmented__label {
color: var(--kz-segmented-fg);
}
.kodza-segmented__option:has(.kodza-segmented__input:focus-visible) {
outline: 2px solid var(--kz-segmented-fg);
outline-offset: 2px;
}
.kodza-segmented__option:has(.kodza-segmented__input:disabled) {
cursor: not-allowed;
opacity: 0.4;
}
/* Without the script: the chosen option fills with ink */
.kodza-segmented:not(.is-ready) .kodza-segmented__option:has(.kodza-segmented__input:checked) {
background: var(--kz-segmented-ink);
}
.kodza-segmented:not(.is-ready) .kodza-segmented__option:has(.kodza-segmented__input:checked) > .kodza-segmented__label {
color: var(--kz-segmented-on-ink);
}
/* The ink pill (added by the script): two windows slide in the lane, one cut at the pill's left
edge, one at its right edge, while the ink inside them holds still. Only transforms move, so
the slide stays smooth on a busy page, and the corners stay round */
.kodza-segmented__lane {
position: absolute;
inset: var(--kz-segmented-pad);
overflow: hidden;
pointer-events: none;
}
.kodza-segmented__pill,
.kodza-segmented__edge,
.kodza-segmented__mirror {
position: absolute;
inset: 0;
}
.kodza-segmented__pill {
overflow: hidden;
border-radius: var(--kz-radius-pill, 999px) 0 0 var(--kz-radius-pill, 999px);
transform: translateX(var(--kz-seg-l, 0px));
}
.kodza-segmented__edge {
overflow: hidden;
border-radius: 0 var(--kz-radius-pill, 999px) var(--kz-radius-pill, 999px) 0;
transform: translateX(calc(-1 * var(--kz-seg-l, 0px) - var(--kz-seg-r, 100%)));
}
/* The ink, with a white copy of the labels: the text turns white exactly at the edges of the
pill, never all at once */
.kodza-segmented__mirror {
background: var(--kz-segmented-ink);
color: var(--kz-segmented-on-ink);
transform: translateX(var(--kz-seg-r, 100%));
}
.kodza-segmented__ghost {
position: absolute;
top: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
padding: 0 16px;
}
.kodza-segmented__mirror .kodza-segmented__badge {
background: var(--kz-segmented-badge-on-ink);
color: var(--kz-segmented-on-ink);
}
/* --icons: round options around one icon */
.kodza-segmented--icons .kodza-segmented__option,
.kodza-segmented--icons .kodza-segmented__ghost {
padding: 0 9px;
}
/* --block: the width of a form field, in equal segments */
.kodza-segmented--block {
display: block;
width: 100%;
max-width: var(--kz-segmented-width);
}
.kodza-segmented--block .kodza-segmented__option {
flex: 1 1 0;
padding: 0 8px;
}
.kodza-segmented--block .kodza-segmented__ghost {
padding: 0 8px;
}
@media (prefers-reduced-motion: reduce) {
.kodza-segmented__option > .kodza-segmented__label {
transition-duration: 0.01ms !important;
}
}
/* Theming example — on a dark background:
.dark-section .kodza-segmented {
--kz-segmented-bg: #161616;
--kz-segmented-fg: #f2f2f0;
--kz-segmented-muted: rgba(242, 242, 240, 0.62);
--kz-segmented-border: rgba(255, 255, 255, 0.12);
--kz-segmented-ink: #f2f2f0;
--kz-segmented-on-ink: #0a0a0a;
--kz-segmented-badge: rgba(255, 255, 255, 0.1);
--kz-segmented-badge-on-ink: rgba(10, 10, 10, 0.12);
}
*/
/* kodza-guard b5ecb7ec5cd0 — generated by Kodza, do not edit.
Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
component. :not(#_) is always true and weighs as much as an id, so these lines win over
theme rules made of classes and tags. Customise the component through its --kz-* variables. */
/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */
:where(.kodza-segmented__legend):not(#_) {
position: revert;
margin-top: revert;
margin-right: revert;
margin-left: revert;
white-space: revert;
}
:where(.kodza-segmented__option):not(#_) {
outline: revert;
background-color: revert;
background-image: revert;
outline-offset: revert;
}
/* What the browser gives, on everything the component leaves to it */
.kodza-segmented:not(#_) {
border-radius: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
position: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-height: revert;
font-family: revert;
font-size: revert;
font-weight: revert;
font-style: revert;
line-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-segmented__legend:not(#_) {
border: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
float: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
font-style: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-segmented__option:not(#_) {
border: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
float: revert;
box-shadow: revert;
appearance: revert;
max-width: revert;
max-height: revert;
color: revert;
font-family: revert;
font-size: revert;
font-weight: revert;
font-style: revert;
line-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-segmented__input:not(#_) {
border: revert;
padding: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
float: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
color: revert;
font-family: revert;
font-size: revert;
font-weight: revert;
font-style: revert;
line-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
white-space: revert;
min-height: revert;
}
.kodza-segmented__label:not(#_),
.kodza-segmented__badge:not(#_),
.kodza-segmented__lane:not(#_),
.kodza-segmented__pill:not(#_),
.kodza-segmented__edge:not(#_),
.kodza-segmented__mirror:not(#_),
.kodza-segmented__name:not(#_) {
box-sizing: revert;
}
.kodza-segmented__label svg:where(:not([class*="kodza-"])):not(#_) {
border: revert;
margin: revert;
padding: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
float: revert;
position: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
color: revert;
font-family: revert;
font-size: revert;
font-weight: revert;
font-style: revert;
line-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-segmented__legend:not(#_):where(:not([hidden])),
.kodza-segmented__input:not(#_):where(:not([hidden])) {
display: revert;
}
.kodza-segmented__legend:not(#_):where([hidden]),
.kodza-segmented__input:not(#_):where([hidden]) {
display: none;
}
/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */
.kodza-segmented:not(#_) {
display: inline-block;
padding: 0;
border: 0;
color: var(--kz-segmented-fg);
}
.kodza-segmented__legend:not(#_) {
margin-bottom: 10px;
padding: 0;
font-family: var(--kz-font-label, var(--kz-font-mono, ui-monospace, "SF Mono", Menlo, monospace));
font-size: var(--kz-font-label-size, 12px);
font-weight: var(--kz-font-label-weight, inherit);
line-height: var(--kz-font-label-leading, inherit);
letter-spacing: var(--kz-font-label-tracking, inherit);
text-transform: var(--kz-font-label-case, inherit);
color: var(--kz-segmented-muted);
}
.kodza-segmented__legend--hidden:not(#_) {
position: absolute;
margin: 0;
white-space: nowrap;
}
.kodza-segmented__option:not(#_) {
position: relative;
display: flex;
box-sizing: border-box;
margin: 0;
padding: 0 16px;
border-radius: var(--kz-radius-pill, 999px);
}
.kodza-segmented__input:not(#_) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: inherit;
}
.kodza-segmented__label svg:not(#_) {
display: block;
}
.kodza-segmented__option:has(.kodza-segmented__input:focus-visible):not(#_) {
outline: 2px solid var(--kz-segmented-fg);
outline-offset: 2px;
}
.kodza-segmented:not(.is-ready) .kodza-segmented__option:has(.kodza-segmented__input:checked):not(#_) {
background: var(--kz-segmented-ink);
}
.kodza-segmented--icons .kodza-segmented__option:not(#_) {
padding: 0 9px;
}
.kodza-segmented--block:not(#_) {
display: block;
}
.kodza-segmented--block:not(#_) {
width: min(100%, var(--kz-segmented-width));
}
.kodza-segmented--block .kodza-segmented__option:not(#_) {
padding: 0 8px;
}
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Segmented Control
// Adds the ink pill: it slides to the option you pick, its front edge first and its back edge
// catching up, with a white copy of the labels cut to the same shape. The radios stay native:
// arrow keys, the form value and the change event are the browser's. The stretch is tuned with
// the constants below (LEAD 1 and LAG 0: a plain slide).
(() => {
const SELECTOR = '.kodza-segmented';
const LEAD = 0.7; // the front edge arrives in this share of the slide
const LAG = 0.14; // the back edge waits this share of the slide before it follows
const SAMPLES = 30; // keyframes per slide: each edge follows its own curve
const ease = (t) => 1 - (1 - t) ** 4; // close to cubic-bezier(0.22, 1, 0.36, 1)
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// The site's pace, --kz-motion-scale (set on :root, read on the instance): every duration of the
// script times it, and 0 moves nothing, like reduced motion
const paceOf = (el) => {
const pace = parseFloat(getComputedStyle(el).getPropertyValue('--kz-motion-scale'));
return pace >= 0 ? pace : 1;
};
const seconds = (value) => {
const n = parseFloat(value);
if (!(n >= 0)) return 0.55;
return /ms\s*$/.test(value) ? n / 1000 : n;
};
// One instance, with its own state: two copies on a page never interfere. Everything it
// starts is tied to `signal` (listeners get { signal }, observers and timers stop on its
// 'abort' event), so kodza:destroy stops it all.
function mount(root, signal) {
const pace = paceOf(root);
const still = reduceMotion || !pace; // the still path: no motion asked, by the visitor or the site
const track = root.querySelector('.kodza-segmented__track');
const options = track ? [...track.querySelectorAll('.kodza-segmented__option')] : [];
const inputs = options.map((option) => option.querySelector('.kodza-segmented__input'));
if (!options.length || inputs.some((input) => !input)) return;
const duration = seconds(getComputedStyle(root).getPropertyValue('--kz-segmented-duration')) * pace * 1000;
// The pill over the labels: the lane, the window cut at its left edge (pill), the window cut
// at its right edge (edge), and the ink with the white copy of the labels (mirror)
const layer = (name) => {
const el = document.createElement('span');
el.className = `kodza-segmented__${name}`;
return el;
};
const lane = layer('lane');
lane.setAttribute('aria-hidden', 'true');
const pill = layer('pill');
const edge = layer('edge');
const mirror = layer('mirror');
const ghosts = options.map((option) => {
const ghost = layer('ghost');
const label = option.querySelector('.kodza-segmented__label');
if (label) ghost.append(label.cloneNode(true));
return ghost;
});
mirror.append(...ghosts);
edge.append(mirror);
pill.append(edge);
lane.append(pill);
track.append(lane);
// Each option's place in the lane, in its own pixels (a parent scaled by a transform, like
// a thumbnail, changes nothing)
let boxes = [];
const measure = () => {
const box = lane.getBoundingClientRect();
const scale = box.width / lane.offsetWidth || 1;
const full = lane.offsetWidth;
boxes = options.map((option) => {
const rect = option.getBoundingClientRect();
const left = (rect.left - box.left) / scale;
const width = rect.width / scale;
return { left, width, right: full - left - width };
});
ghosts.forEach((ghost, i) => {
ghost.style.left = `${boxes[i].left}px`;
ghost.style.width = `${boxes[i].width}px`;
});
};
// The three moving layers for given edges: the windows put their cuts there, the ink cancels
// their shift and stays put
const shifts = ({ left, right }) => [left, -left - right, right];
const rest = (edges) => {
track.style.setProperty('--kz-seg-l', `${edges.left}px`);
track.style.setProperty('--kz-seg-r', `${edges.right}px`);
};
// The edges at a point of a slide: the front edge (the side it goes to) leads, the back
// edge follows, so the pill stretches on the way and shrinks back as it lands
let move = null;
const edgesAt = ({ from, to, forward, grow }, t) => {
const front = ease(grow ? t : Math.min(1, t / LEAD));
const back = grow ? front : ease(Math.max(0, (t - LAG) / (1 - LAG)));
return {
left: from.left + (to.left - from.left) * (forward ? back : front),
right: from.right + (to.right - from.right) * (forward ? front : back),
};
};
const now = () => {
const t = move?.animations[0].currentTime;
return move && t != null && move.animations[0].playState === 'running' ? edgesAt(move, Math.min(1, t / duration)) : null;
};
const stop = () => {
move?.animations.forEach((animation) => animation.cancel());
move = null;
};
// From nothing chosen, the pill opens from the middle of the option
const slide = (from, to) => {
stop();
rest(to);
if (still) return;
const grow = !from;
if (grow) from = { left: to.left + to.width / 2, right: to.right + to.width / 2 };
const plan = { from, to, grow, forward: to.left > from.left };
const frames = [[], [], []];
for (let i = 0; i <= SAMPLES; i += 1) {
shifts(edgesAt(plan, i / SAMPLES)).forEach((x, n) => frames[n].push({ transform: `translateX(${x}px)` }));
}
const timing = { duration, easing: 'linear' };
move = { ...plan, animations: [pill, edge, mirror].map((el, n) => el.animate(frames[n], timing)) };
move.animations[0].onfinish = () => { move = null; };
};
// Nothing chosen: the pill is cut down to nothing
const clear = () => {
stop();
track.style.removeProperty('--kz-seg-l');
track.style.removeProperty('--kz-seg-r');
};
let current = inputs.findIndex((input) => input.checked);
const update = () => {
const next = inputs.findIndex((input) => input.checked);
if (next === current) return;
const from = now() || boxes[current] || null;
current = next;
if (next < 0) return clear();
slide(from, boxes[next]);
};
// A resize that leaves the options where they are (the page around it) lets a slide run on
const place = () => {
const before = boxes;
measure();
const same = move && boxes.every((box, i) => Math.abs(box.left - before[i].left) < 0.5 && Math.abs(box.width - before[i].width) < 0.5);
if (same) return;
stop();
if (current >= 0) rest(boxes[current]);
else clear();
};
root.addEventListener('change', update, { signal });
// A form reset puts the radios back without a change event
root.closest('form')?.addEventListener('reset', () => requestAnimationFrame(update), { signal });
place();
const observer = new ResizeObserver(place);
observer.observe(track);
signal.addEventListener('abort', () => {
observer.disconnect();
stop();
});
document.fonts?.ready.then(() => !signal.aborted && place());
}
// Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
// event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
// markup back. For themes and apps that swap content without a page load. Each running root
// keeps its markup as written under KODZA, shared by every Kodza script on the page: a Kodza
// component inside another one is saved as written, not half-started, and stopped with it. Two
// components on one root (a reveal on a stat card) both start, and stop together.
const KODZA = Symbol.for('kodza');
const RUNNING = Symbol.for(`kodza ${SELECTOR}`); // a root this component runs on, for every copy of this script
const instances = new WeakMap();
const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
const attrsOf = (el) => [...el.attributes].map((a) => [a.name, a.value]);
const put = (el, saved) => {
[...el.attributes].forEach((a) => el.removeAttribute(a.name));
saved.attrs.forEach(([name, value]) => el.setAttribute(name, value));
el.innerHTML = saved.html;
};
// The markup inside a root as written: Kodza components already running in it give back their own
const written = (root) => {
const all = [...root.querySelectorAll('*')];
if (!all.some((el) => el[KODZA])) return root.innerHTML;
const copy = root.cloneNode(true);
const twins = copy.querySelectorAll('*');
let last = null;
all.forEach((el, i) => {
if (!el[KODZA] || last?.contains(el)) return;
last = el;
put(twins[i], el[KODZA]);
});
return copy.innerHTML;
};
const init = (scope) => find(scope).forEach((root) => {
// Already running, maybe from another copy of this script. Marked is-ready with no Kodza component
// running on it, a root is a copy of a started one (a cloned slide): it is left as it is
if (root[RUNNING] || (root.classList.contains('is-ready') && !root[KODZA])) return;
// Rendered by React (data-kodza-manual): React starts it, with an init aimed at that markup once
// it has hydrated it. Any earlier start would change markup React has not taken over yet
const owner = root.closest('[data-kodza-manual]');
if (owner && !(scope && owner.contains(scope))) return;
const controller = new AbortController();
// Another Kodza component already running on this root: its markup as written is kept, and the
// two stop together
const before = root[KODZA];
const saved = { html: before ? before.html : written(root), attrs: before ? before.attrs : attrsOf(root), stop: () => destroy(root) };
if (before) before.above = saved;
instances.set(root, { controller, saved, before });
root[KODZA] = saved;
root[RUNNING] = true;
mount(root, controller.signal);
root.classList.add('is-ready');
});
const destroy = (scope) => find(scope).forEach((root) => {
const instance = instances.get(root);
if (!instance) return;
instances.delete(root);
instance.saved.above?.stop(); // a Kodza component started after it on the same root stops first
// The Kodza components running inside it stop first: once its markup is put back, their own
// script could not find them any more
root.querySelectorAll('*').forEach((el) => el[KODZA]?.stop());
instance.controller.abort();
delete root[RUNNING];
// Started on top of another one: that one stops next, and puts the markup back
if (instance.before) {
delete instance.before.above;
root[KODZA] = instance.before;
return instance.before.stop();
}
delete root[KODZA];
put(root, instance.saved);
});
document.addEventListener('kodza:init', (event) => init(event.detail?.root));
document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
init();
// Loaded in <head>, the script runs before the markup exists: once more when it is parsed
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
'use client';
// Kodza — Segmented Control, for React. From https://kodza.dev/components/segmented-control/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: segmented-control.css and segmented-control.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
// data-kodza-manual keeps the script from starting it on its own: the effect below does, once
// React has hydrated the markup (on a page that streams in, the script can load first).
// Built from your data (tabs, rows, options)? Put what the markup is made of in the key, as plain
// values (ids, text, numbers): a change starts the script again on fresh markup. What the visitor
// changes (the open tab, the sort, what they type) is the script's: keep it out of the key, follow
// it with onClick or onInput on the root, and change it from your code as a visitor would (click
// the tab; set the field's value, then dispatch a bubbling input event).
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './segmented-control.css';
type Variant = "block" | "icons";
export type SegmentedControlProps = Omit<ComponentPropsWithoutRef<'fieldset'>, "children" | "variant" | "vars"> & {
/** Modifier class(es): .kodza-segmented--block, .kodza-segmented--icons */
variant?: Variant | Variant[];
/** Settings, as CSS variables on the root */
vars?: {
/** default: #ffffff */
"--kz-segmented-bg"?: string | number;
/** default: #0a0a0a */
"--kz-segmented-fg"?: string | number;
/** default: rgba(10, 10, 10, 0.58) */
"--kz-segmented-muted"?: string | number;
/** default: rgba(10, 10, 10, 0.1) */
"--kz-segmented-border"?: string | number;
/** default: #0a0a0a */
"--kz-segmented-ink"?: string | number;
/** default: #ffffff */
"--kz-segmented-on-ink"?: string | number;
/** the badge on the track — default: rgba(10, 10, 10, 0.07) */
"--kz-segmented-badge"?: string | number;
/** the badge under the pill — default: rgba(255, 255, 255, 0.2) */
"--kz-segmented-badge-on-ink"?: string | number;
/** the whole pill; the options are 2 × --kz-segmented-pad shorter — default: 44px */
"--kz-segmented-height"?: string | number;
/** the room around the ink pill — default: 4px */
"--kz-segmented-pad"?: string | number;
/** --block: the width it fills, at most — default: var(--kz-field-width, 360px) */
"--kz-segmented-width"?: string | number;
/** the slide of the pill. 0s = no motion — default: 0.55s */
"--kz-segmented-duration"?: string | number;
};
className?: string;
};
export function SegmentedControl({ variant, vars, className, style, ...rest }: SegmentedControlProps) {
const ref = useRef<ComponentRef<'fieldset'>>(null);
const classes = ["kodza-segmented", ...([] as string[]).concat(variant ?? []).map((v) => `kodza-segmented--${v}`), className].filter(Boolean).join(' ');
// Everything the markup is made of: when it changes, React gets a fresh element (see the top)
const key = JSON.stringify([classes, vars, style, rest]);
// Starts the script on this element once React has rendered it, stops it when it goes
useEffect(() => {
const root = ref.current;
let live = true;
// @ts-ignore: a plain script, no types to find
import('./segmented-control.js').then(() => {
if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
});
return () => {
live = false;
document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
};
}, [key]);
return (
<fieldset key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
<legend className="kodza-segmented__legend kodza-segmented__legend--hidden">Billing</legend>
<div className="kodza-segmented__track">
<label className="kodza-segmented__option">
<input className="kodza-segmented__input" type="radio" name="billing" defaultValue="monthly" defaultChecked />
{' '}
<span className="kodza-segmented__label">Monthly</span>
</label>
{' '}
<label className="kodza-segmented__option">
<input className="kodza-segmented__input" type="radio" name="billing" defaultValue="annual" />
{' '}
<span className="kodza-segmented__label">Annual <span className="kodza-segmented__badge">−20%</span></span>
</label>
</div>
</fieldset>
);
}
Checked
Robots poked at it before you did. Every component goes through the same checks, and again each time it changes.