Guías

Integración con React

KymoscopeProvider, useEngine, useEngineState y el componente <Chart> de @kymoscope/sdk/react.

Proporcionar el motor

React
import { useEffect, useState } from 'react'
import { createEngine, type KymoscopeEngine } from '@kymoscope/sdk'
import { KymoscopeProvider } from '@kymoscope/sdk/react'
import '@kymoscope/sdk/styles/charts.css'

export function AnalysisRoot() {
  const [engine, setEngine] = useState<KymoscopeEngine | null>(null)
  useEffect(() => {
    const e = createEngine({ licenseKey: import.meta.env.VITE_KYMOSCOPE_LICENSE_KEY })
    setEngine(e)
    return () => e.dispose()
  }, [])
  return engine ? <KymoscopeProvider engine={engine}><AnalysisUi /></KymoscopeProvider> : null
}

useEngine() devuelve el motor en cualquier punto por debajo del provider, para llamar a operaciones.

Leer el estado

useEngineState(selector, isEqual?) se vuelve a renderizar solo cuando cambia el valor seleccionado (según Object.is, o tu isEqual). Selecciona con precisión.

React
function ImportButton() {
  const engine = useEngine()
  const busy = useEngineState((s) => s.importing > 0)
  return (
    <label className="btn">
      {busy ? 'Importing…' : 'Import'}
      <input type="file" multiple hidden onChange={(e) => void engine.datasets.importFiles([...e.target.files!])} />
    </label>
  )
}

const names = useEngineState(
  (s) => s.datasets.map((d) => d.name),
  (a, b) => a.length === b.length && a.every((x, i) => x === b[i]),
)

Renderizar gráficos

React
function ChartCard({ chart }: { chart: ChartModel }) {
  const [status, setStatus] = useState<ChartStatus | null>(null)
  const view = useRef<ChartView | null>(null)
  return (
    <section className="card">
      <header>
        {chart.title ?? chartLabel(chart.kind)}
        <button onClick={() => view.current?.exportPng().then(save)}>PNG</button>
      </header>
      <div style={{ position: 'relative', height: 300 }}>
        <Chart
          id={chart.id}
          style={{ height: '100%' }}
          options={{ theme }}
          onStatus={setStatus}
          onContextMenu={(e) => openMenu(chart.id, e)}
          viewRef={(v) => { view.current = v }}
        />
        {status === 'no-data' ? <Placeholder>Import a file to start</Placeholder> : null}
      </div>
    </section>
  )
}
  • <Chart> se monta en el primer renderizado y destruye la vista al desmontarse o cuando cambia id.
  • Los cambios en options se aplican con setOptions, sin volver a montar.
  • Las props de callback pueden cambiar en cada renderizado; se llama a la más reciente.
  • viewRef recibe el ChartView tras el montaje y null al desmontar.