# Time range picker

> "Last 15 minutes" for logs, metrics and traces: type 2h or yesterday 14:00–16:00, step by the window, pause live, or drag across a chart to zoom.

A date picker answers "which days", but a logs or metrics screen asks "which stretch of time, ending when": the last fifteen minutes, still moving; the hour before that; yesterday between two and four. This is one hairline plate: ‹ steps back by the window's own length (so "Last 1 hour" becomes the hour before it, fixed), › steps forward and turns live again once it reaches now, and Live breathes while the range follows the clock, Paused when it doesn't. Open it and the field is already focused: type 45m, yesterday, since 9 or 14:00–16:00 and the line under it says exactly what that means before you press Enter. Quick ranges have a highlight that glides with the pointer and a check that draws itself on the current one; ranges you typed come back as Recent. The range's words morph as it changes. Time brush comes with it: wrap any chart and a drag across it becomes the range under the band.

## Install

```bash
npx shadcn@latest add @hairline/time-range-picker
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: none
- Hairline UI components it needs (the CLI installs them too): `text-morph`
- Docs and live preview: https://hairlineui.com/ui/time-range-picker
- Registry item (source): https://hairlineui.com/r/time-range-picker.json

## Usage

```tsx
import { TimeRangePicker, resolveTimeRange, type TimeRange } from "@/components/time-range-picker";

const [range, setRange] = useState<TimeRange>({ type: "relative", duration: 15 * 60_000 });

<TimeRangePicker value={range} onValueChange={setRange} />
```

## Querying logs for the range

Keep the range itself in state, not its start and end, so "Last 15 minutes" stays live. Resolve it whenever you fetch, and refetch on a timer while it's live. Wrap the chart in Time brush to zoom.

```tsx
"use client";
import { useEffect, useState } from "react";
import { TimeBrush, TimeRangePicker, resolveTimeRange, type TimeRange } from "@/components/time-range-picker";

