017 / RECHARTS / AREA

Baseline Area

Recharts

Single-series area visualization showing values above and below an explicit quantitative reference baseline with truthful deviation semantics.

SPEC
#017
ENGINE
Recharts
FAMILY
Area
RENDERER
svg
STATUS
preview

Installation

PLOTCN/REGISTRY/AREA-BASELINE/SOURCE
pnpm dlx shadcn@latest add @plotcn/area-baseline

Checking public registry…

View local registry JSON
REGISTRY direct URL·ENGINE Recharts·FILES 1·DEPENDENCIES 5

Copied as source into your project (requires recharts).

× 340Container width
Measuring preview...
RECHARTS · SVG · 0 × 340pxMotion enabled · ResizeObserver

Overview

Baseline Area is the deviation-specialized chart of the Plotcn Area family. It partitions a single quantitative series across an ordered domain relative to an explicit reference baseline, visually highlighting positive and negative deviations with truthful occupied area fills.

The primary analytical question answered by Baseline Area is:

"How far is this value above or below the configured reference, and where does the signal cross?"

The defining mathematical relationship is:

deviation(x)=value(x)baseline\text{deviation}(x) = \text{value}(x) - \text{baseline}

Unlike generic area charts that silently default to zero or fabricate split datasets, Baseline Area requires an explicit baseline reference, preserves original observation values as canonical data, and derives deviations factually without imposing judgmental "good" or "bad" business labels.

TSX
import { BaselineArea } from "@/components/charts/recharts/area-baseline"const utilizationData = [  { day: "Day 01", utilization: 68 },  { day: "Day 03", utilization: 72 },  { day: "Day 05", utilization: 84 },  { day: "Day 07", utilization: 89 },  { day: "Day 09", utilization: 79 },  { day: "Day 11", utilization: 75 },  { day: "Day 13", utilization: 66 },  { day: "Day 15", utilization: 61 },  { day: "Day 17", utilization: 74 },  { day: "Day 19", utilization: 82 },  { day: "Day 21", utilization: 88 },  { day: "Day 23", utilization: 77 },  { day: "Day 25", utilization: 71 },  { day: "Day 27", utilization: 67 },  { day: "Day 29", utilization: 75 },  { day: "Day 30", utilization: 83 },]export function ResourceUtilizationTracker() {  return (    <BaselineArea      data={utilizationData}      xKey="day"      series={{        key: "utilization",        label: "Resource Utilization",        valueFormatter: (v) => `${v}%`,      }}      baseline={75}      baselineLabel="Target SLA"      aboveLabel="Above SLA"      belowLabel="Below SLA"      aboveColor="var(--chart-1)"      belowColor="var(--chart-2)"      showGrid      showDeviation    />  )}

Area-Family Positioning

The Plotcn Area family provides specialized analytical instruments:

Consideration Prism Area (011) Threshold Line (008) Comparison Area (015) Gradient Depth Area (016) Baseline Area (017)
ConsiderationPrism Area (011)Threshold Line (008)Comparison Area (015)Gradient Depth Area (016)Baseline Area (017)
Primary Question"How much magnitude relative to baseline?""Where does signal cross boundary limits?""How does primary compare to reference series?""How does magnitude change with surface depth?""How far above or below the explicit baseline is the value?"
Fill GeometryUniform fill down to baselineNo filled volume (line stroke only)Dual overlapping series fillsSemantic opacity fade (32% → 2%)Dual-region continuous fill partitioned at baseline
Series RolesSingle seriesSingle signal + boundary linesExactly two: Primary & ReferenceSingle quantitative seriesSingle signal + required reference baseline
Baseline RequirementOptional (y=0y = 0 or domain min)Contextual threshold linesShared area baselineBaseline anchor (y=0y = 0 or min)Strictly required constant baseline (bRb \in \mathbb{R})
Color SemanticsOne series colorSignal color + threshold colorDistinct primary vs reference colorsSingle color driving stroke & gradientSignal stroke + aboveColor + belowColor + baselineColor

Baseline Area vs Threshold Line (008)

  • Threshold Line: Best when the signal curve is the primary focus and horizontal thresholds serve as secondary context or warning limits.
  • Baseline Area: Best when the occupied space above and below the reference is the primary analytical message. The filled volume makes the cumulative duration and severity of deviations immediately visible.

Baseline Area vs Prism Area (011)

  • Prism Area: Treats the baseline as a passive structural floor (conventionally zero). All observations are displayed as a continuous positive volume.
  • Baseline Area: Treats the baseline as an active evaluation reference. Observations above the reference fill downward toward it, while observations below the reference fill upward toward it.

Baseline Model

The Baseline Area evaluation model classifies each observation into one of three factual mathematical states:

SEMANTIC MODELComponent 017 · Baseline Area

Factual Classification Around an Explicit Reference Baseline

Above (deviation > 0)
Baseline (ref = 75)
Below (deviation < 0)
Baseline Area classification modelValues above the configured baseline use the above treatment, values below use the below treatment, and exact values meet the baseline without additional deviation.Baseline (y = 75)Observation: 89%Deviation: +14% (Above)Exact Baseline (0 dev)Observation: 61%Deviation: -14% (Below)Formula: deviation = value - baseline · Above: deviation > 0 · Equal: deviation === 0 · Below: deviation < 0
Core Guarantee: Deviation is computed factually from the explicit reference. Colors indicate relative spatial position, never favorable/unfavorable business judgment.
Original values remain canonical
  1. Above Reference (value>baseline\text{value} > \text{baseline}): The observation exceeds the reference baseline. The area polygon fills downward to the baseline using aboveColor. Deviation is strictly positive.
  2. Exact Baseline (value=baseline\text{value} = \text{baseline}): The observation lands precisely on the reference baseline. Area thickness at this coordinate is zero; deviation is $0$.
  3. Below Reference (value<baseline\text{value} < \text{baseline}): The observation falls below the reference baseline. The area polygon fills upward to the baseline using belowColor. Deviation is strictly negative.
Visual Invariant: Classification is strictly relative to the explicit baseline, never mathematical zero. An observation of +80+80 against a baseline of $100$ is below reference (deviation 20-20), while an observation of 80-80 against a baseline of 100-100 is above reference (deviation +20+20).

