<h1 align="center">🪐 Cosmograph React</h1>

<div align="center">

[![npm version](https://img.shields.io/npm/v/%40cosmograph%2Freact)](https://www.npmjs.com/package/@cosmograph/react/) [![license](https://img.shields.io/badge/license-CC--BY--NC--4.0-teal)](https://github.com/cosmograph-org/cosmograph/blob/main/LICENSE) [![GitHub Issues](https://img.shields.io/github/issues/cosmograph-org/cosmograph-issues?logo=github)](https://github.com/cosmograph-org/cosmograph-issues/issues) [![Discord](https://img.shields.io/discord/988484569789513728?logo=discord&logoColor=white&label=Discord&color=5765F2)](https://discord.gg/Rv8RUQuzsx) [![Docs](https://img.shields.io/badge/documentation%20↗-8b5fbf)](https://cosmograph.app/docs-general/)
</div>

![](https://github.com/user-attachments/assets/799f0d56-4a99-4d6a-83db-c7589f6b342e)

User-friendly library for integrating [@cosmograph/cosmograph](https://www.npmjs.com/package/@cosmograph/cosmograph) into your React applications. Ready-made components and providers make it straightforward to ship interactive knowledge graph explorers—large entity–relationship networks with search, legends, and cross-filtering—alongside semantic maps from machine learning embeddings, without reimplementing layout or WebGL yourself.

## ✨ Features

- Knowledge-graph friendly: compose the graph with search, selection, legends, histograms, and timelines for entity–relationship workloads at scale
- Simple React component API for the full power of Cosmograph
- Ready-to-use interactive components: Timeline, Histogram, Bars, Legends, Search and even more
- React hook for accessing Cosmograph instance
- Full TypeScript support
- Context provider for sharing Cosmograph state

## 🚀 Quick Start

Install the package:

```bash
npm install @cosmograph/react
```

Get the data, configure the graph and render Cosmograph:

```typescript
import React, { useEffect, useState } from 'react'
import { Cosmograph, CosmographConfig, prepareCosmographData } from '@cosmograph/react'

// Points and links data can be:
// - Array of objects
// - File (.csv/.tsv, .parquet/.pq, .arrow, .json)
// - URL string to a file
// - Apache Arrow Table (binary data Uint8Array/ArrayBuffer)
// - DuckDB table name if connection is passed into the Cosmograph constructor

const rawPoints = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]

const rawLinks = [
  { source: 'a', target: 'b' },
  { source: 'b', target: 'c' },
  { source: 'c', target: 'a' },
]

export const component = (): JSX.Element => {
  const [config, setConfig] = useState<CosmographConfig>({})

  // Create a config to map your data into Cosmograph's internal format
  const dataConfig = {
    points: {
      pointIdBy: 'id',
    },
    links: {
      linkSourceBy: 'source',
      linkTargetsBy: ['target'],
    },
  }

  const loadData = async (): Promise<void> => {
    // Prepare data and config for Cosmograph
    const result = await prepareCosmographData(dataConfig, rawPoints, rawLinks)

    if (result) {
      // Update Cosmograph config with prepared output
      const { points, links, cosmographConfig } = result
      setConfig({ points, links, ...cosmographConfig })
    }
  }

  // Load data when component is mounted
  useEffect(() => { loadData() }, [])

  return <Cosmograph {...config} />
}
```

### `CosmographProvider`

`CosmographProvider` connects `Cosmograph` instance with companion components like `CosmographTimeline` and `CosmographHistogram`. Wrap your components with it to enable this connection:

```javascript
import { CosmographProvider, CosmographHistogram, Cosmograph } from '@cosmograph/react'

function App() {
  ...
  return (
    <CosmographProvider>
      <Cosmograph {...config} />
      // Assuming you have a numeric column "value" in your points data
      <CosmographHistogram accessor={"value"}>
    </CosmographProvider>
  )
}
```

> **_⚠️ Note:_** Always place Cosmograph companion components inside `CosmographProvider` and make sure it has `Cosmograph` instance inside.

### `useCosmograph`

After surrounding your app with `CosmographProvider`, the `useCosmograph` hook can now be used to access the `Cosmograph` instance. 

```javascript
import { useCosmograph, CosmographProvider } from '@cosmograph/react'

const FitButton = () => {
  const { cosmograph } = useCosmograph()
  
  return (
    <button onClick={() => cosmograph.fitView()}>
      Fit View
    </button>
  )
}

const App = () => {
  ...
  return (
    <CosmographProvider>
      <Cosmograph {...config}/>
      <FitButton />
    </CosmographProvider>
  )
}
```

> **_❗ Note:_** `useCosmograph` must be called within a component that is a direct descendant of the `CosmographProvider`. Attempting to use it outside of the provider will trigger an error.

### Refs

`Cosmograph` exposes a `ref` property that can be used to access the underlying `Cosmograph` instance, giving you direct access to its methods and properties.

```javascript
import React, { useRef } from 'react'
import { CosmographRef, Cosmograph } from '@cosmograph/react'

function App () {
  ...
  const cosmograph = useRef<CosmographRef>()

  const onClick = (pointIndex: number | undefined) => {
    cosmograph.current?.selectPoint(point)
  }}

  return (
    <Cosmograph {...config} onClick={onClick} ref={cosmograph}/>
  )
}
```

## 🌙 Available Components

`@cosmograph/react` provides a set of components connected to the Cosmograph instance and ready for use:

- [`Cosmograph`](https://cosmograph.app/docs-lib/api/classes/Cosmograph/): The primary component.
- [`CosmographTimeline`](https://cosmograph.app/docs-lib/api/classes/CosmographTimeline/): Offers a timeline feature for visualizing data over time.
- [`CosmographHistogram`](https://cosmograph.app/docs-lib/api/classes/CosmographHistogram/): A fully customizable histogram component.
- [`CosmographBars`](https://cosmograph.app/docs-lib/api/classes/CosmographBars/): A component for visualizing data with categorical bars that allow to search, sort and filter these categories.
- [`CosmographSizeLegend`](https://cosmograph.app/docs-lib/api/classes/CosmographSizeLegend/): A legend component for visualizing data sizes.
- [`CosmographTypeColorLegend`](https://cosmograph.app/docs-lib/api/classes/CosmographTypeColorLegend/): A legend component for visualizing data types with colors.
- [`CosmographRangeColorLegend`](https://cosmograph.app/docs-lib/api/classes/CosmographRangeColorLegend/): A component for visualizing numerical data with colors.
- [`CosmographSearch`](https://cosmograph.app/docs-lib/api/classes/CosmographSearch/): Powerful search for your Cosmograph data with integrated on-graph selection features.
- [`CosmographPopup`](https://cosmograph.app/docs-lib/api/classes/CosmographPopup/): A component for displaying customizable HTML popups, which can be anchored to specific nodes or coordinates on the graph.
- Handy set of **buttons** for common graph interactions:
  - [`CosmographButton`](https://cosmograph.app/docs-lib/api/classes/CosmographButton/): A base button component for custom actions.
  - [`CosmographButtonFitView`](https://cosmograph.app/docs-lib/api/classes/CosmographButtonFitView/): Automatically adjusts the graph's zoom and position to fit all nodes within the viewport.
  - [`CosmographButtonPlayPause`](https://cosmograph.app/docs-lib/api/classes/CosmographButtonPlayPause/): Toggles the force-directed layout simulation.
  - [`CosmographButtonZoomInOut`](https://cosmograph.app/docs-lib/api/classes/CosmographButtonZoomInOut/): Provides buttons for zooming in and out.
  - [`CosmographButtonRectangularSelection`](https://cosmograph.app/docs-lib/api/classes/CosmographButtonRectangularSelection/): Allows users to select nodes by drawing a rectangle.
  - [`CosmographButtonPolygonalSelection`](https://cosmograph.app/docs-lib/api/classes/CosmographButtonPolygonalSelection/): Allows users to select nodes by drawing a custom polygon.

> **_✏️ Note:_** All the components included support refs and can be accessed via `useRef` or `useCallback` for developers to have better control and management. Check out Cosmograph React docs for more details.

## 🛸 Issues and Contributing

While currently closed source, we welcome your feedback! Help improve Cosmograph by submitting bug reports and feature ideas in our [issues repository](https://github.com/cosmograph-org/cosmograph-issues).

## 💫 License

Cosmograph is licensed under the [CC-BY-NC-4.0 license](https://creativecommons.org/licenses/by-nc/4.0/deed.en) and free for any non-commercial usage. If you want to use it in a commercial project, please [reach out to us](mailto:licensing@cosmograph.app).

## 🌌 Cosmograph Universe

[@cosmograph/cosmograph](http://www.npmjs.com/package/@cosmograph/react) - Cosmograph library for JavaScript and TypeScript\
[py_cosmograph](https://github.com/cosmograph-org/py_cosmograph) - Jupyter widget for data science workflows in Python

## 👩🏻‍🚀 Contacts

🌎 [cosmograph.app](https://cosmograph.app)\
📩 [hi@cosmograph.app](mailto:hi@cosmograph.app)\
👾 [Cosmograph Discord channel](https://discord.gg/Rv8RUQuzsx)