export function Logs({ service }: { service: string }) {
  const [range, setRange] = useState<TimeRange>({ type: "relative", duration: 60 * 60_000 });
  const [data, setData] = useState<LogBucket[]>([]);
  const live = range.type !== "absolute";

  useEffect(() => {
    const load = async () => {
      const { start, end } = resolveTimeRange(range);
      const res = await fetch(`/api/logs?service=${service}&from=${start.toISOString()}&to=${end.toISOString()}`);
      setData(await res.json());
    };
    load();
    if (!live) return;
    const timer = setInterval(load, 10_000);
    return () => clearInterval(timer);
  }, [range, live, service]);

  const { start, end } = resolveTimeRange(range);
  return (
    <section>
      <TimeRangePicker label="Time range for logs" value={range} onValueChange={setRange} />
      <TimeBrush start={start} end={end} onSelect={(r) => setRange({ type: "absolute", ...r })}>
        <VolumeChart buckets={data} />
      </TimeBrush>
    </section>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value / defaultValue` | `TimeRange` | `{ type: "relative", duration: 3600000 }` | { type: "relative", duration } (the last N ms, live), { type: "since", start } (until now, live) or { type: "absolute", start, end }. |
| `onValueChange` | `(range, { start, end }) => void` | – | The new range and the times it covers at that moment. Store the range: a relative one keeps moving. |
| `presets` | `{ label, range }[]` | `TIME_RANGE_PRESETS` | Quick ranges. range may be a function of now (Today so far, Yesterday). |
| `timeZone` | `string` | – | Read and show wall-clock times in this IANA zone; the viewer's own by default. |
| `hour12` | `boolean` | `false` | Write times as 2pm. |
| `align` | `"start" \| "end"` | `"end"` | Which edge of the plate the panel lines up with. |
| `open / defaultOpen / onOpenChange` | `boolean / boolean / (open) => void` | – | Control the panel. |
| `label` | `string` | `"Time range"` | Accessible name of the plate. |
| `TimeBrush` | `{ start, end, onSelect, minSpan?, snap?, formatTime?, timeZone? }` | – | Wrap a chart whose x axis runs from start to end; onSelect gets the span dragged across. Spans under minSpan (60s) are ignored. snap rounds each edge to one the chart can show (a day boundary on a daily chart), and the band jumps between them while you drag; formatTime(time, edge) writes the edges, e.g. dates instead of hours. |

## States

- **live**: A relative range ("Last 1 hour") or one that runs until now ("Today so far") is live: an emerald dot breathes beside Live (2.4s). Pressing it freezes the range where it is; the dot shrinks into a ring and the label morphs to Paused. › is disabled while live.
- **step**: ‹ and › move the window by its own length. The label morphs letter by letter ("Last 1 hour" → "Today, 13:20 – 14:20"). Stepping forward into now makes the range live again.
- **open**: The panel unfolds from the plate's edge (a clip from the top, 380ms), 6px clear of it, and lines up with its right edge by default. It lives on the page's body, so no card clips it, and it follows the plate when the page scrolls.
- **typing**: Each keystroke is read; the line under the field crossfades to what it means ("Yesterday, 14:00 – 16:00 · 2h") and a ↵ appears. Enter applies it. Text it can't read shakes the field and the line turns red with examples.
- **quick**: A highlight glides between quick ranges with the pointer or the arrows (220ms); the current range carries a drawn check. Ranges you typed are kept as Recent chips.
- **brush**: Time brush: pressing on a chart and dragging draws a band (a scaled fill and two hairline edges, transforms only) with its start, end and length on a tag above it. Release selects that span; the band fades as the chart redraws. Escape cancels.

## What it handles

A calendar date-range picker answers “which days”. Monitoring screens ask “which stretch of time, ending when”, and their ranges have to keep moving. Grafana and Datadog each built their own; this is yours.

- **Ranges that stay live**: “Last 15 minutes” keeps following the clock; Pause freezes it where it is.
- **Steps by the window**: ‹ and › move back and forward by the range’s own length, and go live again on reaching now.
- **Type any range**: 2h, yesterday, since 9, 14:00–16:00 or 22:00–02:00; the line under the field says what it means before you press Enter.
- **Drag to zoom**: Time brush turns a drag across any chart into the range under it.
- **Any time zone**: Times are read and shown in the zone you pass, across clock changes.
- **Fits a toolbar**: One compact plate that tightens itself on phones.

## Replaces

a calendar date picker, relative-time parsing, a live and paused toggle, chart brushing, time-zone maths

## Where it fits

- **Log viewers**: Show the last 15 minutes of logs and keep following new ones as they arrive.
- **Metrics dashboards**: Switch every chart between the last hour, today and last week in one place.
- **Incidents and traces**: Zoom into the exact minutes something went wrong by dragging across a chart.
- **Analytics and audit logs**: Filter events with typed ranges like “yesterday 14:00–16:00”.

## Notes

- The plate is a labelled group of four buttons. The range button opens a dialog whose field is described by the live reading under it; ↓ moves into the quick ranges (a listbox driven by aria-activedescendant), ←/→ move across, Enter applies, Escape closes and returns focus. New ranges are announced in a status region.
- Typed ranges it reads: 15m, 2 hours, last 7 days, past week, today, yesterday, this week, last week, this month, last month, since 9, since monday, 14:00–16:00, 9am to 5pm, 22:00–02:00 (past midnight), yesterday 14:00-16:00, 16 oct 09:00 – 16 oct 11:30, oct 12 – oct 14, and ISO dates. Times without a date that haven't happened yet today mean yesterday's.
- parseTimeRange, formatTimeRange, resolveTimeRange and stepTimeRange live in time-range-parse.ts with no React, so a server can read the same ranges from a URL.
- Time brush moves only transforms while you drag and renders nothing; touch keeps vertical page scroll (touch-action: pan-y).
- Reduced motion: no unfolding, gliding, breathing or morphing; the words change in place.

License: MIT (https://hairlineui.com/license#components)