Above & Below Semantics

Plotcn separates spatial position from moral or business judgment:

  • Above Does Not Mean "Good": In metrics such as server latency, error rate, memory consumption, or defect count, exceeding a baseline represents degraded performance.
  • Below Does Not Mean "Bad": In costs, wait times, or churn rates, falling below a reference baseline represents favorable outcomes.
  • Semantic Neutrality: aboveColor defaults to var(--chart-1) and belowColor defaults to var(--chart-2). Developers can explicitly configure custom colors when their business domain warrants green/red polarity.

Crossing Behavior

In real continuous signals, the trajectory crosses the reference baseline between discrete sample intervals. Plotcn implements continuous vertical Y-axis segmentation:

CROSSING GEOMETRYContinuous Y Segmentation

Color Transitions Precisely at the Interpolated Baseline Intersection

Sample Nodes (A & B)
Crossing Point (C)
Baseline crossing interpolation diagramDemonstrates that the boundary between aboveColor and belowColor occurs at the exact continuous Y intersection point C along the baseline, rather than switching abruptly at discrete sample indices.Baseline Reference (y = 75)Sample A (May 14)value = 65% (< 75)Intersection Point CExact fill color boundarySample B (May 15)value = 87% (> 75)belowColor regionaboveColor region
Rendering Guarantee: A baseline-aligned hard-stop SVG gradient colors geometry continuously by its vertical plot coordinate. Colors never toggle at discrete X columns.
Continuous Y-scale hard stop
  • Continuous Y Segmentation: A single continuous SVG Area geometry is filled with an SVG <linearGradient> with a sharp stop transition aligned to the exact baseline coordinate.
  • True Interpolated Crossing: The color boundary between aboveColor and belowColor occurs at the exact mathematical crossing point CC along the horizontal baseline line.
  • Zero Artifacts: Crossings do not toggle abruptly by discrete X columns or create jagged polygon seams.

Rendering Architecture

Baseline Area is built purely on top of Recharts and native SVG primitives, guaranteeing zero dependencies on D3, Canvas, or WebGL:

ARCHITECTURERendering Pipeline

Source-First Recharts SVG Rendering Pipeline

O(1) Gradient · Zero Data Duplication
Baseline Area rendering architectureDiagram illustrating the step-by-step pipeline from consumer data and required baseline to validation, safe domain calculation, hard-stop linearGradient generation, and synchronized inspection.1. Consumer Inputsdata: readonly TData[]baseline: number (req)2. Data ValidationFinite baseline checkSanitize NaN/Infinity3. Scale & Gradient Offsetdomain = [min, max + pad]offset = (max-base)/(max-min)4. SVG Hard-Stop Defs0% .. offset% : aboveColoroffset% .. 100% : belowColor5. Recharts Area Chart<Area baseValue={baseline} /><ReferenceLine y={baseline} />6. Inspection Layervalue, baseline, deviationLockable tooltip & A11yPerformance Invariant:Only 1 linearGradient is generated per chart instance. Crossings are continuous SVG geometry without cutting or modifying original consumer observation records.
Pure SVG Pipeline: Free from D3, Canvas, or WebGL dependencies. Directly compatible with React Server Components and Next.js Turbopack.
Registry Component: area-baseline
  1. Consumer Inputs & Validation: Validates that baseline is an explicit finite number. Non-finite data (NaN, Infinity) is normalized to null.
  2. Safe Domain & Baseline Offset: Automatic Y-domain expands to enclose both the dataset range and the baseline. The normalized gradient stop offset is calculated as maxbaselinemaxmin\frac{\text{max} - \text{baseline}}{\text{max} - \text{min}}.
  3. Hard-Stop Linear Gradient: Constructs an SSR-safe <linearGradient> with a deterministic collision-free ID.
  4. Recharts Area & ReferenceLine: Renders <Area baseValue={baseline} fill="url(#id)" stroke={color} /> alongside a subtle dashed <ReferenceLine y={baseline} stroke={baselineColor} />.
  5. Nearest-X Inspection: Provides synchronized tooltips displaying original observed values, reference baseline, and signed deviation (±\pm).

Data Contract

Baseline Area consumes sequential records with an ordered domain key and a single quantitative metric:

Field Type Required Meaning
FieldTypeRequiredMeaning
[xKey]string | DateRequiredOrdered horizontal domain coordinate (day, month, timestamp).
[series.key]number | nullRequiredObserved quantitative metric value.
baselinenumberRequiredExplicit constant reference baseline (prop, not data field).
TypeScript
interface BaselineAreaDatum {  day: string  utilization: number | null}

Series Contract

TypeScript
interface BaselineAreaSeries<TData> {  /** Property key on data records for quantitative values */  key: NumericKeyOf<TData>  /** Human-readable label for tooltip and screen readers */  label: string  /** Optional custom numeric formatter */  valueFormatter?: (value: number) => string}

Color Semantics

The component enforces a clean, multi-token color hierarchy:

  • Signal Stroke (color): Preserves the continuous identity of the quantitative signal across the domain. Defaults to var(--chart-1).
  • Above Region (aboveColor): Applied to occupied area above the baseline. Defaults to var(--chart-1).
  • Below Region (belowColor): Applied to occupied area below the baseline. Defaults to var(--chart-2).
  • Reference Line (baselineColor): Applied to the constant horizontal reference line and label. Defaults to var(--chart-axis).
  • Active Selection (selectionColor): Applied to persistent locked crosshair indicator. Defaults to var(--chart-selection).
03 / Component API & Styling

Props Reference & Interactive Prop Explorer

Inspect every component property, customize semantic color roles live with instant visual feedback, and copy production-ready code with active prop configurations.

Colors & Appearance Configuration

Customize primary, reference, or annotation series colors. Defaults derive from Plotcn theme tokens.

Generated Usage Code (Live Props):
<BaselineArea
  data={data}
  xKey="date"
  seriesKey="value"
/>
Interactive Prop Preview Lab
baselinenumber

Explicit constant reference baseline. Strictly required and validated as finite (never defaults to zero).

Select value to preview live:
Active: baseline={75}Default:
curve"monotone" | "linear" | "step"

