Ruler slider
An adjustable measurement with a draggable tick tape, fixed needle and native slider fallback.
pnpm dlx shadcn@latest add @haze/ruler-slider---
import { cn } from "../../../lib/haze/utils";
import Slider from "./slider.astro";
interface Props {
id: string;
name?: string;
label?: string;
min?: number;
max?: number;
step?: number;
value?: number;
unit?: string;
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Desk height", min = 60, max = 130, step = 1, value = 74, unit = "cm", disabled, class: className, ...rest } = Astro.props;
const floor = Number.isFinite(min) ? min : 0;
const ceiling = Number.isFinite(max) && max > floor ? max : floor + 100;
const increment = Number.isFinite(step) && step > 0 ? step : 1;
const initial = Number.isFinite(value) ? Math.max(floor, Math.min(ceiling, value)) : floor;
const ticks = Math.min(120, Math.max(10, Math.round((ceiling - floor) / increment)));
---
<div data-haze-ruler-slider data-ticks={ticks} data-unit={unit} class={cn("grid w-full min-w-0 gap-3", className)}>
<div class="flex flex-wrap items-baseline justify-between gap-2 text-foreground">
<label for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
<output for={id} data-readout aria-hidden="true" class="text-[1.0625rem]/7 font-medium tabular-nums">{initial} <span class="text-[0.8125rem]/5 font-normal text-muted-foreground">{unit}</span></output>
</div>
<div data-ruler-tape dir="ltr" aria-hidden="true" class="relative h-20 touch-pan-y overflow-hidden mask-[linear-gradient(to_right,transparent,black_12%,black_88%,transparent)] rounded-lg border border-border bg-card select-none data-[enabled]:cursor-ew-resize">
<div data-ticks style={`--ruler-offset:${(initial - floor) / (ceiling - floor) * ticks * 12 + 6}px`} class="absolute top-3 left-1/2 flex w-max -translate-x-(--ruler-offset,0px) items-start transition-[translate] duration-200 ease-snappy [[data-dragging]_&]:duration-75">
{Array.from({ length: ticks + 1 }, (_, index) => <span class="relative flex w-3 shrink-0 justify-center"><span class={cn("w-px bg-foreground/25", index % 5 === 0 ? "h-6" : "h-3")} />{index % 5 === 0 && <span class="absolute top-9 left-1/2 -translate-x-1/2 text-[0.6875rem]/4 text-muted-foreground tabular-nums">{Math.round((floor + index / ticks * (ceiling - floor)) * 100) / 100}</span>}</span>)}
</div>
<span class="pointer-events-none absolute top-2 bottom-2 left-1/2 w-0.5 -translate-x-1/2 rounded-full bg-primary" />
</div>
<Slider id={id} name={name} min={floor} max={ceiling} step={increment} value={initial} disabled={disabled} {...rest} />
<p class="text-[0.8125rem]/5 text-muted-foreground">Drag the ruler or use the slider to choose a precise value.</p>
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const input = root.querySelector<HTMLInputElement>("input[type=range]");
const tape = root.querySelector<HTMLElement>("[data-ruler-tape]");
const ticks = root.querySelector<HTMLElement>("[data-ticks]");
const output = root.querySelector<HTMLOutputElement>("[data-readout]");
if (!input || !tape || !ticks || !output) return;
const minimum = Number(input.min), maximum = Number(input.max), step = Number(input.step);
const length = Number(root.dataset.ticks) * 12;
let drag: { id: number; x: number; y: number; value: number; locked: boolean } | null = null;
const render = () => {
const fraction = (input.valueAsNumber - minimum) / (maximum - minimum);
ticks.style.setProperty("--ruler-offset", `${fraction * length + 6}px`);
output.textContent = `${input.value} ${root.dataset.unit || ""}`;
input.setAttribute("aria-valuetext", output.textContent);
tape.toggleAttribute("data-enabled", !input.matches(":disabled"));
};
const change = (value: number, commit = false) => {
input.value = String(minimum + Math.round((Math.max(minimum, Math.min(maximum, value)) - minimum) / step) * step);
input.dispatchEvent(new Event("input", { bubbles: true }));
if (commit) input.dispatchEvent(new Event("change", { bubbles: true }));
};
tape.addEventListener("pointerdown", (event) => { if (!input.matches(":disabled") && event.isPrimary && event.button === 0) drag = { id: event.pointerId, x: event.clientX, y: event.clientY, value: input.valueAsNumber, locked: false }; });
tape.addEventListener("pointermove", (event) => {
if (!drag || drag.id !== event.pointerId) return;
const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
if (!drag.locked && Math.abs(dy) > Math.abs(dx) && Math.abs(dy) > 5) { drag = null; return; }
if (!drag.locked && Math.abs(dx) > 5) { drag.locked = true; tape.setPointerCapture(event.pointerId); tape.setAttribute("data-dragging", ""); }
if (drag.locked) change(drag.value - dx / length * (maximum - minimum));
});
const finish = (event: PointerEvent, canceled: boolean) => {
if (!drag || drag.id !== event.pointerId) return;
const saved = drag;
drag = null;
tape.removeAttribute("data-dragging");
if (tape.hasPointerCapture(event.pointerId)) tape.releasePointerCapture(event.pointerId);
if (canceled) change(saved.value);
else { if (!saved.locked) change(saved.value + (event.clientX - (tape.getBoundingClientRect().left + tape.clientWidth / 2)) / length * (maximum - minimum)); input.dispatchEvent(new Event("change", { bubbles: true })); }
};
tape.addEventListener("pointerup", (event) => finish(event, false));
tape.addEventListener("pointercancel", (event) => finish(event, true));
tape.addEventListener("lostpointercapture", (event) => { if (event.target === tape && drag) finish(event, true); });
input.addEventListener("input", render);
input.form?.addEventListener("reset", () => queueMicrotask(render));
root.setAttribute("data-enhanced", "");
render();
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-ruler-slider]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-ruler-slider-listener")) {
document.documentElement.setAttribute("data-haze-ruler-slider-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- Choosing a physical measurement benefits from a visible ruler and explicit unit.
- Touch users should be able to drag the scale while keyboard users keep a familiar range input.
When not to use
- Use input for an exact measurement that people will usually type.
- Use elastic-slider when named presets matter more than a continuous scale.
Installation
Add the Haze registry to components.json once, then install Ruler slider with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ruler-slidernpx shadcn@latest add @haze/ruler-slideryarn dlx shadcn@latest add @haze/ruler-sliderbunx --bun shadcn@latest add @haze/ruler-sliderFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller supplied prefix for the control and its associated content. |
| name | string | id | Name submitted by the native form control. |
| label | string | Desk height | Visible measurement name. |
| min | number | 60 | Beginning of the tape. |
| max | number | 130 | End of the tape. |
| step | number | 1 | Smallest selectable increment. |
| value | number | 74 | Initial measurement. |
| unit | string | cm | Unit shown and spoken with the measurement. |
| disabled | boolean | false | Prevents user changes through the native disabled state. |
| class | string | – | Additional classes on this component's outer wrapper. |
| [key: string] | unknown | – | Other range attributes forwarded to the native Slider. |
Keyboard interactions
- Arrow keys
- Increase or decrease by the supplied measurement step.
- HomeEnd
- Reach the shortest or longest measurement.
Accessibility
- The tape and needle are decorative; the labelled native range stays visible for keyboard users and when scripts are unavailable.
- Horizontal dragging waits for an axis decision, allowing a vertical touch gesture to scroll the page.
- A canceled pointer gesture restores the measurement from before the drag.
- The accessible value includes the chosen unit, while the tick count is capped so large domains do not create unbounded markup.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Ruler slider" with `npx shadcn@latest add @haze/ruler-slider`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import RulerSlider from "@/components/haze/ui/ruler-slider.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/ruler-slider.md
Customize with real content
Adapt the Haze ruler-slider ui for our product. Replace the demo values of these props with our real content: id, name, label, min, max, step, value, unit, disabled, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: The tape and needle are decorative; the labelled native range stays visible for keyboard users and when scripts are unavailable. Horizontal dragging waits for an axis decision, allowing a vertical touch gesture to scroll the page. A canceled pointer gesture restores the measurement from before the drag. The accessible value includes the chosen unit, while the tick count is capped so large domains do not create unbounded markup. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ruler-slider, check it fits: use it when choosing a physical measurement benefits from a visible ruler and explicit unit.; touch users should be able to drag the scale while keyboard users keep a familiar range input.. Avoid it when use input for an exact measurement that people will usually type.; use elastic-slider when named presets matter more than a continuous scale.. Alternatives: @haze/slider, @haze/input, @haze/elastic-slider.
Dependencies
- @haze/slider
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.