{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "live-line-chart",
  "type": "registry:component",
  "title": "Live Line Chart",
  "description": "A reading that keeps arriving, against a window that keeps moving.",
  "dependencies": [
    "@base-ui/react",
    "@tanstack/charts",
    "d3-shape",
    "tailwind-variants"
  ],
  "devDependencies": [
    "@types/d3-shape"
  ],
  "registryDependencies": [],
  "cssVars": {
    "light": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    },
    "dark": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    }
  },
  "files": [
    {
      "path": "components/panelui/live-line-chart/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/live-line-chart/index.tsx",
      "content": "'use client';\n\n/**\n * LiveLineChart — a reading that keeps arriving, against a window that keeps\n * moving.\n *\n * ```tsx\n * <LiveLineChart data={points} window={30}>\n *   <LiveLineChart.Grid />\n *   <LiveLineChart.Area />\n *   <LiveLineChart.Line />\n *   <LiveLineChart.Tip />\n *   <LiveLineChart.XAxis />\n * </LiveLineChart>\n * ```\n *\n * ## The same parts as the app\n *\n * The parts and their props are the app library's LiveLineChart. What differs is\n * what the web changes: a colour is named by the theme's role, a reading is taken\n * by hovering, dragging or the arrow keys.\n *\n * ## Two layers\n *\n * The grid and the axes do not move with the clock, so they are one chart\n * definition, rebuilt when the axis changes. The line, the fill and the dots move\n * every frame, against a window tied to the wall clock whether or not a reading\n * arrives, so a feed that stalls shows as the line drifting away from the right\n * edge. A chart definition changes per data update, which is the wrong rate for\n * that, so they are one small SVG layer over the first, written directly and never\n * through React.\n *\n * ## What the clock costs\n *\n * One frame callback, for as long as the chart can be seen. `paused`,\n * `status=\"loading\"`, a hidden page and scrolling off screen all stop it. Under\n * reduced motion it never starts, and the window advances as each reading arrives\n * instead, which is the same picture sampled less often.\n *\n * ## Colour follows the recent direction\n *\n * With `momentumColors`, the line, the fill and the dot take their colour from\n * where the reading has been going, which is the one thing on the chart readable\n * out of the corner of an eye.\n */\nimport { defineChart, lineY } from '@tanstack/charts';\nimport { motion } from '@tanstack/charts/motion';\nimport { Chart } from '@tanstack/charts/react/core';\nimport { scaleLinear } from '@tanstack/charts/scales/linear';\nimport { area as areaPath, curveLinear, curveMonotoneX, line as linePath } from 'd3-shape';\nimport {\n  createContext,\n  forwardRef,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n  type ReactNode,\n} from 'react';\nimport { tv } from 'tailwind-variants';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\nimport { liveLineAccessibility } from './live-line-accessibility';\nimport {\n  liveLineClockRuns,\n  liveLineExtent,\n  liveLineMomentum,\n  liveLineOnPlot,\n  liveLineRun,\n  nearestReading,\n  newestOnPlot,\n  normalizeLiveLinePoints,\n  normalizeLiveLineWindow,\n  reconcileLiveLineActivePoint,\n} from './live-line-lifecycle';\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\n/** Whether the chart is showing data or waiting for it. */\nexport type LiveLineChartStatus = 'loading' | 'ready';\nexport type LiveLineChartCurve = 'monotone' | 'linear';\n\n/** Where the reading has been going, over the last few points. */\nexport type LiveLineMomentum = 'up' | 'down' | 'flat';\n\n/** Which of the theme's roles something is drawn in. */\nexport type LiveLineChartColor =\n  | 'primary'\n  | 'info'\n  | 'success'\n  | 'warning'\n  | 'destructive'\n  | 'chart-1'\n  | 'chart-2'\n  | 'chart-3'\n  | 'chart-4'\n  | 'chart-5'\n  | 'foreground'\n  | 'muted-foreground';\n\n/** A colour per direction, for a chart that is read by its colour. */\nexport interface LiveLineMomentumColors {\n  up?: LiveLineChartColor;\n  down?: LiveLineChartColor;\n  flat?: LiveLineChartColor;\n}\n\n/** One reading. `time` is a timestamp in milliseconds, as `Date.now()` gives. */\nexport interface LiveLinePoint {\n  time: number;\n  value: number;\n}\n\nconst COLOR_VAR: Record<LiveLineChartColor, string> = {\n  primary: 'var(--primary)',\n  info: 'var(--info)',\n  success: 'var(--success)',\n  warning: 'var(--warning)',\n  destructive: 'var(--destructive)',\n  'chart-1': 'var(--chart-1)',\n  'chart-2': 'var(--chart-2)',\n  'chart-3': 'var(--chart-3)',\n  'chart-4': 'var(--chart-4)',\n  'chart-5': 'var(--chart-5)',\n  foreground: 'var(--foreground)',\n  'muted-foreground': 'var(--muted-foreground)',\n};\n\nconst liveLineChartVariants = tv({\n  slots: {\n    root: 'relative grid w-full grid-cols-1 text-foreground',\n    // `pan-y` hands a vertical drag to the page and a sideways one to the chart.\n    plot: 'relative col-start-1 row-start-2 w-full touch-pan-y rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring',\n    chart: 'absolute! inset-0 text-xs',\n    layer: 'pointer-events-none absolute inset-0 size-full overflow-visible',\n    skeleton: 'pointer-events-none absolute h-0.5 rounded-full bg-muted',\n    tip: 'pointer-events-none absolute left-0 top-0 size-2 rounded-full transition-colors duration-300',\n    pulse: 'absolute inset-0 rounded-full motion-reduce:hidden',\n    badge:\n      'absolute right-4 -top-1.5 whitespace-nowrap rounded-md border border-border bg-popover px-1.5 py-0.5 text-xs font-medium tabular-nums text-popover-foreground',\n    crosshair: 'pointer-events-none absolute left-0 w-px opacity-45',\n    dot: 'pointer-events-none absolute left-0 top-0 size-2 rounded-full',\n    readout:\n      'pointer-events-none absolute left-0 top-0 flex w-29 flex-col items-center rounded-lg border border-border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm',\n    readoutValue: 'font-medium tabular-nums',\n    readoutAge: 'text-muted-foreground',\n    header: 'col-start-1 row-start-1 flex items-start justify-between gap-3 pb-3',\n    headerText: 'flex min-w-0 flex-1 flex-col gap-0.5',\n    headerMuted: 'text-xs text-muted-foreground',\n    headerValue: 'text-xl font-bold tabular-nums tracking-tight',\n    headerTrailing: 'flex max-w-[55%] shrink flex-wrap items-center justify-end gap-x-3 gap-y-1 pt-1 text-xs text-muted-foreground',\n  },\n});\n\n/** Room left around the plot, fixed so the moving layer and the guides agree. */\nconst MARGIN = { top: 12, right: 14, bottom: 22, left: 10 };\n\n/** The left margin when a `YAxis` needs somewhere to write. */\nconst Y_AXIS_WIDTH = 44;\n\n/** Half the width of a dot, for centring it on the point it names. */\nconst DOT_RADIUS = 4;\n\n/** The readout's width, for keeping it inside the plot. */\nconst READOUT_WIDTH = 116;\n\n/** A transform and an opacity, so the loop runs on the compositor and repaints nothing. */\nconst STYLES = `@keyframes panelui-live-pulse{from{transform:scale(1);opacity:.55}to{transform:scale(3.2);opacity:0}}`;\n\nconst THEME = {\n  foreground: 'var(--foreground)',\n  muted: 'var(--muted-foreground)',\n  grid: 'var(--border)',\n  background: 'transparent',\n  palette: ['var(--chart-1)'],\n};\n\nconst COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });\nconst COMPACT_SMALL = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 });\n\n/** Below one, a single decimal would round most values down to nothing. */\nconst compactNumber = (value: number) => (Math.abs(value) < 1 ? COMPACT_SMALL : COMPACT).format(value);\n\nconst CURVES = { monotone: curveMonotoneX, linear: curveLinear };\n\n/** Where the guides put the plot, in pixels inside the chart's box. */\ninterface PlotBox {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\ntype Format = (value: number) => string;\n\n/** What the parts have asked for. Formatters are read through `latest`, so a new one costs nothing. */\ninterface Slots {\n  header?: { title: string | undefined; value: string | undefined; format: { current: Format | undefined } };\n  grid?: { rows: number; dashArray: string | undefined; stroke: string };\n  area?: { fill: string | undefined; opacity: number };\n  line?: { stroke: string | undefined; strokeWidth: number };\n  tip?: { badge: boolean; pulse: boolean; className: string | undefined; format: { current: Format | undefined } };\n  xAxis?: { ticks: number; format: { current: ((secondsAgo: number) => string) | undefined } };\n  yAxis?: { ticks: number; format: { current: Format | undefined } };\n  tooltip?: { className: string | undefined; format: { current: Format | undefined } };\n  skeleton?: { base: string | undefined };\n}\n\ninterface LiveLineChartContextValue {\n  setSlot: <K extends keyof Slots>(slot: K, value: Slots[K]) => void;\n  activePoint: LiveLinePoint | null;\n  latest: LiveLinePoint | null;\n  momentum: LiveLineMomentum;\n  color: string;\n}\n\nconst LiveLineChartContext = createContext<LiveLineChartContextValue | null>(null);\n\nfunction useChart(component: string): LiveLineChartContextValue {\n  const context = useContext(LiveLineChartContext);\n  if (!context) {\n    throw new Error(`${component} must be used within a <LiveLineChart>`);\n  }\n  return context;\n}\n\n/** The reading under the crosshair, for something rendered inside the chart. */\nexport function useLiveLineChart() {\n  const { activePoint, latest, momentum, color } = useChart('useLiveLineChart');\n  return { activePoint, latest, momentum, color };\n}\n\n/** Hands a part's formatter to the root without a new function redrawing the chart. */\nfunction useLatest<T>(value: T) {\n  const [latest] = useState(() => ({ current: value }));\n  useEffect(() => {\n    latest.current = value;\n  });\n  return latest;\n}\n\n/** True when the system asks for less motion. */\nfunction useReducedMotion() {\n  const [reduced, setReduced] = useState(false);\n  useEffect(() => {\n    const query = window.matchMedia('(prefers-reduced-motion: reduce)');\n    const read = () => setReduced(query.matches);\n    read();\n    query.addEventListener('change', read);\n    return () => query.removeEventListener('change', read);\n  }, []);\n  return reduced;\n}\n\nexport interface LiveLineChartProps extends Omit<ComponentProps<'div'>, 'ref'> {\n  /** The readings so far. Invalid values are dropped and timestamps are ordered. */\n  data: readonly LiveLinePoint[];\n  /** How much time the plot spans, in seconds. Invalid values use 30. */\n  window?: number;\n  /** Freeze the window where it is. The readings still arrive; the clock stops. */\n  paused?: boolean;\n  /** Fix the value axis instead of deriving it from what is visible. */\n  yDomain?: [number, number];\n  /** Milliseconds for the value axis to settle after the range changes. */\n  domainDuration?: number;\n  /** `monotone` never overshoots between readings; `linear` joins them straight. */\n  curve?: LiveLineChartCurve;\n  /**\n   * The most readings kept. Older ones are dropped, so an unbounded feed does not\n   * grow an array for as long as the page is open. Must be positive and finite.\n   */\n  maxPoints?: number;\n  /** The plot's width ÷ height. */\n  aspectRatio?: number;\n  /** `loading` holds the clock and draws `Skeleton` in place of the line. */\n  status?: LiveLineChartStatus;\n  /** Which role to draw in per direction. Left out, the chart keeps to one colour. */\n  momentumColors?: LiveLineMomentumColors;\n  /** Which of the theme's roles the chart is drawn in, `chart-1` by default. With `momentumColors` it only colours a flat reading, and only if `momentumColors.flat` is not set. */\n  color?: LiveLineChartColor;\n  /** The reading under the crosshair as it moves, and `null` when it is let go. */\n  onActivePointChange?: (point: LiveLinePoint | null) => void;\n  /** Names the chart for a screen reader. Falls back to the Header's title, then to \"Live line chart\". */\n  label?: string;\n  /** Further guidance after the snapshot a screen reader gets. */\n  hint?: string;\n}\n\n/** Imperative handle: land the window on the present, after a pause. */\nexport interface LiveLineChartHandle {\n  sync: () => void;\n}\n\nconst LiveLineChartRoot = forwardRef<LiveLineChartHandle, LiveLineChartProps & RenderProp<'div'>>(function LiveLineChartRoot(\n  {\n    data,\n    window: windowSeconds = 30,\n    paused = false,\n    yDomain,\n    domainDuration = 420,\n    curve = 'monotone',\n    maxPoints = 500,\n    aspectRatio = 2,\n    status = 'ready',\n    momentumColors,\n    color,\n    onActivePointChange,\n    label,\n    hint,\n    className,\n    children,\n    render,\n    ...props\n  },\n  ref\n) {\n  const classes = liveLineChartVariants();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const lineRef = useRef<SVGPathElement>(null);\n  const areaRef = useRef<SVGPathElement>(null);\n  const tipRef = useRef<HTMLDivElement>(null);\n  const crosshairRef = useRef<HTMLDivElement>(null);\n  const dotRef = useRef<HTMLDivElement>(null);\n  const readoutRef = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  const [box, setBox] = useState<PlotBox | null>(null);\n  const [slots, setSlots] = useState<Slots>({});\n  const [activePoint, setActiveState] = useState<LiveLinePoint | null>(null);\n  const [onScreen, setOnScreen] = useState(true);\n  const [pageVisible, setPageVisible] = useState(true);\n  // Advanced while a reading is held, so \"4s ago\" counts up under it.\n  const [, setAgeTick] = useState(0);\n  const reducedMotion = useReducedMotion();\n  // Unique per chart: clips and gradients are found by id across the whole page.\n  const idPrefix = `panelui-live-${useId().replace(/[^a-zA-Z0-9]/g, '')}`;\n\n  useEffect(() => {\n    const node = plotRef.current;\n    if (!node) return;\n    const read = () => setWidth(node.clientWidth);\n    read();\n    const size = new ResizeObserver(read);\n    size.observe(node);\n    const view = new IntersectionObserver(([entry]) => setOnScreen(entry?.isIntersecting ?? true));\n    view.observe(node);\n    return () => {\n      size.disconnect();\n      view.disconnect();\n    };\n  }, []);\n\n  useEffect(() => {\n    const read = () => setPageVisible(document.visibilityState !== 'hidden');\n    read();\n    document.addEventListener('visibilitychange', read);\n    return () => document.removeEventListener('visibilitychange', read);\n  }, []);\n\n  const setSlot = useCallback<LiveLineChartContextValue['setSlot']>(\n    (slot, value) => setSlots((current) => ({ ...current, [slot]: value })),\n    []\n  );\n\n  const loading = status === 'loading';\n  const windowMs = normalizeLiveLineWindow(windowSeconds) * 1000;\n  const points = useMemo(() => normalizeLiveLinePoints(data, maxPoints), [data, maxPoints]);\n  const liveLatest = points[points.length - 1] ?? null;\n\n  const liveExtent = useMemo<[number, number]>(\n    () => yDomain ?? liveLineExtent(points, (liveLatest?.time ?? 0) - windowMs),\n    [points, liveLatest, windowMs, yDomain]\n  );\n  const liveMomentum = liveLineMomentum(points, liveExtent);\n\n  /*\n   * `paused` holds the whole picture and not only the clock. Readings keep arriving\n   * while it is held, so an axis, a dot or a colour taken from the newest one would\n   * go on moving under a frozen line.\n   */\n  const [held, setHeld] = useState<{ extent: [number, number]; latest: LiveLinePoint | null; momentum: LiveLineMomentum } | null>(null);\n  useEffect(() => {\n    if (!paused) setHeld({ extent: liveExtent, latest: liveLatest, momentum: liveMomentum });\n  }, [paused, liveExtent, liveLatest, liveMomentum]);\n  const extent = paused && held ? held.extent : liveExtent;\n  const latest = paused && held ? held.latest : liveLatest;\n  const momentum = paused && held ? held.momentum : liveMomentum;\n\n  const resolved = COLOR_VAR[\n    momentumColors\n      ? momentum === 'up'\n        ? (momentumColors.up ?? 'success')\n        : momentum === 'down'\n          ? (momentumColors.down ?? 'destructive')\n          : (momentumColors.flat ?? color ?? 'chart-1')\n      : (color ?? 'chart-1')\n  ];\n\n  const reported = useRef<LiveLinePoint | null>(null);\n  const report = useLatest(onActivePointChange);\n  const setActivePoint = useCallback(\n    (point: LiveLinePoint | null) => {\n      if (reported.current?.time === point?.time && reported.current?.value === point?.value) return;\n      reported.current = point;\n      setActiveState(point);\n      report.current?.(point);\n    },\n    [report]\n  );\n\n  // A reading trimmed away under the crosshair has nothing left to point at.\n  useEffect(() => {\n    setActivePoint(reconcileLiveLineActivePoint(reported.current, points));\n  }, [points, setActivePoint]);\n\n  useEffect(() => {\n    if (!activePoint) return;\n    const timer = setInterval(() => setAgeTick((tick) => tick + 1), 1000);\n    return () => clearInterval(timer);\n  }, [activePoint]);\n\n  const running = liveLineClockRuns({ paused, loading, reducedMotion, visible: onScreen && pageVisible });\n\n  // Everything the frame callback reads. Refs, because it runs outside React.\n  const nowRef = useRef(0);\n  const domain = useRef({ from: extent, to: extent, start: -Infinity, duration: 0, set: false });\n  const frame = useRef({ points, windowMs, box, curve, activePoint, setActivePoint });\n\n  const draw = useCallback(() => {\n    const { points, windowMs, box, curve, activePoint, setActivePoint } = frame.current;\n    if (!box) return;\n    const xMax = nowRef.current;\n    const xMin = xMax - windowMs;\n\n    const { from, to, start, duration } = domain.current;\n    const raw = duration > 0 ? Math.min(1, (performance.now() - start) / duration) : 1;\n    const eased = 1 - (1 - raw) ** 3;\n    const yMin = from[0] + (to[0] - from[0]) * eased;\n    const yMax = from[1] + (to[1] - from[1]) * eased;\n\n    const xOf = (time: number) => box.x + ((time - xMin) / windowMs) * box.width;\n    const yOf = (value: number) => box.y + box.height - ((value - yMin) / (yMax - yMin || 1)) * box.height;\n\n    const run = liveLineRun(points, xMin, xMax);\n    const factory = CURVES[curve];\n    const reading = run.length > 1;\n    lineRef.current?.setAttribute(\n      'd',\n      reading\n        ? (linePath<LiveLinePoint>()\n            .x(({ time }) => xOf(time))\n            .y(({ value }) => yOf(value))\n            .curve(factory)(run) ?? '')\n        : ''\n    );\n    areaRef.current?.setAttribute(\n      'd',\n      reading\n        ? (areaPath<LiveLinePoint>()\n            .x(({ time }) => xOf(time))\n            .y0(box.y + box.height)\n            .y1(({ value }) => yOf(value))\n            .curve(factory)(run) ?? '')\n        : ''\n    );\n\n    const place = (node: HTMLElement | null, x: number, y: number) => {\n      if (node) node.style.transform = `translate(${x}px, ${y}px)`;\n    };\n\n    const tip = tipRef.current;\n    if (tip) {\n      const newest = newestOnPlot(points, xMin, xMax);\n      tip.style.opacity = newest ? '1' : '0';\n      if (newest) place(tip, xOf(newest.time) - DOT_RADIUS, yOf(newest.value) - DOT_RADIUS);\n    }\n\n    if (activePoint) {\n      // The moment has scrolled off the plot, and there is nothing left to read.\n      if (activePoint.time < xMin) {\n        setActivePoint(null);\n        return;\n      }\n      const x = xOf(activePoint.time);\n      place(crosshairRef.current, x, 0);\n      place(dotRef.current, x - DOT_RADIUS, yOf(activePoint.value) - DOT_RADIUS);\n      const half = READOUT_WIDTH / 2;\n      place(readoutRef.current, Math.min(box.x + box.width - half, Math.max(box.x + half, x)) - half, box.y);\n    }\n  }, []);\n\n  /*\n   * After every render and before the paint, so a part that has just mounted is in\n   * place on its first frame. A render is rare: the clock does not cause one.\n   */\n  useLayoutEffect(() => {\n    frame.current = { points, windowMs, box, curve, activePoint, setActivePoint };\n    if (nowRef.current === 0) nowRef.current = Date.now();\n    draw();\n  });\n\n  useEffect(() => {\n    const current = domain.current;\n    // The first scale lands: there is nothing to move from. It lands as well when the\n    // clock stops, or a pause would finish the move on whatever render came next.\n    if (!current.set || !running) {\n      domain.current = { from: extent, to: extent, start: -Infinity, duration: 0, set: true };\n    } else if (current.to[0] === extent[0] && current.to[1] === extent[1]) {\n      return;\n    } else {\n      const now = performance.now();\n      const eased = 1 - (1 - Math.min(1, (now - current.start) / (current.duration || 1))) ** 3;\n      const from: [number, number] = [\n        current.from[0] + (current.to[0] - current.from[0]) * eased,\n        current.from[1] + (current.to[1] - current.from[1]) * eased,\n      ];\n      domain.current = { from, to: extent, start: now, duration: domainDuration, set: true };\n    }\n    draw();\n  }, [extent, running, domainDuration, draw]);\n\n  useEffect(() => {\n    if (!running) return;\n    let id = requestAnimationFrame(function tick() {\n      nowRef.current = Date.now();\n      draw();\n      id = requestAnimationFrame(tick);\n    });\n    return () => cancelAnimationFrame(id);\n  }, [running, draw]);\n\n  // With no clock the window lands on the present as each reading arrives.\n  useEffect(() => {\n    if (running || paused) return;\n    nowRef.current = Date.now();\n    draw();\n  }, [running, paused, points, draw]);\n\n  useImperativeHandle(\n    ref,\n    () => ({\n      sync: () => {\n        nowRef.current = Date.now();\n        draw();\n      },\n    }),\n    [draw]\n  );\n\n  const { header, grid, area, line, tip, xAxis, yAxis, tooltip, skeleton } = slots;\n  const seconds = windowMs / 1000;\n\n  const definition = useMemo(() => {\n    const valueTicks = Math.max(1, yAxis?.ticks ?? grid?.rows ?? 4);\n    const timeTicks = Math.max(1, xAxis?.ticks ?? 4);\n    // Even steps across the axis, so a rule stays put when the scale under it moves.\n    const values = Array.from({ length: valueTicks + 1 }, (_, index) => extent[0] + ((extent[1] - extent[0]) * index) / valueTicks);\n    const offsets = Array.from({ length: timeTicks + 1 }, (_, index) => -seconds + (seconds * index) / timeTicks);\n    return defineChart({\n      theme: THEME,\n      // Empty: it only tells the guides their scales hold numbers.\n      marks: [lineY<LiveLinePoint>([], { id: 'live-line-guides', x: 'time', y: 'value' })],\n      margin: { ...MARGIN, left: yAxis ? Y_AXIS_WIDTH : MARGIN.left },\n      motion: false as const,\n      keyboard: false,\n      pointer: false,\n      focusRing: false,\n      scales: {\n        x: {\n          scale: scaleLinear([-seconds, 0], [0, 1]),\n          axis:\n            xAxis && !loading\n              ? {\n                  line: false as const,\n                  tickLabels: {\n                    opacity: 1,\n                    anchor: ({ value }: { value: number }) =>\n                      value === -seconds ? ('start' as const) : value === 0 ? ('end' as const) : undefined,\n                  },\n                  ticks: {\n                    size: 0,\n                    values: offsets,\n                    format: (value: number) => {\n                      const secondsAgo = Math.abs(value);\n                      const format = xAxis.format.current;\n                      return format ? format(secondsAgo) : secondsAgo === 0 ? 'now' : `-${Number(secondsAgo.toFixed(1))}s`;\n                    },\n                  },\n                }\n              : (false as const),\n        },\n        y: {\n          scale: scaleLinear(extent, [0, 1]),\n          grid: grid ? { stroke: grid.stroke, strokeOpacity: 1, strokeDasharray: grid.dashArray } : false,\n          axis:\n            yAxis && !loading\n              ? {\n                  line: false as const,\n                  tickLabels: { opacity: 1 },\n                  ticks: { size: 0, values, format: (value: number) => (yAxis.format.current ?? compactNumber)(value) },\n                }\n              : grid\n                ? { line: false as const, ticks: { size: 0, values, format: () => '' } }\n                : (false as const),\n        },\n      },\n    });\n  }, [extent, seconds, grid, xAxis, yAxis, loading]);\n\n  // The definition turns motion off, and a renderer is still required.\n  const renderer = useMemo(() => motion(), []);\n\n  const headerFormat = header?.format.current;\n  const tipFormat = tip?.format.current;\n  const snapshot = liveLineAccessibility({\n    name: label ?? header?.title,\n    status,\n    latest,\n    activePoint,\n    momentum,\n    windowSeconds: seconds,\n    paused,\n    now: Date.now(),\n    valueOverride: header?.value,\n    formatLatest: headerFormat ?? tipFormat ?? compactNumber,\n    formatActive: tooltip?.format.current ?? headerFormat ?? tipFormat ?? compactNumber,\n  });\n\n  const canRead = tooltip !== undefined && !loading;\n  useEffect(() => {\n    if (!canRead) setActivePoint(null);\n  }, [canRead, setActivePoint]);\n\n  const readAt = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (!canRead || !box) return;\n    const rect = event.currentTarget.getBoundingClientRect();\n    const x = Math.min(Math.max(event.clientX - rect.left, box.x), box.x + box.width);\n    const xMin = nowRef.current - windowMs;\n    setActivePoint(nearestReading(liveLineOnPlot(points, xMin, nowRef.current), xMin + ((x - box.x) / box.width) * windowMs));\n  };\n\n  const readByKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    if (event.key === 'Escape') {\n      setActivePoint(null);\n      return;\n    }\n    if ((event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') || !canRead) return;\n    event.preventDefault();\n    const onPlot = liveLineOnPlot(points, nowRef.current - windowMs, nowRef.current);\n    if (!onPlot.length) return;\n    const at = activePoint ? onPlot.findIndex(({ time }) => time === activePoint.time) : onPlot.length;\n    const step = event.key === 'ArrowLeft' ? -1 : 1;\n    setActivePoint(onPlot[Math.min(Math.max(at + step, 0), onPlot.length - 1)] ?? null);\n  };\n\n  const context = useMemo<LiveLineChartContextValue>(\n    () => ({ setSlot, activePoint, latest, momentum, color: resolved }),\n    [setSlot, activePoint, latest, momentum, resolved]\n  );\n\n  const lineStroke = line?.stroke ?? resolved;\n  const areaFill = area?.fill ?? resolved;\n  const secondsAgo = activePoint ? Math.max(0, Math.round((Date.now() - activePoint.time) / 1000)) : 0;\n  const paint = { transition: 'stroke 300ms' };\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'live-line-chart',\n        className: classes.root({ className }),\n        children: (\n          <>\n            <style>{STYLES}</style>\n            <div\n              ref={plotRef}\n              data-slot=\"live-line-chart-plot\"\n              role=\"img\"\n              aria-label={snapshot}\n              aria-description={hint}\n              tabIndex={tooltip ? 0 : undefined}\n              className={classes.plot()}\n              style={{ aspectRatio }}\n              onKeyDown={readByKey}\n              onBlur={() => setActivePoint(null)}\n              onPointerDown={readAt}\n              onPointerMove={(event) => {\n                // A finger reads only what it is dragging across; a hover reads on its own.\n                if (event.pointerType === 'mouse' || event.buttons > 0) readAt(event);\n              }}\n              onPointerUp={(event) => {\n                if (event.pointerType !== 'mouse') setActivePoint(null);\n              }}\n              onPointerLeave={() => setActivePoint(null)}\n              onPointerCancel={() => setActivePoint(null)}\n            >\n              {width > 0 ? (\n                <Chart\n                  definition={definition}\n                  renderer={renderer}\n                  ariaLabel={snapshot}\n                  aspectRatio={aspectRatio}\n                  initialWidth={width}\n                  className={classes.chart()}\n                  onRender={({ scene }) => {\n                    const { x, y, width: plotWidth, height } = scene.chart;\n                    setBox((current) =>\n                      current && current.x === x && current.y === y && current.width === plotWidth && current.height === height\n                        ? current\n                        : { x, y, width: plotWidth, height }\n                    );\n                  }}\n                />\n              ) : null}\n              {box && !loading ? (\n                <>\n                  <svg data-slot=\"live-line-chart-layer\" aria-hidden className={classes.layer()}>\n                    <defs>\n                      {/* The run starts one reading outside the window, and this hides the overhang. */}\n                      <clipPath id={`${idPrefix}-clip`}>\n                        <rect x={box.x} y={0} width={box.width} height={box.y + box.height} />\n                      </clipPath>\n                      {area ? (\n                        <linearGradient id={`${idPrefix}-fill`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                          <stop offset=\"0\" style={{ stopColor: areaFill, stopOpacity: area.opacity, transition: 'stop-color 300ms' }} />\n                          <stop offset=\"1\" style={{ stopColor: areaFill, stopOpacity: 0, transition: 'stop-color 300ms' }} />\n                        </linearGradient>\n                      ) : null}\n                    </defs>\n                    <g clipPath={`url(#${idPrefix}-clip)`}>\n                      {area ? <path ref={areaRef} data-slot=\"live-line-chart-area\" fill={`url(#${idPrefix}-fill)`} /> : null}\n                      {line ? (\n                        <path\n                          ref={lineRef}\n                          data-slot=\"live-line-chart-line\"\n                          fill=\"none\"\n                          stroke={lineStroke}\n                          strokeWidth={line.strokeWidth}\n                          strokeLinecap=\"round\"\n                          strokeLinejoin=\"round\"\n                          style={paint}\n                        />\n                      ) : null}\n                    </g>\n                  </svg>\n                  {activePoint ? (\n                    <div\n                      ref={crosshairRef}\n                      data-slot=\"live-line-chart-crosshair\"\n                      className={classes.crosshair()}\n                      style={{ top: box.y, height: box.height, background: resolved }}\n                    />\n                  ) : null}\n                  {tip && latest ? (\n                    <div ref={tipRef} data-slot=\"live-line-chart-tip\" className={classes.tip()} style={{ background: resolved }}>\n                      {tip.pulse && !paused ? (\n                        <div\n                          className={classes.pulse()}\n                          style={{ background: resolved, animation: 'panelui-live-pulse 1600ms ease-out infinite' }}\n                        />\n                      ) : null}\n                      {/* Never while a reading is held: that is one question, and it has one answer. */}\n                      {tip.badge && !activePoint ? (\n                        <div data-slot=\"live-line-chart-badge\" className={classes.badge({ className: tip.className })}>\n                          {(tipFormat ?? compactNumber)(latest.value)}\n                        </div>\n                      ) : null}\n                    </div>\n                  ) : null}\n                  {activePoint ? (\n                    <>\n                      <div ref={dotRef} data-slot=\"live-line-chart-dot\" className={classes.dot()} style={{ background: resolved }} />\n                      <div\n                        ref={readoutRef}\n                        data-slot=\"live-line-chart-readout\"\n                        className={classes.readout({ className: tooltip?.className })}\n                      >\n                        <span className={classes.readoutValue()}>\n                          {(tooltip?.format.current ?? compactNumber)(activePoint.value)}\n                        </span>\n                        <span className={classes.readoutAge()}>{secondsAgo === 0 ? 'just now' : `${secondsAgo}s ago`}</span>\n                      </div>\n                    </>\n                  ) : null}\n                </>\n              ) : null}\n              {box && loading && skeleton ? (\n                <div\n                  data-slot=\"live-line-chart-skeleton\"\n                  aria-hidden\n                  className={classes.skeleton()}\n                  style={{ left: box.x, width: box.width, top: box.y + box.height / 2 - 1, background: skeleton.base }}\n                />\n              ) : null}\n            </div>\n            {children}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n\n  return <LiveLineChartContext.Provider value={context}>{element}</LiveLineChartContext.Provider>;\n});\nLiveLineChartRoot.displayName = 'LiveLineChart';\n\nexport interface LiveLineChartGridProps {\n  /** How many bands the plot is divided into. Give it the same number as `YAxis`'s `ticks`. */\n  rows?: number;\n  /** The stroke's dash pattern. `\"none\"` for a solid rule. */\n  dashArray?: string;\n  /** Which of the theme's roles the lines are drawn in. Defaults to the border colour. */\n  color?: LiveLineChartColor;\n}\n\n/** The horizontal rules the readings are judged against. */\nfunction LiveLineChartGrid({\n  rows = 4,\n  dashArray = '4 6',\n  color,\n}: LiveLineChartGridProps) {\n  const { setSlot } = useChart('LiveLineChart.Grid');\n  const stroke = color ? COLOR_VAR[color] : 'var(--border)';\n  useEffect(() => {\n    setSlot('grid', { rows, dashArray, stroke });\n    return () => setSlot('grid', undefined);\n  }, [rows, dashArray, stroke, setSlot]);\n  return null;\n}\nLiveLineChartGrid.displayName = 'LiveLineChart.Grid';\n\nexport interface LiveLineChartLineProps {\n  /** The stroke's width. */\n  strokeWidth?: number;\n  /** Which of the theme's roles to draw in. Overrides the chart's colour, momentum included. */\n  color?: LiveLineChartColor;\n}\n\n/** The line. */\nfunction LiveLineChartLine({\n  strokeWidth = 2,\n  color,\n}: LiveLineChartLineProps) {\n  const { setSlot } = useChart('LiveLineChart.Line');\n  const stroke = color ? COLOR_VAR[color] : undefined;\n  useEffect(() => {\n    setSlot('line', { stroke, strokeWidth });\n    return () => setSlot('line', undefined);\n  }, [stroke, strokeWidth, setSlot]);\n  return null;\n}\nLiveLineChartLine.displayName = 'LiveLineChart.Line';\n\nexport interface LiveLineChartAreaProps {\n  /** Opacity at the top of the fill, fading to nothing at the bottom of the plot. */\n  opacity?: number;\n  /** Which of the theme's roles to draw in. Overrides the chart's colour, momentum included. */\n  color?: LiveLineChartColor;\n}\n\n/** The fill under the line, so a chart that wants only the shape simply does not have one. */\nfunction LiveLineChartArea({\n  opacity = 0.22,\n  color,\n}: LiveLineChartAreaProps) {\n  const { setSlot } = useChart('LiveLineChart.Area');\n  const fill = color ? COLOR_VAR[color] : undefined;\n  useEffect(() => {\n    setSlot('area', { fill, opacity });\n    return () => setSlot('area', undefined);\n  }, [fill, opacity, setSlot]);\n  return null;\n}\nLiveLineChartArea.displayName = 'LiveLineChart.Area';\n\nexport interface LiveLineChartTipProps {\n  /**\n   * Write the current reading in a badge beside the dot. Off by default, because a\n   * floating card nobody opened reads as a tooltip. Turn it on where the chart has\n   * no header to put the reading in.\n   */\n  badge?: boolean;\n  /** Ring the dot with a repeating pulse. Held while paused and under reduced motion. */\n  pulse?: boolean;\n  /** Format the badge. Defaults to a compact number. */\n  formatValue?: (value: number) => string;\n  /** Added to the badge's surface. */\n  className?: string;\n}\n\n/**\n * The dot at the leading end. It rides the newest reading and not the right-hand\n * edge, so a feed that stops is a dot drifting left with the rest of the line.\n */\nfunction LiveLineChartTip({\n  badge = false,\n  pulse = true,\n  formatValue,\n  className,\n}: LiveLineChartTipProps) {\n  const { setSlot } = useChart('LiveLineChart.Tip');\n  const format = useLatest(formatValue);\n  useEffect(() => {\n    setSlot('tip', { badge, pulse, className, format });\n    return () => setSlot('tip', undefined);\n  }, [badge, pulse, className, format, setSlot]);\n  return null;\n}\nLiveLineChartTip.displayName = 'LiveLineChart.Tip';\n\nexport interface LiveLineChartXAxisProps {\n  /** How many steps along the bottom. There is a label at each end of each one. */\n  ticks?: number;\n  /** Rewrites a label. Given how many seconds back the tick is. */\n  formatTick?: (secondsAgo: number) => string;\n}\n\n/**\n * How far back the plot reaches. The labels are offsets from now and never change:\n * a moving window labelled with clock times would rewrite every one of them on\n * every frame.\n */\nfunction LiveLineChartXAxis({\n  ticks = 4,\n  formatTick,\n}: LiveLineChartXAxisProps) {\n  const { setSlot } = useChart('LiveLineChart.XAxis');\n  const format = useLatest(formatTick);\n  useEffect(() => {\n    setSlot('xAxis', { ticks, format });\n    return () => setSlot('xAxis', undefined);\n  }, [ticks, format, setSlot]);\n  return null;\n}\nLiveLineChartXAxis.displayName = 'LiveLineChart.XAxis';\n\nexport interface LiveLineChartYAxisProps {\n  /** How many steps up the side. There is a label at each end of each one. */\n  ticks?: number;\n  /** Format a value. Defaults to a compact number. */\n  formatValue?: (value: number) => string;\n}\n\n/** The scale up the left-hand side, with room made for it. */\nfunction LiveLineChartYAxis({\n  ticks = 4,\n  formatValue,\n}: LiveLineChartYAxisProps) {\n  const { setSlot } = useChart('LiveLineChart.YAxis');\n  const format = useLatest(formatValue);\n  useEffect(() => {\n    setSlot('yAxis', { ticks, format });\n    return () => setSlot('yAxis', undefined);\n  }, [ticks, format, setSlot]);\n  return null;\n}\nLiveLineChartYAxis.displayName = 'LiveLineChart.YAxis';\n\nexport interface LiveLineChartTooltipProps {\n  /** Format the value. Defaults to a compact number. */\n  formatValue?: (value: number) => string;\n  /** Added to the readout's surface. */\n  className?: string;\n}\n\n/**\n * Hover, drag or use the arrow keys to read a reading that has already gone past.\n * The crosshair is pinned to the moment and not the place on screen, so it travels\n * left with the reading it named. Escape or moving away lets it go.\n */\nfunction LiveLineChartTooltip({\n  formatValue,\n  className,\n}: LiveLineChartTooltipProps) {\n  const { setSlot } = useChart('LiveLineChart.Tooltip');\n  const format = useLatest(formatValue);\n  useEffect(() => {\n    setSlot('tooltip', { className, format });\n    return () => setSlot('tooltip', undefined);\n  }, [className, format, setSlot]);\n  return null;\n}\nLiveLineChartTooltip.displayName = 'LiveLineChart.Tooltip';\n\nexport interface LiveLineChartSkeletonProps {\n  /** Which of the theme's roles the line is drawn in. Defaults to the muted colour. */\n  color?: LiveLineChartColor;\n}\n\n/** The waiting state: a flat line down the middle of the plot, shown while `status=\"loading\"`. */\nfunction LiveLineChartSkeleton({\n  color,\n}: LiveLineChartSkeletonProps) {\n  const { setSlot } = useChart('LiveLineChart.Skeleton');\n  const base = color && COLOR_VAR[color];\n  useEffect(() => {\n    setSlot('skeleton', { base });\n    return () => setSlot('skeleton', undefined);\n  }, [base, setSlot]);\n  return null;\n}\nLiveLineChartSkeleton.displayName = 'LiveLineChart.Skeleton';\n\nexport interface LiveLineChartHeaderProps extends Omit<ComponentProps<'div'>, 'title'> {\n  /** Small line above the value: what is being watched. */\n  title?: string;\n  /** The readout. Left out, it shows the current reading. */\n  value?: string;\n  /** One muted line under the value. */\n  caption?: ReactNode;\n  /** Format the derived value. Defaults to a compact number. */\n  formatValue?: (value: number) => string;\n  /** Trailing slot: a pause control, a badge, a unit. */\n  children?: ReactNode;\n}\n\n/**\n * The strip above the plot. The value falls back to the reading under the crosshair,\n * then to the latest one, so reading back through the window shows here with nothing\n * to wire up. It is hidden from a screen reader, which has the chart's snapshot.\n */\nfunction LiveLineChartHeader({\n  title,\n  value,\n  caption,\n  formatValue,\n  className,\n  children,\n  render,\n  ...props\n}: LiveLineChartHeaderProps & RenderProp<'div'>) {\n  const { setSlot, activePoint, latest } = useChart('LiveLineChart.Header');\n  const slots = liveLineChartVariants();\n  const format = useLatest(formatValue);\n  const shown = activePoint ?? latest;\n\n  useEffect(() => {\n    setSlot('header', { title, value, format });\n    return () => setSlot('header', undefined);\n  }, [title, value, format, setSlot]);\n\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'live-line-chart-header',\n        className: slots.header({ className }),\n        children: (\n          <>\n            <div aria-hidden className={slots.headerText()}>\n              {title ? <div className={slots.headerMuted()}>{title}</div> : null}\n              <div className={slots.headerValue()}>{value ?? (shown ? (formatValue ?? compactNumber)(shown.value) : '–')}</div>\n              {caption ? <div className={slots.headerMuted()}>{caption}</div> : null}\n            </div>\n            {children ? <div className={slots.headerTrailing()}>{children}</div> : null}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nLiveLineChartHeader.displayName = 'LiveLineChart.Header';\n\nexport const LiveLineChart = Object.assign(LiveLineChartRoot, {\n  Header: LiveLineChartHeader,\n  Grid: LiveLineChartGrid,\n  Area: LiveLineChartArea,\n  Line: LiveLineChartLine,\n  Tip: LiveLineChartTip,\n  XAxis: LiveLineChartXAxis,\n  YAxis: LiveLineChartYAxis,\n  Tooltip: LiveLineChartTooltip,\n  Skeleton: LiveLineChartSkeleton,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport {\n  LiveLineChartHeader,\n  LiveLineChartGrid,\n  LiveLineChartArea,\n  LiveLineChartLine,\n  LiveLineChartTip,\n  LiveLineChartXAxis,\n  LiveLineChartYAxis,\n  LiveLineChartTooltip,\n  LiveLineChartSkeleton,\n};\n"
    },
    {
      "path": "components/panelui/live-line-chart/live-line-accessibility.ts",
      "type": "registry:component",
      "target": "@components/panelui/live-line-chart/live-line-accessibility.ts",
      "content": "import type { LiveLineReading } from './live-line-lifecycle';\n\nexport interface LiveLineAccessibilityInput {\n  name?: string;\n  status: 'loading' | 'ready';\n  latest: LiveLineReading | null;\n  activePoint: LiveLineReading | null;\n  momentum: 'up' | 'down' | 'flat';\n  windowSeconds: number;\n  paused: boolean;\n  now: number;\n  valueOverride?: string;\n  formatLatest: (value: number) => string;\n  formatActive: (value: number) => string;\n}\n\n/** One bounded snapshot for a stream, rather than one node per arriving point. */\nexport function liveLineAccessibility({\n  name,\n  status,\n  latest,\n  activePoint,\n  momentum,\n  windowSeconds,\n  paused,\n  now,\n  valueOverride,\n  formatLatest,\n  formatActive,\n}: LiveLineAccessibilityInput): string {\n  const parts = [name?.trim() || 'Live line chart'];\n\n  if (status === 'loading' || !latest) {\n    parts.push(status === 'loading' ? 'Loading' : 'No readings');\n    if (paused) parts.push('Paused');\n    return parts.join('. ');\n  }\n\n  if (activePoint) {\n    const secondsAgo = Math.max(0, Math.round((now - activePoint.time) / 1000));\n    parts.push(`Selected value, ${formatActive(activePoint.value)}`);\n    parts.push(secondsAgo === 0 ? 'Just now' : `${secondsAgo} seconds ago`);\n  } else {\n    parts.push(`Current value, ${valueOverride ?? formatLatest(latest.value)}`);\n    parts.push(`Trend, ${momentum === 'up' ? 'rising' : momentum === 'down' ? 'falling' : 'steady'}`);\n  }\n\n  parts.push(`${windowSeconds}-second window`);\n  if (paused) parts.push('Paused');\n  return parts.join('. ');\n}\n"
    },
    {
      "path": "components/panelui/live-line-chart/live-line-lifecycle.ts",
      "type": "registry:component",
      "target": "@components/panelui/live-line-chart/live-line-lifecycle.ts",
      "content": "export interface LiveLineReading {\n  time: number;\n  value: number;\n}\n\nexport const DEFAULT_LIVE_LINE_WINDOW = 30;\nexport const DEFAULT_LIVE_LINE_MAX_POINTS = 500;\n\nexport function normalizeLiveLineWindow(seconds: number): number {\n  return Number.isFinite(seconds) && seconds > 0 ? Math.max(seconds, 1) : DEFAULT_LIVE_LINE_WINDOW;\n}\n\nexport function normalizeLiveLineMaxPoints(maxPoints: number): number {\n  return Number.isFinite(maxPoints) && maxPoints > 0 ? Math.max(1, Math.floor(maxPoints)) : DEFAULT_LIVE_LINE_MAX_POINTS;\n}\n\n/**\n * Builds the one ordered, finite buffer everything else reads. For duplicate\n * timestamps the last input wins, as a corrected reading replaces the one it\n * shares a time with.\n */\nexport function normalizeLiveLinePoints<T extends LiveLineReading>(data: readonly T[], maxPoints: number): T[] {\n  const byTime = new Map<number, T>();\n  for (const point of data) {\n    if (Number.isFinite(point.time) && Number.isFinite(point.value)) byTime.set(point.time, point);\n  }\n  return [...byTime.values()]\n    .sort((left, right) => left.time - right.time)\n    .slice(-normalizeLiveLineMaxPoints(maxPoints));\n}\n\n/** The clock runs only while something can see it move. */\nexport function liveLineClockRuns(options: {\n  paused: boolean;\n  loading: boolean;\n  reducedMotion: boolean;\n  visible: boolean;\n}): boolean {\n  return !options.paused && !options.loading && !options.reducedMotion && options.visible;\n}\n\n/** The same moment in a new buffer, or null once it has been trimmed away. */\nexport function reconcileLiveLineActivePoint<T extends LiveLineReading>(active: T | null, points: readonly T[]): T | null {\n  if (!active) return null;\n  return points.find((point) => point.time === active.time) ?? null;\n}\n\n/**\n * The value axis, from what is in the window and not everything kept: a spike\n * that has scrolled off should stop holding the axis open.\n */\nexport function liveLineExtent(points: readonly LiveLineReading[], from: number): [number, number] {\n  let min = Infinity;\n  let max = -Infinity;\n  for (const point of points) {\n    if (point.time < from) continue;\n    if (point.value < min) min = point.value;\n    if (point.value > max) max = point.value;\n  }\n  if (min === Infinity) return [0, 1];\n  if (min === max) return [min - 1, max + 1];\n  const headroom = (max - min) * 0.12;\n  return [min - headroom, max + headroom];\n}\n\n/** Where the last few readings have been going, as a share of the axis. */\nexport function liveLineMomentum(points: readonly LiveLineReading[], extent: [number, number]): 'up' | 'down' | 'flat' {\n  if (points.length < 2) return 'flat';\n  const recent = points.slice(-6);\n  const span = Math.abs(extent[1] - extent[0]) || 1;\n  const change = (recent[recent.length - 1]!.value - recent[0]!.value) / span;\n  return change > 0.04 ? 'up' : change < -0.04 ? 'down' : 'flat';\n}\n\n/**\n * The readings to draw. The run starts one reading before the window, so the line\n * enters from the edge instead of beginning wherever the oldest survivor sits; the\n * plot's clip hides the overhang. It stops at the window's end, which a paused\n * chart is behind.\n */\nexport function liveLineRun<T extends LiveLineReading>(points: readonly T[], xMin: number, xMax: number): readonly T[] {\n  let start = 0;\n  let end = 0;\n  for (const point of points) {\n    if (point.time > xMax) break;\n    end += 1;\n    if (point.time < xMin) start = end - 1;\n  }\n  return points.slice(start, end);\n}\n\n/** The reading the leading dot rides: the newest on the plot, or null if the feed stopped too long ago. */\nexport function newestOnPlot<T extends LiveLineReading>(points: readonly T[], xMin: number, xMax: number): T | null {\n  for (let index = points.length - 1; index >= 0; index -= 1) {\n    const point = points[index]!;\n    if (point.time <= xMax) return point.time >= xMin ? point : null;\n  }\n  return null;\n}\n\n/** The readings inside the plot's window: the only ones a pointer or a key can read. */\nexport function liveLineOnPlot<T extends LiveLineReading>(points: readonly T[], xMin: number, xMax: number): T[] {\n  return points.filter(({ time }) => time >= xMin && time <= xMax);\n}\n\n/** The reading nearest a moment, which on a feed with gaps is not the nearest on screen. */\nexport function nearestReading<T extends LiveLineReading>(points: readonly T[], at: number): T | null {\n  let best: T | null = null;\n  let bestGap = Infinity;\n  for (const point of points) {\n    const gap = Math.abs(point.time - at);\n    if (gap < bestGap) {\n      bestGap = gap;\n      best = point;\n    }\n  }\n  return best;\n}\n"
    }
  ]
}