Interpolation curve applied to the signal boundary stroke and filled area geometry.

Select value to preview live:
Active: curve="monotone"Default: "monotone"
fillOpacitynumber

Fill opacity applied to both above and below occupied area regions.

Select value to preview live:
Active: fillOpacity={0.24}Default: 0.24
showGridboolean

Whether to render subtle horizontal Cartesian grid reference lines.

Select value to preview live:
Active: showGrid={true}Default: true
showLegendboolean

Whether to render above/below/baseline status indicator legend.

Select value to preview live:
Active: showLegend={false}Default: false
showDeviationboolean

Whether to derive and display signed arithmetic deviation in inspection tooltips.

Select value to preview live:
Active: showDeviation={true}Default: true
lockableTooltipboolean

Enables persistent inspection pinning on click or keyboard Enter/Space.

Select value to preview live:
Active: lockableTooltip={true}Default: true
missingValuePolicy"gap" | "connect"

Policy for missing data: "gap" preserves truthful breaks; "connect" bridges across gaps.

Select value to preview live:
Active: missingValuePolicy="gap"Default: "gap"
motionboolean | { duration?: number }

Enables entrance path animation. Automatically bypassed when prefers-reduced-motion is active.

Select value to preview live:
Active: motion={true}Default: true
All Properties (24)
Component properties
PropertyTypeDefaultRequiredDescription
dataReq
readonly TData[][]Yes

Readonly array of observation records. Caller data is never mutated or reordered.

xKeyReq
keyof TData & stringYes

Property name on data records representing the horizontal domain coordinate.

BaselineAreaSeries<TData>Yes

Single quantitative series configuration defining metric key, label, and valueFormatter.

numberYes

Explicit constant reference baseline. Strictly required and validated as finite (never defaults to zero).

string"Reference"No

Human-readable label for the reference line (e.g. Target, SLA, Budget, Baseline).

string"Above reference"No

Label for observations exceeding the baseline (communicates position, not business outcome).

string"Below reference"No

Label for observations falling below the baseline (communicates position, not business outcome).

number | string320No

Container height in pixels or standard CSS dimension string.

"monotone" | "linear" | "step""monotone"No

Interpolation curve applied to the signal boundary stroke and filled area geometry.

[number, number] | "auto""auto"No

Explicit Y-axis numeric domain bounds, or "auto" to safely enclose both data and baseline.

stringvar(--chart-1)No

Primary signal stroke and active observation marker color.

stringvar(--chart-1)No

Area fill color for observations exceeding the reference baseline.

stringvar(--chart-2)No

Area fill color for observations falling below the reference baseline.

stringvar(--chart-axis)No

Stroke color for the constant horizontal reference baseline line.

stringvar(--chart-selection)No

Color for locked inspection crosshair reference line.

number0.24No

Fill opacity applied to both above and below occupied area regions.

booleantrueNo

Whether to render subtle horizontal Cartesian grid reference lines.

booleantrueNo

Whether to render horizontal domain tick labels.

booleantrueNo

Whether to render vertical metric scale ticks.

booleanfalseNo

Whether to render above/below/baseline status indicator legend.

booleantrueNo

Whether to derive and display signed arithmetic deviation in inspection tooltips.

booleantrueNo

Enables persistent inspection pinning on click or keyboard Enter/Space.

"gap" | "connect""gap"No

Policy for missing data: "gap" preserves truthful breaks; "connect" bridges across gaps.

boolean | { duration?: number }trueNo

Enables entrance path animation. Automatically bypassed when prefers-reduced-motion is active.

04 / Cookbook & States

Component Variants & Edge States

Production cookbooks showcasing configuration variants alongside verified handling of loading, empty data, and network error states.

Utilization vs 75% Target Baseline

Standard single-series resource utilization tracking positive and negative deviations from an explicit 75% reference target.

<BaselineArea
  data={utilizationData}
  xKey="day"
  series={{
    key: "utilization",
    label: "Resource Utilization",
    valueFormatter: (v) => `${v}%`,
  }}
  baseline={75}
  baselineLabel="Target SLA"
  aboveLabel="Above SLA"
  belowLabel="Below SLA"
  showGrid
  showDeviation
/>

Frequent Reference Crossings

Validates continuous vertical Y segmentation when data oscillates frequently above and below the reference baseline.

<BaselineArea
  data={crossingData}
  xKey="day"
  series={{
    key: "utilization",
    label: "Resource Utilization",
    valueFormatter: (v) => `${v}%`,
  }}
  baseline={75}
  curve="monotone"
  fillOpacity={0.3}
  showGrid
/>

Zero Baseline (Positive/Negative)

Explicit baseline={0} anchor demonstrating truthful handling of mathematical zero without collapsing negative values.

<BaselineArea
  data={growthData}
  xKey="month"
  series={{
    key: "growth",
    label: "Net Growth",
    valueFormatter: (v) => `${v}%`,
  }}
  baseline={0}
  baselineLabel="Zero Growth"
  aboveLabel="Positive Growth"
  belowLabel="Contraction"
  showGrid
/>

Linear Interpolation with Exact Crossings

Piecewise linear segments demonstrating deterministic vertex alignment and exact baseline intersection geometry.

<BaselineArea
  data={utilizationData}
  xKey="day"
  series={{
    key: "utilization",
    label: "Resource Utilization",
  }}
  baseline={75}
  curve="linear"
  showGrid
/>

Status Legend Enabled

Displays structural sample swatches for Above Reference, Below Reference, and the Reference Baseline.

<BaselineArea
  data={utilizationData}
  xKey="day"
  series={{
    key: "utilization",
    label: "Resource Utilization",
  }}
  baseline={75}
  showLegend
  showGrid
/>
Lifecycle & Exception States
01. Loading State

Skeletons indicate runtime fetch or pending data queries.

02. Empty Data State

Handles empty collections ([]) gracefully without crashing.

03. Error State

Graceful failure banner when data source or script fails.

05 / Responsive Lab

Container-Driven Breakpoints

Baseline Area preserves the constant horizontal reference baseline, continuous above/below segmentation, and nearest-X inspection across all viewport dimensions down to 320px.

