Integration

State Control Patterns

Control Telva with persistent IDs, controlled documents, or direct TelvaApp commands.

State Control Patterns

Telva supports three complementary control strategies:

  1. persistence by editor ID
  2. controlled-document sync
  3. imperative command control through TelvaApp

Persisted by id

<Telva id="Telva-persisted-id" />

A stable id lets the editor restore/persist its state under that key.

Swapping editor identity

When id changes, Telva creates a new TelvaApp instance and remounts internal selectors.

import * as React from 'react'
import { Telva } from 'telva'

export default function ChangingId() {
  const [id, setId] = React.useState('example')

  React.useEffect(() => {
    const timeout = setTimeout(() => setId('example-2'), 2000)
    return () => clearTimeout(timeout)
  }, [])

  return <Telva id={id} />
}

Use this intentionally for workspace switching, not for frequent updates.

Controlled document mode

Provide document and mirror changes in onChange.

import * as React from 'react'
import { TVDocument, Telva, TelvaApp } from 'telva'

export default function ControlledEditor() {
  const [doc, setDoc] = React.useState<TVDocument>(/* initial document */)

  const handleChange = React.useCallback((app: TelvaApp) => {
    setDoc(app.document)
  }, [])

  return <Telva document={doc} onChange={handleChange} />
}

Controlled-mode guidance

  • keep updates immutable
  • debounce expensive persistence side effects
  • avoid replacing document.id unless loading a truly different project

Imperative mode (onMount + app ref)

import * as React from 'react'
import { ColorStyle, TVShapeType, Telva, TelvaApp } from 'telva'

export default function Imperative() {
  const appRef = React.useRef<TelvaApp>()

  const onMount = React.useCallback((app: TelvaApp) => {
    appRef.current = app
    app.createShapes({
      id: 'rect1',
      type: TVShapeType.Rectangle,
      point: [0, 0],
      size: [100, 100],
    })
  }, [])

  React.useEffect(() => {
    const id = setInterval(() => {
      const app = appRef.current
      if (!app) return
      const rect = app.getShape('rect1')
      if (!rect) return

      app.updateShapes({
        id: rect.id,
        style: {
          ...rect.style,
          color: rect.style.color === ColorStyle.Blue ? ColorStyle.Red : ColorStyle.Blue,
        },
      })
    }, 1000)

    return () => clearInterval(id)
  }, [])

  return <Telva onMount={onMount} />
}

Choosing the right control model

NeedRecommended approach
Basic editor with persistenceid only
External source of truthcontrolled document + onChange
Editor automation / command scriptingimperative TelvaApp via onMount

On this page