Heat Calendar
Composable activity calendar with Grid, Legend, and Tooltip parts, controlled range selection, and UTC calendar dates. Supply weekly intensities to visualize activity and total a selected span.
Preview
"use client";
import {
HeatCalendar,
HeatCalendarGrid,
HeatCalendarLegend,
HeatCalendarTooltip,
} from "@/components/charts/heat-calendar";
/** Deterministic demo field so every render agrees; weekends run quieter. */
function demoLevel(week: number, day: number) {
const s = Math.sin(week * 12.9898 + day * 78.233) * 43758.5453;
const r = s - Math.floor(s);
return day >= 5 ? Math.max(0, r - 0.55) * 1.4 : r;
}
const values = Array.from({ length: 16 }, (_, w) => Array.from({ length: 7 }, (_, d) => demoLevel(w, d)));
export function HeatCalendarPreview() {
return (
<HeatCalendar unit="commits" weeks={16} maxCount={14} values={values}>
<HeatCalendarGrid>
<HeatCalendarTooltip />
</HeatCalendarGrid>
<HeatCalendarLegend />
</HeatCalendar>
);
}
"use client";
// beui.dev/charts/heat-calendar
import { cn } from "@/lib/utils";
import { HeatCalendarContext, useHeatCalendarModel } from "./heat-calendar/context";
import { HeatCalendarGrid } from "./heat-calendar/grid";
import { HeatCalendarLegend } from "./heat-calendar/legend";
import { HeatCalendarTooltip } from "./heat-calendar/tooltip";
import type { HeatCalendarProps } from "./heat-calendar/types";
/** Compose Grid, Tooltip and Legend, or omit children for the complete chart. */
export function HeatCalendar({ children, className, ...props }: HeatCalendarProps) {
const model = useHeatCalendarModel(props);
return (
<HeatCalendarContext.Provider value={model}>
<div className={cn("w-fit max-w-full", className)}>
{children === undefined ? (
<>
<HeatCalendarGrid>
<HeatCalendarTooltip />
</HeatCalendarGrid>
<HeatCalendarLegend />
</>
) : (
children
)}
</div>
</HeatCalendarContext.Provider>
);
}
export { useHeatCalendar } from "./heat-calendar/context";
export { HeatCalendarGrid } from "./heat-calendar/grid";
export { HeatCalendarLegend } from "./heat-calendar/legend";
export { HeatCalendarTooltip } from "./heat-calendar/tooltip";
export type { HeatCalendarCell, HeatCalendarProps, HeatCalendarSelection } from "./heat-calendar/types";
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i @floating-ui/dom clsx motion tailwind-mergeAdd util files
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// beui.dev/charts/heat-calendar
import { cn } from "@/lib/utils";
import { HeatCalendarContext, useHeatCalendarModel } from "./heat-calendar/context";
import { HeatCalendarGrid } from "./heat-calendar/grid";
import { HeatCalendarLegend } from "./heat-calendar/legend";
import { HeatCalendarTooltip } from "./heat-calendar/tooltip";
import type { HeatCalendarProps } from "./heat-calendar/types";
/** Compose Grid, Tooltip and Legend, or omit children for the complete chart. */
export function HeatCalendar({ children, className, ...props }: HeatCalendarProps) {
const model = useHeatCalendarModel(props);
return (
<HeatCalendarContext.Provider value={model}>
<div className={cn("w-fit max-w-full", className)}>
{children === undefined ? (
<>
<HeatCalendarGrid>
<HeatCalendarTooltip />
</HeatCalendarGrid>
<HeatCalendarLegend />
</>
) : (
children
)}
</div>
</HeatCalendarContext.Provider>
);
}
export { useHeatCalendar } from "./heat-calendar/context";
export { HeatCalendarGrid } from "./heat-calendar/grid";
export { HeatCalendarLegend } from "./heat-calendar/legend";
export { HeatCalendarTooltip } from "./heat-calendar/tooltip";
export type { HeatCalendarCell, HeatCalendarProps, HeatCalendarSelection } from "./heat-calendar/types";
"use client";
import { useReducedMotion } from "motion/react";
import { createContext, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import type { HeatCalendarCell, HeatCalendarProps, HeatCalendarSelection } from "./types";
import { addDays, CELL, EMPTY, fmtMonth, GAP, MONTH_ROW, mondayOf, PITCH, STEPS, startOfDay } from "./utils";
/**
* Weeks of activity as a single-hue grid with month labels, so
* magnitude reads as the strength of one color and the eye needs no legend
* to find a date. Cells spring in on a diagonal wave. Hovering one lifts it
* and its neighbours in a small ripple and glides a tooltip with its date and
* exact count; clicking pins the cell so touch and keyboard get the same
* readout; from there the grid dims and hovering previews the span from that
* cell to the pointer with its total, a second click locks it and a third
* clears it; hovering a legend step filters
* the grid to that level. Hover lifts are gated to pointer devices, and
* reduced motion keeps the fades only.
*/
export function useHeatCalendarModel({
unit = "commits",
weeks = 16,
maxCount = 14,
values,
endDate,
color = "var(--accent)",
selection: controlledSelection,
defaultSelection = null,
onSelectionChange,
}: HeatCalendarProps) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [storedHover, setHover] = useState<HeatCalendarCell | null>(null);
const [internalSelection, setInternalSelection] = useState(defaultSelection);
const requestedSelection = controlledSelection === undefined ? internalSelection : controlledSelection;
const setSelection = (next: HeatCalendarSelection | null) => {
if (controlledSelection === undefined) setInternalSelection(next);
onSelectionChange?.(next);
};
const gridRef = useRef<HTMLDivElement>(null);
const tooltipId = useId();
const [step, setStep] = useState<number | null>(null);
// the entrance wave owns the cells until it has landed; the ripple takes over after
const [settled, setSettled] = useState(false);
useEffect(() => {
const t = setTimeout(() => setSettled(true), reduce ? 0 : (weeks + 7) * 18 + 500);
return () => clearTimeout(t);
}, [weeks, reduce]);
// "today" is read after mount: the server and a viewer on another calendar
// day must produce the same HTML, so the grid renders first and its dates
// fill in on the client. An explicit `endDate` is deterministic and skips this.
const [today, setToday] = useState<Date | null>(null);
useEffect(() => setToday(startOfDay(new Date())), []);
const end = useMemo(() => (endDate ? startOfDay(endDate) : today), [endDate, today]);
const start = useMemo(() => (end ? addDays(mondayOf(end), -(weeks - 1) * 7) : null), [end, weeks]);
const level = (w: number, d: number) => Math.max(0, Math.min(1, values?.[w]?.[d] ?? 0));
const bucket = (v: number) => Math.min(4, Math.floor(v * 5));
const fill = (b: number) => (b === 0 ? EMPTY : `color-mix(in srgb, ${color} ${STEPS[b]}%, transparent)`);
const count = (v: number) => Math.round(v * maxCount);
const dateOf = (w: number, d: number) => (start ? addDays(start, w * 7 + d) : null);
const future = (w: number, d: number) => {
const date = dateOf(w, d);
return end !== null && date !== null && date > end;
};
const validCell = (cell: HeatCalendarCell) =>
Number.isInteger(cell.w) &&
Number.isInteger(cell.d) &&
cell.w >= 0 &&
cell.w < weeks &&
cell.d >= 0 &&
cell.d < 7 &&
!future(cell.w, cell.d);
const selection =
requestedSelection &&
validCell(requestedSelection.start) &&
(!requestedSelection.end || validCell(requestedSelection.end))
? requestedSelection
: null;
if (requestedSelection && !selection && controlledSelection === undefined) setInternalSelection(null);
const pinned = selection?.start ?? null;
const spanEnd = selection?.end ?? null;
const hover = storedHover && validCell(storedHover) ? storedHover : null;
if (storedHover && !hover) setHover(null);
// one label per month, at its first column; the leading label yields if the
// next month starts within two columns, so two labels never overlap
const cols = useMemo(() => {
const list = Array.from({ length: weeks }, (_, w) => {
const date = start ? addDays(start, w * 7) : null;
const m = date ? date.getUTCMonth() : -1;
const fresh =
start !== null && date !== null && (w === 0 || addDays(start, (w - 1) * 7).getUTCMonth() !== m);
return { id: `w${w}`, w, m, label: fresh && date ? fmtMonth.format(date) : null };
});
if (list[1]?.label || list[2]?.label) list[0].label = null;
return list;
}, [start, weeks]);
// one click anchors a span and dims everything else; hovering then previews
// the run from the anchor to the pointer and totals it live, and a second
// click locks it so the number stays on screen while the pointer moves on
const idx = (c: HeatCalendarCell) => c.w * 7 + c.d;
const clear = () => {
setSelection(null);
};
const spanTo = spanEnd ?? (pinned ? (hover ?? pinned) : null);
const span =
pinned && spanTo
? { lo: Math.min(idx(pinned), idx(spanTo)), hi: Math.max(idx(pinned), idx(spanTo)) }
: null;
let spanTotal = 0;
if (span) {
for (let i = span.lo; i <= span.hi; i++) {
if (future(Math.floor(i / 7), i % 7)) break;
spanTotal += count(level(Math.floor(i / 7), i % 7));
}
}
const select = (cell: HeatCalendarCell) => {
// a locked span clears on the next click anywhere, so leaving it is one press
if (spanEnd) {
clear();
} else if (pinned && idx(pinned) === idx(cell)) {
setSelection(null);
} else if (pinned) {
setSelection({ start: pinned, end: cell });
} else {
setSelection({ start: cell });
}
};
/** the cell the grid reacts to: lift, ripple and label highlight follow the pointer */
const hot = hover ?? spanEnd ?? pinned;
/** the cell the tooltip hangs from: a locked span keeps it on its end */
const tip = spanEnd ?? hover ?? pinned;
const tipDate = tip ? dateOf(tip.w, tip.d) : null;
const hotMonth = hot ? (dateOf(hot.w, hot.d)?.getUTCMonth() ?? null) : null;
const tipX = tip ? tip.w * PITCH + CELL / 2 : 0;
const tipY = tip ? MONTH_ROW + GAP + tip.d * PITCH : 0;
const tooltip =
tip && tipDate
? {
date: tipDate,
count: count(level(tip.w, tip.d)),
total: spanTotal,
startDate: start && span ? addDays(start, span.lo) : tipDate,
endDate: start && span ? addDays(start, span.hi) : tipDate,
days: span ? span.hi - span.lo + 1 : 1,
}
: null;
return {
unit,
weeks,
reduce,
canHover,
hover,
pinned,
spanEnd,
step,
setStep,
settled,
start,
end,
level,
bucket,
fill,
count,
dateOf,
future,
cols,
clear,
span,
spanTotal,
select,
hot,
tip,
tipDate,
hotMonth,
tipX,
tipY,
setHover,
gridRef,
tooltipId,
tooltip,
selection,
setSelection,
};
}
export const HeatCalendarContext = createContext<ReturnType<typeof useHeatCalendarModel> | null>(null);
/** Read the shared data and selection from any descendant of HeatCalendar. */
export function useHeatCalendar() {
const context = useContext(HeatCalendarContext);
if (!context) throw new Error("HeatCalendar parts must be inside HeatCalendar");
return context;
}
"use client";
import { AnimatePresence, motion } from "motion/react";
import type { ReactNode } from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { useHeatCalendar } from "./context";
import { DAYS, fmtDay, GAP, LIFT, MONTH_ROW, PITCH } from "./utils";
export function HeatCalendarGrid({ children, className }: { children?: ReactNode; className?: string }) {
const {
weeks,
reduce,
canHover,
pinned,
step,
settled,
level,
bucket,
fill,
count,
dateOf,
future,
cols,
clear,
span,
select,
hot,
hotMonth,
setHover,
gridRef,
tooltipId,
unit,
} = useHeatCalendar();
return (
<div
ref={gridRef}
className={cn("relative grid", className)}
style={{
width: weeks * PITCH - GAP,
maxWidth: "100%",
gridTemplateColumns: `repeat(${weeks}, minmax(0, 1fr))`,
gridTemplateRows: `${MONTH_ROW}px repeat(7, auto)`,
gap: GAP,
}}
onPointerLeave={() => setHover(null)}
>
{cols.map((c) =>
c.label ? (
<span
key={c.id}
className={cn(
"whitespace-nowrap text-[10px] leading-none transition-colors duration-200",
hotMonth === c.m ? "text-foreground" : "text-muted-foreground",
)}
style={{ gridColumn: c.w + 1, gridRow: 1 }}
>
{c.label}
</span>
) : null,
)}
{cols.map(({ id, w }) =>
DAYS.map(({ id: dayId, d }) => {
const date = dateOf(w, d);
if (future(w, d)) return null;
const v = level(w, d);
const b = bucket(v);
const i = w * 7 + d;
const on = hot?.w === w && hot?.d === d;
const isEnd = span ? i === span.lo || i === span.hi : pinned?.w === w && pinned?.d === d;
const dim = (step !== null && step !== b) || (span !== null && (i < span.lo || i > span.hi));
// the ripple: the hovered cell rises most, the ring around it a little, two out barely
const dist = hot ? Math.max(Math.abs(hot.w - w), Math.abs(hot.d - d)) : 9;
const lift =
reduce || !canHover ? 1 : dist === 0 ? LIFT[0] : canHover && dist < LIFT.length ? LIFT[dist] : 1;
return (
// the outer span owns the legend dim so it never fights the transforms inside
<span
key={`${id}-${dayId}`}
className="relative block aspect-square w-full transition-opacity duration-200"
style={{
gridColumn: w + 1,
gridRow: d + 2,
opacity: dim ? 0.25 : 1,
zIndex: lift > 1 ? LIFT.length - dist : 0,
}}
>
{/* the hit area is the cell plus half the gap on every side, so the grid
has no dead space between cells and a fast pointer never falls through;
the visual inside never takes pointer events, so a lifted neighbour
cannot steal a click either */}
<motion.button
type="button"
aria-label={`${count(v)} ${unit}${date ? ` on ${fmtDay.format(date)}` : ""}`}
data-heat-cell={`${w}-${d}`}
aria-pressed={isEnd}
aria-describedby={on ? tooltipId : undefined}
onPointerEnter={() => setHover({ w, d })}
onFocus={() => setHover({ w, d })}
onBlur={() => setHover(null)}
onClick={() => select({ w, d })}
onKeyDown={(e) => {
if (e.key === "Escape") clear();
}}
className="absolute -inset-0.5 block rounded-[5px] outline-none focus-visible:ring-2 focus-visible:ring-ring"
whileTap={reduce ? undefined : { scale: 0.9, transition: SPRING_PRESS }}
>
<motion.span
className="pointer-events-none absolute inset-0.5 block rounded-[4px]"
style={{
background: fill(b),
boxShadow: isEnd ? "0 0 0 2px var(--background), 0 0 0 3.5px var(--foreground)" : "none",
transition: "box-shadow 150ms",
}}
// the diagonal wave: each cell arrives (w + d) steps after the corner;
// once settled, the ripple spreads out from the hovered cell by distance
initial={reduce ? false : { opacity: 0, scale: 0.4 }}
animate={
settled
? {
opacity: 1,
scale: lift,
transition: { ...SPRING_PRESS, delay: Math.min(dist, 3) * 0.03 },
}
: {
opacity: 1,
scale: 1,
transition: reduce ? { duration: 0 } : { ...SPRING_PRESS, delay: (w + d) * 0.018 },
}
}
>
{/* the ring lives INSIDE the cell: inset-0 fills its box and
borderRadius:inherit copies its corner, so it always shares the
cell's exact size, scale (hover lift included) and roundness and
cannot drift however the cells are restyled */}
<AnimatePresence>
{on && !isEnd ? (
<motion.span
className="pointer-events-none absolute inset-0 block border-[1.5px]"
style={{
borderRadius: "inherit",
borderColor: "color-mix(in srgb, var(--foreground) 55%, transparent)",
}}
initial={reduce ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.12, ease: EASE_OUT }}
/>
) : null}
</AnimatePresence>
</motion.span>
</motion.button>
</span>
);
}),
)}
{children}
</div>
);
}
"use client";
import { cn } from "@/lib/utils";
import { useHeatCalendar } from "./context";
import { fmtRange, STEPS } from "./utils";
export function HeatCalendarLegend({ className }: { className?: string }) {
const { start, end, step, setStep, fill, canHover, reduce } = useHeatCalendar();
return (
<div className={cn("mt-3 flex flex-wrap items-center justify-between gap-3", className)}>
<span className="text-xs text-muted-foreground">
{start && end ? `${fmtRange.format(start)} – ${fmtRange.format(end)}` : "\u00a0"}
</span>
{/* hovering a step keeps only cells of that level lit, so the legend doubles as a filter */}
<span className="flex items-center gap-1" onPointerLeave={() => setStep(null)}>
<span className="mr-0.5 text-xs text-muted-foreground">less</span>
{STEPS.map((s, i) => (
<button
type="button"
aria-label={`Show activity level ${i}`}
aria-pressed={step === i}
key={s}
onPointerEnter={() => {
if (canHover) setStep(i);
}}
onFocus={() => setStep(i)}
onBlur={() => setStep(null)}
onClick={() => setStep(step === i ? null : i)}
className="size-3 rounded-[3px] transition-transform duration-150"
style={{ background: fill(i), transform: !reduce && step === i ? "scale(1.25)" : undefined }}
/>
))}
<span className="ml-0.5 text-xs text-muted-foreground">more</span>
</span>
</div>
);
}
"use client";
import { type ReactNode, useMemo, useState } from "react";
import { NumberTicker } from "@/components/motion/number-ticker";
import { Tooltip } from "@/components/motion/tooltip";
import { cn } from "@/lib/utils";
import { useHeatCalendar } from "./context";
import { fmtDay, fmtRange } from "./utils";
export function HeatCalendarTooltip({
children,
className,
}: {
children?: ReactNode | ((data: NonNullable<ReturnType<typeof useHeatCalendar>["tooltip"]>) => ReactNode);
className?: string;
}) {
const { gridRef, tooltipId, tip, tooltip, unit } = useHeatCalendar();
const [dismissed, setDismissed] = useState<typeof tip>(null);
const anchorRef = useMemo(() => ({ get current() {
return tip ? gridRef.current?.querySelector<HTMLElement>(`[data-heat-cell="${tip.w}-${tip.d}"]`) ?? null : null;
}}), [gridRef, tip]);
return (
<Tooltip
key={tip ? `${tip.w}-${tip.d}` : "closed"}
open={tooltip !== null && dismissed !== tip}
onOpenChange={(open) => { if (!open) setDismissed(tip); }}
id={tooltipId}
anchorRef={anchorRef}
className={cn("flex flex-wrap items-center gap-1.5", className)}
content={tooltip &&
(typeof children === "function"
? children(tooltip)
: (children ?? (
<>
<span className="inline-flex items-center gap-1 font-mono tabular-nums">
<NumberTicker
value={tooltip.days > 1 ? tooltip.total : tooltip.count}
duration={0.35}
startOnView={false}
/>{" "}
{unit}
</span>
<span className="text-muted-foreground">
{tooltip.days > 1 && tooltip.startDate && tooltip.endDate
? `${fmtRange.format(tooltip.startDate)} – ${fmtRange.format(tooltip.endDate)}`
: fmtDay.format(tooltip.date)}
</span>
{tooltip.days > 1 ? <span className="text-muted-foreground">{tooltip.days} days</span> : null}
</>
)))}
/>
);
}
import type { ReactNode } from "react";
export type HeatCalendarCell = { w: number; d: number };
export interface HeatCalendarSelection {
start: HeatCalendarCell;
end?: HeatCalendarCell;
}
export interface HeatCalendarProps {
/** Noun after every count, e.g. "commits", "ships". */
unit?: string;
/** Number of week columns. */
weeks?: number;
/** Count a cell at intensity 1 stands for; a cell reads `intensity × maxCount`. */
maxCount?: number;
/** `values[week][day]` intensities in 0..1, seven days per week. Missing values are zero. */
values?: number[][];
/** Last UTC calendar day of the grid. Defaults to today after mount; explicit dates render identically in every timezone. */
endDate?: Date;
/** The single hue. Any CSS color; magnitude maps to its strength, never to a second color. */
color?: string;
className?: string;
children?: ReactNode;
/** Controlled selection; null clears it. Cell coordinates are zero-based week/day (Monday first). */
selection?: HeatCalendarSelection | null;
defaultSelection?: HeatCalendarSelection | null;
onSelectionChange?: (selection: HeatCalendarSelection | null) => void;
}
/** Five buckets: 0 is the neutral empty cell, 1 to 4 mix the one hue in harder. */
export const STEPS = [0, 24, 46, 70, 94] as const;
export const EMPTY = "color-mix(in srgb, var(--foreground) 6%, transparent)";
/** Cell size and gap; every position in the grid and the tooltip derive from these. */
export const CELL = 16;
export const GAP = 4;
export const PITCH = CELL + GAP;
export const MONTH_ROW = 12;
export const DAYS = Array.from({ length: 7 }, (_, d) => ({ id: `d${d}`, d }));
/** How far a cell rises when it is the hovered one, its neighbour, or two away. */
export const LIFT = [1.3, 1.08, 1.03];
export const startOfDay = (d: Date) => {
const x = new Date(d);
x.setUTCHours(0, 0, 0, 0);
return x;
};
export const addDays = (d: Date, n: number) => {
const x = new Date(d);
x.setUTCDate(x.getUTCDate() + n);
return x;
};
/** Monday on or before `d`, so every column reads Mon to Sun, top to bottom. */
export const mondayOf = (d: Date) => addDays(startOfDay(d), -((d.getUTCDay() + 6) % 7));
export const fmtDay = new Intl.DateTimeFormat("en-US", {
timeZone: "UTC",
weekday: "short",
month: "short",
day: "numeric",
});
export const fmtMonth = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", month: "short" });
export const fmtRange = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", month: "short", day: "numeric" });
"use client";
import { animate, motion, useInView, useReducedMotion } from "motion/react";
import { useEffect, useMemo, useRef, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface NumberTickerProps {
value: number;
/** Digits to pad to (left). */
pad?: number;
/** Per-digit roll duration in seconds. */
duration?: number;
/** Stagger between digits. */
stagger?: number;
/** Render only after the element enters the viewport. */
startOnView?: boolean;
prefix?: string;
suffix?: string;
/** Add a small blur during digit rolls. */
blur?: boolean;
className?: string;
digitClassName?: string;
/** Insert locale group separators (commas). Server-component safe. */
locale?: boolean;
/** Custom formatter. Client-only — server components must use `locale` instead. */
format?: (value: number) => string;
}
const DIGIT_HEIGHT_EM = 1.1;
const DIGITS = Array.from({ length: 10 }, (_, n) => n);
export function NumberTicker({
value,
pad,
duration = 0.9,
stagger = 0.04,
startOnView = true,
prefix,
suffix,
blur = false,
className,
digitClassName,
locale,
format,
}: NumberTickerProps) {
const containerRef = useRef<HTMLSpanElement>(null);
const inView = useInView(containerRef, { once: true, amount: 0.6 });
const [armed, setArmed] = useState(!startOnView);
useEffect(() => {
if (startOnView && inView) setArmed(true);
}, [startOnView, inView]);
const text = useMemo(() => {
const rounded = Math.round(value);
const formatted = format
? format(rounded)
: locale
? rounded.toLocaleString()
: rounded.toString();
return pad ? formatted.padStart(pad, "0") : formatted;
}, [value, pad, format, locale]);
const glyphs = useMemo(() => {
const chars = text.split("");
// Key by place value (position from the right): a changing digit keeps its
// identity and rolls to the new value instead of remounting and replaying
// from 0. Growing numbers add glyphs on the left without re-keying the
// ones, tens, hundreds already on screen.
return chars.map((char, i) => ({ char, id: `g-${chars.length - 1 - i}` }));
}, [text]);
const readableText = `${prefix ?? ""}${text}${suffix ?? ""}`;
// Stagger is an entrance flourish. Once the reveal has played, value
// changes roll every digit immediately — a per-digit delay on live updates
// reads as lag.
const [entered, setEntered] = useState(false);
useEffect(() => {
if (!armed || entered) return;
const total = (duration + glyphs.length * stagger) * 1000;
const t = window.setTimeout(() => setEntered(true), total);
return () => window.clearTimeout(t);
}, [armed, entered, duration, stagger, glyphs.length]);
return (
<span
ref={containerRef}
className={cn("inline-flex items-center tabular-nums", className)}
>
<span className="sr-only">{readableText}</span>
<span aria-hidden="true" className="inline-flex items-center">
{prefix ? <span>{prefix}</span> : null}
{glyphs.map(({ char, id }, i) => {
const isDigit = /\d/.test(char);
if (!isDigit) {
return (
<span key={id} className="inline-block">
{char}
</span>
);
}
const digit = Number(char);
return (
<Digit
key={id}
digit={armed ? digit : 0}
delay={entered ? 0 : i * stagger}
duration={duration}
blur={blur}
className={digitClassName}
/>
);
})}
{suffix ? <span>{suffix}</span> : null}
</span>
</span>
);
}
function Digit({
digit,
delay,
duration,
blur,
className,
}: {
digit: number;
delay: number;
duration: number;
blur: boolean;
className?: string;
}) {
const reduce = useReducedMotion();
const columnRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
if (reduce || !blur || !columnRef.current || !Number.isFinite(digit)) {
return;
}
const node = columnRef.current;
const controls = animate(
node,
{ filter: ["blur(10px)", "blur(0px)"] },
{
duration: Math.min(duration * 0.75, 0.32),
delay,
ease: EASE_OUT,
},
);
return () => {
controls.stop();
node.style.filter = "blur(0px)";
};
}, [blur, delay, digit, duration, reduce]);
return (
<span
className={cn("relative inline-block overflow-hidden", className)}
style={{ height: `${DIGIT_HEIGHT_EM}em`, width: "1ch" }}
>
<motion.span
ref={columnRef}
initial={{ y: 0 }}
animate={{ y: `-${digit * DIGIT_HEIGHT_EM}em` }}
transition={
reduce
? { duration: 0 }
: { duration, delay, ease: EASE_OUT }
}
className="absolute inset-x-0 top-0 flex flex-col items-center will-change-[transform,filter]"
>
{DIGITS.map((n) => (
<span
key={n}
className="flex h-[1.1em] items-center justify-center leading-none"
>
{n}
</span>
))}
</motion.span>
</span>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import { TooltipPositioner } from "./tooltip/positioner";
import { useTooltipPointer } from "./tooltip/use-position";
import {
cloneElement,
isValidElement,
type PointerEvent,
type ReactElement,
type ReactNode,
type RefObject,
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
export interface TooltipProps {
content: ReactNode;
children?: ReactElement;
/** Existing trigger for controlled integrations such as chart cells. */
anchorRef?: RefObject<HTMLElement | SVGElement | null>;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: { x: number; y: number };
/** Follow real pointer coordinates; keyboard focus still uses the anchor. */
followCursor?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
id?: string;
side?: Side;
/** Delay before showing (ms). Default 120. */
delay?: number;
className?: string;
/** Classes for the outer wrapper span. Use to fix baseline / fill parent. */
wrapperClassName?: string;
}
// Once any tooltip has just closed, neighbouring tooltips open without the
// initial delay — moving along a toolbar feels instant after the first one.
const WARM_WINDOW_MS = 300;
let lastHiddenAt = 0;
export function Tooltip({
content,
children,
side = "top",
delay = 120,
className,
wrapperClassName,
anchorRef: externalAnchorRef,
anchorPoint,
followCursor = false,
open: controlledOpen,
onOpenChange,
id: providedId,
}: TooltipProps) {
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (controlledOpen === undefined) setInternalOpen(next);
onOpenChange?.(next);
},
[controlledOpen, onOpenChange],
);
const generatedId = useId();
const id = providedId ?? generatedId;
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const wrapperRef = useRef<HTMLSpanElement>(null);
const anchorRef = externalAnchorRef ?? wrapperRef;
const hover = useHoverGesture();
const floatingRef = useRef<HTMLSpanElement | null>(null);
const pointer = useTooltipPointer(anchorRef, followCursor);
const focused = useRef(false);
const show = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
if (open) return;
const warm = Date.now() - lastHiddenAt < WARM_WINDOW_MS;
if (warm) {
setOpen(true);
return;
}
timer.current = setTimeout(() => {
setOpen(true);
}, delay);
}, [delay, setOpen, open]);
const hide = useCallback(() => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
if (open) lastHiddenAt = Date.now();
setOpen(false);
}, [open, setOpen]);
const leave = useCallback(() => {
if (focused.current) return;
if (timer.current) clearTimeout(timer.current);
// Bridge the small physical gap to a stationary, readable tooltip.
if (followCursor) hide();
else timer.current = setTimeout(hide, 100);
}, [followCursor, hide]);
const insideTooltip = useCallback(
(target: Element) => Boolean(floatingRef.current?.contains(target)),
[],
);
// A finger never hovers, and Safari does not focus a button on tap either, so
// the label is only reachable if the tap itself opens the tooltip. A click
// carries no pointerType, so the pointerdown that preceded it is what says
// whether this was a tap; keyboard activation arrives with no pointerdown at
// all, and focus has already shown the label there.
const tap = useTapGesture<boolean>();
const toggleOnTap = useCallback(() => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) {
hide();
return;
}
if (timer.current) clearTimeout(timer.current);
setOpen(true);
}, [hide, tap, setOpen]);
// ...and closed again by the next tap that lands somewhere else. The label
// covers nothing interactive, so that tap passes through to what it hit.
useDismiss(open, hide, anchorRef, { ignore: insideTooltip });
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current);
},
[],
);
if (!externalAnchorRef && !isValidElement(children)) return children;
// The label describes the trigger, so it has to name the trigger itself.
// Everything else the tooltip needs is read off the anchor below instead of
// cloned on: a handler written onto the child is the child's handler as far
// as that child can tell, and a component that owns its activation —
// hard-wiring onClick and spreading the rest of its props over it, as
// ThemeToggle does — then runs the tooltip's instead of its own. Composing
// with `props.onClick` cannot save it either, because a component element's
// props hold nothing the component does internally.
const trigger = isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, {
"aria-describedby":
[(children.props as Record<string, unknown>)["aria-describedby"], open ? id : undefined]
.filter(Boolean)
.join(" ") || undefined,
})
: null;
return (
<>
{!externalAnchorRef ? (
// biome-ignore lint/a11y/noStaticElementInteractions: This wrapper observes bubbling trigger events without replacing the control's handlers.
<span
ref={wrapperRef}
className={cn("relative inline-flex align-middle", wrapperClassName)}
// Pointer events, not the mouse pair: a tap fires compatibility
// mouseenter/mouseleave that carry no pointerType, which raced the tap
// path into opening and closing the same label.
onPointerEnter={(event: PointerEvent) => {
if (hover.enter(event)) show();
}}
onPointerLeave={(event: PointerEvent) => {
if (hover.leave(event)) leave();
}}
onFocus={() => {
focused.current = true;
show();
}}
onBlur={() => {
focused.current = false;
hide();
}}
onPointerDown={(event: PointerEvent) => tap.start(event, open)}
// A gesture the platform took away sends no click, and a key press
// starts an activation that never had a pointer behind it. Either way
// the record has to go, or the next click reads a finger that has long
// since lifted.
onPointerCancel={tap.drop}
onKeyDown={(event) => {
tap.drop();
if (event.key === "Escape") hide();
}}
onClick={toggleOnTap}
>
{trigger}
</span>
) : null}
{typeof document !== "undefined"
? createPortal(
<AnimatePresence>
{open ? (
<TooltipPositioner
key="tooltip"
anchorRef={anchorRef}
floatingRef={floatingRef}
anchorPoint={anchorPoint}
followCursor={followCursor}
side={side}
onDismiss={hide}
pointer={pointer}
>
{(positioned, isPresent) => (
<TooltipSurface
id={id}
ready={positioned}
side={side}
onPointerEnter={() => {
if (timer.current) clearTimeout(timer.current);
}}
onPointerLeave={leave}
style={{
maxWidth: "calc(100vw - 16px)",
whiteSpace: "normal",
pointerEvents: isPresent && !followCursor ? "auto" : "none",
}}
className={cn("overflow-hidden", className)}
>
{content}
</TooltipSurface>
)}
</TooltipPositioner>
) : null}
</AnimatePresence>,
document.body,
)
: null}
</>
);
}
"use client";
import { useIsPresent } from "motion/react";
import { useCallback, useState, type ReactNode } from "react";
import { useTooltipPosition } from "./use-position";
type PositionProps = Parameters<typeof useTooltipPosition>[0];
/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */
export function TooltipPositioner({
children,
...position
}: Omit<PositionProps, "open" | "onPosition"> & {
children: (ready: boolean, present: boolean) => ReactNode;
}) {
const present = useIsPresent();
const [ready, setReady] = useState(false);
const onPosition = useCallback(() => setReady(true), []);
useTooltipPosition({ ...position, open: present, onPosition });
return (
<span
ref={position.floatingRef}
inert={!present}
aria-hidden={!present || undefined}
className="pointer-events-none fixed left-0 top-0 z-[9999] w-max"
style={{ visibility: "hidden", maxWidth: "calc(100vw - 16px)" }}
>
{children(ready, present)}
</span>
);
}
"use client";
import {
autoUpdate,
computePosition,
flip,
offset,
shift,
type Placement,
type VirtualElement,
} from "@floating-ui/dom";
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
export type TooltipSide = "top" | "right" | "bottom" | "left";
export type TooltipPoint = { x: number; y: number };
/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */
export function useTooltipPosition({
open,
anchorRef,
floatingRef,
anchorPoint,
followCursor,
side,
onDismiss,
onPosition,
pointer,
}: {
open: boolean;
anchorRef: RefObject<HTMLElement | SVGElement | null>;
floatingRef: RefObject<HTMLSpanElement | null>;
anchorPoint?: TooltipPoint;
followCursor: boolean;
side: TooltipSide;
onDismiss: () => void;
onPosition: () => void;
pointer: ReturnType<typeof useTooltipPointer>;
}) {
const { cursor, onMove } = pointer;
const cursorSide = useRef<Placement | null>(null);
useLayoutEffect(() => {
cursorSide.current = open ? side : null;
}, [open, side]);
const frame = useRef<number | null>(null);
const version = useRef(0);
const update = useRef<() => void>(() => {});
const schedule = useCallback(() => {
// Invalidate older async calculations as soon as new geometry is requested.
version.current++;
if (frame.current !== null) return;
frame.current = requestAnimationFrame(() => {
frame.current = null;
update.current();
});
}, []);
useLayoutEffect(() => {
onMove.current = schedule;
return () => {
onMove.current = null;
};
}, [onMove, schedule]);
const pointX = anchorPoint?.x;
const pointY = anchorPoint?.y;
// Latest committed inputs are read without recreating observers for every period/content update.
useLayoutEffect(() => {
update.current = () => {
const anchor = anchorRef.current;
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const revision = ++version.current;
const currentCursor = followCursor ? cursor.current : null;
const reference: Element | VirtualElement =
currentCursor || pointX !== undefined || pointY !== undefined
? {
contextElement: anchor,
getBoundingClientRect: () => {
const rect = anchor.getBoundingClientRect();
const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);
const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);
return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };
},
}
: anchor;
void computePosition(reference, floating, {
strategy: "fixed",
placement: currentCursor ? (cursorSide.current ?? side) : side,
middleware: [offset(currentCursor ? 12 : 8), flip({ padding: 8 }), shift({ padding: 8 })],
}).then(({ x, y, placement }) => {
if (version.current !== revision || !floating.isConnected) return;
// Hold the chosen side for this hover session. Crossing a flip threshold
// repeatedly must not bounce the surface above and below the pointer.
if (currentCursor) cursorSide.current = placement;
else cursorSide.current = null;
const dpr = window.devicePixelRatio || 1;
floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;
const origin = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
floating.style.setProperty(
"--tooltip-origin",
origin[placement.split("-")[0] as TooltipSide],
);
floating.style.visibility = "visible";
floating.dataset.placement = placement;
onPosition();
});
};
if (open) schedule();
}, [
open,
anchorRef,
floatingRef,
followCursor,
pointX,
pointY,
side,
schedule,
onPosition,
cursor,
]);
useLayoutEffect(() => {
const anchor = anchorRef.current;
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const stop = autoUpdate(anchor, floating, schedule);
const onScroll = () => {
// A stationary pointer no longer describes the same chart point after scrolling.
if (followCursor && cursor.current) onDismiss();
};
window.addEventListener("scroll", onScroll, true);
return () => {
stop();
window.removeEventListener("scroll", onScroll, true);
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = null;
};
}, [open, anchorRef, floatingRef, followCursor, onDismiss, schedule, cursor]);
useLayoutEffect(
() => () => {
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
},
[],
);
}
/** Pointer lifetime belongs to the trigger, including the opening delay. */
export function useTooltipPointer(
anchorRef: RefObject<HTMLElement | SVGElement | null>,
followCursor: boolean,
) {
const cursor = useRef<TooltipPoint | null>(null);
const onMove = useRef<(() => void) | null>(null);
const pointerFocus = useRef(false);
useLayoutEffect(() => {
const anchor = anchorRef.current;
if (!anchor || !followCursor) return;
const point = (event: PointerEvent) => {
if (event.type === "pointermove" && event.pointerType === "touch" && !event.buttons) return;
cursor.current = { x: event.clientX, y: event.clientY };
if (event.type === "pointerdown") pointerFocus.current = true;
onMove.current?.();
};
const keyboard = () => {
cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const focus = () => {
if (!pointerFocus.current) cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const leave = () => {
cursor.current = null;
};
anchor.addEventListener("pointerenter", point as EventListener, { passive: true });
anchor.addEventListener("pointermove", point as EventListener, { passive: true });
anchor.addEventListener("pointerdown", point as EventListener, { passive: true });
anchor.addEventListener("pointerleave", leave);
anchor.addEventListener("pointercancel", leave);
anchor.addEventListener("keydown", keyboard);
anchor.addEventListener("focusin", focus);
return () => {
cursor.current = null;
anchor.removeEventListener("pointerenter", point as EventListener);
anchor.removeEventListener("pointermove", point as EventListener);
anchor.removeEventListener("pointerdown", point as EventListener);
anchor.removeEventListener("pointerleave", leave);
anchor.removeEventListener("pointercancel", leave);
anchor.removeEventListener("keydown", keyboard);
anchor.removeEventListener("focusin", focus);
};
}, [anchorRef, followCursor]);
return { cursor, onMove };
}
"use client";
import { motion, useReducedMotion } from "motion/react";
import type { ComponentProps, ReactNode, Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
/** Presentation only: the unanimated parent owns measurement and positioning. */
export function TooltipSurface({
children,
side: _side = "top",
className,
ref,
ready = true,
style,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
/** Start the entrance only after the positioning layer has been measured. */
ready?: boolean;
side?: "top" | "right" | "bottom" | "left";
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion();
const closed = { opacity: 0, scale: reduce ? 1 : 0.94 };
return (
<motion.span
ref={ref}
role="tooltip"
initial={closed}
animate={{
...(ready ? { opacity: 1, scale: 1 } : closed),
transition: { duration: 0.18, ease: EASE_OUT },
}}
exit={{ ...closed, transition: { duration: 0.12, ease: EASE_OUT } }}
style={{ transformOrigin: "var(--tooltip-origin, center)", ...style }}
className={cn(
"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
API Reference
HeatCalendar
unit?stringNoun after every count, e.g. "commits", "ships".
—weeks?numberNumber of week columns.
—maxCount?numberCount a cell at intensity 1 stands for; a cell reads `intensity × maxCount`.
—values?number[][]`values[week][day]` intensities in 0..1, seven days per week. Missing values are zero.
—endDate?DateLast UTC calendar day of the grid. Defaults to today after mount; explicit dates render identically in every timezone.
—color?stringThe single hue. Any CSS color; magnitude maps to its strength, never to a second color.
—className?string—selection?HeatCalendarSelection | nullControlled selection; null clears it. Cell coordinates are zero-based week/day (Monday first).
—defaultSelection?HeatCalendarSelection | null—onSelectionChange?((selection: HeatCalendarSelection | null) => void)—HeatCalendarGrid
className?string—HeatCalendarLegend
className?string—HeatCalendarTooltip
className?string—Related components
Returns Calendar
Composable monthly returns calendar with Grid and Tooltip parts, controlled month or year selections, and compounded totals. Supply your own years and monthly percentages.
Price Target Fan
Composable price target chart with Header, Plot, SVG, Axes, History, Targets, Now, Cursor, and Tooltip parts. Supply dated price history and targets; scrub with a pointer or keyboard and customize the active readout.
Treemap
Proportional tiles that morph with your data, with value and share tooltips.
Contributed by
SavvaUpdated