Desktop
>= 1024px

Spacious Cartesian grid, full domain tick density, inline baseline label annotations, and detailed inspection card.

Tablet
640px - 1023px

Adaptive domain tick thinning, preserved reference line geometry, and compact inspection gutters.

Mobile
< 640px

Compact gutters, touch-forgiving nearest-X scrubbing, truthful missing breaks, and uncompromised continuous Y color segmentation.

Tablet Preview (768px Container Constraint)
Mobile Preview (390px Container Constraint)

Accessibility & Data Safety

  • One Tab Stop: Root figure is keyboard-focusable with comprehensive shortcuts:
    • ArrowLeft / ArrowRight: Navigate chronological observations.
    • Home / End: Jump to first / last observation.
    • Enter / Space: Pin or unpin persistent tooltip inspection.
    • Escape: Dismiss locked inspection.
  • Off-Screen Structured Table: Accessible <table className="sr-only"> presents raw values, baseline reference, deviation arithmetic, and relative position classification to screen readers.
  • Factual Narration: Screen reader captions state deviations factually without editorializing (e.g. "7 units above reference", not "Performance good").
  • Reduced Motion: Entrance reveal animations immediately bypass when prefers-reduced-motion is active.
06 / Assistive Technology

Accessibility & Navigation Standards

Single keyboard tab stop on root figure with ArrowLeft, ArrowRight, Home, End, Enter/Space, and Escape shortcuts. Structured data table provided for assistive technologies.

Semantic Role & Landmark

Container mounts as region with explicit assistive label.

Color-Independent Legibility

Reference line geometry, active dot marker, signed +/- deviation readout, and structured offscreen HTML table ensure complete non-color accessibility.

Screen Reader Summary

Embeds visually hidden summary (.sr-only) declaring: “Announces domain coordinate, observed value, reference baseline, and signed deviation. Classifications are narrated factually without business value judgments.

Reduced Motion Support

All entrance animations immediately bypass when prefers-reduced-motion is detected in user system preferences.

Keyboard Interaction Model
Keyboard interaction model
KeyAction
ArrowRightInspect next chronological observation across the domain.
ArrowLeftInspect previous chronological observation across the domain.
HomeJump inspection directly to the first observation.
EndJump inspection directly to the final observation.
Enter / SpaceLock or unlock persistent inspection at the active coordinate.
EscapeRelease locked selection and dismiss active inspection tooltip.

Data Safety Guarantees

  • ✓ Baseline is explicit and never silently assumed to be zero
  • ✓ Baseline is constant and finite in V1
  • ✓ Automatic domain always encloses the reference baseline
  • ✓ Explicit domain is respected without clamping the baseline
  • ✓ Values are classified relative to baseline, not zero
  • ✓ Positive raw values can be below baseline; negative raw values can be above baseline
  • ✓ Exact-baseline values remain exact with zero deviation
  • ✓ Missing values never collapse into baseline values
  • ✓ Zero remains a valid observation
  • ✓ Non-finite values (NaN, Infinity) never reach SVG geometry
  • ✓ Caller data is never mutated
07 / Source Anatomy

Internal Architecture & File Dependencies

Source-first ownership model. Inspect the exact component call tree, dependencies, and full implementation below.

Component Architecture Call Tree
BaselineArea(Root figure element with keyboard navigation and ARIA accessibility shell)
├──ResponsiveContainer[Responsive container wrapper]

Handles container dimension measurement and SVG viewBox sizing

├──AreaChart[Recharts Cartesian SVG coordinator]

Coordinates scales, Cartesian grid, defs linearGradient, Area geometry, and ReferenceLine

└──BaselineAreaLegend[Status indicator legend]

Displays above, below, and baseline reference swatches

