### Quick Start: Basic Line Chart with ChartGPU Component Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/GETTING_STARTED.md Demonstrates how to use the ChartGPU component to render a simple line chart. It includes defining chart options with data, axis types, and applying basic styling and theme. This is the recommended way to get started with chartgpu-react. ```tsx import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions } from 'chartgpu-react'; const options: ChartGPUOptions = { series: [ { type: 'line', data: [ { x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 4 }, ], }, ], xAxis: { type: 'value' }, yAxis: { type: 'value' }, }; export function MyChart() { return ( ); } ``` -------------------------------- ### Install chartgpu-react and Dependencies Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/GETTING_STARTED.md Installs the chartgpu-react package along with its core dependencies: @chartgpu/chartgpu, react, and react-dom. This command is essential for setting up the charting library in a React project. ```bash npm install chartgpu-react @chartgpu/chartgpu react react-dom ``` -------------------------------- ### Run ChartGPU React Examples in Dev Mode Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md Starts the development server for ChartGPU React examples. The server typically runs on http://localhost:3000 and automatically opens the examples page in the browser. ```bash npm run dev ``` -------------------------------- ### Imperative ChartGPU Handle API Example (TypeScript/React) Source: https://context7.com/chartgpu/chartgpu-react/llms.txt Illustrates the imperative usage of the ChartGPU component via its ref (ChartGPUHandle) in React with TypeScript. This example demonstrates real-time data streaming using `appendData`, programmatic control of zoom levels with `setZoomRange`, and positioning the crosshair/tooltip with `setInteractionX`. It also shows how to access the underlying chart instance and container element. ```tsx import { useEffect, useMemo, useRef } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUHandle, ChartGPUOptions, DataPoint } from 'chartgpu-react'; export function ImperativeChartExample() { const ref = useRef(null); const options: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, dataZoom: [{ type: 'inside' }, { type: 'slider' }], autoScroll: true, }), [] ); useEffect(() => { let x = 0; const timer = window.setInterval(() => { // appendData - efficiently add points without rebuilding options const next: DataPoint = { x, y: Math.sin(x * 0.05) }; ref.current?.appendData(0, [next]); x++; }, 50); // Programmatic zoom control ref.current?.setZoomRange(80, 100); // Zoom to last 20% // Programmatic crosshair/tooltip positioning ref.current?.setInteractionX(50); return () => window.clearInterval(timer); }, []); // Access underlying instance const handleClick = () => { const chart = ref.current?.getChart(); const container = ref.current?.getContainer(); console.log('Chart instance:', chart); console.log('Container element:', container); }; return ; } ``` -------------------------------- ### ChartGPU React Development Commands Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md Provides essential commands for developing the ChartGPU React library. Includes instructions for installing dependencies, running type checking, and building the library for production. ```bash # Install dependencies npm install # Run type checking npm run typecheck # Build library npm run build ``` -------------------------------- ### Manual Chart Synchronization with connectCharts in React Source: https://context7.com/chartgpu/chartgpu-react/llms.txt Demonstrates how to manually synchronize two ChartGPU instances using the `connectCharts` helper. This is useful when you need to manage the connection lifecycle explicitly. It uses `useEffect` to establish the connection and `useState` to get chart instances. ```tsx import { useEffect, useMemo, useState } from 'react'; import { ChartGPU, connectCharts } from 'chartgpu-react'; import type { ChartGPUInstance, ChartGPUOptions } from 'chartgpu-react'; export function ManualSync() { const [a, setA] = useState(null); const [b, setB] = useState(null); useEffect(() => { if (!a || a.disposed) return; if (!b || b.disposed) return; // Connect charts with sync options const disconnect = connectCharts([a, b], { syncZoom: true }); // Cleanup on unmount or when charts change return () => disconnect(); }, [a, b]); const options: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, }), [] ); return ( <>
); } ``` -------------------------------- ### Create Interactive Annotation UI with ChartGPU React Source: https://context7.com/chartgpu/chartgpu-react/llms.txt This example demonstrates how to add an interactive annotation UI to a ChartGPU chart using the `createAnnotationAuthoring` helper. It includes features like a context menu, drag handles, and undo/redo functionality. The `useEffect` hook is used to initialize the authoring tool and manage its disposal. ```tsx import { useEffect, useMemo, useRef, useState } from 'react'; import { ChartGPU, createAnnotationAuthoring } from 'chartgpu-react'; import type { ChartGPUHandle, ChartGPUInstance, ChartGPUOptions } from 'chartgpu-react'; export function AnnotationAuthoringExample() { const ref = useRef(null); const [chart, setChart] = useState(null); const options: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 1 }, { x: 1, y: 3 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: [{ type: 'inside' }, { type: 'slider' }], // Do not include 'annotations' in options - authoring helper manages them }), [] ); useEffect(() => { const container = ref.current?.getContainer(); const instance = ref.current?.getChart(); if (!container || !instance || instance.disposed) return; const authoring = createAnnotationAuthoring(container, instance, { enableContextMenu: true, menuZIndex: 1000, }); // IMPORTANT: dispose authoring before the chart disposes return () => authoring.dispose(); }, [chart]); return ( ); } ``` -------------------------------- ### Example: Annotation Authoring in React Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/recipes/annotation-authoring.md This React component demonstrates how to integrate `createAnnotationAuthoring` into a ChartGPU chart. It sets up the chart instance, initializes the authoring helper, and ensures proper disposal of the authoring overlay when the component unmounts. It also includes important notes about managing the `options` prop. ```tsx import { useEffect, useMemo, useRef, useState } from 'react'; import { ChartGPU, createAnnotationAuthoring } from 'chartgpu-react'; import type { ChartGPUHandle, ChartGPUInstance, ChartGPUOptions } from 'chartgpu-react'; export function AnnotationAuthoringExample() { const ref = useRef(null); const [chart, setChart] = useState(null); const options: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 1 }, { x: 1, y: 3 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: [{ type: 'inside' }, { type: 'slider' }], // Note: Do not include 'annotations' in options when using createAnnotationAuthoring. // The authoring helper manages annotations via chart.setOption(), and including // annotations in the options prop can cause them to be overwritten on re-renders. }), [] ); useEffect(() => { const container = ref.current?.getContainer(); const instance = ref.current?.getChart(); if (!container || !instance || instance.disposed) return; const authoring = createAnnotationAuthoring(container, instance, { enableContextMenu: true, menuZIndex: 1000, }); // IMPORTANT: dispose authoring before the chart disposes. return () => authoring.dispose(); }, [chart]); return ( ); } ``` -------------------------------- ### External Render Mode Example Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-handle.md Demonstrates how to implement an external render loop for the chart. This involves setting the render mode to 'external' and manually calling `renderFrame()` when `needsRender()` returns true. ```typescript // Assuming 'handle' is a ref to ChartGPUHandle if (handle.current?.needsRender()) { handle.current.renderFrame(); } ``` -------------------------------- ### Enable Annotation Authoring UI with ChartGPU React Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md This example demonstrates how to integrate an annotation authoring UI into a ChartGPU chart using the `createAnnotationAuthoring` function. It captures the chart instance and container, initializes the authoring tool with options like context menu, and ensures the authoring tool is disposed when the component unmounts. ```tsx import { useEffect, useRef, useState } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUHandle, ChartGPUInstance } from 'chartgpu-react'; import { createAnnotationAuthoring } from 'chartgpu-react'; function AnnotationAuthoringExample() { const chartRef = useRef(null); const [chart, setChart] = useState(null); useEffect(() => { const container = chartRef.current?.getContainer(); const instance = chartRef.current?.getChart(); if (!container || !instance) return; const authoring = createAnnotationAuthoring(container, instance, { enableContextMenu: true, }); // IMPORTANT: dispose authoring before disposing the chart return () => authoring.dispose(); }, [chart]); return ; } ``` -------------------------------- ### Enable DataZoom and Track Zoom Changes in ChartGPU React Source: https://context7.com/chartgpu/chartgpu-react/llms.txt This example shows how to enable zoom and pan functionality using `dataZoom` and how to monitor zoom range changes with the `onZoomChange` event in ChartGPU React. It utilizes the `ChartGPU` component and React's `useState` and `useMemo` hooks. ```tsx import { useMemo, useState } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions, ZoomRange } from 'chartgpu-react'; export function DataZoomExample() { const [zoom, setZoom] = useState(null); const options: ChartGPUOptions = useMemo( () => ({ series: [ { type: 'line', data: Array.from({ length: 200 }, (_, i) => ({ x: i, y: Math.sin(i * 0.05) * 10, })), }, ], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: [{ type: 'inside' }, { type: 'slider' }], }), [] ); return ( <>
Zoom: {zoom ? `${zoom.start.toFixed(2)} - ${zoom.end.toFixed(2)}` : 'none'}
setZoom(range)} /> ); } ``` -------------------------------- ### ChartGPU React Global Styles Source: https://github.com/chartgpu/chartgpu-react/blob/main/examples/index.html Global CSS styles for ChartGPU React applications. It sets up basic box-sizing, font styles for the body, and defines styles for containers, headings, and various UI elements like error messages and info boxes. These styles ensure a consistent and visually appealing presentation for the charting components. ```css * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; background: #0a0a0a; color: #e0e0e0; line-height: 1.6; } .container { max-width: 1200px; margin: 0 auto; padding: 2rem; } h1 { font-size: 2.5rem; font-weight: 700; margin-bottom: 0.5rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } .subtitle { color: #a0a0a0; margin-bottom: 3rem; font-size: 1.1rem; } .example-section { margin-bottom: 3rem; } .example-title { font-size: 1.5rem; font-weight: 600; margin-bottom: 1rem; color: #f0f0f0; } .chart-container { background: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 8px; padding: 1.5rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); } .error-message { background: #2a1515; border: 1px solid #5a2020; border-radius: 8px; padding: 1rem; color: #ff6b6b; margin-bottom: 1rem; } .info-box { background: #1a2a3a; border: 1px solid #2a4a6a; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; color: #9ab4d0; } .info-box strong { color: #b0d0ff; } ``` -------------------------------- ### Implement Scatter Density Chart in React Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/recipes/scatter-density.md This example demonstrates how to configure ChartGPU React to render a scatter plot in density mode. It uses `useMemo` to optimize data and options, preventing unnecessary re-uploads of large datasets. Key options include `type: 'scatter'`, `mode: 'density'`, `binSize`, `densityColormap`, and `densityNormalization`. ```tsx import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions, ScatterPointTuple } from 'chartgpu-react'; import { useMemo } from 'react'; function generatePoints(count: number): ScatterPointTuple[] { const out: ScatterPointTuple[] = []; for (let i = 0; i < count; i++) { out.push([Math.random() * 100, Math.random() * 100]); } return out; } export function ScatterDensityChart() { const data = useMemo(() => generatePoints(250_000), []); const options: ChartGPUOptions = useMemo( () => ({ xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, series: [ { type: 'scatter', name: 'Density', data, mode: 'density', binSize: 2, densityColormap: 'viridis', densityNormalization: 'log', sampling: 'none', }, ], grid: { left: 60, right: 40, top: 40, bottom: 40 }, }), [data] ); return ; } ``` -------------------------------- ### ChartGPU React: Enable dataZoom and Handle Zoom Changes Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/recipes/datazoom-basics.md This example shows how to enable the 'inside' and 'slider' dataZoom types for a ChartGPU React component. It also demonstrates how to use the onZoomChange prop to capture and display the current zoom range, updating the UI when the user zooms or pans. ```tsx import { useMemo, useState } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions, ZoomRange } from 'chartgpu-react'; export function DataZoomExample() { const [zoom, setZoom] = useState(null); const options: ChartGPUOptions = useMemo( () => ({ series: [ { type: 'line', data: Array.from({ length: 200 }, (_, i) => ({ x: i, y: Math.sin(i * 0.05) * 10, })), } ], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: [{ type: 'inside' }, { type: 'slider' }], }), [] ); return ( <>
Zoom: {zoom ? `${zoom.start.toFixed(2)} → ${zoom.end.toFixed(2)}` : 'none'}
setZoom(range)} /> ); } ``` -------------------------------- ### Implement External Render Loop for ChartGPU React Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md This example illustrates how to use ChartGPU in an 'external' render mode, where the application controls the render loop using `requestAnimationFrame`. This is useful for optimizing performance or integrating with custom rendering pipelines. It uses a `useRef` to access the ChartGPU handle and checks `needsRender()` before calling `renderFrame()`. ```tsx import { useEffect, useRef } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUHandle } from 'chartgpu-react'; function ExternalLoop() { const ref = useRef(null); useEffect(() => { let raf = 0; const loop = () => { if (ref.current?.needsRender()) { ref.current.renderFrame(); } raf = requestAnimationFrame(loop); }; raf = requestAnimationFrame(loop); return () => cancelAnimationFrame(raf); }, []); return ; } ``` -------------------------------- ### ChartGPU Initialization Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-component.md Demonstrates the asynchronous creation of a ChartGPU instance. It takes a container element, chart options (with theme merged), and an optional shared GPU context. ```javascript ChartGPU.create(containerDiv, effectiveOptions, gpuContext?) ``` -------------------------------- ### Get Current Crosshair/Tooltip Position Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-handle.md Retrieves the current domain-space x-value of the active crosshair or tooltip. Returns `null` if the crosshair is not currently active. ```typescript const currentX = chartRef.current?.getInteractionX(); ``` -------------------------------- ### Migrate ChartGPUChart onInit to ChartGPU onReady Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/legacy-chartgpuchart.md Shows how to replace the 'onInit' callback from ChartGPUChart with the 'onReady' callback in ChartGPU. Both callbacks receive the chart instance, but 'onReady' is the new standard. ```tsx console.log(chart)} />; ``` ```tsx console.log(chart)} />; ``` -------------------------------- ### Get Underlying ChartGPUInstance Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-handle.md Retrieves the underlying ChartGPUInstance. Returns null if the chart has not yet initialized or if it has been disposed. It's recommended to check the 'disposed' status before using the instance. ```typescript const instance: ChartGPUInstance | null = chartRef.current?.getChart(); if (instance && !instance.disposed) { // Use the instance } ``` -------------------------------- ### Link Local ChartGPU Package for Development Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md Instructions for linking a local version of the '@chartgpu/chartgpu' package into the 'chartgpu-react' project. This is useful for testing changes across both repositories simultaneously without publishing. ```bash # 1. Link the @chartgpu/chartgpu package from the sibling repo cd ../chart-gpu npm link # 2. Link @chartgpu/chartgpu into this project cd ../chartgpu-react npm link @chartgpu/chartgpu # 3. Build and run - will use the linked local package npm run build npm run dev ``` -------------------------------- ### Get Chart Container Element Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-handle.md Returns the HTMLDivElement used as the container for the chart. This is useful for integrating with other libraries or performing DOM manipulations, such as passing it to annotation authoring helpers. ```typescript const container: HTMLDivElement | null = chartRef.current?.getContainer(); if (container) { // Use the container } ``` -------------------------------- ### Get Current Render Mode Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-handle.md Retrieves the current rendering mode of the chart, which can be either 'auto' or 'external'. Understanding the render mode is crucial for managing chart updates effectively. ```typescript const mode: RenderMode = chartRef.current.getRenderMode(); ``` -------------------------------- ### Set Programmatic Zoom Range Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-handle.md Programmatically sets the zoom range of the chart in percentage. This method is only effective if data zooming is enabled on the chart. It takes start and end values between 0 and 100. ```typescript chartRef.current?.setZoomRange(25, 75); ``` -------------------------------- ### Connect and Sync Multiple ChartGPU Instances Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md Demonstrates how to synchronize interactions (like crosshair and tooltip) between multiple ChartGPU charts using the `connectCharts` function. It also shows how to optionally synchronize zoom levels and how to disconnect the charts later. ```tsx import { connectCharts } from 'chartgpu-react'; // When you have two ChartGPUInstance objects: const disconnect = connectCharts([chartA, chartB]); // With zoom sync: // const disconnect = connectCharts([chartA, chartB], { syncZoom: true }); // Later: disconnect(); ``` -------------------------------- ### Manual Chart Connection in ChartGPU Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/FAQ.md Illustrates the manual approach to connecting multiple ChartGPU charts using the `connectCharts` function. This provides more control over chart synchronization, useful outside of React components. ```javascript import ChartGPU, { connectCharts } from 'chartgpu'; const chartA = new ChartGPU(document.getElementById('chartA'), optionsA); const chartB = new ChartGPU(document.getElementById('chartB'), optionsB); connectCharts([chartA, chartB]); ``` -------------------------------- ### Implement External Render Mode with ChartGPU React Source: https://context7.com/chartgpu/chartgpu-react/llms.txt This example demonstrates how to use `renderMode: 'external'` in ChartGPU React to manually control the chart's rendering loop using `requestAnimationFrame`. This allows for custom rendering logic and optimization. The `useEffect` hook sets up and cleans up the animation frame loop. ```tsx import { useEffect, useRef } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUHandle, ChartGPUOptions } from 'chartgpu-react'; export function ExternalRenderLoop() { const ref = useRef(null); const options: ChartGPUOptions = { renderMode: 'external', series: [{ type: 'line', data: [{ x: 0, y: 1 }, { x: 1, y: 2 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, }; useEffect(() => { let rafId = 0; const loop = () => { const handle = ref.current; // Only render when chart has pending changes if (handle && handle.needsRender()) { handle.renderFrame(); } rafId = window.requestAnimationFrame(loop); }; rafId = window.requestAnimationFrame(loop); return () => window.cancelAnimationFrame(rafId); }, []); return ; } ``` -------------------------------- ### Check WebGPU Browser Support Source: https://context7.com/chartgpu/chartgpu-react/llms.txt Asynchronously checks if the browser supports WebGPU. It verifies the existence of the 'gpu' property in the navigator object and attempts to request a GPU adapter. Returns a boolean indicating support and logs warnings or errors if issues are encountered. ```typescript const checkWebGPUSupport = async (): Promise => { if (!('gpu' in navigator)) { console.warn('WebGPU not supported in this browser'); return false; } try { const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { console.warn('No GPU adapter found'); return false; } return true; } catch (error) { console.error('WebGPU initialization failed:', error); return false; } }; // Usage checkWebGPUSupport().then((supported) => { if (supported) { // Render charts } else { // Show fallback or error message } }); ``` -------------------------------- ### Imperative Chart Creation with useChartGPU Hook Source: https://context7.com/chartgpu/chartgpu-react/llms.txt The `useChartGPU` hook enables imperative chart creation within a specified DOM element. It requires a `containerRef` pointing to the DOM element and `ChartGPUOptions` for chart configuration. It returns the chart instance, readiness status, and any potential errors, useful for scenarios where direct DOM manipulation is needed. ```tsx import { useMemo, useRef } from 'react'; import { useChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions } from 'chartgpu-react'; export function HookChart() { const containerRef = useRef(null); const options: ChartGPUOptions = useMemo( () => ({ series: [ { type: 'line', data: [ { x: 0, y: 0 }, { x: 1, y: 2 }, { x: 2, y: 1 }, ], }, ], xAxis: { type: 'value' }, yAxis: { type: 'value' }, }), [] ); const { chart, isReady, error } = useChartGPU(containerRef, options); if (error) return
WebGPU not supported: {error.message}
; return ( <> {!isReady &&
Loading...
}
); } ``` -------------------------------- ### Create and Manage ChartGPU Instance with useChartGPU (React) Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/hooks.md The `useChartGPU` hook creates and manages a ChartGPU instance within a specified DOM element. It handles initialization, option updates, resizing, and cleanup. It checks for WebGPU support and returns the chart instance, readiness status, and any errors. ```typescript import { useChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions, ChartGPUCreateContext } from 'chartgpu-react'; function useChartGPU( containerRef: React.RefObject, options: ChartGPUOptions, gpuContext?: ChartGPUCreateContext ): { chart: ChartGPUInstance | null; isReady: boolean; error: Error | null; } ``` ```tsx import { useMemo, useRef } from 'react'; import { useChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions } from 'chartgpu-react'; export function HookChart() { const containerRef = useRef(null); const options: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 0 }, { x: 1, y: 2 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, }), [] ); const { isReady, error } = useChartGPU(containerRef, options); if (error) return
WebGPU not supported
; return ( <> {!isReady &&
Loading…
}
); } ``` -------------------------------- ### Declarative ChartGPU Component Basic Usage (TypeScript/React) Source: https://context7.com/chartgpu/chartgpu-react/llms.txt Demonstrates the basic usage of the ChartGPU component in a React application using TypeScript. It configures a simple line chart with initial data and event handlers for chart readiness, clicks, crosshair movements, and zoom changes. The component manages its lifecycle and resize events automatically. ```tsx import { useMemo, useRef, useState } from 'react'; import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUHandle, ChartGPUInstance, ChartGPUOptions } from 'chartgpu-react'; export function BasicChart() { const ref = useRef(null); const [chart, setChart] = useState(null); const options: ChartGPUOptions = useMemo( () => ({ series: [ { type: 'line', data: [ { x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 4 }, { x: 3, y: 9 }, ], lineStyle: { width: 2, color: '#667eea' }, }, ], xAxis: { type: 'value' }, yAxis: { type: 'value' }, }), [] ); return ( { setChart(c); console.log('Chart ready:', c); }} onClick={(p) => console.log('Clicked:', p)} onCrosshairMove={(p) => console.log('Crosshair x:', p.x)} onZoomChange={(range) => console.log('Zoom:', range.start, range.end)} /> ); } ``` -------------------------------- ### Ensure Container Height for ChartGPU React Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/TROUBLESHOOTING.md When a ChartGPU React chart renders blank or with 0px height, ensure its container element has an explicit, non-zero height. This can be set via inline styles or CSS. The component and hook use ResizeObserver to handle resizing, but they cannot recover if the container's height is permanently zero. ```jsx import React from 'react'; import { ChartGPU } from 'chartgpu-react'; function MyChart() { return (
); } export default MyChart; ``` -------------------------------- ### Client-Side Rendering for SSR Frameworks with ChartGPU React Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/TROUBLESHOOTING.md To avoid 'navigator is not defined' errors and hydration mismatches in SSR frameworks like Next.js or Remix, render ChartGPU components exclusively on the client-side. Use dynamic imports with `ssr: false` or conditional rendering within a `useEffect` hook to ensure WebGPU-related code only executes in the browser. ```jsx import dynamic from 'next/dynamic'; import React from 'react'; const ChartGPUWithNoSSR = dynamic(() => import('chartgpu-react').then(mod => mod.ChartGPU), { ssr: false, loading: () =>

Loading chart...

}); function MyPage() { return (

My Chart Page

); } export default MyPage; ``` ```jsx import React, { useEffect, useState } from 'react'; import { ChartGPU } from 'chartgpu-react'; function MyChartComponent() { const [isClient, setIsClient] = useState(false); useEffect(() => { setIsClient(true); }, []); return (
{isClient && }
); } export default MyChartComponent; ``` -------------------------------- ### Basic ChartGPU Component Usage in React Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md Demonstrates how to use the ChartGPU component in a React application. It takes options for chart configuration and style properties for rendering. Ensure React 18+ and a browser with WebGPU support are available. ```tsx import { ChartGPU } from 'chartgpu-react'; import type { ChartGPUOptions } from 'chartgpu-react'; function MyChart() { const options: ChartGPUOptions = { series: [ { type: 'line', data: [ { x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 4 }, { x: 3, y: 9 }, ], lineStyle: { width: 2, color: '#667eea', }, }, ], xAxis: { type: 'value' }, yAxis: { type: 'value' }, }; return ; } ``` -------------------------------- ### Connect Multiple Charts in ChartGPU React Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/FAQ.md Shows how to synchronize interactions like crosshairs and tooltips between multiple ChartGPU charts using the `useConnectCharts` hook in React. This enables a linked charting experience. ```javascript import React from 'react'; import { useConnectCharts } from 'chartgpu-react'; import ChartGPU from 'chartgpu-react'; function ConnectedCharts() { const chartA = React.useRef(null); const chartB = React.useRef(null); useConnectCharts([chartA, chartB]); return (
); } ``` -------------------------------- ### Import Core Helpers and Types from chartgpu-react Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/API.md Demonstrates how to import core helper functions like 'createChart' and 'connectCharts', as well as 'createAnnotationAuthoring' which is a patched version for improved text-annotation hit-testing. These are re-exported from the peer dependency '@chartgpu/chartgpu'. ```typescript import { connectCharts, createAnnotationAuthoring } from 'chartgpu-react'; ``` -------------------------------- ### Create Synced Dashboard with Shared GPU in React Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/recipes/chart-sync.md This snippet demonstrates how to create a multi-chart dashboard in React using ChartGPU. It utilizes `useGPUContext` to share a single `GPUDevice` and `PipelineCache` across all charts, and `useConnectCharts` to synchronize crosshair and zoom functionalities. This approach optimizes performance by avoiding redundant GPU device allocations and ensures a consistent user experience. ```tsx import { useMemo, useState } from 'react'; import { ChartGPU, useGPUContext, useConnectCharts } from 'chartgpu-react'; import type { ChartGPUInstance, ChartGPUOptions } from 'chartgpu-react'; export function SyncedDashboard() { const { adapter, device, pipelineCache, isReady, error } = useGPUContext(); const [chartA, setChartA] = useState(null); const [chartB, setChartB] = useState(null); const [chartC, setChartC] = useState(null); // Sync crosshair and zoom across all three charts useConnectCharts([chartA, chartB, chartC], { syncZoom: true }); const optionsA: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 1 }, { x: 1, y: 3 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: { enabled: true }, }), [] ); const optionsB: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'bar', data: [{ x: 0, y: 5 }, { x: 1, y: 2 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: { enabled: true }, }), [] ); const optionsC: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 4 }, { x: 1, y: 1 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, dataZoom: { enabled: true }, }), [] ); if (error) return
WebGPU not supported: {error.message}
; if (!isReady) return
Initializing GPU...
; const gpuContext = { adapter: adapter!, device: device!, pipelineCache: pipelineCache! }; return ( <>
); } ``` -------------------------------- ### Updating Chart Options Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-component.md Shows how to update the chart's configuration by calling the `setOption` method on the chart instance. This performs a full replacement of the existing options. ```javascript chart.setOption(effectiveOptions) ``` -------------------------------- ### Create Shared GPU Context with useGPUContext (React) Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/hooks.md The `useGPUContext` hook creates and manages shared GPU resources (Adapter, Device, PipelineCache) for use in multi-chart dashboards. It ensures that only one set of GPU resources is initialized, improving performance by avoiding redundant requests and shader compilations. The hook returns the GPU resources, readiness status, and any errors encountered during initialization. ```typescript import { useGPUContext } from 'chartgpu-react'; import type { UseGPUContextResult } from 'chartgpu-react'; function useGPUContext(): { adapter: GPUAdapter | null; device: GPUDevice | null; pipelineCache: PipelineCache | null; isReady: boolean; error: Error | null; } ``` -------------------------------- ### Share GPU Context for Multi-Chart Dashboards in ChartGPU React Source: https://github.com/chartgpu/chartgpu-react/blob/main/README.md Shows how to create a shared WebGPU context (adapter, device, and pipeline cache) using `useGPUContext` for multiple ChartGPU instances within a dashboard. This optimizes resource usage by allowing charts to share the same GPU resources and pipeline configurations. ```tsx import { ChartGPU, useGPUContext } from 'chartgpu-react'; function Dashboard() { const { adapter, device, pipelineCache, isReady, error } = useGPUContext(); if (error) return
{error.message}
; if (!isReady || !adapter || !device) return
Loading…
; const gpuContext = pipelineCache ? { adapter, device, pipelineCache } : { adapter, device }; return ( <> ); } ``` -------------------------------- ### Manually Sync Charts with connectCharts Function Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/recipes/chart-sync.md Illustrates manual chart synchronization using the `connectCharts` function, which is re-exported from `@chartgpu/chartgpu`. This method requires using `useEffect` to establish the connection and returning a cleanup function to disconnect the charts. Zoom synchronization can be enabled by passing the `syncOptions` object. ```tsx import { useEffect, useMemo, useState } from 'react'; import { ChartGPU, connectCharts } from 'chartgpu-react'; import type { ChartGPUInstance, ChartGPUOptions } from 'chartgpu-react'; export function ManualSync() { const [a, setA] = useState(null); const [b, setB] = useState(null); useEffect(() => { if (!a || a.disposed) return; if (!b || b.disposed) return; // Pass syncOptions as the second argument (optional) const disconnect = connectCharts([a, b], { syncZoom: true }); return () => disconnect(); }, [a, b]); const options: ChartGPUOptions = useMemo( () => ({ series: [{ type: 'line', data: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }], xAxis: { type: 'value' }, yAxis: { type: 'value' }, tooltip: { show: true, trigger: 'axis' }, }), [] ); return ( <>
); } ``` -------------------------------- ### ChartGPU Component API Source: https://github.com/chartgpu/chartgpu-react/blob/main/docs/api/chartgpu-component.md This section details the props available for the ChartGPU React component, which is a recommended wrapper for charting functionalities. It also outlines the imperative handle methods accessible via a ref. ```APIDOC ## ChartGPU Component API ### Description The `ChartGPU` component is a React wrapper for advanced charting. It accepts various props to configure its appearance, behavior, and event handling. An imperative handle is also exposed via `ref` for direct manipulation. ### Props #### `options` (ChartGPUOptions) - Required Full chart configuration object. Updates call `setOption(...)` with a full replacement. #### `gpuContext` (ChartGPUCreateContext) - Optional **Init-only.** Shared GPU context for multi-chart dashboards. Changing after mount has no effect. #### `theme` (ChartGPUOptions['theme']) - Optional Theme override merged into `options` (`'dark' | 'light' | ThemeConfig`). #### `style` (React.CSSProperties) - Optional Applied to the container `
`. Provide an explicit `height`. #### `className` (string) - Optional Applied to the container `
`. #### `onReady` ((chart: ChartGPUInstance) => void) - Optional Called after async create completes successfully. #### `onClick` ((payload: ChartGPUEventPayload) => void) - Optional Wires to `chart.on('click', ...)`. #### `onMouseOver` ((payload: ChartGPUEventPayload) => void) - Optional Wires to `chart.on('mouseover', ...)`. #### `onMouseOut` ((payload: ChartGPUEventPayload) => void) - Optional Wires to `chart.on('mouseout', ...)`. #### `onCrosshairMove` ((payload: ChartGPUCrosshairMovePayload) => void) - Optional Wires to `chart.on('crosshairMove', ...)`. #### `onDataAppend` ((payload: ChartGPUDataAppendPayload) => void) - Optional Wires to `chart.on('dataAppend', ...)`. Fires when data is appended via `appendData(...)`. #### `onDeviceLost` ((payload: ChartGPUDeviceLostPayload) => void) - Optional Wires to `chart.on('deviceLost', ...)`. Most relevant when using shared `gpuContext`. #### `onZoomChange` ((range: ZoomRange) => void) - Optional Fires on `zoomRangeChange` event. Also emits the current range once on subscribe (initial hydration). ### Imperative Handle (`ChartGPUHandle`) Accessible via `ref`. Exposes the following methods: - `getChart()`: Returns the chart instance. - `getContainer()`: Returns the container DOM element. - `appendData(seriesIndex, newPoints)`: Appends data to a series. - `renderFrame(): boolean`: Renders a single frame (external mode). - `needsRender(): boolean`: Checks if a render is pending. - `getRenderMode()`: Gets the current render mode. - `setRenderMode(mode)`: Sets the render mode. - `setOption(options)`: Updates chart options with a full replacement. - `setZoomRange(start, end)`: Sets the zoom range. - `setInteractionX(x, source?)`: Sets the interaction X coordinate. - `getInteractionX()`: Gets the interaction X coordinate. - `hitTest(e)`: Performs a hit test at the given event coordinates. ### Lifecycle & Behavior #### Async Initialization On mount, `ChartGPU.create(containerDiv, effectiveOptions, gpuContext?)` is called. If the component unmounts before creation completes, the instance is disposed. #### Options Updates Changes to `options` or `theme` trigger `chart.setOption(effectiveOptions)` (full replacement). #### Resize Behavior A `ResizeObserver` is used to call `chart.resize()` on container resize. Calls are debounced (100ms). #### Zoom Change Events If `onZoomChange` is provided, the component subscribes to `zoomRangeChange` and fires the callback on changes. It also fires the initial zoom range on subscription. ```