Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

14.1 KB
Raw Blame
/**
 * The plot frame every time-series chart draws in (the daily Token stacked bar, the cost line,
 * the requests and score trends): 4 horizontal grid lines + y-axis ticks, x-axis dates, a
 * hover vertical indicator line + a transparent hit area + a value bubble
 * that follows the cursor at its lower-right (flipping to the other side of
 * the pointer near the edges, see chart-geom's bubblePosition). "Data marks" (line / area / bars) are drawn by
 * the caller as children in the same x()/y() coordinate system;
 * see chart-geom.ts for the coordinate math.
 *
 * **1 canvas unit = 1 CSS pixel**: the SVG renders at real pixel width per
 * geom.w (not scaled via viewBox), so sizing requirements like "25px bar
 * width" land on real display pixels. The canvas width is supplied by the
 * caller after measuring the container with useChartWidth; when the canvas
 * is wider than the container (e.g. the Token bar chart stretched out by its bar-width floor), the outer container scrolls horizontally, and the bubble scrolls along with the content.
 *
 * Two hit-granularity tiers: the default is "whole column" (the cost line —
 * a column only has one value); the bar chart passes hitLayer to override
 * it as "per-segment" (a column has three segments, each independently
 * hoverable), in which case hover only serves as the bubble's anchor (a
 * column index).
 * The hover vertical line likewise has two tiers: on the line chart it's a
 * necessary x-position indicator, while on the bar chart the bar itself
 * already indicates the x position — an extra vertical line would just be
 * noise, so the bar chart passes hoverLine={false} to turn it off.
 *
 * The usage charts drop the buckets that recorded nothing before they get
 * here, so their x axis covers unequal spans of time; axisBreaks draws the
 * "//" between two points that are not neighbours, which is what keeps the
 * axis from being read as a continuous one.
 *
 * The frame's own ink (the muted one) is what a mark painted with an empty `ink` draws in — the
 * cost line, a single series with no identity to tell apart.
 */
import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
  type RefObject,
} from "react";
import {
  bubblePosition,
  CHART_H,
  PAD_L,
  PAD_T,
  sparseLabelIdx,
  type ChartGeom,
} from "./chart-geom";
import { ChartAxis, ChartAxisBreak, ChartCursor, ChartGrid, ChartHit } from "../marks/marks";

/** Height (CSS px) of the invisible band laid over a line series so it can be hovered: a 2px stroke is too thin to aim at. */
export const LINE_HIT_H = 10;

/*
 * Every data line on the page — the cost line, the success-rate lines, the cache-hit-rate
 * curve — is drawn at the theme's one line width (useChartStyle), so no line reads as more
 * important than another just because it was written later. Chrome (grid lines, the hover
 * indicator, axis-break marks) stays at 1 and is deliberately not that width.
 */

/** Cell width (CSS px) below which axis-break marks are dropped: any narrower and successive marks sit closer together than they are wide, smearing into a hatched baseline. */
const AXIS_BREAK_MIN_STEP = 8;

/**
 * Hover bands for a line series, one per bucket: a transparent rect the width
 * of the cell, centred on that bucket's point. Put these in ChartFrame's
 * `hitLayer` **after** the bar hits, so a line stays reachable where it runs
 * across a tall segment — the lines draw above the bars, and they answer the
 * pointer above them too.
 *
 * Per bucket rather than one band along the whole path, so entering anywhere
 * on the line reports which bucket the pointer is over as well as which
 * series it belongs to.
 */
export function LineHits({
  geom,
  values,
  onEnter,
  onLeave,
}: {
  geom: ChartGeom;
  values: readonly number[];
  onEnter: (i: number) => void;
  onLeave?: () => void;
}) {
  return values.map((v, i) => (
    <ChartHit
      key={i}
      x={geom.x(i) - geom.step / 2}
      y={geom.y(v) - LINE_HIT_H / 2}
      width={geom.step}
      height={LINE_HIT_H}
      cursor="pointer"
      onMouseEnter={() => onEnter(i)}
      onMouseLeave={onLeave}
    />
  ));
}

/**
 * Measure the available width inside the chart card (CSS pixels, rounded
 * down — a few stray tenths of a pixel would otherwise spawn a scrollbar out of nowhere).
 * The canvas is drawn at real pixels, so the container must be measured
 * first; returns 0 before it's measured (the first frame), and the caller
 * skips rendering the chart at that point.
 * What's measured is the **outer plain div** (not the scroll container), whose width is independent of the canvas content and won't trigger the scrollbar back and forth.
 */
export function useChartWidth(): [RefObject<HTMLDivElement | null>, number] {
  const ref = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const measure = () => setWidth(Math.floor(el.getBoundingClientRect().width));
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  return [ref, width];
}

