npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tinybirdco/charts

v0.2.4

Published

The Tinybird Charts library

Downloads

3,557

Readme

@tinybirdco/charts (beta)

@tinybirdco/charts is a charting library for React applications, designed to make it easy to create and customize a variety of charts using data from your Tinybird. endpoints. The library leverages the power of Echarts and SWR for efficient data fetching and visualization.

@tinybirdco/charts is currently in public beta. It is not feature-complete and may change in the future. If you have any feedback or suggestions, please join us in the Slack community.

Installation

To install the library, run:

npm install @tinybirdco/charts

Usage

Chart components

You can directly use a chart component by passing its required props:

import React from 'react'
import { LineChart } from '@tinybirdco/charts'

function MyLineChart() {
  return (
    <LineChart
      categories={['category1', 'category2']}
      index="index_field"
      title="My Line Chart"
      description="This is a line chart"
      showLegend={true}
      height={400}
      width="100%"
      endpoint="https://api.tinybird.co/v0/pipes/my_pipe.json"
      token="your_tinybird_token"
      params={{ filter: 'value' }}
      backgroundColor="#fff"
      textColor="#333"
      borderRadius="8px"
    />
  )
}

Reusing styles and query config using the ChartProvider

You can wrap components within <ChartProvider> to share styles, query configuration and custom loading and error states among several charts.

function App() {
  return (
    <ChartProvider
      styles={{
        backgroundColor: '#fff',
        textColor: '#333',
        colorPalette: ['#5470c6', '#91cc75', '#fac858']
      }}
      queryConfig={{
        endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
        token: 'your_tinybird_token',
        refreshInterval: 10000
      }}
      fallbacks={{
        loading: <div>Loading...</div>,
        error: ({ error }) => <div>Error: {error}</div>
      }}
    >
      <LineChart title="KPIS" index="date" categories={['visits', 'hits']} />
      <BarChart title="Top devices" index="device" categories={['visits', 'hits']} />
    </ChartProvider>
  )
}

Adding extra behavior to the fetcher

You can add your own fetcher to the ChartProvider or to a specific chart component using the fetcher prop. This can be useful to add custom headers or dealing with JWT tokens.

function App() {
  return (
    <ChartProvider
      queryConfig={{
        endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
        token: getToken(),
        fetcher: async endpoint => {
          const url = new URL(endpoint)
          const response = await fetch(url)
          if (!response.ok) {
            if (response.status === 401) {
              const refreshedToken = await refreshToken()
              url.searchParams.set('token', refreshedToken)
              return fetch(url).then(res => res.json())
            } else {
              throw new Error(await response.text())
            }
          }
          return response.json()
        }
      }}
    >
      <LineChart title="KPIS" index="date" categories={['visits', 'hits']} />
      <BarChart title="Top devices" index="device" categories={['visits', 'hits']} />
    </ChartProvider>
  )
}

Using the hook

You can use the useQuery hook to fetch data and pass it directly to the component:

import React from 'react'
import { LineChart, useQuery } from '@tinybirdco/charts'

function MyHookLineChart() {
  const { data, meta, error, loading } = useQuery({
    endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
    token: 'your_tinybird_token',
    params: { filter: 'value' }
  })

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error}</div>

  return (
    <LineChart
      categories={['category1', 'category2']}
      index="index_field"
      title="My Line Chart"
      description="This is a line chart"
      showLegend={true}
      height={400}
      width="100%"
      data={data}
      meta={meta}
    />
  )
}

export default MyHookLineChart

Extra personalization using ECharts options

You can pass extra options to the Echarts instance using the options prop. This can be useful to customize the chart appearance or behavior.

import { AreaChart } from '@tinybirdco/charts'

function ExtraOptionsChart() {
  return (
    <AreaChart
      categories={['category1', 'category2']}
      index="index_field"
      title="Extra Options Chart"
      height={400}
      width="100%"
      endpoint="https://api.tinybird.co/v0/pipes/my_pipe.json"
      token="your_tinybird_token"
      options={{
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%'
        },
        animation: true,
        animationDuration: 1000,
        tooltip: {
          backgroundColor: '#fff',
          textStyle: {
            color: '#333'
          }
        }
      }}
    />
  )
}

You can also use the useQuery hook to retrieve the data from the endpoint, so you can render the data as you wish or using other chart libraries.

Components

The library provides the following chart components:

  • AreaChart
  • BarChart
  • BarList
  • DonutChart
  • LineChart
  • PieChart
  • Table

All components share the same API, making it easy to switch between different types of charts.

API

Component props

