Number 92: Time ruler you can fling
Specification
- Catalogue
- No. 92 of 110
- Section
- Pickers and booking
- Interaction
- Drag
- Element
- Picker, Input
- Preview
- Live component
- Imports
- react 19.3.1, @number-flow/react 0.6.2
- Added
Notes
A time above a ruler. Drag the ruler under the fixed mark and the time runs with it; fling it and it coasts, then settles on the nearest step of 5, 15 or 30 minutes.
A thumb-friendly way to pick a time on a phone, with no tiny dropdown of 96 options. It is the bare time input; the booking rail with free times places a meeting in the gaps of a day.
2px of ruler per minute, and the day wraps round. On release the landing is decided at once: where the ruler would coast at the speed it was let go (21 frames of velocity), rounded to the step. One spring carries it there, starting with 60% of the hand's speed because the throw is already in the landing, so a flick coasts and a slow release just settles. The spring steps v += ((target - x) x 0.022 - v x 0.26) x dt with dt in sixtieths of a second, capped at 2.5, so a dropped frame loses the same energy. A release more than 80ms after the hand stopped throws nothing, and a fling is capped at 14px a frame. Ticks near the mark stand tall and dark and fall away toward the edges (scaleY(0.55 + 0.45f), opacity 0.18 + 0.82f). Digits roll on tabular figures. Left and Right step by the step size, Page Up and Page Down by an hour; a sideways trackpad swipe moves it and vertical scrolling passes through. The clock follows the visitor's locale (12 or 24 hours) after the page loads. The settled time is announced; the readout is not read out on every frame. Instant under reduced motion.
Code
React and plain CSS"use client";
import { useEffect, useId, useRef, useState, useSyncExternalStore, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { tourDrag } from "@/components/pieces/kit/tour-drag";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { radioArrows } from "@/components/pieces/shared";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./time-ruler.css";
/** Ruler pixels per minute, the ruler's width, and a day. */
const PX = 2;
const WIDTH = 340;
const HALF = (WIDTH - 36) / 2;
const DAY = 1440;
const START = 570;
const STEPS = [5, 15, 30] as const;
/** How far a fling carries: 6 frames of velocity plus up to 30 more (the default momentum gives 21). */
const CARRY = 21;
const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));
const wrap = (m: number) => ((m % DAY) + DAY) % DAY;
/** 24-hour clocks where the visitor's locale uses them; 12-hour on the server and in the first render. */
function use24h(): boolean {
return useSyncExternalStore(
() => () => {},
() => /h2[34]/.test(new Intl.DateTimeFormat(undefined, { hour: "numeric" }).resolvedOptions().hourCycle ?? ""),
() => false,
);
}
function label(m: number, h24: boolean) {
const t = wrap(Math.round(m));
const h = Math.floor(t / 60);
const mm = String(t % 60).padStart(2, "0");
return h24 ? { time: `${String(h).padStart(2, "0")}:${mm}`, mer: "" } : { time: `${h % 12 || 12}:${mm}`, mer: h < 12 ? "AM" : "PM" };
}
/** One digit on a strip of 0 to 9 that rolls through a window fading at top and bottom. */
function Digit({ d }: { d: string }) {
return (
<span className="tr-col" aria-hidden="true">
<span className="tr-strip" style={{ translate: `0 ${-Number(d) * 1.5}em` }}>
{"0123456789".split("").map((n) => (
<span key={n}>{n}</span>
))}
</span>
</span>
);
}
function TimeRulerDemo() {
const reduce = useSafeReducedMotion();
const h24 = use24h();
const uid = useId();
const [pos, setPos] = useState(START);
const [settled, setSettled] = useState(START);
const [step, setStep] = useState<(typeof STEPS)[number]>(15);
const p = useRef({ x: START, v: 0, to: START });
const raf = useRef(0);
const detach = useRef<(() => void) | null>(null);
const ruler = useRef<HTMLDivElement>(null);
const stepRef = useRef(step);
useEffect(() => {
stepRef.current = step;
}, [step]);
const set = (x: number) => {
p.current.x = x;
setPos(x);
};
// A frame-rate independent spring: dt is in sixtieths of a second (capped at 2.5), and the loop parks once settled.
const runSpring = () => {
if (raf.current) return;
let prev = 0;
const tick = (t: number) => {
const dt = prev ? clamp((t - prev) / 16.67, 0, 2.5) : 1;
prev = t;
const c = p.current;
c.v += ((c.to - c.x) * 0.022 - c.v * 0.26) * dt;
const x = c.x + c.v * dt;
if (Math.abs(c.to - x) < 0.01 && Math.abs(c.v) < 0.01) {
c.v = 0;
set(c.to);
setSettled(c.to);
raf.current = 0;
return;
}
set(x);
raf.current = requestAnimationFrame(tick);
};
raf.current = requestAnimationFrame(tick);
};
const halt = () => {
cancelAnimationFrame(raf.current);
raf.current = 0;
};
const goTo = (to: number, v: number) => {
p.current.to = to;
p.current.v = v;
if (reduce) {
p.current.v = 0;
set(to);
setSettled(to);
return;
}
runSpring();
};
useEffect(
() => () => {
halt();
detach.current?.();
},
[],
);
// A sideways trackpad swipe moves it too; vertical scrolling passes through to the page.
useEffect(() => {
const el = ruler.current;
if (!el) return;
let idle = 0;
const wheel = (e: WheelEvent) => {
if (Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return;
e.preventDefault();
cancelAnimationFrame(raf.current);
raf.current = 0;
p.current.x += e.deltaX / PX;
setPos(p.current.x);
window.clearTimeout(idle);
idle = window.setTimeout(() => {
const s = stepRef.current;
p.current.to = Math.round(p.current.x / s) * s;
p.current.v = 0;
runSpring();
}, 120);
};
el.addEventListener("wheel", wheel, { passive: false });
return () => {
el.removeEventListener("wheel", wheel);
window.clearTimeout(idle);
};
// runSpring only reads refs; binding it once is enough.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
if (e.button !== 0 || !e.isPrimary) return;
halt();
p.current.v = 0;
const el = e.currentTarget;
const scale = el.getBoundingClientRect().width / el.offsetWidth || 1;
const g = { x: e.clientX, t: performance.now(), v: 0 };
const move = (ev: PointerEvent) => {
const now = performance.now();
// The ruler moves under a fixed mark, so dragging left is later in the day.
const dm = -(ev.clientX - g.x) / scale / PX;
const dt = Math.max(1, now - g.t) / 16.67;
g.v = g.v * 0.5 + (dm / dt) * 0.5;
g.x = ev.clientX;
g.t = now;
set(p.current.x + dm);
};
const up = () => {
stop();
// A hand that stopped before letting go threw nothing; a flick is capped so it spins hours, never days.
const v = performance.now() - g.t > 80 ? 0 : clamp(g.v, -14, 14);
const s = stepRef.current;
const land = Math.round((p.current.x + v * CARRY) / s) * s;
// The landing already includes the throw, so the spring starts with only 60% of the hand's speed.
goTo(land, v * 0.6);
};
const stop = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
window.removeEventListener("pointercancel", up);
detach.current = null;
};
detach.current?.();
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
window.addEventListener("pointercancel", up);
detach.current = stop;
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
const d = e.key === "ArrowRight" || e.key === "ArrowUp" ? step : e.key === "ArrowLeft" || e.key === "ArrowDown" ? -step : e.key === "PageUp" ? 60 : e.key === "PageDown" ? -60 : 0;
if (!d) return;
e.preventDefault();
goTo(Math.round(p.current.to / step) * step + d, 0);
};
const ticks: { m: number; x: number; f: number; kind: "hour" | "quarter" | "five" }[] = [];
const span = HALF / PX + 10;
for (let m = Math.ceil((pos - span) / 5) * 5; m <= pos + span; m += 5) {
const x = (m - pos) * PX;
const f = clamp(1 - Math.pow(Math.abs(x) / HALF, 2), 0, 1);
const w = wrap(m);
ticks.push({ m, x, f, kind: w % 60 === 0 ? "hour" : w % 15 === 0 ? "quarter" : "five" });
}
const { time, mer } = label(pos, h24);
const done = label(settled, h24);
return (
<div className="dm tr">
<p id={`${uid}-l`} className="tr-label">
Arrival time
</p>
<div className="tr-read" aria-hidden="true">
<span className="tr-time">
{time.split("").map((c, i) =>
c === ":" ? (
<span key={`c${i}`} className="tr-colon">
:
</span>
) : (
<Digit key={time.length - i} d={c} />
),
)}
</span>
{mer && <span className="tr-mer">{mer}</span>}
</div>
<p className="sr-only" aria-live="polite">
{`${done.time} ${done.mer}`.trim()}
</p>
<div
ref={ruler}
className="tr-ruler"
role="slider"
tabIndex={0}
aria-labelledby={`${uid}-l`}
aria-valuetext={`${time} ${mer}`.trim()}
aria-valuenow={wrap(Math.round(pos))}
aria-valuemin={0}
aria-valuemax={DAY - 1}
onPointerDown={onDown}
onKeyDown={onKey}
>
<div className="tr-track">
{ticks.map((t) => (
<span key={t.m} className="tr-tick" data-kind={t.kind} style={{ transform: `translateX(${t.x.toFixed(2)}px) scaleY(${(0.55 + 0.45 * t.f).toFixed(3)})`, opacity: 0.18 + 0.82 * t.f }} />
))}
{ticks
.filter((t) => t.kind === "hour")
.map((t) => {
const h = Math.floor(wrap(t.m) / 60);
return (
<span key={`h${t.m}`} className="tr-hour" style={{ transform: `translateX(${t.x.toFixed(2)}px) translateX(-50%)`, opacity: 0.15 + 0.85 * t.f }}>
{h24 ? String(h).padStart(2, "0") : `${h % 12 || 12} ${h < 12 ? "AM" : "PM"}`}
</span>
);
})}
</div>
<span className="tr-mark" aria-hidden="true" />
</div>
<div className="tr-steps" role="radiogroup" aria-label="Settles on" onKeyDown={radioArrows}>
{STEPS.map((s) => (
<button key={s} type="button" role="radio" aria-checked={step === s} tabIndex={step === s ? 0 : -1} className="tr-step" onClick={() => setStep(s)}>
{s} min
</button>
))}
</div>
</div>
);
}
// What a hovered card shows: four steps with the arrow key, then a fling that coasts and settles two hours on.
const TOUR: Tour = [
{ key: "ArrowRight", on: ".tr-ruler", wait: 250 },
{ key: "ArrowRight", on: ".tr-ruler", wait: 250 },
{ key: "ArrowRight", on: ".tr-ruler", wait: 250 },
{ key: "ArrowRight", on: ".tr-ruler", wait: 700 },
{
run: (root) => {
const el = root.querySelector(".tr-ruler");
if (el) tourDrag(el, [0.7, 0.5], [0.4, 0.5], 160, { release: "moving" });
},
wait: 1800,
},
];
export default function TimeRulerEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Time ruler you can fling" tour={TOUR}>
<TimeRulerDemo />
</PieceStage>
);
}