export function ChartFrame({
  geom,
  fmtY,
  dates,
  hover,
  onHover,
  bubble,
  hitLayer,
  labels,
  fmtX,
  yTicks,
  rightAxis,
  hoverLine = true,
  axisBreaks,
  children,
}: {
  geom: ChartGeom;
  /** y-axis tick formatting (abbreviated for Token, currency for cost). */
  fmtY: (v: number) => string;
  /** Each point's date (x-axis labels and the hit area align to this). */
  dates: string[];
  /** Currently hovered column index (the anchor for the vertical line and bubble). */
  hover: number | null;
  /** Callback for the default hit area (whole column); always called with null when the mouse leaves the whole chart. */
  onHover: (i: number | null) => void;
  /** Bubble content while hovering point i (omit to not show a bubble). */
  bubble?: (i: number) => ReactNode;
  /** Custom hit layer (per-segment hits for the bar chart): omit to use the default "whole column" transparent hit area. */
  hitLayer?: ReactNode;
  /** Indices for x-axis labels (omit for the default first/middle/last sparse labeling): the bar chart's cells are each wide, so it can label more via autoLabelIdx. */
  labels?: number[];
  /** x-axis label formatting. Defaults to dropping a date's year (`slice(5)` → `mm-dd`); series charts pass their own granularity-aware short form. */
  fmtX?: (d: string) => string;
  /** Explicit y-axis ticks. Omit to divide the geom's min..max range into four equal intervals. */
  yTicks?: number[];
  /** Right-hand axis for an overlay drawn on its own scale (the Token chart's cache-hit-rate curve): tick values, their y mapping, and label formatting. Give the geom PAD_R_AXIS so the labels have room. */
  rightAxis?: { y: (v: number) => number; ticks: number[]; fmt: (v: number) => string };
  /** Hover vertical indicator line (drawn by default): the bar chart turns it off — the bar itself already indicates the x position, so an extra line is just noise. */
  hoverLine?: boolean;
  /** Indices after which the x axis skips at least one interval (the usage charts drop the buckets that recorded nothing): a break mark is drawn between that point and the next, so a compressed axis never reads as a continuous one. */
  axisBreaks?: number[];
  /** Data marks: bars / line / area, drawn between the grid and the hit area. */
  children?: ReactNode;
}) {
  const { x, y, w, innerH, step, min, max } = geom;
  const gridLevels =
    yTicks ?? [0, 0.25, 0.5, 0.75, 1].map((fraction) => min + (max - min) * fraction);
  const labelIdx = labels ?? sparseLabelIdx(dates.length);
  const scrollRef = useRef<HTMLDivElement>(null);

  // The bubble follows the pointer **imperatively** (lower-right, flipping
  // at the edges — see chart-geom's bubblePosition): mousemove only records
  // the client position and schedules a single rAF, whose callback batches
  // the layout reads (svg origin, the scroll container's visible window,
  // the bubble's real size) and then writes style.left/top directly. No
  // React state is involved, so a 60–120Hz pointer neither re-renders the
  // few-hundred-element svg nor forces multiple sync layouts per event.
  // The bubble mounts hidden and is revealed by its first placement (on
  // entry, mouseenter fires before the first mousemove has sampled the pointer).
  const svgRef = useRef<SVGSVGElement>(null);
  const bubbleRef = useRef<HTMLDivElement>(null);
  const mouseRef = useRef<{ cx: number; cy: number } | null>(null);
  const rafRef = useRef(0);
  const placeBubble = () => {
    const el = bubbleRef.current;
    const svg = svgRef.current;
    const sc = scrollRef.current;
    const m = mouseRef.current;
    if (!el || !svg || !sc || !m) return;
    const r = svg.getBoundingClientRect();
    // Pointer in canvas coordinates (the svg's top-left is the content
    // origin; bubble and content scroll together, so content pixels are
    // enough), bounded by the *visible* window rather than the full canvas —
    // that is what keeps the bubble on screen when the Token bar canvas is scrolled.
    const pos = bubblePosition(m.cx - r.left, m.cy - r.top, el.offsetWidth, el.offsetHeight, {
      left: sc.scrollLeft,
      right: sc.scrollLeft + sc.clientWidth,
      bottom: CHART_H,
    });
    el.style.left = `${pos.left}px`;
    el.style.top = `${pos.top}px`;
    el.style.visibility = "visible";
  };
  const schedulePlace = () => {
    if (rafRef.current) return;
    rafRef.current = requestAnimationFrame(() => {
      rafRef.current = 0;
      placeBubble();
    });
  };
  useEffect(() => () => cancelAnimationFrame(rafRef.current), []);

  // Re-place synchronously (before paint) when the bubble's content changes:
  // its size changes as hover moves between days/buckets, which can change
  // the flip decision. Keyed on the hover anchor and the bubble renderer's
  // identity (the parent re-creates the callback whenever its own hover
  // state — e.g. the bar chart's segment key — changes) instead of running on every render.
  useLayoutEffect(placeBubble, [bubble, hover]);

  return (
    // The canvas is measured from this container and bars shrink to fit it, so
    // there is nothing to scroll; the box stays scroll-aware because the bubble
    // is its absolutely-positioned child and is anchored in content pixels.
    <div ref={scrollRef} className="relative overflow-x-auto">
      <svg
        ref={svgRef}
        viewBox={`0 0 ${w} ${CHART_H}`}
        width={w}
        height={CHART_H}
        // ui-chart: a theme may redraw the parts, which carry data-part — the grid, the axis
        // labels and breaks here, the series, areas, bars and points in the caller's marks.
        className="ui-chart text-fg-muted"
        role="img"
        onMouseLeave={() => {
          onHover(null);
          // Drop the pointer sample: on re-entry the bubble stays hidden until the fresh position is known, rather than flashing at the stale one.
          mouseRef.current = null;
        }}
        // Only record the client position and coalesce into one rAF: all layout reads happen inside the rAF callback (see placeBubble).
        onMouseMove={(e) => {
          mouseRef.current = { cx: e.clientX, cy: e.clientY };
          schedulePlace();
        }}
      >
        {/* Grid lines and y-axis ticks (recessive gray) */}
        {gridLevels.map((v, i) => (
          <g key={i}>
            <ChartGrid x1={PAD_L} x2={w - geom.padR} y={y(v)} />
            <ChartAxis x={PAD_L - 6} y={y(v) + 3} anchor="end">
              {fmtY(v)}
            </ChartAxis>
          </g>
        ))}

        {/* Right-hand axis ticks (an overlay's own scale, e.g. a percentage) */}
        {rightAxis?.ticks.map((v) => (
          <ChartAxis key={`r${v}`} x={w - geom.padR + 6} y={rightAxis.y(v) + 3} anchor="start">
            {rightAxis.fmt(v)}
          </ChartAxis>
        ))}

        {/* Hover vertical indicator line (line-chart-only: the bar chart's bar itself is the x indicator, see hoverLine) */}
        {hoverLine && hover !== null && dates[hover] && (
          <ChartCursor x={x(hover)} y1={PAD_T} y2={PAD_T + innerH} />
        )}

        {/* Data marks (provided by the caller) */}
        {children}

        {/* Axis breaks: the "//" that says the two points either side of it are
            not neighbours in time. Drawn over the marks (the cost chart's area
            fill reaches the baseline) but never hoverable — the hit layer below
            owns the pointer. */}
        {step >= AXIS_BREAK_MIN_STEP &&
          axisBreaks?.map((i) =>
            i + 1 < geom.n ? (
              <ChartAxisBreak key={`break-${i}`} x={(x(i) + x(i + 1)) / 2} y={PAD_T + innerH} />
            ) : null,
          )}

        {/* x-axis dates */}
        {labelIdx.map((i) => {
          const d = dates[i];
          if (!d) return null;
          return (
            <ChartAxis key={i} x={x(i)} y={CHART_H - 6} anchor="middle">
              {(fmtX ?? ((v: string) => v.slice(5)))(d)}
            </ChartAxis>
          );
        })}

        {/* Hover hit area (larger than the mark itself): whole column by default, the bar chart swaps in hitLayer for per-segment */}
        {hitLayer ??
          dates.map((_, i) => (
            <ChartHit
              key={`hit-${i}`}
              x={PAD_L + step * i}
              y={PAD_T}
              width={step}
              height={innerH}
              onMouseEnter={() => onHover(i)}
            />
          ))}
      </svg>

      {bubble && hover !== null && dates[hover] && (
        <div
          ref={bubbleRef}
          className="pointer-events-none absolute rounded border border-line bg-overlay px-2 py-1 text-xs whitespace-nowrap shadow-sm"
          // Mounted hidden at the origin; placeBubble moves it to the
          // pointer's lower-right (flipping near the right/bottom edges, see
          // bubblePosition) and reveals it. The declared style below never
          // changes between renders, so React leaves the imperative
          // left/top/visibility writes alone (nowrap keeps the measured
          // width the true content width, independent of where the bubble lands).
          style={{ left: 0, top: 0, visibility: "hidden" }}
        >
          {bubble(hover)}
        </div>
      )}
    </div>
  );
}