# Technical Documentation: airbnb/visx

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/airbnb/visx)

### Overview (`README.md`)

<p align="center">
  <img src="./assets/visx-geometry.png" />
</p>

<p align="center">
  <a title="npm version" href="https://www.npmjs.com/~visx">
    <img src="https://img.shields.io/npm/v/@visx/demo.svg?style=flat-square" />
  </a>
  <a title="@visx/shape npm downloads" href="https://www.npmjs.com/package/@visx/shape">
    <img src="https://img.shields.io/npm/dm/@visx/shape.svg?style=flat-square" />
  </a>
</p>

### visx

visx is a collection of reusable low-level visualization components. visx combines the power of d3
to generate your visualization with the benefits of react for updating the DOM.


> [!IMPORTANT]
> **visx v4 is the current stable release** and requires React 18 or 19.
>
> ```bash
> npm install @visx/shape
> ```
>
> Upgrading from v3? See the [visx 4 migration guide](./MIGRATION.md).

<br />

<p align="center">
  <strong>
    <a href="https://airbnb.io/visx">Docs</a>
  </strong>
  &bull;
  <strong>
    <a href="https://airbnb.io/visx/gallery">Gallery</a>
  </strong>
  &bull;
  <strong>
    <a href="./CHANGELOG.md">Changelog</a>
  </strong>
  &bull;
  <strong>
    <a href="./MIGRATION.md">Migration</a>
  </strong>
</p>

<p align="center">
  <a href="https://airbnb.io/visx/gallery">
    <img src="./assets/visx-gallery.png" />
  </a>
</p>

## Usage

Let's make a simple bar graph.

First we'll install the relevant packages:

```bash
npm install --save @visx/mock-data @visx/group @visx/shape @visx/scale
```

<img src="./assets/simplebar.png" height="150" />

```
/* Detailed source-code truncated for AI context efficiency. */
```

