1.0.1 • Published 3 years ago

visyn_component_curve_editor v1.0.1

Weekly downloads
3
License
BSD-3-Clause
Repository
github
Last release
3 years ago

Curve Editor

An interactive component to draw functions using various interpolation techniques.

Todos

  • Support inline styling instead of CSS classes for more dynamic graphs
  • Revisit the behaviour in different viewports:
    • Be truly responsive for all devices
    • The margin of the axes is currently set to 50px (has to be dynamic)
    • Add a utility wrapper function to autosize the viewport to the current container
  • Enable zoom & pan
  • Add documentation and property descriptions
  • Unit tests

Usage

The editor itself is an uncontrolled component, such that the points need to be stored in the component which uses the editor. Also, to support all kinds of scales, D3 scales such as scaleLinear and scaleSymlog from the d3-scale package have to be passed as scales property. Regarding the scaling of the component, the viewport size has to passed which will be set on the SVG element. Usually, the viewport size and the scales are used together, please see below for a full example.

import * as React from 'react';

import {CurveEditor, IPoint} from 'visyn_component_curve_editor';
// Include style for default styling
import 'visyn_component_curve_editor/dist/scss/base/base.css'
import {scaleLinear} from 'd3-scale';

const MARGIN_BOTTOM = 50;
const MARGIN_RIGHT = 50;

const VIEWBOX_SIZE: [number, number] = [600, 400];

const SCALES = {
  x: scaleLinear().domain([0, 100]).range([0, VIEWBOX_SIZE[0] - 2 * MARGIN_RIGHT]).clamp(true),
  y: scaleLinear().domain([0, 1]).range([VIEWBOX_SIZE[1] - 2 * MARGIN_BOTTOM, 0]).clamp(true)
};


export default function CurveEditorDemoSmall() {
    const [points, setPoints] = React.useState<IPoint[]>([]);

    return <CurveEditor
        points={points}
        setPoints={setPoints}
        scales={SCALES}
        viewBoxSize={VIEWBOX_SIZE}
    />;
}

The following example makes use of most functionality such as showing the different interpolation functions, enabling reference points or line continuations and rendering a histogram behind the graph.

import * as React from 'react';

import {IFunction, IPoint, CurveEditor, DEFAULT_CURVE_TYPES, LinearContinuations} from 'visyn_component_curve_editor';
import {scaleLinear} from 'd3-scale';
import {histogram} from 'd3-array';

import 'visyn_component_curve_editor/dist/scss/base/base.css'

const NORMAL_DISTRIBUTION = [36.52, 56.62 /* More values...*/];

const REFERENCE_POINTS = Array(10).fill(null).map((_, i) => i * 10);

const MARGIN_BOTTOM = 50;
const MARGIN_RIGHT = 50;
const VIEWBOX_SIZE: [number, number] = [600, 400];

const X_DOMAIN: [number, number] = [0, 100];
const Y_DOMAIN: [number, number] = [0, 1];

const SCALES = {
  x: scaleLinear().domain(X_DOMAIN).range([0, VIEWBOX_SIZE[0] - 2 * MARGIN_RIGHT]).clamp(true),
  y: scaleLinear().domain(Y_DOMAIN).range([VIEWBOX_SIZE[1] - 2 * MARGIN_BOTTOM, 0]).clamp(true)
};

const EXAMPLE_PLOT = [].map((x, id) => ({
  x,
  y: Math.random(),
  id: id.toString()
}));

export default function CurveEditorDemo() {
  const [curveType, setCurveType] = React.useState<string>('Linear');
  const [enableMouseFollow, setEnableMouseFollow] = React.useState<boolean>(false);
  const [enableReferencePoints, setEnableReferencePoints] = React.useState<boolean>(false);
  const [enableContinuation, setEnableContinuation] = React.useState<boolean>(false);
  const [enableHistogram, setEnableHistogram] = React.useState<boolean>(false);
  const [points, setPoints] = React.useState<IPoint[]>(EXAMPLE_PLOT);
  const [f, _setF] = React.useState<IFunction | null>(null);
  const [debouncedF, setDebouncedF] = React.useState<IFunction | null>(null);

  React.useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedF(f);
    }, 500);

    return () => {
      clearTimeout(handler);
    }
  }, [f]);

  const examplePoints = React.useMemo(() => [10, 20, 30, 50, 80].map((x, id) => ({
    x,
    y: debouncedF?.get(x) ?? 0,
    id: id.toString()
  })), [debouncedF]);

  const setF = React.useCallback((f) => _setF(() => f), [_setF]);

  return (
    <div style={{ display: 'flex', flexDirection: 'row' }}>
      <main style={{ maxWidth: 600, maxHeight: 600, flex: 1 }}>
        <CurveEditor
          points={points}
          setPoints={setPoints}
          referencePoints={enableReferencePoints ? REFERENCE_POINTS : undefined}
          onNewFunction={setF}
          scales={SCALES}
          viewBoxSize={VIEWBOX_SIZE}
          curveType={DEFAULT_CURVE_TYPES[curveType]}
          enableMouseFollow={enableMouseFollow}
        >
          {(scales) => <>
            {enableHistogram && <g className="curve-editor__hist">
              {histogram().domain(scales.x.domain() as [number, number]).thresholds(scales.x.ticks())(NORMAL_DISTRIBUTION).map((h, i) => <rect
                key={i}
                data-tooltip={h.length}
                transform={`translate(${scales.x(h.x0!)}, ${scales.y(h.length / NORMAL_DISTRIBUTION.length)})`}
                fillOpacity={0.2}
                width={(scales.x(h.x1!) || 0) - (scales.x(h.x0!) || 0)}
                height={(scales.y(0) || 0) - (scales.y(h.length / NORMAL_DISTRIBUTION.length) || 0)} />)}
            </g>}
            {enableContinuation && <LinearContinuations
              points={points}
              scales={scales}
              leftProps={{
                stroke: 'green'
              }}
              rightProps={{
                stroke: 'red'
              }}
            />}
          </>}
        </CurveEditor>
      </main>
      <aside style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', marginLeft: 20 }}>
        <p>Curve Style:</p>
        <select onChange={(e) => setCurveType(e.currentTarget.value)} value={curveType}>
          {Object.keys(DEFAULT_CURVE_TYPES).map((c) => <option key={c} value={c}>{c}</option>)}
        </select>
        <p>Options:</p>
        <label><input type="checkbox" onChange={(e) => setEnableMouseFollow(e.currentTarget.checked)} checked={enableMouseFollow} /> Mouse Follow</label>
        <label><input type="checkbox" onChange={(e) => setEnableReferencePoints(e.currentTarget.checked)} checked={enableReferencePoints} /> Reference Points</label>
        <label><input type="checkbox" onChange={(e) => setEnableContinuation(e.currentTarget.checked)} checked={enableContinuation} /> Continuation</label>
        <label><input type="checkbox" onChange={(e) => setEnableHistogram(e.currentTarget.checked)} checked={enableHistogram} /> Histogram</label>
        <p>Example Points:</p>
        {examplePoints.map(({ x, y, id }) => <div key={id}>{x}: {Math.round(y * 100) / 100}</div>)}
      </aside>
    </div>
  );
}

This repository is part of the Target Discovery Platform (TDP). For tutorials, API docs, and more information about the build and deployment process, see the documentation page.

Build Instructions