Data fetching:

  • endpoint: String. The Tinybird endpoint to fetch data from. Only required if data is not provided.
  • token: String. The Tinybird token to use for authentication. Only required if endpoint is provided.
  • params: Object. Additional parameters to pass to the Tinybird endpoint.
  • refreshInterval: Number. The interval in milliseconds to refresh the data.
  • loading: Boolean. Whether the chart is in a loading state.
  • error: String or null. Error message if the chart failed to load.
  • fallbackLoading: React element. The loading fallback component.
  • fallbackError: React element. The error fallback component.
  • onSuccess: Function. Callback function to run when the data is successfully fetched.
  • onError: Function. Callback function to run when the data fails to fetch.

Data:

  • categories: Array of strings. The categories to display on the chart.
  • index: String. The field to use as the index for the chart.
  • title: String. The title of the chart.
  • description: String. The description of the chart.
  • data: Array of objects. The data to display on the chart.
  • meta: Array of objects. Metadata about the chart data.
  • stacked: Boolean. Whether to stack the chart bars/areas.
  • groupBy: String. The field to group the data by.
  • options: Object. Additional options for Echarts.

Styling:

  • height: Number or String. The height of the chart.
  • width: Number or String. The width of the chart.
  • backgroundColor: String. The background color of the chart.
  • borderColor: String. The border color of the chart.
  • borderRadius: Number or String. The border radius of the chart.
  • boxShadow: String. The box shadow of the chart.
  • colorPalette: Array of strings. The color palette for the chart.
  • fontFamily: String. The font family for the chart.
  • fontSize: Number or String. The font size for the chart.
  • padding: Number or String. The padding for the chart.
  • textColor: String. The text color for the chart.
  • showLegend: Boolean. Whether to show the legend.

Hooks

useQuery

The useQuery hook is a custom hook that fetches data from a Tinybird endpoint and returns the data, meta, error and loading state.

import { useQuery } from '@tinybirdco/charts'

function MyComponent() {
  const { data, meta, error, loading } = useQuery({
    endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
    token: 'your_tinybird_token',
    params: { filter: 'value' }
  })

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error}</div>

  return (
    <div>
      <span>Meta:</span>
      <div>{JSON.stringify(meta)}</div>
      <span>Data:</span>
      <div>{JSON.stringify(data)}</div>
    </div>
  )
}

BarList customization

CSS Custom Variables

The BarList component supports advanced styling customization through CSS custom variables. This allows you to fully control the appearance of the component, including colors, fonts, and other stylistic aspects.

Here is a list of the available CSS custom variables you can use to style the BarList component:

:root {
  --barlist-background-color: #f5f5f5;
  --barlist-font-family: 'Arial, sans-serif';
  --barlist-font-size: 14px;
  --barlist-text-color: #333;
  --barlist-index-font-family: 'Arial, sans-serif';
  --barlist-index-line-height: 1.5;
  --barlist-index-font-size: 12px;
  --barlist-index-font-weight: 400;
  --barlist-index-text-color: #666;
  --barlist-index-text-transform: none;
  --barlist-category-font-family: 'Arial, sans-serif';
  --barlist-category-line-height: 1.5;
  --barlist-category-font-size: 14px;
  --barlist-category-font-weight: 600;
  --barlist-category-text-color: #000;
  --barlist-category-text-transform: none;
  --barlist-bar-background-color: #e0e0e0;
  --barlist-bar-border-radius: 4px;
  --barlist-value-font-family: 'Arial, sans-serif';
  --barlist-value-font-size: 14px;
  --barlist-value-line-height: 1.5;
  --barlist-value-font-weight: 700;
  --barlist-value-text-color: #333;
  --barlist-category-text-color-hover: #555;
  --barlist-category-font-weight-hover: 700;
  --barlist-category-text-color-selected: #111;
  --barlist-category-font-weight-selected: 700;
}

Rendering custom components

The BarList component can be customized to render custom elements for categories and indexes by using the following props:

  • categoryConfig: A map of category names to configuration objects. Each configuration object can have the following properties:

    • label: React element. The label to display for the category.
    • renderValue: Function. A function that returns a React element to render the value for the category.
  • indexConfig:

    • label: React element. The label to display for the index.
    • renderBarContent: Function. A function that returns a React element to render the content for the bar.

Here is an example of how you can use these props to render custom components for categories and indexes:

import { BarList } from '@tinybirdco/charts'

function MyCustomBarList() {
  return (
    <BarList
      title="Custom Bar List"
      index="category"
      indexConfig={{
        label: 'Category',
        renderBarContent: ({ label }) => (
          <Link to={`/category/${label}`}>{label}</Link>
        )
      }}
      categories={['category1', 'category2']}
      categoryConfig={{
        category1: {
          label: <span>Category 1</span>,
          renderValue: ({ value }) => <span>{formatNumber(value)}</span>
        },
        category2: {
          label: <span>Category 2</span>
        }
      }}
    />
  )
}