Movable window range
Choose and pan an indexed data window with bounded edges, a chart overview and native range controls.
pnpm dlx shadcn@latest add @haze/window-range---
import { cn } from "../../../lib/haze/utils";
import Slider from "./slider.astro";
interface Props {
id: string;
label?: string;
data?: number[];
labels?: string[];
start?: number;
end?: number;
minSpan?: number;
maxSpan?: number;
startName?: string;
endName?: string;
disabled?: boolean;
class?: string;
}
const { id, label = "Reporting window", data = [14, 18, 16, 24, 30, 22, 27, 32, 28, 36, 42, 38, 45, 41, 48, 51, 43, 56, 52, 61, 58], labels = [], start = 5, end = 14, minSpan = 1, maxSpan, startName = `${id}-start`, endName = `${id}-end`, disabled, class: className } = Astro.props;
const values = data.length ? data.map((value) => Number.isFinite(value) ? Math.max(0, value) : 0) : [0];
const last = values.length - 1;
const shortest = Math.max(0, Math.min(last, Math.round(Number.isFinite(minSpan) ? minSpan : 1)));
const longest = Math.max(shortest, Math.min(last, Math.round(maxSpan !== undefined && Number.isFinite(maxSpan) ? maxSpan : last)));
const initialStart = Math.max(0, Math.min(last - shortest, Math.round(Number.isFinite(start) ? start : 0)));
const initialEnd = Math.max(initialStart + shortest, Math.min(last, initialStart + longest, Math.round(Number.isFinite(end) ? end : last)));
const names = values.map((_, index) => labels[index] || `Day ${index + 1}`);
const peak = Math.max(1, ...values);
const points = values.map((value, index) => `${last ? index / last * 400 : 200},${76 - value / peak * 68}`).join(" ");
const text = "hidden text-muted-foreground tabular-nums [[data-haze-window-range][data-enhanced]_&]:inline";
---
<fieldset data-haze-window-range data-labels={JSON.stringify(names)} data-min-span={shortest} data-max-span={longest} disabled={disabled} class={cn("grid w-full min-w-0 gap-3 text-foreground", className)}>
<legend class="mb-3 text-[0.8125rem]/5 font-medium">{label}</legend>
<div data-window-chart aria-hidden="true" class="relative h-24 touch-pan-y overflow-hidden rounded-lg border border-border bg-card select-none data-[enabled]:cursor-ew-resize">
<svg viewBox="0 0 400 80" preserveAspectRatio="none" class="pointer-events-none h-full w-full text-foreground">
<polygon points={`0,80 ${points} 400,80`} fill="currentColor" class="opacity-10" />
<polyline points={points} stroke="currentColor" fill="none" stroke-width="2" vector-effect="non-scaling-stroke" />
</svg>
<span data-window-frame style={`left:${last ? initialStart / last * 100 : 0}%;width:${last ? (initialEnd - initialStart) / last * 100 : 100}%`} class="pointer-events-none absolute inset-y-0 min-w-0.5 rounded-md border-2 border-foreground bg-foreground/8 transition-[left,width] duration-150 ease-snappy [[data-dragging]_&]:duration-75" />
</div>
<div class="grid gap-2 rounded-xl border border-border bg-card p-3">
<div class="flex flex-wrap justify-between gap-1 text-[0.8125rem]/5"><label for={`${id}-start`} class="font-medium">Start</label><output data-start-value for={`${id}-start`} aria-hidden="true" class={text}>{names[initialStart]}</output></div>
<Slider id={`${id}-start`} name={startName} min={0} max={last} value={initialStart} data-window-start aria-label="Window start" />
<div class="flex flex-wrap justify-between gap-1 text-[0.8125rem]/5"><label for={`${id}-end`} class="font-medium">End</label><output data-end-value for={`${id}-end`} aria-hidden="true" class={text}>{names[initialEnd]}</output></div>
<Slider id={`${id}-end`} name={endName} min={0} max={last} value={initialEnd} data-window-end aria-label="Window end" />
<div data-window-pan-control hidden class="grid gap-1 border-t border-border pt-2">
<label for={`${id}-pan`} class="text-[0.8125rem]/5 font-medium">Move the whole window</label>
<Slider id={`${id}-pan`} name={`${id}-position`} min={0} max={Math.max(0, last - initialEnd + initialStart)} value={initialStart} disabled data-window-pan />
</div>
</div>
<p data-window-status role="status" class="text-[0.8125rem]/5 text-muted-foreground">{names[initialStart]} – {names[initialEnd]} · {initialEnd - initialStart + 1} points</p>
<noscript><p class="text-[0.8125rem]/5 text-muted-foreground">Choose start and end indices from 0 to {last}; the chart shows the initial window.</p></noscript>
</fieldset>
<script>
function enhance(root: HTMLFieldSetElement) {
if (root.hasAttribute("data-enhanced")) return;
const start = root.querySelector<HTMLInputElement>("[data-window-start]");
const end = root.querySelector<HTMLInputElement>("[data-window-end]");
const pan = root.querySelector<HTMLInputElement>("[data-window-pan]");
const chart = root.querySelector<HTMLElement>("[data-window-chart]");
const frame = root.querySelector<HTMLElement>("[data-window-frame]");
const status = root.querySelector<HTMLElement>("[data-window-status]");
if (!start || !end || !pan || !chart || !frame || !status) return;
const labels = JSON.parse(root.dataset.labels || "[]") as string[];
const last = labels.length - 1;
const minSpan = Number(root.dataset.minSpan), maxSpan = Number(root.dataset.maxSpan);
let a = start.valueAsNumber, b = end.valueAsNumber;
let drag: { id: number; x: number; y: number; start: number; end: number; locked: boolean } | null = null;
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, Math.round(value)));
const render = (announce = false) => {
start.min = String(Math.max(0, b - maxSpan)); start.max = String(Math.max(0, b - minSpan));
end.min = String(Math.min(last, a + minSpan)); end.max = String(Math.min(last, a + maxSpan));
start.value = String(a); end.value = String(b);
pan.max = String(last - (b - a)); pan.value = String(a); pan.disabled = !!root.closest("fieldset:disabled") || last === 0;
start.setAttribute("aria-valuetext", labels[a]); end.setAttribute("aria-valuetext", labels[b]);
pan.setAttribute("aria-valuetext", `${labels[a]} to ${labels[b]}`);
root.querySelector<HTMLElement>("[data-start-value]")!.textContent = labels[a];
root.querySelector<HTMLElement>("[data-end-value]")!.textContent = labels[b];
frame.style.left = `${last ? a / last * 100 : 0}%`; frame.style.width = `${last ? (b - a) / last * 100 : 100}%`;
chart.toggleAttribute("data-enabled", !root.closest("fieldset:disabled") && last > 0);
[start, end, pan].forEach((input) => { const domain = Number(input.max) - Number(input.min); input.closest<HTMLElement>("[data-haze-slider]")?.style.setProperty("--slider-fill", String(domain > 0 ? (input.valueAsNumber - Number(input.min)) / domain : 0)); });
if (announce) { status.textContent = `${labels[a]} – ${labels[b]} · ${b - a + 1} points`; root.dispatchEvent(new CustomEvent("haze:window-range-change", { bubbles: true, detail: { start: a, end: b } })); }
};
const move = (position: number, span = b - a) => { a = clamp(position, 0, last - span); b = a + span; render(); };
start.addEventListener("input", () => { a = clamp(start.valueAsNumber, Math.max(0, b - maxSpan), b - minSpan); render(); });
end.addEventListener("input", () => { b = clamp(end.valueAsNumber, a + minSpan, Math.min(last, a + maxSpan)); render(); });
pan.addEventListener("input", () => move(pan.valueAsNumber));
[start, end, pan].forEach((input) => input.addEventListener("change", () => render(true)));
chart.addEventListener("pointerdown", (event) => { if (!root.closest("fieldset:disabled") && last > 0 && event.isPrimary && event.button === 0) drag = { id: event.pointerId, x: event.clientX, y: event.clientY, start: a, end: b, locked: false }; });
chart.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; chart.setPointerCapture(event.pointerId); chart.setAttribute("data-dragging", ""); }
if (drag.locked) move(drag.start + dx / chart.clientWidth * last, drag.end - drag.start);
});
const finish = (event: PointerEvent, canceled: boolean) => {
if (!drag || drag.id !== event.pointerId) return;
const saved = drag; drag = null; chart.removeAttribute("data-dragging");
if (chart.hasPointerCapture(event.pointerId)) chart.releasePointerCapture(event.pointerId);
if (canceled) { a = saved.start; b = saved.end; render(); }
else {
if (!saved.locked) move((event.clientX - chart.getBoundingClientRect().left) / chart.clientWidth * last - (b - a) / 2);
[start, end, pan].forEach((input) => input.dispatchEvent(new Event("input", { bubbles: true })));
render(true);
}
};
chart.addEventListener("pointerup", (event) => finish(event, false));
chart.addEventListener("pointercancel", (event) => finish(event, true));
chart.addEventListener("lostpointercapture", (event) => { if (event.target === chart && drag) finish(event, true); });
root.form?.addEventListener("reset", () => queueMicrotask(() => { a = Number(start.defaultValue); b = Number(end.defaultValue); render(true); }));
root.querySelector<HTMLElement>("[data-window-pan-control]")!.hidden = false;
root.setAttribute("data-enhanced", "");
render();
}
const init = () => document.querySelectorAll<HTMLFieldSetElement>("[data-haze-window-range]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-window-range-listener")) {
document.documentElement.setAttribute("data-haze-window-range-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A report needs a contiguous window within an ordered set of observations.
- People should move a complete interval while preserving its current length.
When not to use
- Use date-range-picker for calendar dates without an indexed series.
- Use range-histogram-slider for a numeric distribution whose observations are unordered.
Installation
Add the Haze registry to components.json once, then install Movable window range with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/window-rangenpx shadcn@latest add @haze/window-rangeyarn dlx shadcn@latest add @haze/window-rangebunx --bun shadcn@latest add @haze/window-rangeFirst 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. |
| label | string | Reporting window | Legend for the reporting interval. |
| data | number[] | Demo activity series | Ordered nonnegative chart values; invalid observations become zero. |
| labels | string[] | Day 1, Day 2, … | Optional accessible names for each data index. |
| start | number | 5 | Initial zero based start index. |
| end | number | 14 | Initial zero based end index. |
| minSpan | number | 1 | Smallest permitted distance between the two indices. |
| maxSpan | number | data.length - 1 | Largest permitted distance between the two indices. |
| startName | string | id-start | Submitted start index field name. |
| endName | string | id-end | Submitted end index field name. |
| disabled | boolean | false | Prevents user changes through the native disabled state. |
| class | string | – | Additional classes on this component's outer wrapper. |
Keyboard interactions
- Tab
- Reach start, end and move window controls in order.
- ArrowsHomeEnd
- Resize the focused edge or pan the current interval.
Accessibility
- The start, end and enhanced whole window control are real range inputs; each edge announces its supplied point label.
- Dynamic native bounds express the minimum and maximum interval length without allowing the edges to cross.
- A whole window control mirrors chart dragging, so selecting or panning never requires a pointer.
- Pointer cancellation restores both original indices, vertical gestures remain page scrolls, and commits announce the complete selected interval.
- Empty data becomes a single zero point; a one point series disables panning rather than dividing by zero.
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 "Movable window range" with `npx shadcn@latest add @haze/window-range`. 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 WindowRange from "@/components/haze/ui/window-range.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/window-range.md
Customize with real content
Adapt the Haze window-range ui for our product. Replace the demo values of these props with our real content: id, label, data, labels, start, end, minSpan, maxSpan, startName, endName, disabled, class. Keep the layout, the heading level rules and these accessibility details: The start, end and enhanced whole window control are real range inputs; each edge announces its supplied point label. Dynamic native bounds express the minimum and maximum interval length without allowing the edges to cross. A whole window control mirrors chart dragging, so selecting or panning never requires a pointer. Pointer cancellation restores both original indices, vertical gestures remain page scrolls, and commits announce the complete selected interval. Empty data becomes a single zero point; a one point series disables panning rather than dividing by zero. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using window-range, check it fits: use it when a report needs a contiguous window within an ordered set of observations.; people should move a complete interval while preserving its current length.. Avoid it when use date-range-picker for calendar dates without an indexed series.; use range-histogram-slider for a numeric distribution whose observations are unordered.. Alternatives: @haze/range-slider, @haze/range-histogram-slider, @haze/date-range-picker.
Dependencies
- @haze/slider
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.