For more examples using `visx`, check out the [gallery](https://airbnb.io/visx/gallery).

## Motivation

**Goal**

The goal is to create a library of components you can use to make both your own reusable chart
library or your slick custom one-off chart. visx is largely unopinionated and is meant to be built
upon. Keep your bundle sizes down and use only the packages you need.

**How?**

Under the hood, visx is using d3 for the calculations and math. If you're creating your own awesome
chart library on top of visx, it's easy to create a component api that hides d3 entirely. Meaning
your team could create charts as easily as using reusable react components.

**But why?**

Mixing two mental models for updating the DOM is never a good time. Copy and pasting d3 code into
`useEffect()` is just that. This collection of components lets you easily build your own reusable
visualization charts or library without having to learn d3. No more selections or
`enter()`/`exit()`/`update()`.

## FAQ

1. What does `visx` stand for?

   > visx stands for visualization components.

1. Do you plan on supporting animation/transitions?

   > A common criticism of visx is it doesn't have animation baked in, but this was a conscious
   > choice. It's a powerful feature to not bake it in.
   >
   > Imagine your app already bundles `react-motion`, adding a hypothetical `@visx/animation` is
   > bloat. Since visx is react, it already supports all react animation libs.
   >
   > Charting libraries are like style guides. Each org or app will eventually want full control
   > over their own implementation.
   >
   > visx makes this easier for everyone. No need to reinvent the wheel each time.
   >
   > more info: <https://github.com/airbnb/visx/issues/6>

1. Do I have to use every package to make a chart?

   > nope! pick and choose the packages you need.

1. Can I use this to create my own library of charts for my team?

   > Please do.

1. Does visx work with [preact](https://preactjs.com/)?

   > yup! alias `react` + `react-dom` to `preact/compat`. For visx v4, configure your package
   > manager to satisfy the React 18/19 peer dependency range.

1. I like using d3.

   > Me too.

## Thanks

Thanks to [Happo](https://happo.io) for providing the visual regression testing platform that
helps us review UI changes and catch unintended visual regressions.

<p>
  <a href="https://happo.io">
    <img src="./assets/happo-wordmark.svg" alt="Happo" height="60" />
  </a>
</p>

## Development

Please see [CONTRIBUTING.md](./CONTRIBUTING.md)

:v:

[MIT](./LICENSE)

---

### Overview (`packages/visx-a11y/Readme.md`)

# @visx/a11y

Accessibility helpers for primitive visx charts without changing the low-level visx primitive model.
The package is split into server-safe entries for generated semantics and a client React entry for
hooks and companion components.

## Installation

```sh
npm install --save @visx/a11y
```

## Motivation

visx is intentionally low level: primitives take props, compose freely, and stay out of your app's
state model. That is what makes visx useful for unusual charts, custom dashboards, and product
interfaces that do not fit a fixed charting API.

The tradeoff is that primitive charts tend to rebuild the same accessibility layer:

- chart titles and long descriptions
- series labels and point value labels
- hidden data tables for exact values
- live regions for async chart updates
- keyboard affordances for chart exploration
- rules for hiding decorative SVG chrome

That works for one chart. It gets noisy when a registry or dashboard has many charts built from
different visx packages. Small differences creep in, dense charts can produce too much screen reader
output, and teams end up copying local helpers from chart to chart.

`@visx/a11y` gives those charts a shared semantic layer while keeping the rendering primitives
plain. It does not ship a chart component, impose SVG structure, or hide non-data elements
automatically. Instead, it gives you spreadable props, generated descriptions, table fallbacks, and
small React helpers that you can attach to the primitives you already render.

## Primitive-first design

The a11y package is a semantics layer, not a chart framework.

- visx primitives remain prop-driven.
- Server helpers are pure functions with no DOM or React hook requirements.
- The client hook uses React `useId()` only when `id` is omitted.
- Consumers own the SVG render tree, focus ring styling, and decorative element visibility.
- Data table and announcer components are independently usable.
- Dense charts degrade to summary descriptions above `pointDescriptionThreshold`.
- `keyboardNavEnabled` controls roving focus for point-by-point chart exploration.

This keeps chart registry items and product charts able to opt in one layer at a time. If a chart
needs custom descriptions, a visible data table, a separate live region, or no interactive keyboard
state yet, the primitive API still supports that.

## Basic usage

Use the server entry when a server-rendered chart only needs generated SVG semantics, a text
description, or an HTML table fallback.

```tsx
import type { ChartA11yConfig } from '@visx/a11y/server';
import {
  generateChartDescription,
  generateDataTableHTML,
  getChartAriaProps,
} from '@visx/a11y/server';

type Datum = {
  month: string;
  revenue: number;
};

const config: ChartA11yConfig<Datum> = {
  id: 'revenue-chart',
  title: 'Revenue by month',
  chartType: 'line',
  data,
  x: (datum) => datum.month,
  y: (datum) => datum.revenue,
  yLabel: 'Revenue',
  formatY: (value) => `$${value}`,
};

const a11y = getChartAriaProps(config);
const description = generateChartDescription(config);
const tableHtml = generateDataTableHTML(config);
```

Use `useChartA11y` from the React entry when chart components need React-bound props and companion
components.

```tsx
'use client';

import { useChartA11y } from '@visx/a11y/react';

export function RevenueChart({ data }) {
  const a11y = useChartA11y({
    id: 'revenue-chart',
    title: 'Revenue by month',
    chartType: 'line',
    data,
    x: (datum) => datum.month,
    y: (datum) => datum.revenue,
    yLabel: 'Revenue',
    formatY: (value) => `$${value}`,
  });

  return (
    <>
      <svg {...a11y.svgProps} id={a11y.id}>
        <desc id={a11y.descriptionId}>{a11y.description}</desc>
        {/* chart marks */}
      </svg>
      <a11y.DataTable />
      <a11y.Announcer />
    </>
  );
}
```

## Recipes

### Level 1: Chart semantics, description, and table fallback

Start by spreading `svgProps`, rendering the generated description, and adding the pre-bound data
table and live announcer. This gives the chart an accessible name, a chart-level description, and an
exact-value table fallback without changing the visual chart.

```tsx
const a11y = useChartA11y({
  id: 'revenue-chart',
  title: 'Revenue by month',
  chartType: 'line',
  data,
  x: (datum) => datum.month,
  y: (datum) => datum.revenue,
  yLabel: 'Revenue',
  formatY: (value) => `$${value}`,
});

return (
  <>
    <svg {...a11y.svgProps} id={a11y.id}>
      <desc id={a11y.descriptionId}>{a11y.description}</desc>
      <g>
        {data.map((datum) => (
          <circle key={datum.month} />
        ))}
      </g>
    </svg>
    <a11y.DataTable />
    <a11y.Announcer />
  </>
);
```

### Level 2: Series and point semantics

After Level 1 is in place, spread `getSeriesProps` on each rendered series group and `getPointProps`
on each rendered data mark. This adds per-series labels and per-point value labels for charts below
the configured `pointDescriptionThreshold`.

```tsx
const a11y = useChartA11y({
  id: 'revenue-chart',
  title: 'Revenue by month',
  chartType: 'line',
  data,
  x: (datum) => datum.month,
  y: (datum) => datum.revenue,
  yLabel: 'Revenue',
  formatY: (value) => `$${value}`,
  series: [{ label: 'Revenue' }],
});

return (
  <>
    <svg {...a11y.svgProps} id={a11y.id}>
      <desc id={a11y.descriptionId}>{a11y.description}</desc>
      <g {...a11y.getSeriesProps(0)}>
        {data.map((datum, index) => (
          <circle key={datum.month} {...a11y.getPointProps(0, index)} />
        ))}
      </g>
    </svg>
    <a11y.DataTable />
    <a11y.Announcer />
  </>
);
```

### Level 3: Keyboard navigation and tooltip bridge

Keep `keyboardNavEnabled` enabled when a chart should support point-by-point keyboard exploration.
`useChartA11y` adds roving focus props to each data mark and calls `onPointFocus` when keyboard
focus moves to a point. Use that callback to mirror the same tooltip, crosshair, or active-point
state that pointer interaction uses.

```tsx
const a11y = useChartA11y({
  id: 'revenue-chart',
  title: 'Revenue by month',
  chartType: 'line',
  data,
  x: (datum) => datum.month,
  y: (datum) => datum.revenue,
  yLabel: 'Revenue',
  formatY: (value) => `$${value}`,
  series: [{ label: 'Revenue' }],
  onPointFocus: ({ datum, index, seriesIndex }) => {
    showTooltip({
      datum,
      index,
      seriesIndex,
    });
  },
});

return (
  <svg {...a11y.svgProps} id={a11y.id}>
    <desc id={a11y.descriptionId}>{a11y.description}</desc>
    <g {...a11y.getSeriesProps(0)}>
      {data.map((datum, index) => (
        <circle
          key={datum.month}
          className={a11y.focusedPoint?.index === index ? 'is-keyboard-focused' : undefined}
          {...a11y.getPointProps(0, index)}
        />
      ))}
    </g>
  </svg>
);
```

Use `useChartKeyboardNav` directly when a custom chart already owns its generated ARIA semantics but
still wants the same roving-focus behavior, point focus state, and `onPointFocus` callback.

## Keyboard interaction model

When keyboard navigation is enabled, `useChartA11y` starts in chart mode. The chart root is
tabbable, and data marks become tabbable only while keyboard exploration is active. Navigation is
enabled by default for charts with at least one point and no more than `pointDescriptionThreshold`
points.

| Key                | Result                                                                                       |
| ------------------ | -------------------------------------------------------------------------------------------- |
| `Tab`              | Moves focus to or away from the chart root through normal page tab order.                    |
| `Enter` or `Space` | Enters data mode and focuses the first data point, or the last focused point when returning. |
| `ArrowRight`       | Moves to the next point in the current series, wrapping at the end.                          |
| `ArrowLeft`        | Moves to the previous point in the current series, wrapping at the beginning.                |
| `ArrowDown`        | Moves to the next non-empty series and keeps the closest point index.                        |
| `ArrowUp`          | Moves to the previous non-empty series and keeps the closest point index.                    |
| `Home`             | Moves to the first point in the current series.                                              |
| `End`              | Moves to the last point in the current series.                                               |
| `Control` + `Home` | Moves to the first point in the chart.                                                       |
| `Control` + `End`  | Moves to the last point in the chart.                                                        |
| `Escape`           | Exits data mode and returns focus to the chart root.                                         |
| `?` or `F1`        | Announces the configured keyboard help text through `Announcer`.                             |

### Decorative chart chrome

`@visx/a11y` annotates the chart elements it receives through the hook. Consumers are responsible
for hiding decorative chart chrome from assistive technology. Grid lines, axis ticks, background
rects, clipping helpers, and other non-data elements should usually be rendered with
`aria-hidden="true"` so screen readers focus on the title, description, series, points, and data
table.

```tsx
<svg {...a11y.svgProps} id={a11y.id}>
  <rect aria-hidden="true" width={width} height={height} />
  <GridRows aria-hidden="true" scale={yScale} width={innerWidth} />
  <AxisBottom aria-hidden="true" scale={xScale} />
  <g {...a11y.getSeriesProps(0)}>{/* data marks */}</g>
</svg>
```

---

### Overview (`packages/visx-annotation/Readme.md`)

# @visx/annotation

<p>
  <a title="@visx/annotation npm downloads" href="https://www.npmjs.com/package/@visx/annotation">
    <img src="https://img.shields.io/npm/dm/@visx/annotation.svg?style=flat-square" />
  </a>
</p>

SVG `Annotation`s enable you to label points, thresholds, or regions of a visualization to provide
additional context to for your chart consumer. This package is heavily inspired by
[Susie Lu](https://github.com/susielu/)'s
[`react-annotation`](https://github.com/susielu/react-annotation) library.

Each annotation consists of three (optional) parts:

1. `Subject` (`CircleSubject`, `LineSubject`, more 🔜) – what part of a chart is being annotated
   (point, line, region)

2. `Label` – the text component for the annotation. Handles SVG text wrapping using `@visx/text`,
   and supports `title` and `subtitle` customization as well as vertical & horizontal anchors /
   alignment

3. `Connector` – line connecting a subject and label

The `Annotation` or `EditableAnnotation` component wrappers allow you to compose these components
and simplify their individual positioning:

```tsx
<EditableAnnotation
  x={subjectX}
  y={subjectY}
  dx={labelDx} // x offset of label from subject
  dy={labelDy} // y offset of label from subject
  onDragEnd={({ x, y, dx, dy }) => ...}
>
  <Connector />
  <CircleSubject />
  <Label title="Context about this point" subtitle="More deets">
</EditableAnnotation>
```

Components can also be used in isolation, in which case you must specify exact positions for each
item:

```tsx
() => (
  <g>
    <Connector x={subjectX} y={subjectY} dx={labelDx} dy={labelDy} />
    <CircleSubject x={subjectX} y={subjectY} />
    <Label x={subjectX + labelDx} y={subjectY + labelDy} title="...">
  </g>
)
```

##### ⚠️ `ResizeObserver` dependency

The `Label` component relies on `ResizeObserver`s for auto-sizing. If you need a polyfill, you can
either polute the `window` object or inject it cleanly through props:

```tsx
import { ResizeObserver } from 'your-favorite-polyfill';

function App() {
  return <Label resizeObserverPolyfill={ResizeObserver} {...} />
```

## Installation

```
npm install --save @visx/annotation
```

---

### Overview (`packages/visx-axis/Readme.md`)

# @visx/axis

<p>
  <a title="@visx/axis npm downloads" href="https://www.npmjs.com/package/@visx/axis">
    <img src="https://img.shields.io/npm/dm/@visx/axis.svg?style=flat-square" />
  </a>
</p>

An axis component consists of a line with ticks, tick labels, and an axis label that helps viewers
interpret your graph.

You can use one of the 4 pre-made axes, or you can create your own based on the `<Axis />` element.
Note that the `@visx/react-spring` package exports an `AnimatedAxis` variant with animated ticks.

## Installation

```
npm install --save @visx/axis
```

---

### Overview (`packages/visx-bounds/Readme.md`)

# @visx/bounds

<p>
  <a title="@visx/bounds npm downloads" href="https://www.npmjs.com/package/@visx/bounds">
    <img src="https://img.shields.io/npm/dm/@visx/bounds.svg?style=flat-square" />
  </a>
</p>

```
npm install --save @visx/bounds
```

### `withBoundingRects` HOC

It's often useful to determine whether elements (e.g., tooltips) overflow the bounds of their parent
container and adjust positioning accordingly. The `withBoundingRects` higher-order component is
meant to simplify this computation by passing in a component's bounding rect as well as its
_parent's_ bounding rect.

### Example usage

Example usage with a `<Tooltip />` component

```tsx
import React from 'react';
import { withBoundingRects, WithBoundingRectsProps } from '@visx/bounds';

type TooltipProps = Omit<WithBoundingRectsProps, 'nodeRef'> & {
  left: number;
  top: number;
  nodeRef?: React.Ref<HTMLDivElement>;
  children?: React.ReactNode;
};

function Tooltip({
  left: initialLeft,
  top: initialTop,
  rect,
  parentRect,
  nodeRef,
  children,
}: TooltipProps) {
  let left = initialLeft;
  let top = initialTop;

  if (rect && parentRect) {
    left = rect.right > parentRect.right ? left - rect.width : left;
    top = rect.bottom > parentRect.bottom ? top - rect.height : top;
  }

  return (
    <div ref={nodeRef} style={{ top, left, ...myTheme }}>
      {children}
    </div>
  );
}

export default withBoundingRects(Tooltip);
```

---

### Overview (`packages/visx-brush/Readme.md`)

# @visx/brush

<a title="@visx/brush npm downloads" href="https://www.npmjs.com/package/@visx/brush">
  <img src="https://img.shields.io/npm/dm/@visx/brush.svg?style=flat-square" />
</a>

A brush allows you to select a sub-region of your chart or axis.

## Installation

```
npm install --save @visx/brush
```

---

### Overview (`packages/visx-chart/Readme.md`)

# @visx/chart

Chart-level React hooks and helpers for building primitive visx charts without adopting a chart
framework. The package starts with shared layout and domain helpers that registry-style charts can
use before composing `@visx/axis`, `@visx/scale`, `@visx/shape`, and other low-level primitives.

## Installation

```sh
npm install --save @visx/chart
```

## Motivation

visx charts are usually assembled from several packages: one package for scales, one for axes, one
for marks, one for interaction, and application code for the SVG frame around them. That composition
is the point, but every primitive chart still tends to rebuild the same chart-level setup:

- outer SVG dimensions
- margin defaults
- inner drawable width and height
- `xMax` and `yMax` aliases used throughout visx examples
- common numeric domains for primitive chart scales
- responsive width fallbacks while parent measurement initializes
- stable layout objects for downstream hooks and components

Those details are small, but they become repetitive in examples, dashboards, and registry items.
`@visx/chart` gives primitive charts one shared place for that chart-level setup while leaving scale
construction, rendering, interaction, animation, and state ownership in user code.

## Primitive-first design

The chart package is a convenience layer, not a chart framework.

- Hooks return ordinary values that can be passed to any visx primitive.
- The package does not render SVG elements or own a chart scene graph.
- Data accessors, scales, axes, marks, events, and animation remain explicit.
- Layout defaults are normalized, but callers can keep their own sizing system.
- You can use the chart hooks with one visx package, many visx packages, or custom SVG.

This keeps registry examples compact without hiding the pieces that make visx flexible. If a chart
needs a custom margin model, responsive container, canvas renderer, or no shared layout helper at
all, the primitive API still supports that.

## Basic usage

Use `useChartDimensions` to normalize an outer chart size and margin into the inner drawing area.

```tsx
import { Group } from '@visx/group';
import { useChartDimensions } from '@visx/chart';

const margin = { top: 16, right: 16, bottom: 32, left: 40 };

export function ChartFrame({ width, height, children }) {
  const dimensions = useChartDimensions({ width, height, margin });

  return (
    <svg width={dimensions.width} height={dimensions.height}>
      <Group left={dimensions.margin.left} top={dimensions.margin.top}>
        {children(dimensions)}
      </Group>
    </svg>
  );
}
```

The hook fills missing margin sides with `0`, treats non-finite dimensions as `0`, and clamps the
inner drawing area to `0` so marks never receive negative layout space.

## Numeric domains

Use the domain helpers when a primitive chart needs the usual safe defaults for empty, invalid, or
single-value data.

```tsx
import { getPositiveDomain, getZeroBaselineDomain } from '@visx/chart';

const yDomain = getZeroBaselineDomain(data.map((datum) => datum.value));
const stackedYDomain = getPositiveDomain(
  data.map((datum) => datum.desktop + datum.mobile + datum.tablet),
);
```

`getZeroBaselineDomain` includes zero and expands equal domains. `getPositiveDomain` returns a
positive `[0, max]` domain with an empty fallback of `[0, 1]`. `getPaddedDomain` is available for
plots such as scatter charts where the domain should wrap finite values with proportional padding.

## Axis ticks

Use the tick helpers when a chart axis may become too dense in responsive layouts.
`getVisibleTickValues` thins explicit category tick values while preserving the first and last tick
by default, and `getAxisTickCount` computes a conservative numeric tick count from the available
axis length.

```tsx
import { getAxisTickCount, getVisibleTickValues } from '@visx/chart';

const xTickValues = getVisibleTickValues(months, {
  axisLength: dimensions.innerWidth,
  minTickSpacing: 48,
});
const yNumTicks = getAxisTickCount({
  axisLength: dimensions.innerHeight,
  maxTicks: 5,
  minTickSpacing: 48,
});
```

The helpers only choose visible axis labels. They do not remove data points, bars, bins, or table
fallback rows.

## Responsive width fallback

Use `getResponsiveWidth` when a responsive container may report `0`, `NaN`, or another
non-renderable width while layout measurement initializes.

```tsx
import { getResponsiveWidth } from '@visx/chart';

const chartWidth = getResponsiveWidth(measuredWidth, 640);
```

The helper returns the measured width only when it is finite and greater than `0`; otherwise it
returns the fallback width.

## Chart config

Use `ChartConfig` when labels, colors, icons, and theme-specific tokens should live outside the
chart data. This mirrors the way registry charts are usually copied into app code: the data can come
from an API while chart presentation stays colocated with the component.

```tsx
import { getChartConfigColor, getChartConfigLabel, type ChartConfig } from '@visx/chart';

const chartConfig = {
  bookings: {
    label: 'Bookings',
    color: 'var(--chart-1)',
  },
  revenue: {
    label: 'Revenue',
    theme: {
      light: 'oklch(0.646 0.222 41.116)',
      dark: 'oklch(0.488 0.243 264.376)',
    },
  },
} satisfies ChartConfig;

const label = getChartConfigLabel(chartConfig, 'bookings');
const color = getChartConfigColor(chartConfig, 'bookings', 'currentColor');
```

`getChartCssVariables` can turn a config into `--color-*` CSS variables for chart shells that want
the same token style as copied registry components.

## Working with scales

`xMax` and `yMax` are aliases for `innerWidth` and `innerHeight`, matching the naming used in many
visx examples.

```tsx
import { useChartDimensions } from '@visx/chart';
import { useScale } from '@visx/scale/react';

export function useRevenueScales({ data, width, height }) {
  const dimensions = useChartDimensions({
    width,
    height,
    margin: { top: 16, right: 16, bottom: 32, left: 48 },
  });
  const maxRevenue = Math.max(0, ...data.map((datum) => datum.revenue));

  const xScale = useScale({
    type: 'band',
    domain: data.map((datum) => datum.month),
    range: [0, dimensions.xMax],
    padding: 0.2,
  });

  const yScale = useScale({
    type: 'linear',
    domain: [0, maxRevenue],
    range: [dimensions.yMax, 0],
    nice: true,
  });

  return { dimensions, xScale, yScale };
}
```

## Recipes

### Bar chart shell

```tsx
import { AxisBottom, AxisLeft } from '@visx/axis';
import { Group } from '@visx/group';
import { Bar } from '@visx/shape';
import { useChartDimensions } from '@visx/chart';
import { useScale } from '@visx/scale/react';

const margin = { top: 16, right: 16, bottom: 32, left: 48 };

export function RevenueBars({ data, width, height }) {
  const dimensions = useChartDimensions({ width, height, margin });
  const maxRevenue = Math.max(0, ...data.map((datum) => datum.revenue));
  const xScale = useScale({
    type: 'band',
    domain: data.map((datum) => datum.month),
    range: [0, dimensions.xMax],
    padding: 0.2,
  });
  const yScale = useScale({
    type: 'linear',
    domain: [0, maxRevenue],
    range: [dimensions.yMax, 0],
    nice: true,
  });

  return (
    <svg width={dimensions.width} height={dimensions.height}>
      <Group left={dimensions.margin.left} top={dimensions.margin.top}>
        {data.map((datum) => {
          const barX = xScale(datum.month) ?? 0;
          const barY = yScale(datum.revenue) ?? 0;

          return (
            <Bar
              key={datum.month}
              x={barX}
              y={barY}
              width={xScale.bandwidth()}
              height={dimensions.yMax - barY}
              fill="currentColor"
            />
          );
        })}
        <AxisBottom top={dimensions.yMax} scale={xScale} />
        <AxisLeft scale={yScale} />
      </Group>
    </svg>
  );
}
```

### Responsive dimensions

`useChartDimensions` does not measure the DOM. Pair it with your app's layout system or with
`@visx/responsive` when a chart should fill available space.

```tsx
import { getResponsiveWidth } from '@visx/chart';
import { ParentSize } from '@visx/responsive';

export function ResponsiveRevenueBars({ data }) {
  return (
    <ParentSize>
      {({ width }) => (
        <RevenueBars data={data} width={getResponsiveWidth(width, 640)} height={320} />
      )}
    </ParentSize>
  );
}
```

---

### Overview (`packages/visx-chord/Readme.md`)

# @visx/chord

<a title="@visx/chord npm downloads" href="https://www.npmjs.com/package/@visx/chord">
  <img src="https://img.shields.io/npm/dm/@visx/chord.svg?style=flat-square" />
</a>

Chord diagrams show directed relationships among a group of entities in a radial layout.

## Installation

```
npm install --save @visx/chord
```

---

### Overview (`packages/visx-clip-path/Readme.md`)

# @visx/clip-path

<a title="@visx/clip-path npm downloads" href="https://www.npmjs.com/package/@visx/clip-path">
  <img src="https://img.shields.io/npm/dm/@visx/clip-path.svg?style=flat-square" />
</a>

React utilities for defining `<clipPath>` SVG elements, with or without data, to be clip masks for
other SVG elements by using their `clip-path` property.

## Installation

```
npm install --save @visx/clip-path
```

---

### Overview (`packages/visx-curve/Readme.md`)

# @visx/curve

<a title="@visx/curve npm downloads" href="https://www.npmjs.com/package/@visx/curve">
  <img src="https://img.shields.io/npm/dm/@visx/curve.svg?style=flat-square" />
</a>

## Installation

```
npm install --save @visx/curve
```

## Overview

The `@visx/curve` package is a wrapper of the [d3-shape](https://github.com/d3/d3-shape) curve
functions. A `curve` is a function that can be passed into other `visx` objects that draw lines or
paths, such as a `LinePath`, to change the way the line between points is drawn. Click on the
example below for an interactive way to explore curve aesthetics.

Any function with the prefix `curve` in `d3` can be used through `visx` like so:

```javascript
import { curveCatmullRomOpen } from '@visx/curve';
let line = (<Shape.LinePath curve={curveCatmullRomOpen} />)

// or if you want namespace all Curves under the `Curve`
import * as Curve from `@visx/curve`;
let line = (<Shape.LinePath curve={Curve.curveCatmullRomOpen} />)
```

## Functions

| visx                  | d3                                                                            |
| --------------------- | ----------------------------------------------------------------------------- |
| curveBasis            | [curveBasis](https://github.com/d3/d3-shape#curveBasis)                       |
| curveBasisClose       | [curveBasisClosed](https://github.com/d3/d3-shape#curveBasisClosed)           |
| curveBasisOpen        | [curveBasisOpen](https://github.com/d3/d3-shape#curveBasisOpen)               |
| curveStep             | [curveStep](https://github.com/d3/d3-shape#curveStep)                         |
| curveStepAfter        | [curveStepAfter](https://github.com/d3/d3-shape#curveStepAfter)               |
| curveStepBefore       | [curveStepbefore](https://github.com/d3/d3-shape#curveStepBefore)             |
| curveBundle           | [curveBundle](https://github.com/d3/d3-shape#curveBundle)                     |
| curveLinear           | [curveLinear](https://github.com/d3/d3-shape#curveLinear)                     |
| curveLinearClosed     | [curveLinearClosed](https://github.com/d3/d3-shape#curveLinearClosed)         |
| curveMonotoneX        | [curveMonotoneX](https://github.com/d3/d3-shape#curveMonotoneX)               |
| curveMonotoneY        | [curveMonotoneY](https://github.com/d3/d3-shape#curveMonotoneY)               |
| curveCardinal         | [curveCardinal](https://github.com/d3/d3-shape#curveCardinal)                 |
| curveCardinalClosed   | [curveCardinalClosed](https://github.com/d3/d3-shape#curveCardinalClosed)     |
| curveCardinalOpen     | [curveCardinalOpen](https://github.com/d3/d3-shape#curveCardinalOpen)         |
| curveCatmullRom       | [curveCatmullRom](https://github.com/d3/d3-shape#curveCatmullRom)             |
| curveCatmullRomClosed | [curveCatmullRomClosed](https://github.com/d3/d3-shape#curveCatmullRomClosed) |
| curveCatmullRomOpen   | [curveCatmullRomOpen](https://github.com/d3/d3-shape#curveCatmullRomOpen)     |
| curveNatural          | [curveNatural](https://github.com/d3/d3-shape#curveNatural)                   |

---

### Overview (`packages/visx-delaunay/Readme.md`)

# @visx/delaunay

<a title="@visx/delaunay npm downloads" href="https://www.npmjs.com/package/@visx/delaunay">
  <img src="https://img.shields.io/npm/dm/@visx/delaunay.svg?style=flat-square" />
</a>

## Overview

A Voronoi diagram partitions a two-dimensional plane into regions based on a set of input points.
Each unique input point maps to a corresponding region, where each region represents _all points
that are closer to the input point than to any other input point_.

Not only are Voronoi diagrams 😍, but they can be used to
[improve the interactive experience of a visualization](https://www.visualcinnamon.com/2015/07/voronoi.html).
This is most often accomplished by overlaying an invisible voronoi grid on top of the visualization
to increase the target area of interaction sites such as points on a scatter plot.

The `@visx/delaunay` package provides a wrapper around the existing
[d3-delaunay](https://github.com/d3/d3-delaunay) package with some `react`-specific utilities.

## Installation

```
npm install --save @visx/delaunay
```

## Usage

The `@visx/delaunay` package exports a wrapped version of the d3 `voronoi` and `delaunay` layouts for flexible usage,
as well as a `<Polygon />` component for rendering Voronoi and Delaunay regions.

```js
import { voronoi, Polygon } from '@visx/delaunay';

const points = Array(n).fill(null).map(() => ({
  x: Math.random() * innerWidth,
  y: Math.random() * innerHeight,
}));

// width + height set an extent on the voronoi
// x + y set relevant accessors depending on the shape of your data
const voronoiDiagram = voronoi({
  data: points,
  x: d => d.x,
  y: d => d.y,
  width,
  height,
});

const polygons = Array.from(voronoiDiagram.cellPolygons());

return (
  <svg>
    <Group>
      {polygons.map((polygon) => (
        <Polygon key={...} polygon={polygon} />
      ))}
      {points.map(({ x, y }) => (
        <circle key={...} cx={x} cy={y} />
      )}
    </Group>
  </svg>
)
```

Additional information about the voronoi diagram API can be found in the
[d3-delaunay documentation](https://github.com/d3/d3-delaunay#voronoi).

---

### Overview (`packages/visx-demo/Readme.md`)

# @visx/demo

<a href="https://airbnb.io/visx/gallery">https://airbnb.io/visx/gallery</a>

<p align="center">
  <a href="https://airbnb.io/visx/gallery">
    <img src="/assets/visx-gallery.png" />
  </a>
</p>

---

### Overview (`packages/visx-drag/Readme.md`)

# @visx/drag

<a title="@visx/drag npm downloads" href="https://www.npmjs.com/package/@visx/drag">
  <img src="https://img.shields.io/npm/dm/@visx/drag.svg?style=flat-square" />
</a>

`@visx/drag` provides `react` components and hooks for making items within an interface (or chart)
draggable.

## Installation

```
npm install --save @visx/drag
```

---

### Overview (`packages/visx-event/Readme.md`)

# @visx/event

<a title="@visx/event npm downloads" href="https://www.npmjs.com/package/@visx/event">
  <img src="https://img.shields.io/npm/dm/@visx/event.svg?style=flat-square" />
</a>

## Installation

```
npm install --save @visx/event
```

## Usage

`@visx/event` exports a utility `localPoint` that takes an `SVG` `MouseEvent` or `TouchEvent` as
input and returns a `{ x: number; y: number; }` point coordinate (or `null` in the case the event
has no `ownerSVGElement`) within the coordinate system of the `SVG`. This makes placement of
tooltips, finding nearby datum, etc. easier.

Example:

```tsx
import { localPoint } from '@visx/event';

<svg>
  <SomeElement
    {...}
    onMouseMove={(event: MouseEvent) => {
      const point = localPoint(event) || { x: 0, y: 0 };
      // use coordinates ...
    }}
  />
  {...}
</svg>
```

You may optionally pass a reference to the SVG node

```tsx
import { useRef } from 'react';
import { localPoint } from '@visx/event';

const svgRef = useRef<SVGSVGElement>(null);

<svg ref={svgRef}>
  <SomeElement
    {...}
    onMouseMove={(event: MouseEvent) => {
      const point = localPoint(svgRef.current, event) || { x: 0, y: 0 };
      // use coordinates ...
    }}
  />
  {...}
</svg>
```

---

### Overview (`packages/visx-geo/Readme.md`)

# @visx/geo

<a title="@visx/geo npm downloads" href="https://www.npmjs.com/package/@visx/geo">
  <img src="https://img.shields.io/npm/dm/@visx/geo.svg?style=flat-square" />
</a>

The `@visx/geo` package provides `react` components for rendering common and custom geographic
projections. `<Projection />` can be used to render preset projections
(`projection='orthographic' | 'albers' | 'albersUsa' | 'mercator' | 'naturalEarth' | 'equalEarth'`)
along with configurable `<Graticule />`s lines. Convenience projections such as `<Mercator />` are
also exported, along with `<CustomProjection />` and `<Graticule />` for full customization.

## Installation

```
npm install --save @visx/geo
```

---

### Overview (`packages/visx-glyph/Readme.md`)

# @visx/glyph

<a title="@visx/glyph npm downloads" href="https://www.npmjs.com/package/@visx/glyph">
  <img src="https://img.shields.io/npm/dm/@visx/glyph.svg?style=flat-square" />
</a>

Glyphs are small marks or symbols that you can use in your charts. Example:
[https://airbnb.io/visx/glyphs](https://airbnb.io/visx/glyphs)

## Installation

```
npm install --save @visx/glyph
```

---

### Overview (`packages/visx-gradient/Readme.md`)

# @visx/gradient

<a title="@visx/gradient npm downloads" href="https://www.npmjs.com/package/@visx/gradient">
  <img src="https://img.shields.io/npm/dm/@visx/gradient.svg?style=flat-square" />
</a>

Inspired by: https://dribbble.com/shots/3380672-Sketch-Gradients-Freebie

## Example

```js
import { AreaClosed } from '@visx/shape';
import { GradientPinkBlue } from '@visx/gradient';

const GradientArea = () => {
  return (
    <svg>
      <GradientPinkBlue id="gradient" />
      <AreaClosed fill="url('#gradient')" />
    </svg>
  );
};
```

## The Definition Caveat

Like patterns, gradients are "defined." When you render `<GradientPinkBlue />`, it's rendering a
[`<linearGradient/>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient)
element inside a `<def>` in the SVG.

It's often better to think of these as variable definitions rather than true DOM elements. When you
use `fill="url('#gradient')"` you're referencing the gradient's id: `gradient`.

## Make your own!

In addition to the preset linear gradients, you can make any linear or radial gradient like so:

```js
import { LinearGradient, RadialGradient } from '@visx/gradient';

<LinearGradient from="#a18cd1" to="#fbc2eb" />;
<RadialGradient from="#a18cd1" to="#fbc2eb" />;
```

## Installation

```
npm install --save @visx/gradient
```

---

### Overview (`packages/visx-grid/Readme.md`)

# @visx/grid

<a title="@visx/grid npm downloads" href="https://www.npmjs.com/package/@visx/grid">
  <img src="https://img.shields.io/npm/dm/@visx/grid.svg?style=flat-square" />
</a>

The `@visx/grid` package lets you create gridlines for charts. `<GridRows />` render horizontally,
`<GridColumns />` render vertically, or you can use a `<Grid />` to get them both at once!

## Usage

```js
import { Grid } from '@visx/grid';
// or
// import * as Grid from '@visx/grid';
// <Grid.Grid />

const grid = (
  <Grid
    xScale={xScale}
    yScale={yScale}
    width={xMax}
    height={yMax}
    numTicksRows={numTicksForHeight(height)}
    numTicksColumns={numTicksForWidth(width)}
  />
);
```

## Installation

```
npm install --save @visx/grid
```

---

### Overview (`packages/visx-group/Readme.md`)

# @visx/group

<a title="@visx/group npm downloads" href="https://www.npmjs.com/package/@visx/group">
  <img src="https://img.shields.io/npm/dm/@visx/group.svg?style=flat-square" />
</a>

`<Group />` provides a simplified API for SVG `<g />` elements, which are containers for other SVG
objects. You may pass in a `top` and `left` margin (instead of `transform={translate(...)}`) and a
`className`.

## Installation

```
npm install --save @visx/group
```

---

### Overview (`packages/visx-heatmap/Readme.md`)

# @visx/heatmap

<a title="@visx/heatmap npm downloads" href="https://www.npmjs.com/package/@visx/heatmap">
  <img src="https://img.shields.io/npm/dm/@visx/heatmap.svg?style=flat-square" />
</a>

A Heatmap is an arrangement of shapes where the data values are represented as colors.

## Example

<img style="display:block; width:34vw;" src="http://i.imgur.com/OzSD3X3.png">

```js
<HeatmapRect
  data={data}
  xScale={xScale}
  yScale={yScale}
  colorScale={colorScale}
  opacityScale={opacityScale}
  binWidth={bWidth}
  binHeight={bWidth}
  step={dStep}
  gap={0}
/>
```

Heatmaps generally require structure that has this shape:

```js
[
  {
    bin: 1,
    bins: [
      {
        count: 20,
        bin: 23,
      },
    ],
  },
];
```

However, you're welcome to use your own structure by defining `x`, `y`, `z` accessors such as:

```js
// Example accessors
const x = (d) => d.myBin;
const y = (d) => d.myBins;
const z = (d) => d.myCount;

// Example scale with an accessors
const xScale = scaleLinear({
  range: [0, xMax],
  domain: extent(data, x),
});
```

## Installation

```
npm install --save @visx/heatmap
```

---

### Overview (`packages/visx-hierarchy/Readme.md`)

# @visx/hierarchy

<a title="@visx/hierarchy npm downloads" href="https://www.npmjs.com/package/@visx/hierarchy">
  <img src="https://img.shields.io/npm/dm/@visx/hierarchy.svg?style=flat-square" />
</a>

Many datasets are intrinsically hierarchical. This package contains several `react` components for
visualizing hierarchical data and largely mirrors
[`d3-hierarchy`](https://github.com/d3/d3-hierarchy).

Many components take the same input `hierarchy` data root node as defined in as specified in the
[`d3-hierarchy`](https://github.com/d3/d3-hierarchy) module. For convenience, this package also
exports the [`d3-hierarchy`](https://github.com/d3/d3-hierarchy)utility to generate this format.

```js
// equivalent to `import { hierarchy } from 'd3-hierarchy';`
import { hierarchy } from '@visx/hierarchy';

const root = hierarchy({
  name: 'root',
  children: [
    { name: 'child #1' },
    {
      name: 'child #2',
      children: [{ name: 'grandchild #1' }, { name: 'grandchild #2' }, { name: 'grandchild #3' }],
    },
  ],
});
```

## Installation

```
npm install --save @visx/hierarchy
```

---

### Overview (`packages/visx-kernel/Readme.md`)

# @visx/kernel

Shared primitives for first-party visx hooks.

`@visx/kernel` keeps user-input handling consistent across the hooks surface: referential stability,
structural equality, accessor normalization, and shared development warnings live in one package
instead of being reimplemented in each consumer package. It also provides stable id generation for
shared SVG and a11y patterns.

## Installation

```sh
npm install --save @visx/kernel
```

## Motivation

visx hooks are designed around one idea: hooks own the math, users own the render tree. That means
first-party hooks like `useScale`, `useAxis`, and `usePie` all receive the same kinds of user input:
data arrays, accessors, options objects, dimensions, ids, and callbacks.

Without a shared substrate, each package has to answer the same questions independently:

- Does this object-shaped input have the same values as last render?
- Should a string accessor and a simple property function behave the same way?
- How do we keep callback identity stable while reading fresh state?
- How do we warn about dirty data with consistent source tags and structured details?
- How do we generate stable ids for clip paths, gradients, labels, and a11y relationships?

Those are cross-cutting contracts, not chart-specific features. `@visx/kernel` keeps them small,
audited, and consistent so the hooks surface behaves like one library instead of many similar local
implementations.

## Primitive-first design

Kernel is not a chart package. It does not create scales, render axes, lay out marks, or own chart
state. It provides the tiny pieces that make those packages predictable.

- Hooks return ordinary values and refs.
- Pure helpers are safe to import on the server.
- User input is normalized before package-specific work begins.
- Warning payloads share one shape across packages.
- Public helpers are added only when multiple first-party packages need the same behavior.

Most applications should use higher-level visx packages directly. Kernel is mainly for first-party
hooks and advanced users building the same kind of low-level primitives.

## Basic usage

### Stabilize object-shaped inputs

Use `useStructuralMemo` when an options object should keep the same reference if its shallow values
are unchanged.

```tsx
import { useStructuralMemo } from '@visx/kernel';

function ChartFrame({ margin }) {
  const stableMargin = useStructuralMemo(
    {
      top: margin?.top ?? 0,
      right: margin?.right ?? 0,
      bottom: margin?.bottom ?? 0,
      left: margin?.left ?? 0,
    },
    1,
  );

  return <g transform={`translate(${stableMargin.left}, ${stableMargin.top})`} />;
}
```

### Normalize accessors

Use `normalizeAccessor` when an API accepts either a string key or a function accessor.

```ts
import { normalizeAccessor } from '@visx/kernel';

type Datum = { label: string; value: number };

const getValue = normalizeAccessor<Datum, number>('value');
const value = getValue({ label: 'Q1', value: 42 }, 0, []);
```

Simple property accessors normalize to the same cached function as their string-key equivalent.

```ts
const byKey = normalizeAccessor<Datum, number>('value');
const byFunction = normalizeAccessor<Datum, number>((datum) => datum.value);

byKey === byFunction; // true
```

### Compute domains with shared warnings

`useDomain` normalizes accessors, skips invalid values, stabilizes the returned domain, and emits
structured development warnings for dirty input.

```tsx
import { useDomain } from '@visx/kernel';

function RevenueChart({ data }) {
  const domain = useDomain({
    data,
    accessor: 'revenue',
    type: 'linear',
  });

  return <span>{domain.join(' - ')}</span>;
}
```

### Keep callbacks and ids stable

Use `useStableCallback` when event handlers need stable identity but fresh closed-over values. Use
`useStableId` for SVG definitions and a11y relationships that must not remount every render.

```tsx
import { useLatestRef, useStableCallback, useStableId } from '@visx/kernel';

function InteractiveLayer({ data, onSelect }) {
  const dataRef = useLatestRef(data);
  const clipId = useStableId('scatter-clip');
  const handlePointerMove = useStableCallback((index: number) => {
    onSelect(dataRef.current[index]);
  });

  return (
    <svg>
      <clipPath id={clipId}>
        <rect width={400} height={240} />
      </clipPath>
      <rect clipPath={`url(#${clipId})`} onPointerMove={() => handlePointerMove(0)} />
    </svg>
  );
}
```

### Build and cache path strings

Use `createPath` when a package needs a small SVG path builder with shared precision behavior. Pass
the resulting string to `toPath2D` when drawing the same path on Canvas.

```ts
import { createPath, toPath2D } from '@visx/kernel';

const d = createPath(2).moveTo(0, 0).lineTo(12.345, 67.89).closePath().toString();
const path = toPath2D(d);
```

`toPath2D(d)` returns a real `Path2D` in browsers. On the server, it returns a minimal object that
stores the path string for cache identity and string inspection; it is not a drawing polyfill.

### Format numbers consistently

Use `formatNumber` when a hook needs a small default formatter without adding a d3-format
dependency.

```ts
import { formatNumber } from '@visx/kernel';

const label = formatNumber(1234.56, {
  maximumFractionDigits: 1,
  minimumFractionDigits: 1,
});
```

### Capture warning details

Use `setWarnHandler` in tests, docs, or integrations that need structured warning payloads.

```ts
import { setWarnHandler } from '@visx/kernel';

const restore = setWarnHandler(({ code, details, source }) => {
  console.info(source, code, details);
});

try {
  renderChartWithDirtyData();
} finally {
  restore();
}
```

---

### Overview (`packages/visx-legend/Readme.md`)

# @visx/legend

<a title="@visx/legend npm downloads" href="https://www.npmjs.com/package/@visx/legend">
  <img src="https://img.shields.io/npm/dm/@visx/legend.svg?style=flat-square" />
</a>

Legends associate shapes and colors to data, and are associated with scales.

## Example

```js
import { LegendThreshold } from '@visx/legend';
import { scaleThreshold } from '@visx/scale';

const threshold = scaleThreshold({
  domain: [0.02, 0.04, 0.06, 0.08, 0.1],
  range: ['#f2f0f7', '#dadaeb', '#bcbddc', '#9e9ac8', '#756bb1', '#54278f'],
});

function MyChart() {
  return (
    <div>
      <svg>{/** chart stuff */}</svg>
      <LegendThreshold
        scale={threshold}
        direction="column-reverse"
        itemDirection="row-reverse"
        labelMargin="0 20px 0 0"
        shapeMargin="1px 0 0"
      />
    </div>
  );
}
```

## Installation

```
npm install --save @visx/legend
```

---

### Overview (`packages/visx-marker/Readme.md`)

# @visx/marker

<a title="@visx/marker npm downloads" href="https://www.npmjs.com/package/@visx/marker">
  <img src="https://img.shields.io/npm/dm/@visx/marker.svg?style=flat-square" />
</a>

Markers are graphical objects attached to a `<path>`, `<line>`, `<polyline>`, or `<polygon>`
element. [MDN `<marker>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/marker)

## Installation

```
npm install --save @visx/marker
```

---

### Overview (`packages/visx-mock-data/Readme.md`)

# @visx/mock-data

<a title="@visx/mock-data npm downloads" href="https://www.npmjs.com/package/@visx/mock-data">
  <img src="https://img.shields.io/npm/dm/@visx/mock-data.svg?style=flat-square" />
</a>

The `@visx/mock-data` package is here to help you test out your graphs.

## Installation

```
npm install --save @visx/mock-data
```

## Generators

Generators can create simple generic data for you like this:

```js
import Mock from '@visx/mock-data';
const points = Mock.genRandomNormalPoints();
```

### `Mock.genRandomNormalPoints()`

Returns a series of random normal x,y points.

### `Mock.getDateValue(n)`

Generates `n` date values an hour apart from each other starting with the current time.

## Mocks

Mock are essentially a bunch of data dumps that you can use like this:

```js
import Mock from '@visx/mock-data';
// or import { cityTemperature } from '@visx/mock-data';
const data = Mock.cityTemperature;
```

### `Mock.appleStock`

```js
interface AppleStock {
  date: string;
  close: number;
}

const appleStock: AppleStock[] = [
  { date: '2007-04-24T07:00:00.000Z', close: 93.24 },
  ...
];
```

### `Mock.bitcoinPrice`

```js
interface BitcoinPrices {
  currency: string;
  prices: BitcoinPrice[];
}

const bitcoinPrice: BitcoinPrices = {
  currency: 'USD',
  prices: [
    { price: '2486.69', time: '2017-07-03T00:00:00Z' },
    ...
  ]
};
```

### `Mock.browserUsage`

```js
const browserUsage: BrowserUsage[] = [
  {
    date: '2015 Jun 15',
    'Google Chrome': '48.09',
    'Internet Explorer': '24.14',
    Firefox: '18.82',
    Safari: '7.46',
    'Microsoft Edge': '0.03',
    Opera: '1.32',
    Mozilla: '0.12',
    'Other/Unknown': '0.01',
  },
  ...
];
```

### `Mock.cityTemperature`

```ts
interface CityTemperature {
  date: string;
  'New York': string;
  'San Francisco': string;
  Austin: string;
}

const cityTemperature: CityTemperature[] = [
  {
    date: '20111001',
    'New York': '63.4',
    'San Francisco': '62.7',
    Austin: '72.2',
  },
  ...
];
```

### `Mock.exoplanets`

```ts
interface Exoplanets {
  name: string;
  radius: number;
  distance: number | null;
}

const exoplanets: Exoplanets[] = [
  {
    name: 'Jupiter',
    radius: 10.97,
    distance: 0,
  },
  ...
];
```

### `Mock.groupDateValue`

```ts
interface GroupDateValue {
  key: string;
  value: string;
  date: string;
}

const groupDateValue: GroupDateValue[] = [
  { key: 'Group1', value: '37', date: '04/23/12' },
  ...
];
```

### `Mock.lesMiserables`

```ts
interface LesMiserablesNode {
  id: string;
  group: number;
}

interface LesMiserablesLink {
  source: string;
  target: string;
  value: number;
}

interface LesMiserables {
  nodes: LesMiserablesNode[];
  links: LesMiserablesLink[];
}

const lesMiserables: LesMiserables = {
  nodes: [
    { id: 'Myriel', group: 1 },
    ...
  ],
  links: [
    { source: 'Napoleon', target: 'Myriel', value: 1 },
    ...
  ],
};
```

### `Mock.letterFrequency`

```ts
interface LetterFrequency {
  letter: string;
  frequency: number;
}

const letterFrequency: LetterFrequency[] = [
  { letter: 'A', frequency: 0.08167 },
  ...
];
```

### `Mock.shakespeare`

```ts
interface Shakespeare {
  id: string;
  parent: string | null;
  size: number | null;
}

const shakespeare: Shakespeare[] = [
  {
    id: 'Shakespeare',
    parent: null,
    size: 0,
  },
  ...
];
```

## Source For Components

### `generators/`

- [genDateValue()](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/generators/genDateValue.ts)
- [genRandomNormalPoints()](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/generators/genRandomNormalPoints.ts)

### `mocks/`

- [appleStock](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/mocks/appleStock.ts)
- [browserUsage](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/mocks/browserUsage.ts)
- [cityTemperature](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/mocks/cityTemperature.ts)
- [groupDateValue](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/mocks/groupDateValue.ts)
- [letterFrequency](https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/src/mocks/letterFrequency.ts)

---

### Overview (`packages/visx-network/Readme.md`)

# @visx/network

<a title="@visx/network npm downloads" href="https://www.npmjs.com/package/@visx/network">
  <img src="https://img.shields.io/npm/dm/@visx/network.svg?style=flat-square" />
</a>

A simple package to visualize a network or graph layout. Does not currently handle network layout.

## Example Usage

```js
import { Graph, DefaultLink, DefaultNode } from '@visx/network';
const nodes = [
  { x: 50, y: 20 },
  { x: 200, y: 300 },
  { x: 300, y: 40 },
];

const dataSample = {
  nodes,
  links: [
    { source: nodes[0], target: nodes[1] },
    { source: nodes[1], target: nodes[2] },
    { source: nodes[2], target: nodes[0] },
  ],
};

const MyGraph = () => (
  <Graph graph={dataSample} linkComponent={DefaultLink} nodeComponent={DefaultNode} />
);
```

## Installation

```
npm install --save @visx/network
```

---

### Overview (`packages/visx-pattern/Readme.md`)

# @visx/pattern

<a title="@visx/pattern npm downloads" href="https://www.npmjs.com/package/@visx/pattern">
  <img src="https://img.shields.io/npm/dm/@visx/pattern.svg?style=flat-square" />
</a>

Inspired by: http://riccardoscalco.github.io/textures/

## Example

```js
import { AreaClosed } from '@visx/shape';
import { PatternLines } from '@visx/pattern';

const PatternArea = () => {
  return (
    <svg>
      <PatternLines
        id="lines"
        height={5}
        width={5}
        stroke={'black'}
        strokeWidth={1}
        orientation={['diagonal']}
      />
      <AreaClosed fill="url('#lines')" />
    </svg>
  );
};
```

## The Definition Caveat

Like gradients, patterns are "defined." When you put down a `<PatternXYZ />`, it's putting a
[`<pattern/>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Patterns) attribute in the
SVG.

It's often better to think of these as variable definitions rather than true DOM elements. When you
use `fill="url('#pattern')"` you're referencing the pattern's id: `pattern`.

## Pre-Made Patterns

### `PatternsCircles`



```js
<PatternCircles id="circles" height={6} width={6} stroke={'black'} strokeWidth={1} />
```

### `PatternsHexagons`



```js
<PatternHexagons id="hexagons" height={3} size={8} stroke={'red'} strokeWidth={1} />
```

### `PatternsLines`



```js
<PatternLines
  id="lines"
  height={5}
  width={5}
  stroke={'black'}
  strokeWidth={1}
  orientation={['diagonal']}
/>
```

### `PatternsWaves`



```js
<PatternWaves id="waves" height={4} width={4} stroke={'blue'} strokeWidth={1} />
```

## Installation

```
npm install --save @visx/pattern
```

---

### Overview (`packages/visx-point/Readme.md`)

# @visx/point

<a title="@visx/point npm downloads" href="https://www.npmjs.com/package/@visx/point">
  <img src="https://img.shields.io/npm/dm/@visx/point.svg?style=flat-square" />
</a>

A simple class to represent an `x, y` coordinate.

## Installation

```
npm install --save @visx/point
```

## Example Usage

```js
import { Point } from '@visx/point';

const point = new Point({ x: 2, y: 3 });
const { x, y } = point.value(); // Get the coords as an object
const [x, y] = point.toArray(); // or array
```

## Methods

### `point.value()`

Returns an `{ x, y }` object with the x and y coordinates.

### `point.toArray()`

Returns the coordinates as an array `[x, y]`.

---

### Overview (`packages/visx-react-spring/README.md`)

# @visx/react-spring

<a title="@visx/react-spring npm downloads" href="https://www.npmjs.com/package/@visx/react-spring">
  <img src="https://img.shields.io/npm/dm/@visx/react-spring.svg?style=flat-square" />
</a>

Although `visx` is largely unopinioned on animation, there is value in abstracting the complexity +
boilerplate of building **animated** `visx` visualization components. This package requires
`react-spring` as a `peerDependency` (to be compatible with any usage within your app) and exports
all `visx` components that depend on `react-spring`.

[`react-spring`](https://www.react-spring.io/) provides performant primitives for animating react
components and is our recommended library for making animated charts. In order to minimize
`react-spring` as a dependency across other `visx` packages, we've consolidated components which
depend on it here.

## Installation

```
npm install --save react-spring @visx/react-spring
```

---

### Overview (`packages/visx-registry/Readme.md`)

# @visx/registry

Source files and validation scripts for the visx shadcn registry. This package is private and has no
runtime API; it exists to ship drop-in chart components through GitHub registry installs.

## Motivation

visx is intentionally low level: primitives take props, compose freely, and stay out of your app's
state model. That is what makes visx useful for unusual charts, custom dashboards, and product
interfaces that do not fit a fixed charting API.

The tradeoff is that teams often need a good starting point before they can customize. A line chart,
bar chart, heatmap chart, or treemap chart usually needs the same surrounding work:

- responsive SVG sizing
- theme token usage
- axis and grid styling
- accessible SVG labels and descriptions
- hidden data table fallbacks
- live region wiring
- installable dependency metadata

That work is valuable, but it is repetitive. `@visx/registry` packages those starting points as
copyable registry items while keeping the installed output plain React and visx primitives.

## Registry-first design

The registry package is distribution infrastructure, not a chart framework.

- Registry items install into user projects as source files.
- Installed charts depend on public visx packages, not `@visx/registry`.
- Source files live under `registry/charts`.
- The repository root `registry.json` is the public GitHub registry entrypoint.
- The source registries are committed, but generated `public/r` item JSON is not.
- Each chart remains editable after install.

This keeps the installed result compatible with the rest of visx: users can change scales, marks,
themes, accessibility labels, data accessors, and layout directly in their app.

## Local development

Add or edit chart source in `registry/charts`, then update `registry.json` with the item metadata,
dependencies, source path, and install target.

```sh
yarn registry:validate
```

This validates both the root GitHub registry entrypoint and the package source registry with the
shadcn CLI.

Run the focused registry test suite when changing chart source, metadata, or build scripts:

```sh
yarn vitest run --project @visx/registry
```

Run the install smoke when changing public item names, file targets, dependencies, or exported
component names:

```sh
yarn registry:smoke
```

The smoke test installs every registry item into fresh Next and Vite fixtures with the real shadcn
CLI and typechecks the installed source.

## Item structure

Each registry item should have a stable install name and a matching component export.

```txt
registry/charts/line-chart/line-chart.tsx
components/charts/line-chart.tsx
export function LineChart()
```

Use the `-chart` suffix for chart item names, source files, targets, and exported components. This
keeps registry install names, file names, and generated import names predictable.

## GitHub installs

The public registry entrypoint is the repository root `registry.json`, which includes this package's
source registry:

```txt
registry.json
packages/visx-registry/registry.json
```

After the registry branch lands on the default branch and the referenced visx packages are
published, items can be installed with the shadcn CLI by GitHub address:

```sh
npx shadcn@latest add airbnb/visx/line-chart
```

The local smoke test builds registry item JSON into a temporary directory only so unpublished branch
changes can still be installed into fresh fixtures.

## Accessibility and theming

Registry charts should ship with live accessibility wiring from `@visx/a11y` and theme token usage
from `@visx/theme`.

Use `showLiveRegion={false}` when rendering multiple charts on a page that owns a single shared
announcer. The chart should still render its SVG semantics and hidden data table fallback.

Charts should read theme values through visx theme hooks and CSS-ready variables, rather than
hard-coding light and dark mode branches.

---

### Overview (`packages/visx-responsive/Readme.md`)

# @visx/responsive

<a title="@visx/responsive npm downloads" href="https://www.npmjs.com/package/@visx/responsive">
  <img src="https://img.shields.io/npm/dm/@visx/responsive.svg?style=flat-square" />
</a>

The `@visx/responsive` package is here to help you make responsive graphs by providing a collection
of hooks, enhancers and components.

## Installation

```
npm install --save @visx/responsive
```

## Hooks

### `useScreenSize`

If you would like your graph to adapt to the screen size, you can use the `useScreenSize()` hook. It
returns current screen width and height and updates the value automatically on browser window
resize. You can optionally pass a config object as an argument to the hook. Config object attributes
are:

- `initialSize` - initial size before measuring the screen, defaults to `{ width: 0, height: 0 }`.
- `debounceTime` - determines how often the size is updated in milliseconds, defaults to `300`.
- `enableDebounceLeadingCall` - determines whether the size is updated immediately on first render,
  defaults to `true`. This is essentially the value of
  [`options.leading` in Lodash's `debounce`](https://lodash.com/docs/4.17.15#debounce).

#### Example

```tsx
import { useScreenSize } from '@visx/responsive';

const ChartToRender = () => {
  const { width, height } = useScreenSize({ debounceTime: 150 });

  return (
    <svg width={width} height={height}>
      {/* content */}
    </svg>
  );
};

const chartToRender = <ChartToRender myProp="string" />;
```

### `useParentSize`

If you want your graph to adapt to its parent size, you can use `useParentSize()` hook.
`<ParentSize>` uses this hook internally. The hook returns `width`, `height`, `left`, `top`
properties which describe dimensions of the container which received `parentRef` ref. You can
optionally pass a config object as an argument to the hook. Config object attributes are:

- `initialSize` - initial size before measuring the parent, defaults to
  `{ width: 0, height: 0, left: 0, top: 0 }`.
- `debounceTime` - determines how often the size is updated in miliseconds, defaults to `300`.
- `enableDebounceLeadingCall` - determines whether the size is updated immediately on first render,
  defaults to `true`. This is essentially the value of
  [`options.leading` in Lodash's `debounce`](https://lodash.com/docs/4.17.15#debounce).
- `ignoreDimensions` - array of dimensions for which an update should be skipped. For example, if
  you pass `['width']`, width changes of the component that received `parentRef` won't be
  propagated. Defaults to `[]` (all dimensions changes trigger updates).

#### Example

```tsx
import { useParentSize } from '@visx/responsive';

const ChartToRender = () => {
  const { parentRef, width, height } = useParentSize({ debounceTime: 150 });

  return (
    <div ref={parentRef}>
      <svg width={width} height={height}>
        {/* content */}
      </svg>
    </div>
  );
};

const chartToRender = <ChartToRender myProp="string" />;
```

## Enhancers / (HOCs)

### `withScreenSize`

If you prefer to use an enhancer, you can use the `withScreenSize()`. The resulting component will
pass `screenWidth` and `screenHeight` props to the wrapped component containing the respective
screen dimensions. You can also optionally pass config props to the wrapped component:

- `debounceTime` - determines how often the size is updated in milliseconds, defaults to `300`.
- `windowResizeDebounceTime` - deprecated, equivalent to the above, kept for backwards compatibility
- `enableDebounceLeadingCall` - determines whether the size is updated immediately on first render,
  defaults to `true`. This is essentially the value of
  [`options.leading` in Lodash's `debounce`](https://lodash.com/docs/4.17.15#debounce).

#### Example

```tsx
import { withScreenSize, WithScreenSizeProvidedProps } from '@visx/responsive';

interface Props extends WithScreenSizeProvidedProps {
  myProp: string;
}

const MySuperCoolVisxChart = ({ myProp, screenWidth, screenHeight }: Props) => {
  // ...
};

const ChartToRender = withScreenSize(MySuperCoolVisxChart);

const chartToRender = <ChartToRender myProp="string" />;
```

### `withParentSize`

If you prefer to use an enhancer to adapt your graph to its parent component's size, you can use
`withParentSize()`. The resulting component will pass `parentWidth` and `parentHeight` props to the
wrapped component containing the respective parent's dimensions. You can also optionally pass config
props to the wrapped component:

- `initialWidth` - initial chart width used before the parent size is determined.
- `initialHeight` - initial chart height used before the parent size is determined.
- `debounceTime` - determines how often the size is updated in miliseconds, defaults to `300`.
- `enableDebounceLeadingCall` - determines whether the size is updated immediately on first render,
  defaults to `true`. This is essentially the value of
  [`options.leading` in Lodash's `debounce`](https://lodash.com/docs/4.17.15#debounce).

#### Example

```tsx
import { withParentSize, WithParentSizeProvidedProps } from '@visx/responsive';

interface Props extends WithParentSizeProvidedProps {
  myProp: string;
}

const MySuperCoolVisxChart = ({ myProp, parentWidth, parentHeight }: Props) => {
  // ...
};

const ChartWithParentSize = withParentSize(MySuperCoolVisxChart);

const chartToRender = <ChartWithParentSize myProp="string" initialWidth={400} />;
```

## Components

### `ParentSize`

You might do the same thing as `useParentSize` or `withParentSize` using the `ParentSize` component.

#### Example

```tsx
import { ParentSize } from '@visx/responsive';

const chartToRender = (
  <ParentSize>
    {(parent) => (
      <MySuperCoolVisxChart
        parentWidth={parent.width}
        parentHeight={parent.height}
        parentTop={parent.top}
        parentLeft={parent.left}
        // this is the referrer to the wrapper component
        parentRef={parent.ref}
        // this function can be called inside MyVisxChart to cause a resize of the wrapper component
        resizeParent={parent.resize}
      />
    )}
  </ParentSize>
);
```

### `ScaleSVG`

You can also create a responsive chart with a specific viewBox with the `ScaleSVG` component.

#### Example

```tsx
import { ScaleSVG } from '@visx/responsive';

const chartToRender = (
  <ScaleSVG width={400} height={400}>
    <MySuperCoolVXChart />
  </ScaleSVG>
);
```

## ⚠️ `ResizeObserver` dependency

`useParentSize`, `ParentSize` and `withParentSize` rely on `ResizeObserver`s for auto-sizing. If you
need a polyfill, you can either pollute the `window` object or inject it cleanly like this:

```tsx
import { ResizeObserver } from 'your-favorite-polyfill';

// hook
useParentSize({ resizeObserverPolyfill: ResizeObserver });

// component
<ParentSize resizeObserverPolyfill={ResizeObserver} {...}>
  {() => {...}}
</ParentSize>

// enhancer
withParentSize(MyComponent, ResizeObserver);
```

---

### Overview (`packages/visx-sankey/Readme.md`)

# @visx/sankey

<a title="@visx/sankey npm downloads" href="https://www.npmjs.com/package/@visx/sankey">
  <img src="https://img.shields.io/npm/dm/@visx/sankey.svg?style=flat-square" />
</a>

Sankey diagrams visualize the directed flow between nodes in an acyclic network. This package
contains `react` components for visualizing sankey diagrams and largely mirrors
[`d3-sankey`](https://github.com/d3/d3-sankey).

Many components take the same input `sankey` data as defined in as specified in the
[`d3-sankey`](https://github.com/d3/d3-sankey) module to output a graph of the sankey layout. For
convenience, this package also exports the [`d3-sankey`](https://github.com/d3/d3-sankey)utility to
generate this format.

## Installation

```
npm install --save @visx/sankey
```

## Usage

The `@visx/sankey` package exports a wrapped version of `d3-sankey` for flexible usage, as well as a
`<Sankey />` component for rendering the sankey layout.

```js
// equivalent to `import { sankey } from 'd3-sankey';`
import { sankey } from '@visx/sankey';

const generator = sankey();
const graph = generator({
  nodes: [{ name: 'node 1' }, { name: 'node 2' }, { name: 'node 3' }],
  links: [
    { source: 0, target: 1, value: 10 },
    { source: 1, target: 2, value: 5 },
  ],
});
```

```js
import { Sankey, sankeyCenter } from '@visx/sankey';

const nodes = [{ name: 'node 1' }, { name: 'node 2' }, { name: 'node 3' }];
const links = [
  { source: 0, target: 1, value: 10 },
  { source: 1, target: 2, value: 5 },
];
const data = { nodes, links };

return (
  <svg>
    <Sankey root={data} nodeAlign={sankeyCenter} size={[100, 100]} />
  </svg>
);
```

The layout output can also be customized by providing a children function to the `<Sankey />`
component.

```js
import { Sankey, sankeyCenter } from '@visx/sankey';
import { Group } from '@visx/group';
import { BarRounded, LinkHorizontal } from '@visx/group';

const nodes = [{ name: 'node 1' }, { name: 'node 2' }, { name: 'node 3' }];
const links = [
  { source: 0, target: 1, value: 10 },
  { source: 1, target: 2, value: 5 },
];
const data = { nodes, links };

return (
  <svg>
    <Sankey root={data} nodeAlign={sankeyCenter} size={[100, 100]}>
      {({ graph, createPath }) => (
        <>
          <Group>
            {graph.links.map((link, i) => (
              <LinkHorizontal
                key={i}
                data={link}
                path={createPath}
                fill="transparent"
                stroke="#f50057"
                strokeWidth={link.width}
                strokeOpacity={0.5}
              />
            ))}
          </Group>
          <Group>
            {graph.nodes.map(({ y0, y1, x0, x1, name }, i) => (
              <BarRounded
                key={i}
                width={x1 - x0}
                height={y1 - y0}
                x={x0}
                y={y0}
                radius={3}
                fill="#f50057"
                all
              />
            ))}
          </Group>
        </>
      )}
    </Sankey>
  </svg>
);
```

---

### Overview (`packages/visx-scale/Readme.md`)

# @visx/scale

<a title="@visx/scale npm downloads" href="https://www.npmjs.com/package/@visx/scale">
  <img src="https://img.shields.io/npm/dm/@visx/scale.svg?style=flat-square" />
</a>

## Installation

```sh
npm install --save @visx/scale
```

## Overview of scales

The `@visx/scale` package aims to provide a wrapper around existing `d3` scaling originally defined
in the [d3-scale](https://github.com/d3/d3-scale) package.

Scales are functions that help you map your data values to the physical pixel size that your graph
requires. For example, let's say you wanted to create a bar chart to show populations per country.
If you were to use a 1-to-1 scale (IE: 1 pixel per y value) your bar for the USA would be about
321.4 million pixels high!

Instead, you can tell `visx` a function to use that takes a data value (like your population per
country) and quantitatively maps to another dimensional space, like pixels.

For example, we could create a linear scale like this:

```js
const graphWidth = 500;
const graphHeight = 200;
const [minX, maxX] = getXMinAndMax();
const [minY, maxY] = getYMinAndMax();

const xScale = Scale.scaleLinear({
  domain: [minX, maxX], // x-coordinate data values
  range: [0, graphWidth], // svg x-coordinates, svg x-coordinates increase left to right
  round: true,
});

const yScale = Scale.scaleLinear({
  domain: [minY, maxY], // y-coordinate data values
  // svg y-coordinates, these increase from top to bottom so we reverse the order
  // so that minY in data space maps to graphHeight in svg y-coordinate space
  range: [graphHeight, 0],
  round: true,
});

// ...

const points = data.map((d, i) => {
  const barHeight = graphHeight - yScale(d.y);
  return <Shape.Bar height={barHeight} y={graphHeight - barHeight} />;
});
```

## Different types of scales

### Band scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#_band)

Example:

```js
const scale = Scale.scaleBand({
  /*
    range,
    round,
    domain,
    padding,
    nice = false
  */
});
```

### Linear scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scaleLinear)

Example:

```js
const scale = Scale.scaleLinear({
  /*
    range,
    round,
    domain,
    nice = false,
    clamp = false,
  */
});
```

### Log scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scaleLog)

Example:

```js
const scale = Scale.scaleLog({
  /*
    range,
    round,
    domain,
    base,
    nice = false,
    clamp = false,
  */
});
```

**Important note:** As log(0) = -∞, a log scale domain must be strictly-positive or
strictly-negative; the domain must not include or cross zero.

### Radial scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scaleRadial)

Example:

```js
const scale = Scale.scaleRadial({
  /*
    range,
    round,
    domain,
    nice = false,
    clamp = false,
  */
});
```

### Ordinal scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scaleOrdinal)

Example:

```js
const scale = Scale.scaleOrdinal({
  /*
    range,
    domain,
    unknown,
  */
});
```

### Point scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scalePoint)

Example:

```js
const scale = Scale.scalePoint({
  /*
    range,
    round,
    domain,
    padding,
    align,
    nice = false,
  */
});
```

### Power scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scalePow)

Example:

```js
const scale = Scale.scalePower({
  /*
    range,
    round,
    domain,
    exponent,
    nice = false,
    clamp = false,
  */
});
```

### Square Root scale

[Original d3 docs](https://github.com/d3/d3-scale#scaleSqrt)

Example:

```js
// No need to set the exponent, It is always 0.5
const scale = Scale.scaleSqrt({
  /*
    range,
    round,
    domain,
    nice = false,
    clamp = false,
  */
});
```

### Time scale

[Original d3 docs](https://github.com/d3/d3-scale/blob/master/README.md#scaleTime)

Example:

```js
const scale = Scale.scaleTime({
  /*
    range,
    round,
    domain,
    nice = false,
    clamp = false,
   */
});
```

You also can scale time with Coordinated Universal Time via `scaleUtc`.

Example:

```js
const scale = Scale.scaleUtc({
  /*
    range,
    round,
    domain,
    nice = false,
    clamp = false,
   */
});
```

### Color Scales

D3 scales offer the ability to map points to colors. You can use
[`d3-scale-chromatic`](https://github.com/d3/d3-scale-chromatic) in conjunction with visx's
`scaleOrdinal` to make color scales.

You can install `d3-scale-chromatic` with npm:

```sh
npm install --save d3-scale-chromatic
```

You create a color scale like so:

```js
import { scaleOrdinal } from '@visx/scale';
import { schemeSet1 } from 'd3-scale-chromatic';

const colorScale = scaleOrdinal({
  domain: arrayOfThings,
  range: schemeSet1,
});
```

This generates a color scale with the following colors:



There are a number of other
[categorical color schemes](https://github.com/d3/d3-scale-chromatic/blob/master/README.md#categorical)
available, along with other continuous color schemes.

---

### Overview (`packages/visx-shape/Readme.md`)

# @visx/shape

<a title="@visx/shape npm downloads" href="https://www.npmjs.com/package/@visx/shape">
  <img src="https://img.shields.io/npm/dm/@visx/shape.svg?style=flat-square" />
</a>

Shapes are the core elements of `visx`. Most of what you see on the screen, like lines, bars, and
areas are all made with shape primitives.

## Installation

```
npm install --save @visx/shape
```

---

### Overview (`packages/visx-stats/Readme.md`)

# @visx/stats

<a title="@visx/stats npm downloads" href="https://www.npmjs.com/package/@visx/stats">
  <img src="https://img.shields.io/npm/dm/@visx/stats.svg?style=flat-square" />
</a>

The package provides `react` components for visualizing distributions, such as Box Plots and Violin
Plots

## Installation

```
npm install --save @visx/stats
```

---

### Overview (`packages/visx-text/Readme.md`)

# @visx/text

<a title="@visx/text npm downloads" href="https://www.npmjs.com/package/@visx/text">
  <img src="https://img.shields.io/npm/dm/@visx/text.svg?style=flat-square" />
</a>

The `@visx/text` provides a better SVG `<Text>` component with the following features

- Word-wrapping (when `width` prop is defined)
- Vertical alignment (`verticalAnchor` prop)
- Rotation (`angle` prop)
- Scale-to-fit text (`scaleToFit` prop)

## Example

Simple demo to show off a useful feature. Since svg `<text>` itself does not support
`verticalAnchor`, normally text rendered at `0,0` would be outside the viewport and thus not
visible. By using `<Text>` with the `verticalAnchor="start"` prop, the text will now be visible as
you'd expect.

```jsx
import React from 'react';
// note: react@18 syntax
import { createRoot } from 'react-dom/client';
import { Text } from '@visx/text';

const App = () => (
  <svg>
    <Text verticalAnchor="start">Hello world</Text>
  </svg>
);

const root = createRoot(document.getElementById('root'));

root.render(<App />);
```

## Installation

```
npm install --save @visx/text
```

---

### Overview (`packages/visx-theme/Readme.md`)

# @visx/theme

Utilities for sharing visual tokens across visx charts without changing the low-level visx primitive
model. The package is split into an RSC-safe root entry for CSS scoping and a client entry for React
hooks.

## Installation

```sh
npm install --save @visx/theme
```

## Motivation

visx is intentionally low level: primitives take props, compose freely, and stay out of your app's
state model. That is what makes visx useful for unusual charts, custom dashboards, and product
interfaces that do not fit a fixed charting API.

The tradeoff is that every primitive chart tends to rebuild the same styling layer:

- categorical colors for each series
- axis strokes, tick labels, and grid lines
- text colors, font family, and chart surfaces
- light/dark color branches
- design-system token plumbing

That works for one chart. It gets noisy when a dashboard has many charts built from different visx
packages. Small differences creep in, dark mode becomes duplicated JavaScript, and teams end up
copying local helpers from chart to chart.

`@visx/theme` gives those charts a shared visual language while keeping the rendering primitives
plain. It does not make `@visx/axis`, `@visx/grid`, or `@visx/shape` theme-aware. Instead, it gives
you CSS-ready values and small prop helpers that you can pass to the primitives you already use.

## Primitive-first design

The theme package is a convenience layer, not a chart framework.

- visx primitives remain prop-driven.
- Theme hooks return ordinary strings, numbers, and prop objects.
- CSS owns resolved colors through custom properties.
- Explicit chart props and `ChartConfig.color` overrides always win.
- Apps own light/dark mode, class names, data attributes, and design-system providers.
- You can use one hook, the whole provider, or only `ThemeScope`.

This keeps shadcn/ui integration zero-config for common apps without making shadcn/ui a requirement
or a constraint. If a chart needs a custom palette, a per-series CSS variable, a hand-tuned axis, or
no theme integration at all, the primitive API still supports that.

## Basic usage

Use `ThemeScope` from the root entry when a server component or app layout only needs to provide the
chart CSS variable boundary.

```tsx
import { ThemeScope } from '@visx/theme';
import type { ReactNode } from 'react';

export default function DashboardLayout({ children }: { children: ReactNode }) {
  return (
    <ThemeScope theme="auto" className="dashboard-charts">
      {children}
    </ThemeScope>
  );
}
```

Use `ThemeProvider` from the client entry when chart components need theme hooks.

```tsx
'use client';

import { ThemeProvider } from '@visx/theme/react';
import type { ReactNode } from 'react';

export function ChartShell({ children }: { children: ReactNode }) {
  return <ThemeProvider theme="auto">{children}</ThemeProvider>;
}
```

`theme="auto"` does not emit generated variables. It returns CSS-ready `var(...)` values, so the app
can own the current light or dark mode through classes, data attributes, media queries, or inline
CSS variables.

## shadcn/ui variables

The default auto theme reads the same chart variable names commonly used by shadcn/ui:

```css
.light {
  --chart-1: #2563eb;
  --chart-2: #16a34a;
  --background: #ffffff;
  --card: #ffffff;
  --border: #e5e7eb;
  --foreground: #0f172a;
  --muted-foreground: #64748b;
}

.dark {
  --chart-1: #60a5fa;
  --chart-2: #4ade80;
  --background: #020617;
  --card: #0f172a;
  --border: #334155;
  --foreground: #f8fafc;
  --muted-foreground: #94a3b8;
}
```

When the surrounding app flips `.light` to `.dark`, CSS variables update the chart colors.
`@visx/theme` does not install a mode switcher, call `matchMedia`, or read the DOM.

### Auto-mode limitation

CSS-backed tokens update through variables in auto mode:

- colors
- categorical colors
- background, surface, border, and text colors
- font family

JS-only numeric values cannot update from CSS alone:

- chart margins
- axis stroke width and tick length
- grid stroke width
- font sizes

Auto mode uses the light theme numeric defaults for those JS-only values. Pass an explicit theme
object from `defineTheme` when light and dark modes need different layout measurements.

## Migrating from `@visx/xychart`

Existing xychart code can keep using `XYChartTheme` directly. New primitive charts can reuse the
same visual choices with `fromXYChartTheme`.

```tsx
import { XYChart, buildChartTheme } from '@visx/xychart';
import { ThemeScope, fromXYChartTheme } from '@visx/theme';

const legacyTheme = buildChartTheme({
  backgroundColor: '#ffffff',
  colors: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'],
  gridColor: '#f3f4f6',
  gridColorDark: '#e5e7eb',
  tickLength: 4,
});

const primitiveTheme = fromXYChartTheme(legacyTheme);

export function Dashboard() {
  return (
    <>
      <XYChart theme={legacyTheme}>{/* existing chart */}</XYChart>
      <ThemeScope theme={primitiveTheme}>{/* new primitive chart */}</ThemeScope>
    </>
  );
}
```

The adapter is one-way and structural. `@visx/theme` does not import from `@visx/xychart`, and there
is no `toXYChartTheme` adapter.

## Recipes

### Line chart

```tsx
import { AxisBottom } from '@visx/axis';
import { GridRows } from '@visx/grid';
import { LinePath } from '@visx/shape';
import { useAxisStyle, useColor, useGridStyle } from '@visx/theme/react';

export function RevenueLine({ data, xScale, yScale }) {
  const axis = useAxisStyle('bottom');
  const grid = useGridStyle();
  const lineColor = useColor(0);

  return (
    <>
      <GridRows scale={yScale} stroke={grid.stroke} strokeWidth={grid.strokeWidth} />
      <LinePath
        data={data}
        x={(datum) => xScale(datum.date)}
        y={(datum) => yScale(datum.revenue)}
        stroke={lineColor}
        strokeWidth={2}
      />
      <AxisBottom
        scale={xScale}
        stroke={axis.stroke}
        tickLength={axis.tickLength}
        tickStroke={axis.tickStroke}
        tickLabelProps={axis.tickLabelProps}
      />
    </>
  );
}
```

### Bar chart

```tsx
import { AxisBottom, AxisLeft } from '@visx/axis';
import { Bar } from '@visx/shape';
import type { ChartConfig } from '@visx/theme';
import { useAxisStyle, useChartConfig } from '@visx/theme/react';

const seriesConfig = {
  desktop: { label: 'Desktop' },
  mobile: { label: 'Mobile' },
} satisfies ChartConfig<'desktop' | 'mobile'>;

export function TrafficBars({ data, xScale, yScale }) {
  const xAxis = useAxisStyle('bottom');
  const yAxis = useAxisStyle('left');
  const { getColor, getLabel } = useChartConfig(seriesConfig, {
    order: ['desktop', 'mobile'],
  });

  return (
    <>
      {data.map((datum) => (
        <Bar
          key={datum.browser}
          x={xScale(datum.browser)}
          y={yScale(datum.desktop)}
          width={xScale.bandwidth()}
          height={yScale(0) - yScale(datum.desktop)}
          fill={getColor('desktop')}
          aria-label={`${getLabel('desktop')} traffic`}
        />
      ))}
      <AxisBottom scale={xScale} {...xAxis} />
      <AxisLeft scale={yScale} {...yAxis} />
    </>
  );
}
```

### Area chart

```tsx
import { AxisLeft } from '@visx/axis';
import { AreaClosed } from '@visx/shape';
import { useAxisStyle, useColor, useGridStyle } from '@visx/theme/react';

export function ConversionArea({ data, xScale, yScale }) {
  const axis = useAxisStyle('left');
  const grid = useGridStyle();
  const fill = useColor(1);
  const stroke = useColor('highlight');

  return (
    <>
      <AreaClosed
        data={data}
        x={(datum) => xScale(datum.date)}
        y={(datum) => yScale(datum.conversionRate)}
        yScale={yScale}
        fill={fill}
        fillOpacity={0.18}
        stroke={stroke}
        strokeWidth={2}
      />
      <line x1={0} x2="100%" y1={0} y2={0} stroke={grid.stroke} />
      <AxisLeft
        scale={yScale}
        stroke={axis.stroke}
        tickStroke={axis.tickStroke}
        tickLabelProps={axis.tickLabelProps}
      />
    </>
  );
}
```

---

### Overview (`packages/visx-threshold/Readme.md`)

# @visx/threshold

<a title="@visx/threshold npm downloads" href="https://www.npmjs.com/package/@visx/threshold">
  <img src="https://img.shields.io/npm/dm/@visx/threshold.svg?style=flat-square" />
</a>

`@visx/threshold` allows for creation of Difference Charts in `react`, which highlight the delta
between two line series.

## Installation

```
npm install --save @visx/threshold
```

---

### Overview (`packages/visx-tooltip/Readme.md`)

# @visx/tooltip

<a title="@visx/tooltip npm downloads" href="https://www.npmjs.com/package/@visx/tooltip">
  <img src="https://img.shields.io/npm/dm/@visx/tooltip.svg?style=flat-square" />
</a>

The `@visx/tooltip` package provides utilities for making it easy to add `Tooltip`s to a
visualization and includes hooks, higher-order component (HOC) enhancers, and Tooltip components.

### Installation

```
npm install --save @visx/tooltip
```

### Modern Floating UI tooltips

`@visx/tooltip` also includes an additive Floating UI-backed surface for modern tooltip positioning.
Import it from the explicit React subpath:

```tsx
import {
  ChartTooltip,
  ChartTooltipContent,
  FloatingTooltip,
  useChartTooltip,
  useFloatingTooltip,
} from '@visx/tooltip/floating';
```

Existing `@visx/tooltip` exports are unchanged. Use the modern subpath when a chart needs
collision-aware placement, virtual anchors, SVG or cursor anchoring, arrows, controlled state, or
config-driven chart tooltip content.

#### Manual chart tooltip

`useChartTooltip()` owns tooltip open state, anchor state, and rendered items. Your chart still owns
nearest-datum lookup and event handling.

```tsx
import { localPoint } from '@visx/event';
import { ChartTooltip, type ChartTooltipConfig, useChartTooltip } from '@visx/tooltip/floating';

type Datum = { month: string; revenue: number };

const tooltipConfig = {
  revenue: {
    label: 'Revenue',
    color: '#3b82f6',
    formatValue: (value) => `$${Number(value).toLocaleString()}`,
  },
} satisfies ChartTooltipConfig<Datum>;

function RevenueChart({ data, width, height }: { data: Datum[]; width: number; height: number }) {
  const tooltip = useChartTooltip<Datum>({ placement: 'top', offset: 10 });

  return (
    <>
      <svg
        ref={tooltip.containerRef}
        width={width}
        height={height}
        onPointerMove={(event) => {
          const point = localPoint(event.currentTarget, event);
          if (!point) return;

          const datum = findNearestDatum(point, data);

          tooltip.show({
            anchor: point,
            items: [
              {
                key: 'revenue',
                datum,
                label: datum.month,
                rawValue: datum.revenue,
              },
            ],
          });
        }}
        onPointerLeave={tooltip.hide}
      >
        {data.map((datum) => (
          <circle key={datum.month} cx={xScale(datum.month)} cy={yScale(datum.revenue)} r={4} />
        ))}
      </svg>

      <ChartTooltip {...tooltip.tooltipProps} config={tooltipConfig} />
    </>
  );
}
```

When `tooltip.show()` receives `{ x, y }`, the coordinates are treated as CSS pixels local to the
element registered with `containerRef`. If you have SVG user-space coordinates from scales or glyph
positions, pass a shorthand SVG point instead:

```tsx
tooltip.show({
  anchor: { type: 'svg-local-point', x: xScale(datum.month), y: yScale(datum.revenue) },
  items: [{ key: 'revenue', datum, rawValue: datum.revenue }],
});
```

#### Low-level primitives

Use `FloatingTooltip` directly when you want complete control over positioning and content.

```tsx
<FloatingTooltip.Root
  open={open}
  anchor={{ type: 'point', x: event.clientX, y: event.clientY }}
  placement="right"
  offset={12}
  arrow
>
  <FloatingTooltip.Portal>
    <FloatingTooltip.Positioner className="Tooltip">
      <FloatingTooltip.Content>
        <FloatingTooltip.Arrow />
        {children}
      </FloatingTooltip.Content>
    </FloatingTooltip.Positioner>
  </FloatingTooltip.Portal>
</FloatingTooltip.Root>
```

#### DOM trigger tooltip

`FloatingTooltip.Trigger` is optional. When rendered, it wires hover, focus, dismiss, and tooltip
ARIA props through Floating UI. If `Root` also receives an explicit `anchor`, the trigger owns DOM
interactions while the anchor owns positioning.

```tsx
<FloatingTooltip.Provider delay={700} skipDelay={300}>
  <FloatingTooltip.Root>
    <FloatingTooltip.Trigger render={<button type="button">Export</button>} />
    <FloatingTooltip.Portal>
      <FloatingTooltip.Positioner>
        <FloatingTooltip.Content>Download chart data</FloatingTooltip.Content>
      </FloatingTooltip.Positioner>
    </FloatingTooltip.Portal>
  </FloatingTooltip.Root>
</FloatingTooltip.Provider>
```

Tooltip content should be brief and non-interactive. If content includes links, buttons, form
controls, or rich navigation, use a popover-style primitive instead of tooltip behavior.

### Hooks and Enhancers

This package provides two ways to add tooltip **state** logic to your chart components:

- a hook: `useTooltip()`
- a higher order component (HOC): `withTooltip()`

The `useTooltip` hook is the recommended way to add tooltip state logic to your components, but can
only be used in functional components. The `withTooltip` HOC can be used with both functional and
class components, and is the recommended way to add tooltip state logic to class components.

Both `useTooltip` and `withTooltip` expose the same values and functions for use in your component:

| Name          | Type   | Description                                                                                                                                           |
| :------------ | :----- | :---------------------------------------------------------------------------------------------------------------------------------------------------- |
| showTooltip   | func   | Call this function with the signature `func({ tooltipData, tooltipLeft, tooltipTop })` to set the tooltip state to the specified values.              |
| hideTooltip   | func   | Call this function to close a tooltip, i.e., set the `showTooltip` state to `false`.                                                                  |
| tooltipOpen   | bool   | Whether the tooltip state is open or closed                                                                                                           |
| tooltipLeft   | number | The `tooltipLeft` position passed to the `showTooltip` func, intended to be used for tooltip positioning                                              |
| tooltipTop    | number | The `tooltipTop` position passed to the `showTooltip` func, intended to be used for tooltip positioning                                               |
| tooltipData   | any    | The `tooltipData` value passed to the `showTooltip` func, intended to be used for any data that your tooltip might need to render                     |
| updateTooltip | func   | Call this function with the signature `func({ tooltipOpen, tooltipLeft, tooltipTop, tooltipData })` to set the tooltip state to the specified values. |

In the case of `useTooltip`, these will be returned from the `useTooltip()` call in your component.
In the case of `withTooltip`, they will be passed as props to your wrapped component. Refer to the
[Examples](#examples) section for a basic demo of each approach.

#### useTooltip()

If you would like to add tooltip state logic to a functional component, you may use the
`useTooltip()` hook which will return an object with several properties that you can use to manage
the tooltip state of your component. **For correct tooltip positioning, it is important to wrap your
component in an element (e.g., `div`) with `relative` positioning**. This is handled for you by the
`withTooltip` HOC, but not with the `useTooltip()` hook.

#### withTooltip(BaseComponent [, containerProps [, renderContainer]])

If you would like to add tooltip state logic to a class component, you may wrap it in
`withTooltip(BaseComponent [, containerProps [, renderContainer])`.

The HOC will wrap your component in a `div` with `relative` positioning by default and handle state
for tooltip positioning, visibility, and content by injecting the following props into your
`BaseComponent`:

You may override the container by specifying `containerProps` as the second argument to
`withTooltip`, or by specifying `renderContainer` as the third argument to `withTooltip`.

### Components

Tooltip **components** render tooltip **state** and can be used in conjunction with `useTooltip` and
`withTooltip` above.

> Note: Because Tooltip and TooltipWithBounds components are rendered within `<div>` elements, they
> **cannot** be inserted within any VisX charts (`<svg>` elements). Instead, place them anywhere
> outside of your rendered charts.

#### Tooltip

This is a simple Tooltip container component meant to be used to actually render a Tooltip. It
accepts the following props, and will spread any additional props on the tooltip container div
(i.e., ...restProps):

| Name      | Type             | Default | Description                                                                   |
| :-------- | :--------------- | :------ | :---------------------------------------------------------------------------- |
| left      | number or string | --      | Sets style.left of the tooltip container                                      |
| top       | number or string | --      | Sets style.top of the tooltip container                                       |
| className | string           | --      | Adds a class (in addition to `visx-tooltip-portal`) to the tooltip container  |
| style     | object           | --      | Sets / overrides any styles on the tooltip container (including top and left) |
| children  | node             | --      | Sets the children of the tooltip, i.e., the actual content                    |
| unstyled  | bool             | true    | Whether the tooltip should use styles from the style prop or not              |

#### TooltipWithBounds

This tooltip component is exactly the same as `Tooltip` above, but it is aware of its boundaries
meaning that it will flip left/right and bottom/top based on whether it would overflow its parent's
boundaries. It accepts the following props, and will spread any additional props on the Tooltip
component (i.e., ...restProps):

| Name       | Type   | Default | Description                                                                                                                                                                      |
| :--------- | :----- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| left       | number | --      | The horizontal position of the cursor, tooltip will be place to the left or right of this coordinate depending on the width of the tooltip and the size of the parent container. |
| top        | number | --      | The vertical position of the cursor, tooltip will be place to the bottom or top of this coordinate depending on the height of the tooltip and the size of the parent container.  |
| offsetLeft | number | 10      | Horizontal offset of the tooltip from the passed `left` value, functions as a horizontal padding.                                                                                |
| offsetTop  | number | 10      | Vertical offset of the tooltip from the passed `top` value, functions as a vertical padding.                                                                                     |
| style      | object | --      | Sets / overrides any styles on the tooltip container (including top and left)                                                                                                    |
| children   | node   | --      | Sets the children of the tooltip, i.e., the actual content                                                                                                                       |
| unstyled   | bool   | true    | Whether the tooltip should use styles from the style prop or not                                                                                                                 |

Note that this component is positioned using a `transform`, so overriding `left` and `top` via
styles may have no effect.

#### useTooltipInPortal

##### ⚠️ `ResizeObserver` dependency

This hook relies on `ResizeObserver`s. If you need a polyfill, you can either polute the `window`
object or inject it cleanly using the `polyfill` config option below.

`useTooltipInPortal` is a hook which gives you a `TooltipInPortal` component for rendering `Tooltip`
or `TooltipWithBounds` in a `Portal`, outside of your component DOM tree which can be useful in many
circumstances (see below for more on `Portal`s).

##### API

```
/* Detailed source-code truncated for AI context efficiency. */
```

#### Portal

`Portal` is a component which simply renders its children inside a `div` element appended to
`document.body` created by `ReactDOM`. A `Portal` can be an effective strategy for solving the
[`z-index` stacking context problem](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context)
for `Tooltip`s.

For example, if your chart is rendered inside a stacking context with a lower `z-index` than a
surrounding container, it may get clipped by that container even if you specify a higher `z-index`.
This is solvable with a `Portal` because the separate container will not be subject to the stacking
context of your chart.

To use a `Portal`, simply pass your `Tooltip` as a child: `<Portal><Tooltip {...} /></Portal>`. You
will also need to correct the `left` and `top` positions to be in _page coordinates_, not the
coordinates of your container which you would use when _not_ using a `Portal`. If reacting to a
mouse event, you can use `event.pageX/Y`. Alternatively, if you have container coordinates, you can
convert them to page coordinates using the following (note: `useTooltipInPortal` handles this for
you):

```js
const pageX = containerX + containerBoundingBox.left + window.scrollLeft;
const pageY = containerY + containerBoundingBox.top + window.scrollTop;
```

### Examples

#### useTooltip and useTooltipInPortal For Functional Components

```
/* Detailed source-code truncated for AI context efficiency. */
```

#### withTooltip For Class Components

```js
import { withTooltip, TooltipWithBounds } from '@visx/tooltip';
import { localPoint } from '@visx/event';

class Chart extends React.Component {
  handleMouseOver = (event, datum) => {
    const coords = localPoint(event.target.ownerSVGElement, event);
    this.props.showTooltip({
      tooltipLeft: coords.x,
      tooltipTop: coords.y,
      tooltipData: datum
    });
  };

  render() {
    const {
      tooltipData,
      tooltipLeft,
      tooltipTop,
      tooltipOpen,
      hideTooltip
    } = this.props;

    return (
      // note React.Fragment is only available in >= react@16.2
      <React.Fragment>
        <svg width={...} height={...}>
          // Chart here...
          <SomeChartElement onMouseOver={this.handleMouseOver} onMouseOut={hideTooltip} />
        </svg>

        {tooltipOpen && (
          <TooltipWithBounds
            // set this to random so it correctly updates with parent bounds
            key={Math.random()}
            top={tooltipTop}
            left={tooltipLeft}
          >
            Data value <strong>{tooltipData}</strong>
          </TooltipWithBounds>
        )}
      </React.Fragment>
    );
  }
}

const ChartWithTooltip = withTooltip(Chart);

render(<ChartWithTooltip />, document.getElementById("root"));
```

Example codesandbox [here](https://codesandbox.io/s/kw02m019mr).

---

### Overview (`packages/visx-vendor/Readme.md`)

# @visx/vendor

This package consists of vendored packages for other `visx` packages. It is meant to enable dual
support for export of CommonJS and ESM formats by _re-exporting_ some `visx` dependencies, and even
some transitive dependencies, which are ESM-only.

This package is heavily based off of
[`victory-vendor`](https://github.com/FormidableLabs/victory/tree/main/packages/victory-vendor)
which aims to solve the same problem.

## Vendored packages

All vendored packages are listed as `dependencies` in the `package.json` of this package (note that
the `installConfig.hoistingLimits` option is set for this package to guarantee version specificity
in this large monorepo where we may have mixed versions of `d3` packages). For each (non-types)
package `<pkg>`, we generate the following:

- an ESM version of the package in `esm/<pkg>.js`
- a CJS version of the package in `lib/<pkg>.js`
  - this points to the fully-transpiled version of the package in
    `vendor-cjs/vendor-<pkg>/src/index.js`
  - `vendor-cjs/vendor-<pkg>/LICENSE` contains the upstream license of the vendored package
  - other ESM-only packages (e.g., `<pkg2>`) that are referenced by `<pkg>` are updated to point to
    `vendor-cjs/vendor-<pkg2>/src/index.js`
- TypeScript types from `@types/<pkg>` as root `<pkg>.d.ts` files (when available as specified in
  the `package.json` `dependencies`)
- a root `<pkg>.js` file (pointing to the CJS version of the lib) for tooling that doesn't yet
  support `package.json:exports`
  ([conditional exports](https://nodejs.org/api/packages.html#conditional-exports))

## How it works

We provide two alternate paths and behaviors -- for ESM and CommonJS

### ESM

When you use a module `import` syntax like the following, it will resolve to a re-exported version
of `node_modules/d3-interpolate`, the unmodified ESM library from D3.

```ts
import { interpolate } from '@visx/vendor/d3-interpolate';
```

### CommonJS

If you use a CJS `require` syntax like the following, it will resolve to an alternate path that
contains the **transpiled** version of the underlying `d3-*` (or other) library to be found at
`@visx/vendor/vendor-cjs/d3-interpolate/**/*.js`.

```ts
const { interpolate } = require('@visx/vendor/d3-interpolate');
```

Such transpiled versions have _internally consistent_ import references to other other
`@visx/vendor/vendor-cjs/<pkg-name>` paths that need to be transpiled.

### Root index files & types

For tooling that doesn't yet support `package.json:exports`
([conditional exports](https://nodejs.org/api/packages.html#conditional-exports)), we include root
index files for all vendored packages, e.g., `@visx/vendor/d3-array.js`.

Type declaration files are also included in the root, e.g., `@types/d3-array` is exported as
`@visx/vendor/d3-array.d.ts`.

---

### Overview (`packages/visx-visx/Readme.md`)

# @visx/visx

<a title="@visx/visx npm downloads" href="https://www.npmjs.com/package/@visx/visx">
  <img src="https://img.shields.io/npm/dm/@visx/visx.svg?style=flat-square" />
</a>

The one stop install for all `visx` packages.

## Installation

```
npm install --save @visx/visx
```

---

### Overview (`packages/visx-voronoi/Readme.md`)

# @visx/voronoi

<a title="@visx/voronoi npm downloads" href="https://www.npmjs.com/package/@visx/voronoi">
  <img src="https://img.shields.io/npm/dm/@visx/voronoi.svg?style=flat-square" />
</a>

## Overview

A Voronoi diagram partitions a two-dimensional plane into regions based on a set of input points.
Each unique input point maps to a corresponding region, where each region represents _all points
that are closer to the input point than to any other input point_.

Not only are Voronoi diagrams 😍, but they can be used to
[improve the interactive experience of a visualization](https://www.visualcinnamon.com/2015/07/voronoi.html).
This is most often accomplished by overlaying an invisible voronoi grid on top of the visualization
to increase the target area of interaction sites such as points on a scatter plot.

The `@visx/voronoi` package provides a wrapper around the existing
[d3-voronoi](https://github.com/d3/d3-voronoi) package with some `react`-specific utilities.

## Installation

```
npm install --save @visx/voronoi
```

## Usage

The `@visx/voronoi` package exports a wrapped version of the d3 `voronoi` layout for flexible usage,
as well as a `<VoronoiPolygon />` component for rendering Voronoi regions.

```js
import { voronoi, VoronoiPolygon } from '@visx/voronoi';

const points = Array(n).fill(null).map(() => ({
  x: Math.random() * innerWidth,
  y: Math.random() * innerHeight,
}));

// width + height set an extent on the voronoi
// x + y set relevant accessors depending on the shape of your data
const voronoiLayout = voronoi({
  x: d => d.x,
  y: d => d.y,
  width,
  height,
});

const voronoiDiagram = voronoiLayout(data);
const polygons = voronoiDiagram.polygons(); // equivalent to voronoiLayout.polygons(points)

return (
  <svg>
    <Group>
      {polygons.map((polygon) => (
        <VoronoiPolygon key={...} polygon={polygon} />
      ))}
      {points.map(({ x, y }) => (
        <circle key={...} cx={x} cy={y} />
      )}
    </Group>
  </svg>
)
```

For more advanced usage with events, see [this example](https://airbnb.io/visx/voronoi). Additional
information about the voronoi layout + diagram can be found in the
[d3-voronoi documentation](https://github.com/d3/d3-voronoi).

---

### Overview (`packages/visx-wordcloud/Readme.md`)

# `@visx/wordcloud`

<a title="@visx/wordcloud npm downloads" href="https://www.npmjs.com/package/@visx/wordcloud">
  <img src="https://img.shields.io/npm/dm/@visx/wordcloud.svg?style=flat-square" />
</a>

Word clouds are visual representations of text data in which each word's value is indicated by its
font size or color.

## Installation

```
npm install --save @visx/wordcloud
```

---

### Overview (`packages/visx-xychart/README.md`)

# @visx/xychart

<a title="@visx/xychart npm downloads" href="https://www.npmjs.com/package/@visx/xychart">
  <img src="https://img.shields.io/npm/dm/@visx/xychart.svg?style=flat-square" />
</a>

In contrast to other `visx` packages which are low-level, this package seeks to abstract some of the
complexity of common visualization engineering, and exposes a **high-level** x,y (cartesian
coordinate) chart API. However, it is implemented using modularized `React.context` layers for
theme, canvas dimensions, x/y/color scales, data, events, and tooltips which allows for more
expressivity and advanced use cases.

Out of the box it supports the following:

- \* many common `<*Series />` types (animated or not) such as lines, bars, etc.
- \* `<Axis />` (animated or not)
- \* `<Grid />` (animated or not)
- \* `<Annotation />` (animated or not)
- \* `<Tooltip />`
- \* `theme`ing

The following illustrates basic usage to create an animated line chart with a bottom `Axis`, `Grid`,
and `Tooltip`:

```tsx
import {
  AnimatedAxis, // any of these can be non-animated equivalents
  AnimatedGrid,
  AnimatedLineSeries,
  XYChart,
  Tooltip,
} from '@visx/xychart';

const data1 = [
  { x: '2020-01-01', y: 50 },
  { x: '2020-01-02', y: 10 },
  { x: '2020-01-03', y: 20 },
];

const data2 = [
  { x: '2020-01-01', y: 30 },
  { x: '2020-01-02', y: 40 },
  { x: '2020-01-03', y: 80 },
];

const accessors = {
  xAccessor: (d) => d.x,
  yAccessor: (d) => d.y,
};

const render = () => (
  <XYChart height={300} xScale={{ type: 'band' }} yScale={{ type: 'linear' }}>
    <AnimatedAxis orientation="bottom" />
    <AnimatedGrid columns={false} numTicks={4} />
    <AnimatedLineSeries dataKey="Line 1" data={data1} {...accessors} />
    <AnimatedLineSeries dataKey="Line 2" data={data2} {...accessors} />
    <Tooltip
      snapTooltipToDatumX
      snapTooltipToDatumY
      showVerticalCrosshair
      showSeriesGlyphs
      renderTooltip={({ tooltipData, colorScale }) => (
        <div>
          <div style={{ color: colorScale(tooltipData.nearestDatum.key) }}>
            {tooltipData.nearestDatum.key}
          </div>
          {accessors.xAccessor(tooltipData.nearestDatum.datum)}
          {', '}
          {accessors.yAccessor(tooltipData.nearestDatum.datum)}
        </div>
      )}
    />
  </XYChart>
);
```

See sections below for more detailed guidance and advanced usage, or explore the comprehensive API
below.

<hr />

## Basic usage

<details>
  <summary>Installation</summary>

```
npm install --save @visx/xychart react-spring
```

Note: `react-spring` is a required `peerDependency` for importing `Animated*` components.

</details>

<details>
  <summary>Series types</summary>

The following `Series` types are currently supported and we are happy to review or consider
additional Series types in the future.

| Component name        | Description                                                                                      | Usage                                                |
| --------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | --- |
| (Animated)AreaSeries  | Connect data points with a `<path />`, with a color fill to the zero baseline                    | `<AreaSeries />`                                     |
| (Animated)BarSeries   | Render a `<rect />` for each data point                                                          | `<BarSeries />`                                      |
| (Animated)BarGroup    | Group multiple child `<BarSeries />` values together                                             | `<BarGroup><BarSeries /><BarSeries />...</BarGroup>` |
| (Animated)BarStack    | Stack multiple child `<BarSeries />` values together                                             | `<BarStack><BarSeries /><BarSeries />...</BarStack>` |     |
| (Animated)GlyphSeries | Render a `Glyph` (any shape, defaults to `<circle />`) for each data point, e.g., a scatter plot | `<GlyphSeries renderGlyph={() => ...} />`            |
| (Animated)LineSeries  | Connect data points with a `<path>`                                                              | `<GlyphSeries />`                                    |

All `Series` have animated and non-animated variants to give you more control over your bundle size,
support missing (`null`) data, and can be rendered vertically or horizontally.

</details>

<details>
  <summary>Theming</summary>

Default `lightTheme` and `darkTheme` themes are exported from `@visx/xychart` and the utility
`buildChartTheme` is exported to support easy creation of custom themes.

```ts
import { buildChartTheme, XYChart } from '@visx/xychart';
import { TextProps as SVGTextProps } from '@visx/text/lib/Text'; // just for types

const customTheme = buildChartTheme({
  // colors
  backgroundColor: string, // used by Tooltip, Annotation
  colors: string[], // categorical colors, mapped to series via `dataKey`s

  // labels
  svgLabelBig?: SVGTextProps,
  svgLabelSmall?: SVGTextProps,
  htmlLabel?: HTMLTextStyles,

  // lines
  xAxisLineStyles?: LineStyles,
  yAxisLineStyles?: LineStyles,
  xTickLineStyles?: LineStyles,
  yTickLineStyles?: LineStyles,
  tickLength: number,

  // grid
  gridColor: string,
  gridColorDark: string, // used for axis baseline if x/yxAxisLineStyles not set
  gridStyles?: CSSProperties,
});

() => <XYChart theme={customTheme} />
```

For new charts built from low-level visx primitives, use `@visx/theme` as the shared visual token
layer. `@visx/xychart` themes remain supported for `XYChart`, while `@visx/theme` is designed for
RSC-safe CSS variable scoping, shadcn/ui-style tokens, and prop-driven primitive charts.

Existing `XYChartTheme` objects can be reused with `fromXYChartTheme`:

```tsx
import { buildChartTheme } from '@visx/xychart';
import { ThemeScope, fromXYChartTheme } from '@visx/theme';

const xychartTheme = buildChartTheme({
  backgroundColor: '#ffffff',
  colors: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'],
  gridColor: '#f3f4f6',
  gridColorDark: '#e5e7eb',
  tickLength: 4,
});

const primitiveTheme = fromXYChartTheme(xychartTheme);

<ThemeScope theme={primitiveTheme}>
  <PrimitiveChart />
</ThemeScope>;
```

</details>

<details>
  <summary>Tooltips</summary>

`@visx/tooltip` `Tooltip`s are integrated into `@visx/xychart`, and should be rendered as a child of
`XYChart` (or a child where `TooltipContext` is provided).

**`Tooltip` positioning** is handled by the `Tooltip` itself, based on `TooltipContext`. `Tooltip`
is rendered inside a `Portal`, avoiding clipping by parent DOM elements with higher z-index
contexts. See the API below for a full list of `props` to support additional behavior, such as
snapping to data point positions and rendering cross-hairs.

**`Tooltip` content** is controlled by the specified `prop.renderTooltip` which has access to:

- `tooltipData.nearestDatum` – the globally closest `Datum`, **across all** `Series`'s `dataKey`s
- `tooltipData.datumByKey` – the closest `Datum` **for each** `Series`'s `dataKey`; this enables
  "shared tooltips" where you can render the nearest data point for each `Series`.
- a shared `colorScale` which maps `Series`'s `dataKey`s to `theme` colors

</details>

<details>
  <summary>Event handlers</summary>

The following `PointerEvent`s (handling both `MouseEvent`s and `TouchEvent`s) are currently
supported. They may be set on individual `Series` components (e.g.,
`<BarSeries onPointerMove={() => ...} />`), or at the chart level (e.g.,
`<XYChart onPointerMove={() => {}} />`) in which case they are invoked once for _every_ `*Series`.
To **disable** event emitting for any `Series` set `<*Series enableEvents=false />`. The
`onFocus/onBlur` handlers enable you to make your chart events and `Tooltip`s accessible via
keyboard interaction. Note that the current implementation requires your target browser to support
the `SVG 2.0` spec for `tabIndex` on `SVG` elements.

Below, `HandlerParms` has the following type signature:

```ts
type EventHandlerParams<Datum> = {
  datum: Datum; // nearest Datum to event, for Series with `dataKey=key`
  distanceX: number; // x distance between event and Datum, in px
  distanceY;: number; // y distance between event and Datum, in px
  event: React.PointerEvent | React.FocusEvent; // the event
  index: number; // index of Datum in Series `data` array
  key: string; // `dataKey` of Series to which `Datum` belongs
  svgPoint: { x: number; y: number }; // event position in svg-coordinates
};
```

| Prop name       | Signature                                     | `XYChart` support | `*Series` support |
| --------------- | --------------------------------------------- | ----------------- | ----------------- |
| `onPointerMove` | `(params: EventHandlerParams<Datum>) => void` | ✅                | ✅                |
| `onPointerOut`  | `(event: React.PointerEvent) => void`         | ✅                | ✅                |
| `onPointerUp`   | `(params: EventHandlerParams<Datum>) => void` | ✅                | ✅                |
| `onPointerDown` | `(params: EventHandlerParams<Datum>) => void` | ✅                | ✅                |
| `onFocus`       | `(params: EventHandlerParams<Datum>) => void` | ❌                | ✅                |
| `onBlur`        | `(event: React.TouchEvent) => void`           | ❌                | ✅                |

</details>

<details>
  <summary>Annotations</summary>

Composable `@visx/annotations` annotations are integrated into `@visx/xychart` and use its theme and
dimension context. These components allow for annotation of individual points using
`AnnotationCircleSubject`, or x- or y-thresholds using `AnnotationLineSubject`.

[CodeSandbox](https://codesandbox.io/s/annotations-8npmf?file=/Example.tsx)

```tsx
import React from 'react';
import {
  Annotation,
  AnnotationLabel,
  AnnotationConnector,
  AnnotationCircleSubject,
  Grid,
  LineSeries,
  XYChart,
} from '@visx/xychart';

const data = [
  { x: '2020-01-01', y: 50 },
  { x: '2020-01-02', y: 10 },
  { x: '2020-01-03', y: 20 },
  { x: '2020-01-04', y: 5 },
];

const labelXOffset = -40;
const labelYOffset = -50;
const chartConfig = {
  xScale: { type: 'band' },
  yScale: { type: 'linear' },
  height: 300,
  margin: { top: 10, right: 10, bottom: 10, left: 10 },
};

export default () => (
  <XYChart {...chartConfig}>
    <Grid numTicks={3} />
    <LineSeries dataKey="line" data={data} xAccessor={d => d.x} yAccessor={d => d.y} />
    <Annotation
      dataKey="line" // use this Series's accessor functions, alternatively specify x/yAccessor here
      datum={data[2]}
      dx={labelXOffset}
      dy={labelYOffset}
    >
      {/** Text label */}
      <AnnotationLabel
        title="Title"
        subtitle="Subtitle deets"
        showAnchorLine={false}
        backgroundFill="rgba(0,150,150,0.1)"
      />
      {/** Draw circle around point */}
      <AnnotationCircleSubject />
      {/** Connect label to CircleSubject */}
      <AnnotationConnector />
    </AnimatedAnnotation>
  </XYChart>
);
```

</details>

<hr />

##### ⚠️ `ResizeObserver` dependency

Responsive `XYChart`s, `Tooltip`, and `AnnotationLabel` components rely on
[`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)s. If your
browser target needs a polyfill, you can either pollute the `window` object or inject it cleanly
using the `resizeObserverPolyfill` prop for these components. A polyfill passed to `XYChart` will be
accessible to child `Tooltip` and `AnnotationLabel` components.

<details>
  <summary>Examples ✅ ❌</summary>

❌ `Error: This browser does not support ResizeObserver out of the box`

```tsx
// no polyfill, no browser support
() => <XYChart {...} />
() => <XYChart {...}><Tooltip /></XYChart>

```

✅ No errors

```tsx
// no polyfill, target browser supports ResizeObserver
() => <XYChart {...} />
() => <XYChart {...}><Tooltip /></XYChart>

// import the polyfill in the needed module, or set it on `window` object
import ResizeObserver from 'resize-observer-polyfill';
() => <XYChart {...}><Tooltip /></XYChart> // 😎

// cleanly pass polyfill to component that needs it
import ResizeObserver from 'resize-observer-polyfill';
() => (
  <XYChart resizeObserverPolyfill={ResizeObserver} {...}>
    <Tooltip />
  </XYChart>
)
```

  </details>

<hr />

## Advanced usage

<details>
  <summary>Examples</summary>

`XYChart` is implemented using modularized `React.context` layers for scales, canvas dimensions,
data, events, and tooltips which enables more advanced usage than many other chart-level
abstractions.

By default `XYChart` renders all context providers if a given context is not available, but you can
share context across multiple `XYChart`s to implement functionality such as linked tooltips, shared
themes, or shared data.

- [`ThemeProvider` + custom theme chart background example](https://codesandbox.io/s/themeprovider-sbdvz?file=/Example.tsx)
- [`DataProvider/EventEmitterProvider` example of linked tooltips / small multiples](https://codesandbox.io/s/linked-tooltips-7s0jz?file=/Example.tsx)
- [`TooltipProvider` example of programmatic + keyboard tooltip triggering](https://codesandbox.io/s/programmatic-tooltips-hh7ly?file=/Example.tsx)

</details>

<details>
  <summary>DataContext</summary>

This context provides chart canvas dimensions (`width`, `height`, and `margin`), x/y/color scales,
and a data registry. The data registry includes data from all child `*Series`, and x/y/color scales
are updated accordingly accounting for canvas dimensions.

</details>

<details>
  <summary>ThemeContext</summary>

This context provides an `XYChart` theme, its used by all visual elements that compose a chart, and
can be used to render custom visual elements that are on theme.

</details>

<details>
  <summary>EventEmitterContext</summary>

This context provides an event publishing / subscription object which can be used via the
`useEventEmitter` hook. `Series` and `XYChart` events, including tooltip updates, are emitted and
handled with through this context.

[CodeSandbox](https://codesandbox.io/s/eventemitterprovider-w8jhl?file=/Example.tsx)

```tsx
import React, { useState } from 'react';
import { useEventEmitter, EventEmitterProvider } from '@visx/xychart';

const eventSourceId = 'optional-source-id-filter';

const EmitEvent = () => {
  const emit = useEventEmitter();
  return (
    <button onPointerUp={(event) => emit('pointerup', event, eventSourceId)}>emit event</button>
  );
};

const SubscribeToEvent = () => {
  const [clickCount, setClickCount] = useState(0);
  const allowedEventSources = [eventSourceId];
  useEventEmitter('pointerup', () => setClickCount(clickCount + 1), allowedEventSources);

  return <div>Emitted {clickCount} events</div>;
};

export default function Example() {
  return (
    <EventEmitterProvider>
      <EmitEvent />
      <SubscribeToEvent />
    </EventEmitterProvider>
  );
}
```

</details>

<details>
  <summary>TooltipContext</summary>

This context provides access to `@visx/tooltip`s `useTooltip` state, including whether the tooltip
is visible (`tooltipOpen`), tooltlip position (`tooltipLeft`, `tooltipTop`),
`tooltipData: { nearestDatum, datumByKey }` described above, and functions to update context
(`hideTooltip`, `showTooltip`, and `updateTooltip`).

</details>

<hr />

---

### Overview (`packages/visx-zoom/Readme.md`)

# @visx/Zoom

<a title="@visx/zoom npm downloads" href="https://www.npmjs.com/package/@visx/zoom">
  <img src="https://img.shields.io/npm/dm/@visx/zoom.svg?style=flat-square" />
</a>

`@visx/zoom` provides `react` components that make it easy to apply transforms to a viewport or
chart.

## Installation

```
npm install --save @visx/zoom
```

---

### Overview (`packages/visx-demo/src/sandboxes/README.md`)

### Examples

This directory contains examples of `visx` usage.

Each folder is a complete standalone project, and is imported using the Code Sandbox
[import from GitHub feature](https://codesandbox.io/docs/importing#import-from-github).

---

--- METRICS ---
- Files Extracted: 46
- Estimated Token Budget: ~31152 tokens
- Canonical Reference: https://codewiki.google/github.com/airbnb/visx