Involved Source Files & Registry Assets
registry/recharts/area-baseline.tsx
Complete Baseline Area component with explicit reference baseline, hard-stop continuous fill, and nearest-X inspection
registry/recharts/area-baseline.tsx
"use client"import * as React from "react"import {  ResponsiveContainer,  AreaChart,  Area,  XAxis,  YAxis,  Tooltip,  CartesianGrid,  ReferenceLine,} from "recharts"import { HugeiconsIcon } from "@hugeicons/react"import { LockKeyIcon } from "@hugeicons/core-free-icons"import { useChartReducedMotion } from "../shared/use-chart-reduced-motion"import { ChartContainer } from "../shared/chart-container"import {  ChartLoadingState,  ChartEmptyState,  ChartErrorState,  ChartUnavailableState,} from "../shared/chart-state"import { cn } from "@/lib/utils"/* -------------------------------------------------------------------------- *//*  Type Definitions                                                          *//* -------------------------------------------------------------------------- */export type NumericKeyOf<TData> = [keyof TData] extends [never]  ? string  : {      [K in keyof TData]: TData[K] extends number | null | undefined ? K : never    }[keyof TData] extends never  ? string  : {      [K in keyof TData]: TData[K] extends number | null | undefined ? K : never    }[keyof TData] & stringexport type BaselineClassification = "above" | "equal" | "below"/** * Series definition for Baseline Area (single quantitative series relative to explicit baseline). */export interface BaselineAreaSeries<TData extends Record<string, unknown> = Record<string, unknown>> {  /** Property key for quantitative observation values */  key: NumericKeyOf<TData>  /** Human-readable display label for legend, tooltips, and screen readers */  label: string  /** Optional custom numeric formatter for metric values */  valueFormatter?: (value: number) => string}export interface BaselineAreaActiveDatum<  TData extends Record<string, unknown> = Record<string, unknown>,  XVal extends string | number = string | number> {  index: number  x: XVal  raw: TData  value: number | null  baseline: number  deviation: number | null  position: BaselineClassification | "unavailable"  isLocked: boolean}export interface BaselineAreaProps<  TData extends Record<string, unknown> = Record<string, unknown>,  XVal extends string | number = string | number> {  /** Readonly array of observation records. Caller data is never mutated. */  data: readonly TData[]  /** Key for horizontal domain coordinate (e.g. date, month, hour). */  xKey: keyof TData & string  /** Semantic series descriptor defining metric key and label. */  series: BaselineAreaSeries<TData>  /**   * Explicit constant reference baseline value.   * REQUIRED: Plotcn never silently defaults to zero.   */  baseline: number  /** Optional label for the reference baseline (e.g. "Target", "SLA", "Benchmark"). */  baselineLabel?: string  /** Optional label for values exceeding the baseline. (default: "Above reference") */  aboveLabel?: string  /** Optional label for values below the baseline. (default: "Below reference") */  belowLabel?: string  /** Container height in pixels or CSS dimension string. (default: 320) */  height?: number | string  /** Curve interpolation: "monotone" | "linear" | "step". (default: "monotone") */  curve?: "monotone" | "linear" | "step"  /** Explicit Y-axis numeric domain, or "auto" calculation. */  domain?: [number, number] | "auto"  /** Primary signal stroke and active point color. (default: "var(--chart-1, #3b82f6)") */  color?: string  /** Fill color for occupied area above the baseline. (default: "var(--chart-1, #3b82f6)") */  aboveColor?: string  /** Fill color for occupied area below the baseline. (default: "var(--chart-2, #10b981)") */  belowColor?: string  /** Reference baseline stroke and indicator color. (default: "var(--chart-axis, #71717a)") */  baselineColor?: string  /** Active selection / crosshair highlight color. (default: "var(--chart-selection, #38bdf8)") */  selectionColor?: string  /** Fill opacity for above and below occupied regions. (default: 0.24) */  fillOpacity?: number  /** Whether to render subtle horizontal grid reference lines. (default: true) */  showGrid?: boolean  /** Whether to render horizontal domain tick labels. (default: true) */  showXAxis?: boolean  /** Whether to render vertical metric scale ticks. (default: true) */  showYAxis?: boolean  /** Whether to render above/below/baseline status legend. (default: false) */  showLegend?: boolean  /** Whether to derive and display signed deviation in the inspection tooltip. (default: true) */  showDeviation?: boolean  /** Whether to allow locking tooltip inspection on click or Enter/Space. (default: true) */  lockableTooltip?: boolean  /** Handling of missing/null values: "gap" (truthful break) | "connect" (bridge). (default: "gap") */  missingValuePolicy?: "gap" | "connect"  /** Motion preferences. (default: true) */  motion?: boolean | { duration?: number }  /** Initial inspection lock index. */  defaultLockedIndex?: number | null  /** Callback fired when the active inspection datum changes. */  onActiveChange?: (active: BaselineAreaActiveDatum<TData, XVal> | null) => void  /** Optional custom title announced to assistive technology. */  title?: string  /** Optional extended description for assistive technology. */  description?: string  /** Explicit loading state fallback. */  loading?: boolean  /** Explicit empty state fallback. */  empty?: boolean  /** Explicit error state fallback. */  error?: string | Error  /** Explicit unavailable state fallback. */  unavailable?: boolean  /** Additional CSS class for outer container figure. */  className?: string}/* -------------------------------------------------------------------------- *//*  Pure Mathematical Helpers                                                 *//* -------------------------------------------------------------------------- *//** * Factual classification of an observed numeric value relative to an explicit baseline. * Does not assign judgmental "good/bad" value labels. */export function classifyAgainstBaseline(  value: number,  baseline: number): BaselineClassification {  if (value > baseline) return "above"  if (value < baseline) return "below"  return "equal"}/** * Normalizes input records into clean numeric data. * Clamps or sanitizes non-finite values to null to protect SVG geometry. */export function normalizeBaselineData<TData extends Record<string, unknown>>(  data: readonly TData[],  key: string): Array<TData & { _normalizedValue: number | null }> {  if (!Array.isArray(data)) return []  return data.map((item) => {    if (!item || typeof item !== "object") {      return { ...item, _normalizedValue: null }    }    const val = item[key]    const num = typeof val === "number" && Number.isFinite(val) ? val : null    return {      ...item,      _normalizedValue: num,    }  })}/** * Computes a safe Y-domain enclosing all valid series observations AND the explicit baseline. */export function calculateBaselineAreaDomain<TData extends Record<string, unknown>>(  data: ReadonlyArray<TData & { _normalizedValue: number | null }>,  baseline: number,  explicitDomain?: [number, number] | "auto"): [number, number] {  if (    Array.isArray(explicitDomain) &&    explicitDomain.length === 2 &&    typeof explicitDomain[0] === "number" &&    typeof explicitDomain[1] === "number" &&    Number.isFinite(explicitDomain[0]) &&    Number.isFinite(explicitDomain[1])  ) {    return [explicitDomain[0], explicitDomain[1]]  }  const validValues = data    .map((d) => d._normalizedValue)    .filter((v): v is number => typeof v === "number" && Number.isFinite(v))  if (validValues.length === 0) {    if (Number.isFinite(baseline)) {      return [baseline - 10, baseline + 10]    }    return [0, 100]  }  const rawMin = Math.min(...validValues, baseline)  const rawMax = Math.max(...validValues, baseline)  if (rawMin === rawMax) {    const pad = Math.abs(rawMin) > 0 ? Math.abs(rawMin) * 0.15 : 10    return [Number((rawMin - pad).toFixed(2)), Number((rawMax + pad).toFixed(2))]  }  const span = rawMax - rawMin  const padding = span * 0.08  return [    Number((rawMin - padding).toFixed(2)),    Number((rawMax + padding).toFixed(2)),  ]}/** * Computes normalized vertical offset (0.0 to 1.0) of the baseline within the Area polygon's bounding box. * The polygon's top is Math.max(baseline, ...values) (y=0 in objectBoundingBox), * and its bottom is Math.min(baseline, ...values) (y=1 in objectBoundingBox). */export function calculateBaselineGradientOffset(  min: number,  max: number,  baseline: number): number {  if (!Number.isFinite(min) || !Number.isFinite(max) || !Number.isFinite(baseline)) {    return 0.5  }  if (max === min) {    return 0.5  }  const offset = (max - baseline) / (max - min)  return Math.max(0, Math.min(1, offset))}/* -------------------------------------------------------------------------- *//*  Main Component: BaselineArea                                              *//* -------------------------------------------------------------------------- */export function BaselineArea<  TData extends Record<string, unknown> = Record<string, unknown>,  XVal extends string | number = string | number>({  data = [],  xKey,  series,  baseline,  baselineLabel = "Reference",  aboveLabel = "Above reference",  belowLabel = "Below reference",  height = 320,  curve = "monotone",  domain = "auto",  color = "var(--chart-1, #3b82f6)",  aboveColor = "var(--chart-1, #3b82f6)",  belowColor = "var(--chart-2, #10b981)",  baselineColor = "var(--chart-axis, #71717a)",  selectionColor = "var(--chart-selection, #38bdf8)",  fillOpacity = 0.24,  showGrid = true,  showXAxis = true,  showYAxis = true,  showLegend = false,  showDeviation = true,  lockableTooltip = true,  missingValuePolicy = "gap",  motion = true,  defaultLockedIndex = null,  onActiveChange,  title = "Baseline Area Chart",  description,  loading = false,  empty = false,  error,  unavailable = false,  className,}: BaselineAreaProps<TData, XVal>) {  // 1. Validate explicit baseline requirement  const isBaselineValid = typeof baseline === "number" && Number.isFinite(baseline)  // 2. Reduced motion detection  const prefersReducedMotion = useChartReducedMotion()  const isMotionEnabled = motion !== false && !prefersReducedMotion  // 3. Normalize dataset  const normalizedData = React.useMemo(() => {    return normalizeBaselineData(data, series.key)  }, [data, series.key])  // 4. Safe Y domain enclosing both data and baseline  const safeDomain = React.useMemo(() => {    if (!isBaselineValid) return [0, 100] as [number, number]    return calculateBaselineAreaDomain(normalizedData, baseline, domain)  }, [normalizedData, baseline, domain, isBaselineValid])  // 5. Data range for polygon bounding box  const polygonBounds = React.useMemo(() => {    if (!isBaselineValid) return { min: 0, max: 100 }    const validValues = normalizedData      .map((d) => d._normalizedValue)      .filter((v): v is number => typeof v === "number" && Number.isFinite(v))    if (validValues.length === 0) {      return { min: baseline, max: baseline }    }    return {      min: Math.min(...validValues, baseline),      max: Math.max(...validValues, baseline),    }  }, [normalizedData, baseline, isBaselineValid])  // 6. Hard-stop gradient offset calculation  const baselineOffset = React.useMemo(() => {    if (!isBaselineValid) return 0.5    return calculateBaselineGradientOffset(polygonBounds.min, polygonBounds.max, baseline)  }, [polygonBounds.min, polygonBounds.max, baseline, isBaselineValid])  const offsetPercent = React.useMemo(() => {    return Number((baselineOffset * 100).toFixed(3))  }, [baselineOffset])  // 7. SSR-safe deterministic gradient and clip IDs  const rawId = React.useId()  const gradientId = React.useMemo(    () => `plotcn-baseline-${rawId.replace(/[^a-zA-Z0-9_-]/g, "")}`,    [rawId]  )  // 8. Opacity clamping  const clampedOpacity = Math.max(    0,    Math.min(1, typeof fillOpacity === "number" && Number.isFinite(fillOpacity) ? fillOpacity : 0.24)  )  // 9. Inspection state  const [lockedIndex, setLockedIndex] = React.useState<number | null>(() => {    if (      typeof defaultLockedIndex === "number" &&      defaultLockedIndex >= 0 &&      defaultLockedIndex < normalizedData.length    ) {      return defaultLockedIndex    }    return null  })  const [activeIndex, setActiveIndex] = React.useState<number | null>(() => {    if (lockedIndex !== null) return lockedIndex    return normalizedData.length > 0 ? 0 : null  })  // Synchronize inspection datum callback  React.useEffect(() => {    if (!onActiveChange) return    const idx = lockedIndex !== null ? lockedIndex : activeIndex    if (idx === null || idx < 0 || idx >= normalizedData.length) {      onActiveChange(null)      return    }    const item = normalizedData[idx]    const val = item._normalizedValue    const dev = val !== null && isBaselineValid ? val - baseline : null    const pos: BaselineClassification | "unavailable" =      val === null || !isBaselineValid        ? "unavailable"        : classifyAgainstBaseline(val, baseline)    onActiveChange({      index: idx,      x: item[xKey] as XVal,      raw: item,      value: val,      baseline,      deviation: dev,      position: pos,      isLocked: lockedIndex !== null,    })  }, [activeIndex, lockedIndex, normalizedData, xKey, baseline, isBaselineValid, onActiveChange])  // Keyboard navigation on root figure  const handleKeyDown = (e: React.KeyboardEvent<HTMLElement>) => {    if (normalizedData.length === 0) return    const currentIndex = activeIndex ?? 0    switch (e.key) {      case "ArrowLeft": {        e.preventDefault()        const next = Math.max(0, currentIndex - 1)        setActiveIndex(next)        if (lockedIndex !== null) setLockedIndex(next)        break      }      case "ArrowRight": {        e.preventDefault()        const next = Math.min(normalizedData.length - 1, currentIndex + 1)        setActiveIndex(next)        if (lockedIndex !== null) setLockedIndex(next)        break      }      case "Home": {        e.preventDefault()        setActiveIndex(0)        if (lockedIndex !== null) setLockedIndex(0)        break      }      case "End": {        e.preventDefault()        const last = normalizedData.length - 1        setActiveIndex(last)        if (lockedIndex !== null) setLockedIndex(last)        break      }      case "Enter":      case " ": {        if (!lockableTooltip) return        e.preventDefault()        if (lockedIndex === activeIndex) {          setLockedIndex(null)        } else {          setLockedIndex(activeIndex)        }        break      }      case "Escape": {        e.preventDefault()        setLockedIndex(null)        break      }    }  }  // Fallback states  if (loading) {    return (      <ChartContainer style={{ height }} className={className}>        <ChartLoadingState description="Loading baseline observation records..." />      </ChartContainer>    )  }  if (unavailable) {    return (      <ChartContainer style={{ height }} className={className}>        <ChartUnavailableState description="Baseline Area data service is temporarily unavailable." />      </ChartContainer>    )  }  if (!isBaselineValid) {    return (      <ChartContainer style={{ height }} className={className}>        <ChartErrorState          title="Invalid baseline reference"          description="baseline must be an explicit finite number."        />      </ChartContainer>    )  }  if (error) {    const errorDescription =      error instanceof Error ? error.message : typeof error === "string" ? error : "An error occurred."    return (      <ChartContainer style={{ height }} className={className}>        <ChartErrorState title="Baseline Area Error" description={errorDescription} />      </ChartContainer>    )  }  if (empty || normalizedData.length === 0) {    return (      <ChartContainer style={{ height }} className={className}>        <ChartEmptyState description="No observations available for Baseline Area." />      </ChartContainer>    )  }  // Active observation computation  const activeObsIndex = lockedIndex !== null ? lockedIndex : activeIndex  const activeRecord =    activeObsIndex !== null && activeObsIndex >= 0 && activeObsIndex < normalizedData.length      ? normalizedData[activeObsIndex]      : null  const activeRawValue = activeRecord ? activeRecord._normalizedValue : null  const activeDeviation =    activeRawValue !== null ? activeRawValue - baseline : null  const activeClassification =    activeRawValue !== null      ? classifyAgainstBaseline(activeRawValue, baseline)      : "unavailable"  return (    <figure      role="region"      aria-label={title}      tabIndex={0}      onKeyDown={handleKeyDown}      className={cn(        "relative flex flex-col w-full focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--chart-focus,#3b82f6)] focus-visible:ring-offset-2 rounded-xl",        className      )}    >      {/* Optional Accessible Screen Reader Caption */}      <figcaption className="sr-only">        {title}. Reference baseline is set to {baseline}.{" "}        {description ||          `Single quantitative series comparing ${series.label} above and below the reference across ${normalizedData.length} observations.`}      </figcaption>      {/* Main Recharts Area */}      <ChartContainer style={{ height }}>        <ResponsiveContainer width="100%" height="100%" minWidth={0} minHeight={0}>          <AreaChart            data={normalizedData as any}            margin={{ top: 16, right: 16, left: 8, bottom: 8 }}            onMouseMove={(state) => {              if (lockedIndex !== null) return              if (state && state.activeTooltipIndex !== undefined) {                setActiveIndex(Number(state.activeTooltipIndex))              }            }}            onMouseLeave={() => {              if (lockedIndex !== null) return              setActiveIndex(null)            }}            onClick={(state) => {              if (!lockableTooltip) return              if (state && state.activeTooltipIndex !== undefined) {                const clicked = Number(state.activeTooltipIndex)                setLockedIndex(lockedIndex === clicked ? null : clicked)                setActiveIndex(clicked)              }            }}          >            <defs>              <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">                {offsetPercent <= 0 ? (                  <>                    <stop offset="0%" stopColor={belowColor} stopOpacity={clampedOpacity} />                    <stop offset="100%" stopColor={belowColor} stopOpacity={clampedOpacity} />                  </>                ) : offsetPercent >= 100 ? (                  <>                    <stop offset="0%" stopColor={aboveColor} stopOpacity={clampedOpacity} />                    <stop offset="100%" stopColor={aboveColor} stopOpacity={clampedOpacity} />                  </>                ) : (                  <>                    <stop offset="0%" stopColor={aboveColor} stopOpacity={clampedOpacity} />                    <stop offset={`${offsetPercent}%`} stopColor={aboveColor} stopOpacity={clampedOpacity} />                    <stop offset={`${offsetPercent}%`} stopColor={belowColor} stopOpacity={clampedOpacity} />                    <stop offset="100%" stopColor={belowColor} stopOpacity={clampedOpacity} />                  </>                )}              </linearGradient>            </defs>            {showGrid && (              <CartesianGrid                strokeDasharray="3 3"                stroke="var(--border, rgba(255, 255, 255, 0.08))"                vertical={false}              />            )}            {showXAxis && (              <XAxis                dataKey={xKey as any}                axisLine={false}                tickLine={false}                tick={{ fill: "var(--muted-foreground, #a1a1aa)", fontSize: 11 }}                dy={6}              />            )}            {showYAxis && (              <YAxis                domain={safeDomain}                axisLine={false}                tickLine={false}                tick={{ fill: "var(--muted-foreground, #a1a1aa)", fontSize: 11 }}                dx={-4}                tickFormatter={(v) =>                  series.valueFormatter ? series.valueFormatter(v) : v.toLocaleString()                }              />            )}            {/* Explicit Baseline Reference Line */}            <ReferenceLine              y={baseline}              stroke={baselineColor}              strokeDasharray="4 4"              strokeWidth={1.5}              label={                baselineLabel                  ? {                      value: `${baselineLabel} (${baseline})`,                      position: "insideTopRight",                      fill: "var(--muted-foreground, #a1a1aa)",                      fontSize: 10,                      fontFamily: "monospace",                      dy: -8,                    }                  : undefined              }            />            {/* Persistent Locked Crosshair */}            {lockedIndex !== null && activeRecord && (              <ReferenceLine                x={activeRecord[xKey] as any}                stroke={selectionColor}                strokeWidth={1.5}                strokeDasharray="2 2"              />            )}            {/* Main Area Geometry with Baseline BaseValue & Hard-Stop Fill */}            <Area              type={curve}              dataKey="_normalizedValue"              baseValue={baseline}              stroke={color}              strokeWidth={2}              fill={`url(#${gradientId})`}              fillOpacity={1}              isAnimationActive={isMotionEnabled}              animationDuration={                typeof motion === "object" && motion.duration ? motion.duration : 400              }              connectNulls={missingValuePolicy === "connect"}              activeDot={{                r: 5,                fill: color,                stroke: "var(--background, #09090b)",                strokeWidth: 2,              }}            />            {/* Synchronized Nearest-X Tooltip */}            <Tooltip              isAnimationActive={false}              allowEscapeViewBox={{ x: false, y: false }}              cursor={{                stroke: lockedIndex !== null ? "transparent" : "var(--chart-crosshair, rgba(255,255,255,0.15))",                strokeWidth: 1,                strokeDasharray: "3 3",              }}              content={({ active, payload }) => {                if (!active || !payload || payload.length === 0) return null                const datum = payload[0].payload as TData & { _normalizedValue: number | null }                const val = datum._normalizedValue                const dev = val !== null ? val - baseline : null                const classification =                  val !== null ? classifyAgainstBaseline(val, baseline) : "unavailable"                const formattedVal =                  val !== null                    ? series.valueFormatter                      ? series.valueFormatter(val)                      : val.toLocaleString()                    : "—"                const formattedBaseline = series.valueFormatter                  ? series.valueFormatter(baseline)                  : baseline.toLocaleString()                const formattedDev =                  dev !== null                    ? series.valueFormatter                      ? series.valueFormatter(dev)                      : `${dev > 0 ? "+" : ""}${dev.toLocaleString()}`                    : "—"                const isLocked = lockedIndex !== null                let positionText = "Unavailable"                let positionBadgeColor = "bg-zinc-500/10 text-zinc-400 border-zinc-500/20"                if (classification === "above") {                  positionText = aboveLabel                  positionBadgeColor = "bg-blue-500/10 text-blue-400 border-blue-500/25"                } else if (classification === "below") {                  positionText = belowLabel                  positionBadgeColor = "bg-emerald-500/10 text-emerald-400 border-emerald-500/25"                } else if (classification === "equal") {                  positionText = "On reference"                  positionBadgeColor = "bg-zinc-400/10 text-zinc-300 border-zinc-400/25"                }                return (                  <div                    role="tooltip"                    className="plotcn-chart-tooltip rounded-lg border border-border/60 bg-popover/95 p-3 text-popover-foreground shadow-xl backdrop-blur-md min-w-[min(180px,calc(100cqw-16px))] max-w-[min(300px,calc(100cqw-16px))] max-h-[calc(100cqh-16px)] overflow-y-auto text-xs space-y-2"                  >                    <div className="flex items-center justify-between border-b border-border/40 pb-1.5 gap-2">                      <span className="font-mono font-medium text-foreground text-xs">                        {String(datum[xKey])}                      </span>                      {isLocked && (                        <span className="inline-flex items-center gap-1 text-[10px] font-mono uppercase text-sky-400 font-semibold">                          <HugeiconsIcon icon={LockKeyIcon} size={11} /> Locked                        </span>                      )}                    </div>                    {/* Series Value */}                    <div className="flex items-center justify-between gap-4">                      <div className="flex items-center gap-1.5">                        <span                          className="size-2 rounded-full"                          style={{ backgroundColor: color }}                        />                        <span className="text-muted-foreground">{series.label}</span>                      </div>                      <span className="font-mono font-semibold text-foreground">                        {formattedVal}                      </span>                    </div>                    {/* Baseline Reference */}                    <div className="flex items-center justify-between gap-4">                      <div className="flex items-center gap-1.5">                        <span                          className="w-2 h-0.5"                          style={{ backgroundColor: baselineColor }}                        />                        <span className="text-muted-foreground">{baselineLabel}</span>                      </div>                      <span className="font-mono text-muted-foreground">                        {formattedBaseline}                      </span>                    </div>                    {/* Factual Signed Deviation */}                    {showDeviation && dev !== null && (                      <div className="flex items-center justify-between gap-4 pt-1 border-t border-border/30">                        <span className="text-muted-foreground">Deviation</span>                        <span                          className={cn(                            "font-mono font-bold",                            dev > 0 ? "text-blue-400" : dev < 0 ? "text-emerald-400" : "text-muted-foreground"                          )}                        >                          {dev > 0 ? `+${series.valueFormatter ? series.valueFormatter(dev) : dev.toLocaleString()}` : dev < 0 ? `-${series.valueFormatter ? series.valueFormatter(Math.abs(dev)) : Math.abs(dev).toLocaleString()}` : "0"}                        </span>                      </div>                    )}                    {/* Relative Position Classification */}                    <div className="pt-0.5">                      <span                        className={cn(                          "inline-block w-full text-center text-[10px] font-mono px-1.5 py-0.5 rounded border",                          positionBadgeColor                        )}                      >                        {positionText}                      </span>                    </div>                  </div>                )              }}            />          </AreaChart>        </ResponsiveContainer>      </ChartContainer>      {/* Optional Series / Baseline Status Legend */}      {showLegend && (        <div className="mt-3 flex flex-wrap items-center justify-center gap-4 text-xs font-mono text-muted-foreground">          <div className="flex items-center gap-1.5">            <span              className="size-2.5 rounded-xs border"              style={{                backgroundColor: aboveColor,                borderColor: aboveColor,                opacity: clampedOpacity + 0.3,              }}            />            <span>{aboveLabel}</span>          </div>          <div className="flex items-center gap-1.5">            <span              className="size-2.5 rounded-xs border"              style={{                backgroundColor: belowColor,                borderColor: belowColor,                opacity: clampedOpacity + 0.3,              }}            />            <span>{belowLabel}</span>          </div>          <div className="flex items-center gap-1.5">            <span              className="w-3.5 h-0.5 border-t border-dashed"              style={{ borderColor: baselineColor }}            />            <span>{baselineLabel} ({baseline})</span>          </div>        </div>      )}      {/* Off-screen Structured HTML Data Table for Screen Readers */}      <div className="sr-only">        <table>          <caption>{title} - Data Table</caption>          <thead>            <tr>              <th scope="col">{xKey}</th>              <th scope="col">{series.label}</th>              <th scope="col">Reference Baseline</th>              <th scope="col">Deviation</th>              <th scope="col">Position</th>            </tr>          </thead>          <tbody>            {normalizedData.map((row, idx) => {              const val = row._normalizedValue              const dev = val !== null ? val - baseline : null              const pos = val !== null ? classifyAgainstBaseline(val, baseline) : "Unavailable"              return (                <tr key={idx}>                  <td>{String(row[xKey])}</td>                  <td>{val !== null ? val : "Unavailable"}</td>                  <td>{baseline}</td>                  <td>                    {dev !== null                      ? dev > 0                        ? `+${dev}`                        : `${dev}`                      : "Unavailable"}                  </td>                  <td>{pos}</td>                </tr>              )            })}          </tbody>        </table>      </div>    </figure>  )}