Scrub input
Drag the label to scrub a number, or type a sum.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/and the colour tokens go into your CSS.$ pnpm dlx asta-ui@latest add scrub-inputOr install the package
Don’t want the file? Import from
asta-ui/scrub-inputand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-uiimport { ScrubInput } from "asta-ui/scrub-input";Or copy it by hand
Copy this file. Keep the paths, or fix the
@/imports. Then add the tokens fromglobals.css."use client"; import { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const KEYFRAMES = `@keyframes asta-scrub-tip { from { opacity: 0; transform: translateY(-3px) } } @media (prefers-reduced-motion: reduce) { .asta-scrub-a, .asta-scrub-a * { animation: none !important; transition-duration: 0s !important } }`; /* ---------- Units and the expression parser ---------- */ // Each unit belongs to a family and has a factor to that family's base (px, deg, %, ms). const UNITS: Record<string, [family: string, factor: number]> = { px: ["len", 1], rem: ["len", 16], em: ["len", 16], pt: ["len", 4 / 3], deg: ["ang", 1], "°": ["ang", 1], rad: ["ang", 180 / Math.PI], turn: ["ang", 360], "%": ["pct", 1], ms: ["time", 1], s: ["time", 1000], }; type Token = { t: "num"; v: number } | { t: "op"; v: string }; function tokenize(src: string, unit?: string): Token[] | null { const out: Token[] = []; const base = unit ? UNITS[unit] : undefined; const re = /\s*(?:(\d*\.?\d+(?:e[+-]?\d+)?)\s*([a-z%°]*)|([-+*/×÷()]))\s*/giy; let i = 0; while (i < src.length) { re.lastIndex = i; const m = re.exec(src); if (!m) return null; i = re.lastIndex; if (m[3]) { out.push({ t: "op", v: m[3] === "×" ? "*" : m[3] === "÷" ? "/" : m[3] }); continue; } let v = Number(m[1]); const u = m[2].toLowerCase(); if (u && u !== unit) { const typed = UNITS[u]; // A unit from another family ("12px" in an angle field) can't be read. if (!typed || !base || typed[0] !== base[0]) return null; v = (v * typed[1]) / base[1]; } out.push({ t: "num", v }); } return out; } /** * Reads what was typed into a scrub field without eval: numbers with an optional unit ("12px", "1.5rem", "45°"), * + − × ÷ and brackets. A leading +, * or / works on the current value ("+8", "*2"). Returns null when it can't. */ export function parseScrubValue(text: string, current: number, unit?: string): number | null { let src = text.trim().replace(/,/g, ".").replace(/−/g, "-"); if (!src || src.length > 64) return null; let rel: string | null = null; if (/^[+*/×÷]/.test(src)) { rel = src[0] === "×" ? "*" : src[0] === "÷" ? "/" : src[0]; src = src.slice(1); } const tokens = tokenize(src, unit); if (!tokens?.length) return null; let p = 0; const isOp = (...ops: string[]) => tokens[p]?.t === "op" && ops.includes(tokens[p].v as string); const factor = (): number => { const tk = tokens[p++]; if (!tk) return NaN; if (tk.t === "num") return tk.v; if (tk.v === "-") return -factor(); if (tk.v === "+") return factor(); if (tk.v === "(") { const v = expr(); return tokens[p++]?.v === ")" ? v : NaN; } return NaN; }; const term = (): number => { let v = factor(); while (isOp("*", "/")) v = tokens[p++].v === "*" ? v * factor() : v / factor(); return v; }; const expr = (): number => { let v = term(); while (isOp("+", "-")) v = tokens[p++].v === "+" ? v + term() : v - term(); return v; }; let v = expr(); if (p !== tokens.length || !Number.isFinite(v)) return null; if (rel === "+") v = current + v; else if (rel === "*") v = current * v; else if (rel === "/") v = v === 0 ? NaN : current / v; return Number.isFinite(v) ? v : null; } /* ---------- The field ---------- */ export interface ScrubInputProps { /** Short prefix you drag to scrub: "X", "W" or a small icon. */ label: ReactNode; /** Full name for screen readers and the tooltip, e.g. "Rotation". Needed when the label is an icon or one letter. */ title?: string; value?: number; defaultValue?: number; /** Fires on every change, also while scrubbing. */ onChange?: (value: number) => void; min?: number; max?: number; /** One arrow press, or 2px of drag. Shift is ×10, Alt is ×0.1. */ step?: number; /** Most decimals kept. Trailing zeros are hidden. */ precision?: number; /** Unit of the value: px, rem, °, %, ms… Typed units of the same kind convert ("1.5rem" → 24 in a px field). */ unit?: string; /** Submits the number with a form through a hidden input. */ name?: string; disabled?: boolean; size?: "sm" | "md"; className?: string; } const round = (v: number, precision: number) => Math.round(v * 10 ** precision) / 10 ** precision; const fmt = (v: number, precision: number) => String(round(v, precision)).replace(/^-0$/, "0"); const factorOf = (e: { shiftKey: boolean; altKey: boolean }) => (e.shiftKey ? 10 : e.altKey ? 0.1 : 1); /** * The number field of a design tool. Drag the label left or right to scrub (Shift ×10, Alt ×0.1), or click and * type. It reads units and simple sums like "24*2" or "+8" on Enter. Arrow keys step. At min or max the value * nudges toward the edge and a short bar shows which limit it hit. */ export function ScrubInput({ label, title, value, defaultValue = 0, onChange, min = -Infinity, max = Infinity, step = 1, precision = 2, unit, name, disabled, size = "md", className }: ScrubInputProps) { const [inner, setInner] = useState(defaultValue); const current = value ?? inner; const [draft, setDraft] = useState<string | null>(null); const [invalid, setInvalid] = useState(false); const [scrub, setScrub] = useState<null | 1 | 10 | 0.1>(null); const [limit, setLimit] = useState<"min" | "max" | null>(null); const [status, setStatus] = useState(""); const [tipEnd, setTipEnd] = useState(false); const root = useRef<HTMLLabelElement>(null); const input = useRef<HTMLInputElement>(null); const drag = useRef({ x: 0, raw: 0, moved: false, id: -1 }); const timer = useRef<ReturnType<typeof setTimeout>>(undefined); const errId = useId(); useEffect( () => () => { clearTimeout(timer.current); document.documentElement.style.cursor = ""; }, [], ); /** Clamps, rounds and reports. Flags the limit when the wanted value was outside the range. */ const set = (want: number) => { const next = round(Math.min(max, Math.max(min, want)), precision); if (want < min || want > max) { const side = want < min ? "min" : "max"; setLimit(side); setStatus(`${side === "min" ? "Minimum" : "Maximum"} is ${fmt(side === "min" ? min : max, precision)}${unit ?? ""}`); clearTimeout(timer.current); timer.current = setTimeout(() => setLimit(null), 420); } if (next !== current) { if (value === undefined) setInner(next); onChange?.(next); } }; /** Reads the draft. With keepFocus an unreadable draft stays for fixing; otherwise it's dropped. */ const commit = (keepFocus: boolean) => { if (draft === null) return true; const n = parseScrubValue(draft, current, unit); if (n === null && keepFocus) { // Open the hint toward the side with room, measured once. const r = root.current?.getBoundingClientRect(); const edge = root.current?.closest("[role=group],section")?.getBoundingClientRect().right ?? window.innerWidth; setTipEnd(!!r && r.left + 220 > edge); setInvalid(true); setStatus(`Couldn't read “${draft.trim()}”.`); return false; } if (n === null) setStatus(`Kept ${fmt(current, precision)}${unit ?? ""}.`); else set(n); setDraft(null); setInvalid(false); return true; }; const reselect = () => setTimeout(() => input.current?.select()); const onKey = (e: KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter") { e.preventDefault(); if (commit(true)) reselect(); } else if (e.key === "Escape") { if (draft === null) return; e.preventDefault(); setDraft(null); setInvalid(false); reselect(); } else if (["ArrowUp", "ArrowDown", "PageUp", "PageDown"].includes(e.key)) { e.preventDefault(); const base = draft === null ? current : (parseScrubValue(draft, current, unit) ?? current); const dir = e.key === "ArrowUp" || e.key === "PageUp" ? 1 : -1; setDraft(null); setInvalid(false); set(base + dir * step * (e.key.startsWith("Page") ? 10 : factorOf(e))); reselect(); } }; /* Scrubbing. Each move adds its own distance × the current modifier, so switching Shift or Alt mid-drag never jumps. */ const down = (e: PointerEvent<HTMLSpanElement>) => { if (disabled || (e.pointerType === "mouse" && e.button !== 0)) return; e.preventDefault(); try { e.currentTarget.setPointerCapture(e.pointerId); } catch {} commit(false); drag.current = { x: e.clientX, raw: current, moved: false, id: e.pointerId }; setScrub(factorOf(e)); document.documentElement.style.cursor = "ew-resize"; }; const move = (e: PointerEvent<HTMLSpanElement>) => { const d = drag.current; if (scrub === null || e.pointerId !== d.id) return; const dx = e.clientX - d.x; if (!d.moved && Math.abs(dx) < 3) return; d.moved = true; d.x = e.clientX; const f = factorOf(e); if (f !== scrub) setScrub(f); const want = d.raw + (dx / 2) * step * f; // The raw value stays inside the range, so dragging back responds at once. d.raw = Math.min(max, Math.max(min, want)); // Snap to the step in use, so a plain drag gives whole steps and Alt gives tenths. const grid = step * f; set(want < min || want > max ? want : Math.round(want / grid) * grid); }; const up = (e: PointerEvent<HTMLSpanElement>) => { if (scrub === null || e.pointerId !== drag.current.id) return; drag.current.id = -1; setScrub(null); document.documentElement.style.cursor = ""; if (!drag.current.moved) { input.current?.focus(); input.current?.select(); } }; const sm = size === "sm"; const a11yName = title ?? (typeof label === "string" ? label : undefined); return ( <label ref={root} data-scrubbing={scrub !== null || undefined} data-limit={limit ?? undefined} className={cx( "asta-scrub-a group/scrub relative flex min-w-0 items-center rounded-[7px] bg-[color-mix(in_srgb,var(--color-ink)_5%,transparent)] text-ink transition-[background-color,box-shadow] duration-150", "hover:bg-[color-mix(in_srgb,var(--color-ink)_8%,transparent)] focus-within:bg-paper focus-within:shadow-[inset_0_0_0_1.5px_var(--color-brand)]", "data-[scrubbing]:bg-paper data-[scrubbing]:shadow-[inset_0_0_0_1.5px_var(--color-brand)]", invalid && "!shadow-[inset_0_0_0_1.5px_var(--color-ink)]", sm ? "h-8 sm:h-7" : "h-9 sm:h-8", disabled && "pointer-events-none opacity-45", className, )} > <style href="asta-scrub-input" precedence="asta">{KEYFRAMES}</style> <span aria-hidden title={a11yName ? `${a11yName}: drag to change` : undefined} onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up} onLostPointerCapture={up} className={cx( "grid h-full shrink-0 cursor-ew-resize touch-none select-none place-items-center text-[11.5px] font-medium text-mute transition-colors duration-150 hover:text-ink group-data-[scrubbing]/scrub:text-brand [&>svg]:h-3.5 [&>svg]:w-3.5", sm ? "w-6" : "w-7", )} > {label} </span> <input ref={input} role="spinbutton" aria-label={a11yName} aria-valuenow={current} aria-valuemin={Number.isFinite(min) ? min : undefined} aria-valuemax={Number.isFinite(max) ? max : undefined} aria-valuetext={`${fmt(current, precision)}${unit ? ` ${unit}` : ""}`} aria-invalid={invalid || undefined} aria-describedby={invalid ? errId : undefined} inputMode="text" autoComplete="off" spellCheck={false} disabled={disabled} value={draft ?? fmt(current, precision)} onChange={(e) => { setDraft(e.target.value); setInvalid(false); }} onFocus={(e) => e.target.select()} onBlur={() => commit(false)} onKeyDown={onKey} className={cx( "h-full min-w-0 flex-1 bg-transparent pr-1 text-[16px] tabular-nums tracking-[-0.01em] outline-none transition-transform duration-200 ease-[cubic-bezier(.16,1,.3,1)] selection:bg-[color-mix(in_srgb,var(--color-brand)_22%,transparent)]", sm ? "sm:text-[12px]" : "sm:text-[12.5px]", limit === "max" && "translate-x-[3px]", limit === "min" && "-translate-x-[3px]", )} /> {scrub !== null && scrub !== 1 ? ( <span aria-hidden className="mr-1.5 shrink-0 rounded-[4px] bg-brand px-1 text-[10.5px] font-medium leading-4 tabular-nums text-on-brand"> ×{scrub} </span> ) : ( unit && ( <span aria-hidden className="shrink-0 pr-2 text-[11.5px] text-mute"> {unit} </span> ) )} {/* The limit you hit: a short bar on that edge fades in, then out. */} <span aria-hidden className={cx( "pointer-events-none absolute inset-y-1.5 w-[2px] rounded-full bg-brand transition-opacity ease-[cubic-bezier(.16,1,.3,1)]", limit ? "opacity-100 duration-100" : "opacity-0 duration-500", limit === "min" ? "left-0.5" : "right-0.5", )} /> {invalid && ( <span id={errId} className={cx( "absolute top-[calc(100%+6px)] z-10 w-max max-w-[220px] rounded-[8px] bg-ink px-2.5 py-1.5 text-[12px] leading-snug text-paper shadow-[0_8px_24px_-10px_rgb(0_0_0/0.4)] [animation:asta-scrub-tip_.2s_cubic-bezier(.16,1,.3,1)]", tipEnd ? "right-0" : "left-0", )} > Try 24, 1.5rem or 24*2. Esc puts it back. </span> )} <span className="sr-only" role="status" aria-live="polite"> {status} </span> {name && <input type="hidden" name={name} value={current} />} </label> ); } /* ---------- A labelled row of fields ---------- */ export interface ScrubRowProps { /** Muted label on the left, e.g. "Position". */ label?: string; cols?: 1 | 2 | 3 | 4; children: ReactNode; className?: string; } const COLS = { 1: "grid-cols-1", 2: "grid-cols-2", 3: "grid-cols-3", 4: "grid-cols-4" }; export function ScrubRow({ label, cols = 2, children, className }: ScrubRowProps) { return ( <div role="group" aria-label={label} className={cx("grid items-center gap-x-3", label ? "grid-cols-[64px_1fr]" : "grid-cols-1", className)}> {label && <span className="truncate text-[12px] text-mute">{label}</span>} <div className={cx("grid min-w-0 gap-1.5", COLS[cols])}>{children}</div> </div> ); } export default ScrubInput;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Scrub input component to my project. Drag the label to scrub a number, or type a sum. It includes: ScrubInput, ScrubRow, scrub, units, math, keys, limits, touch. Install it: ```sh pnpm dlx asta-ui@latest add scrub-input --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/scrub-input.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { ScrubInput, ScrubRow } from "@/components/astabyte/scrub-input"; ``` Usage example and props: https://ui.astabyte.com/scrub-input Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- asta.js does the scrubbing, the maths and the clamping. Set data-min, data-max, data-step, data-precision and data-unit on each field. --> <section aria-label="Frame properties" style="display:grid;gap:8px;max-width:300px;padding:14px;border-radius:12px;background:var(--paper);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--ink) 10%,transparent)"> <div class="asta-scrub-row" role="group" aria-label="Position"><span class="asta-scrub-row-label">Position</span> <div class="asta-scrub-cells"> <label class="asta-scrub" data-asta-scrub data-unit="px"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="X position: drag to change">X</span><input class="asta-scrub-input" role="spinbutton" aria-label="X position" aria-valuenow="140" aria-valuetext="140 px" value="140" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">px</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 24, 1.5rem or 24*2. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="x" value="140"></label> <label class="asta-scrub" data-asta-scrub data-unit="px"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="Y position: drag to change">Y</span><input class="asta-scrub-input" role="spinbutton" aria-label="Y position" aria-valuenow="70" aria-valuetext="70 px" value="70" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">px</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 24, 1.5rem or 24*2. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="y" value="70"></label> </div></div> <div class="asta-scrub-row" role="group" aria-label="Size"><span class="asta-scrub-row-label">Size</span> <div class="asta-scrub-cells"> <label class="asta-scrub" data-asta-scrub data-unit="px" data-min="1" data-max="560"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="Width: drag to change">W</span><input class="asta-scrub-input" role="spinbutton" aria-label="Width" aria-valuenow="280" aria-valuemin="1" aria-valuemax="560" aria-valuetext="280 px" value="280" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">px</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 24, 1.5rem or 24*2. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="w" value="280"></label> <label class="asta-scrub" data-asta-scrub data-unit="px" data-min="1" data-max="300"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="Height: drag to change">H</span><input class="asta-scrub-input" role="spinbutton" aria-label="Height" aria-valuenow="160" aria-valuemin="1" aria-valuemax="300" aria-valuetext="160 px" value="160" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">px</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 24, 1.5rem or 24*2. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="h" value="160"></label> </div></div> <div class="asta-scrub-row" role="group" aria-label="Shape"><span class="asta-scrub-row-label">Shape</span> <div class="asta-scrub-cells"> <label class="asta-scrub" data-asta-scrub data-unit="°" data-min="-180" data-max="180"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="Rotation: drag to change"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8a5 5 0 1 1-1.6-3.7M13 2.5v2.8h-2.8"/></svg></span><input class="asta-scrub-input" role="spinbutton" aria-label="Rotation" aria-valuenow="0" aria-valuemin="-180" aria-valuemax="180" aria-valuetext="0 °" value="0" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">°</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 45, 0.25turn or 90/2. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="rotation" value="0"></label> <label class="asta-scrub" data-asta-scrub data-unit="px" data-min="0" data-max="80"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="Corner radius: drag to change"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 13V8a5 5 0 0 1 5-5h5"/></svg></span><input class="asta-scrub-input" role="spinbutton" aria-label="Corner radius" aria-valuenow="12" aria-valuemin="0" aria-valuemax="80" aria-valuetext="12 px" value="12" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">px</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 24, 1.5rem or 24*2. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="radius" value="12"></label> </div></div> <div class="asta-scrub-row" role="group" aria-label="Layer"><span class="asta-scrub-row-label">Layer</span> <div class="asta-scrub-cells asta-scrub-cells-1"> <label class="asta-scrub" data-asta-scrub data-unit="%" data-min="0" data-max="100"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true" title="Opacity: drag to change"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2.5a5.5 5.5 0 1 0 0 11zM8 2.5a5.5 5.5 0 0 1 0 11"/></svg></span><input class="asta-scrub-input" role="spinbutton" aria-label="Opacity" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" aria-valuetext="100 %" value="100" inputmode="text" autocomplete="off" spellcheck="false"><span class="asta-scrub-badge" aria-hidden="true"></span><span class="asta-scrub-unit" aria-hidden="true">%</span><span class="asta-scrub-limit" aria-hidden="true"></span><span class="asta-scrub-tip">Try 50, 50% or 100/4. Esc puts it back.</span><span class="asta-sr-only" role="status" data-asta-scrub-status></span><input type="hidden" name="opacity" value="100"></label> </div></div> <div class="asta-scrub-row" role="group" aria-label="Effects"><span class="asta-scrub-row-label">Blur</span> <div class="asta-scrub-cells asta-scrub-cells-1"> <label class="asta-scrub asta-scrub-sm" data-asta-scrub data-unit="px"><span class="asta-scrub-handle" data-asta-scrub-handle aria-hidden="true">B</span><input class="asta-scrub-input" role="spinbutton" aria-label="Blur, locked by the style" value="8" disabled><span class="asta-scrub-unit" aria-hidden="true">px</span></label> </div></div> </section>
Usage
The demo above, as code.
"use client";
import { useEffect, useRef, useState } from "react";
import { ScrubInput, ScrubRow } from "@/components/astabyte/scrub-input";
const icon = (d: string) => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d={d} />
</svg>
);
const ROTATE = icon("M19.5 12a7.5 7.5 0 1 1-2.2-5.3M19.5 4.5v3.5H16");
const RADIUS = icon("M4.5 19.5V12a7.5 7.5 0 0 1 7.5-7.5h7.5");
const OPACITY = icon("M12 3.75a8.25 8.25 0 1 0 0 16.5zM12 3.75a8.25 8.25 0 0 1 0 16.5");
// The canvas is drawn at this size and scaled to fit its box.
const CANVAS = { w: 560, h: 300 };
export default function ScrubInputDemo() {
const [f, setF] = useState({ x: 140, y: 70, w: 280, h: 160, r: 0, radius: 12, o: 100 });
const [locked, setLocked] = useState(false);
const [scale, setScale] = useState(1);
const stage = useRef<HTMLDivElement>(null);
const set = (k: keyof typeof f) => (v: number) => setF((p) => ({ ...p, [k]: v }));
useEffect(() => {
const el = stage.current;
if (!el) return;
const ro = new ResizeObserver(([e]) => setScale(e.contentRect.width / CANVAS.w));
ro.observe(el);
return () => ro.disconnect();
}, []);
const resize = (k: "w" | "h") => (v: number) =>
setF((p) => {
if (!locked) return { ...p, [k]: v };
const ratio = p.w / p.h;
return k === "w" ? { ...p, w: v, h: Math.round((v / ratio) * 100) / 100 } : { ...p, h: v, w: Math.round(v * ratio * 100) / 100 };
});
return (
<div className="flex min-h-[560px] w-full items-center justify-center p-4 sm:p-10">
<div className="grid w-full max-w-[880px] gap-4 md:grid-cols-[1fr_300px]">
<div ref={stage} className="relative aspect-[56/30] overflow-hidden rounded-[14px] bg-paper-2">
<div className="absolute left-0 top-0 origin-top-left" style={{ width: CANVAS.w, height: CANVAS.h, transform: `scale(${scale})` }}>
<div
className="absolute left-0 top-0"
style={{ width: f.w, height: f.h, transform: `translate(${f.x}px, ${f.y}px) rotate(${f.r}deg)`, opacity: f.o / 100 }}
>
<div
className="flex h-full w-full flex-col justify-between overflow-hidden bg-paper p-4 shadow-[0_1px_2px_rgb(0_0_0/0.06),0_12px_32px_-16px_rgb(0_0_0/0.3)]"
style={{ borderRadius: f.radius }}
>
<p className="text-[11px] font-medium text-brand">Astabyte · Spring launch</p>
<p className="text-[22px] font-medium leading-[1.05] tracking-[-0.03em] text-ink">Ship the beta in two weeks</p>
</div>
{/* Selection chrome, as a design tool draws it. */}
<div aria-hidden className="pointer-events-none absolute -inset-px shadow-[0_0_0_1.5px_var(--color-brand)]">
{["-left-1 -top-1", "-right-1 -top-1", "-bottom-1 -left-1", "-bottom-1 -right-1"].map((p) => (
<span key={p} className={`absolute h-2 w-2 bg-paper shadow-[inset_0_0_0_1.5px_var(--color-brand)] ${p}`} />
))}
<span className="absolute left-1/2 top-[calc(100%+8px)] -translate-x-1/2 whitespace-nowrap rounded-[4px] bg-brand px-1.5 text-[11px] leading-[18px] tabular-nums text-on-brand">
{Math.round(f.w)} × {Math.round(f.h)}
</span>
</div>
</div>
</div>
</div>
<section aria-label="Frame properties" className="rounded-[12px] bg-paper shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent),0_12px_32px_-16px_rgb(0_0_0/0.22)]">
<header className="flex h-11 items-center gap-2 px-3.5">
<span className="rounded-[5px] bg-[color-mix(in_srgb,var(--color-ink)_7%,transparent)] px-1.5 py-0.5 text-[11px] text-ink-2">Frame</span>
<span className="truncate text-[13px] font-medium text-ink">Hero card</span>
</header>
<div className="space-y-2 px-3.5 pb-3.5">
<ScrubRow label="Position">
<ScrubInput label="X" title="X position" value={f.x} onChange={set("x")} unit="px" />
<ScrubInput label="Y" title="Y position" value={f.y} onChange={set("y")} unit="px" />
</ScrubRow>
<ScrubRow label="Size">
<ScrubInput label="W" title="Width" value={f.w} onChange={resize("w")} min={1} max={560} unit="px" />
<ScrubInput label="H" title="Height" value={f.h} onChange={resize("h")} min={1} max={300} unit="px" />
</ScrubRow>
<div className="-mt-0.5 flex justify-end">
<button
type="button"
aria-pressed={locked}
onClick={() => setLocked((l) => !l)}
className="flex h-7 items-center gap-1.5 rounded-md px-2 text-[12px] text-mute outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 aria-pressed:text-brand"
>
<svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
{locked ? <path d="M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1" /> : <path d="M11 6.3l1-1a4 4 0 0 1 5.7 5.7l-1 1M13 17.7l-1 1A4 4 0 0 1 6.3 13l1-1M4 4l16 16" />}
</svg>
{locked ? "Ratio locked" : "Lock ratio"}
</button>
</div>
<ScrubRow label="Shape">
<ScrubInput label={ROTATE} title="Rotation" value={f.r} onChange={set("r")} min={-180} max={180} unit="°" />
<ScrubInput label={RADIUS} title="Corner radius" value={f.radius} onChange={set("radius")} min={0} max={80} unit="px" />
</ScrubRow>
<ScrubRow label="Layer" cols={1}>
<ScrubInput label={OPACITY} title="Opacity" value={f.o} onChange={set("o")} min={0} max={100} unit="%" />
</ScrubRow>
</div>
<p className="px-3.5 pb-3.5 text-[12px] leading-relaxed text-mute">
Drag a label to scrub. Shift ×10, Alt ×0.1. Or type <span className="text-ink-2">1.5rem</span>, <span className="text-ink-2">24*2</span> or <span className="text-ink-2">+8</span> and press Enter.
</p>
</section>
</div>
</div>
);
}