Skip to content

Function: encodeFigure() ​

ts
function encodeFigure(figure, options?): EncodedFigure;

Encode an input figure as JSON-safe data: JSON.parse(JSON.stringify(out)) deep-equals out. The input is never mutated.

  • Typed arrays become Plotly's { dtype, bdata } (bit-exact, so NaN, -0 and ±Infinity survive). An array of equal-length typed arrays of one type (a heatmap z as Float64Array[]) becomes one spec with shape: 'rows,cols'. Uint8ClampedArray is 'u1c'. BigInt64Array/BigUint64Array have no Plotly dtype: they become plain number arrays (with a bigint warning), as do BigInt scalars.
  • Plain numbers follow JSON: NaN and ±Infinity become null (a gap, as in Plotly), -0 becomes 0. Use a typed array to keep them.
  • Dates become ISO strings (toISOString(), UTC), which Holochart reads back as dates. An invalid Date becomes null.
  • Functions (ADR-012). A function on an arrayOk attribute of a trace whose type is in registry is evaluated into a per-point array (E8.6): fn(point, i, trace) for each point i, where point holds pointNumber: i and the i-th element of each of the trace's top-level data arrays (x, y, customdata, …) and per-point arrays (text, …; '@column' references resolved), and trace is the input trace. The point count is the shorter of x/y, else the first data array's length; frame traces without data arrays use the figure trace they update. Every other function (config callbacks such as renderHover, non-arrayOk attributes, traces without data or registry) is dropped, as is one that throws.
  • Everything else: undefined keys are omitted and undefined array elements become null (as in JSON). Objects with a toJSON method are encoded through it. Symbols, Maps, Sets, DataViews, ArrayBuffers, other class instances and circular references are dropped (null in arrays).

Every lossy step reports a SerializeWarning, once per path.

Parameters ​

ParameterType
figureAnyFigure
optionsEncodeFigureOptions

Returns ​

EncodedFigure

Example ​

ts
const json = encodeFigure(
  {
    data: [
      {
        type: 'scatter',
        x: Float64Array.of(1, 2),
        y: [3, 4],
        marker: { color: (p) => (p.y > 3 ? 'red' : 'gray') },
      },
    ],
  },
  { registry },
);
// json.data[0].x → { dtype: 'f8', bdata: 'AAAAAAAA8D8AAAAAAAAAQA==' }
// json.data[0].marker.color → ['gray', 'red'] (with a 'function-evaluated' warning)

Released under the MIT License.