React Chart Editable Annotations

Demonstrates how to edit Annotations (shapes, boxes, lines, text, horizontal and vertical line) to a React Chart using SciChart.js, High Performance JavaScript Charts

src/drawExample.ts
import { appTheme } from "./appTheme";
// import SciChartImage from "./scichart-logo-white.png";
import {
    SciChartSurface,
    NumericAxis,
    NumberRange,
    ZoomPanModifier,
    MouseWheelZoomModifier,
    LineAnnotation,
    HorizontalLineAnnotation,
    VerticalLineAnnotation,
    BoxAnnotation,
    CustomAnnotation,
    TextAnnotation,
    EHorizontalAnchorPoint,
    EVerticalAnchorPoint,
    ECoordinateMode,
    ELabelPlacement,
    ZoomExtentsModifier,
    EWrapTo,
    NativeTextAnnotation,
    AnnotationHoverEventArgs,
    AnnotationHoverModifier,
    AnnotationBase,
    EHoverMode,
    translateFromCanvasToSeriesViewRect,
    GenericAnimation,
    easing,
    Thickness,
    translateToNotScaled,
    EAnnotationType,
} from "scichart";

const getImageAnnotation = (x1: number, y1: number, image: any, width: number, height: number): CustomAnnotation => {
    return new CustomAnnotation({
        x1,
        y1,
        verticalAnchorPoint: EVerticalAnchorPoint.Top,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        svgString: `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" style="background-color:transparent">
                        <image href="${image}" height="${height}" width="${width}"/>
                    </svg>`,
    });
};

export const drawExample = (SciChartImage: string) => async (rootElement: string | HTMLDivElement) => {
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    // Create an X,Y axis
    sciChartSurface.xAxes.add(
        new NumericAxis(wasmContext, {
            visibleRange: new NumberRange(0, 10),
        })
    );
    sciChartSurface.yAxes.add(
        new NumericAxis(wasmContext, {
            visibleRange: new NumberRange(0, 10),
        })
    );

    const textColor = appTheme.ForegroundColor;

    const text1 = new TextAnnotation({ text: "Editable Chart Annotations", fontSize: 24, x1: 0.3, y1: 9.7, textColor });
    const text2 = new TextAnnotation({
        text: "Click, Drag and Resize annotations with the mouse",
        fontSize: 18,
        x1: 0.5,
        y1: 9,
        textColor,
    });

    const horizontalLineAnnotation1 = new HorizontalLineAnnotation({
        stroke: appTheme.VividOrange,
        strokeThickness: 3,
        y1: 5,
        x1: 5,
        showLabel: true,
        labelPlacement: ELabelPlacement.TopLeft,
        labelValue: "Not Editable",
    });
    const horizontalLineAnnotation2 = new HorizontalLineAnnotation({
        stroke: appTheme.VividSkyBlue,
        strokeThickness: 3,
        y1: 4,
        showLabel: true,
        labelPlacement: ELabelPlacement.TopRight,
        labelValue: "Draggable HorizontalLineAnnotation",
        axisLabelFill: appTheme.VividSkyBlue,
        axisLabelStroke: appTheme.ForegroundColor,
        isEditable: true,
    });

    const verticalLineAnnotation = new VerticalLineAnnotation({
        stroke: appTheme.VividSkyBlue,
        strokeThickness: 3,
        x1: 9,
        showLabel: true,
        labelPlacement: ELabelPlacement.TopRight,
        labelValue: "Draggable VerticalLineAnnotation",
        axisLabelFill: appTheme.VividSkyBlue,
        axisLabelStroke: appTheme.ForegroundColor,
        isEditable: true,
    });

    const lineAnnotation = new LineAnnotation({
        stroke: appTheme.VividOrange,
        strokeThickness: 3,
        x1: 5.5,
        x2: 7.0,
        y1: 6.0,
        y2: 9.0,
        isEditable: true,
    });

    const boxAnnotation = new BoxAnnotation({
        stroke: appTheme.VividSkyBlue,
        strokeThickness: 1,
        fill: appTheme.VividSkyBlue + "33",
        x1: 1.0,
        x2: 4.0,
        y1: 5.0,
        y2: 7.0,
        isEditable: true,
    });

    const imageAnnotation = getImageAnnotation(7, 7, SciChartImage, 241, 62);
    imageAnnotation.isEditable = true;

    const textAnnotation = new TextAnnotation({
        x1: 1,
        y1: 2,
        xCoordinateMode: ECoordinateMode.DataValue,
        yCoordinateMode: ECoordinateMode.DataValue,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        verticalAnchorPoint: EVerticalAnchorPoint.Center,
        textColor,
        fontSize: 26,
        fontFamily: "Arial",
        text: "Unmovable text",
        isEditable: false,
    });

    const hoverableTextAnnotation = new TextAnnotation({
        x1: 1,
        y1: 1,
        xCoordinateMode: ECoordinateMode.DataValue,
        yCoordinateMode: ECoordinateMode.DataValue,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        verticalAnchorPoint: EVerticalAnchorPoint.Center,
        textColor,
        fontSize: 26,
        fontFamily: "Arial",
        text: "Hover me to select",
        isEditable: true,
        onHover: (args: AnnotationHoverEventArgs) => {
            const { isHovered, sender } = args;
            if (isHovered) {
                // This sets isSelected on the target annotation
                sender.parentSurface.adornerLayer.selectAnnotation(args.mouseArgs);
            } else {
                // this does not actually deselect the annotation on the surface
                sender.isSelected = false;
                // so we manually deselect it
                sender.parentSurface.adornerLayer.deselectAnnotation(sender);
            }
        },
    });

    const textAnnotationSciChart = new TextAnnotation({
        x1: 1,
        y1: 3,
        xCoordinateMode: ECoordinateMode.DataValue,
        yCoordinateMode: ECoordinateMode.DataValue,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        verticalAnchorPoint: EVerticalAnchorPoint.Center,
        textColor,
        fontSize: 26,
        fontFamily: "Arial",
        text: "Moveable TextAnnotation",
        isEditable: true,
    });

    const nativetextWrap = new NativeTextAnnotation({
        x1: 5,
        x2: 9,
        y1: 3,
        xCoordinateMode: ECoordinateMode.DataValue,
        yCoordinateMode: ECoordinateMode.DataValue,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        verticalAnchorPoint: EVerticalAnchorPoint.Center,
        textColor: appTheme.PalePurple,
        fontSize: 24,
        fontFamily: "Arial",
        text: "Native Text Annotations support wordwrap.  Resize me!",
        isEditable: true,
        wrapTo: EWrapTo.Annotation,
    });

    const nativetextScale = new NativeTextAnnotation({
        x1: 5,
        x2: 9,
        y1: 2,
        xCoordinateMode: ECoordinateMode.DataValue,
        yCoordinateMode: ECoordinateMode.DataValue,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        verticalAnchorPoint: EVerticalAnchorPoint.Center,
        textColor: appTheme.PalePurple,
        fontSize: 24,
        fontFamily: "Arial",
        text: "Native Text Annotations can scale on resize.",
        isEditable: true,
        scaleOnResize: true,
    });

    const tooltipPreviewAnnotation = new TextAnnotation({
        x1: 1,
        y1: 8,
        xCoordinateMode: ECoordinateMode.DataValue,
        yCoordinateMode: ECoordinateMode.DataValue,
        textColor: appTheme.ForegroundColor,
        fontSize: 16,
        text: `Move mouse over an annotation to get a tooltip with its type.<tspan x="4" dy="1.2em">The tooltip itself is also an annotation.</tspan>`,
        padding: Thickness.fromNumber(4),
        background: "black",
    });

    const tooltipAnnotation = new TextAnnotation({
        x1: 0,
        y1: 0,
        xCoordShift: 20,
        yCoordShift: 20,
        xCoordinateMode: ECoordinateMode.Pixel,
        yCoordinateMode: ECoordinateMode.Pixel,
        horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
        verticalAnchorPoint: EVerticalAnchorPoint.Top,
        textColor: appTheme.ForegroundColor,
        fontSize: 16,
        text: "",
        padding: Thickness.fromNumber(4),
        background: "black",
        isHidden: true,
    });

    sciChartSurface.annotations.add(
        text1,
        text2,
        horizontalLineAnnotation1,
        horizontalLineAnnotation2,
        verticalLineAnnotation,
        lineAnnotation,
        boxAnnotation,
        imageAnnotation,
        textAnnotation,
        textAnnotationSciChart,
        nativetextWrap,
        nativetextScale,
        hoverableTextAnnotation,
        // customAnnotation,
        tooltipPreviewAnnotation,
        tooltipAnnotation
    );

    sciChartSurface.chartModifiers.add(new ZoomPanModifier({ enableZoom: true }));
    sciChartSurface.chartModifiers.add(new ZoomExtentsModifier());
    sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier());

    let currentTooltipAnimation: GenericAnimation<number>;
    const animateTooltip = () => {
        currentTooltipAnimation?.cancel();
        tooltipAnnotation.isHidden = true;
        currentTooltipAnimation = new GenericAnimation<number>({
            from: 0,
            to: 1,
            duration: 0,
            delay: 500,
            ease: easing.linear,
            onAnimate: (from: number, to: number, progress) => {},
            onCompleted: () => {
                tooltipAnnotation.isHidden = false;
            },
        });
        sciChartSurface.addAnimation(currentTooltipAnimation);
    };

    const annotationHoverModifier = new AnnotationHoverModifier({
        // check hover on all annotations except the one used for tooltip
        targets: (modifier) =>
            modifier.parentSurface.annotations.asArray().filter((annotation) => annotation !== tooltipAnnotation),
        // ignore tooltip annotation if it is overlapping with other
        hoverMode: EHoverMode.TopmostIncluded,
        // needed to update tooltip position when moving the cursor within an annotation
        notifyPositionUpdate: true,
        // manage tooltip visibility and position
        onHover: (args) => {
            const [hoveredAnnotation] = args.hoveredEntities as AnnotationBase[];
            if (hoveredAnnotation) {
                if (hoveredAnnotation.isEditable) {
                    sciChartSurface.domChartRoot.style.cursor = "grab";
                }
                if (hoveredAnnotation.isDraggingStarted) {
                    tooltipAnnotation.isHidden = true;
                    return;
                }

                const borders = tooltipAnnotation.getAnnotationBorders(true);
                tooltipAnnotation.text = mapAnnotationTypeToName(hoveredAnnotation.type);

                const handleAnnotationsOutsideSeriesViewRect = true;
                const translatedMousePoint = translateFromCanvasToSeriesViewRect(
                    args.mouseArgs.mousePoint,
                    sciChartSurface.seriesViewRect,
                    handleAnnotationsOutsideSeriesViewRect
                );
                tooltipAnnotation.x1 = translateToNotScaled(translatedMousePoint.x);
                tooltipAnnotation.y1 = translateToNotScaled(translatedMousePoint.y);

                // initial default offset from pointer
                tooltipAnnotation.xCoordShift = 20;
                const width = Math.abs(borders.x2 - borders.x1);
                const expectedX2Coordinate = tooltipAnnotation.x1 + tooltipAnnotation.xCoordShift + width;
                const unscaledViewWidth = translateToNotScaled(sciChartSurface.seriesViewRect.width);
                if (expectedX2Coordinate > unscaledViewWidth) {
                    tooltipAnnotation.xCoordShift = unscaledViewWidth - width - tooltipAnnotation.x1;
                }

                animateTooltip();
            } else {
                sciChartSurface.domChartRoot.style.cursor = "auto";
                tooltipAnnotation.isHidden = true;
                currentTooltipAnimation?.cancel();
            }
        },
    });

    sciChartSurface.chartModifiers.add(annotationHoverModifier);

    return { sciChartSurface, wasmContext };
};

const mapAnnotationTypeToName = (type: EAnnotationType): string => {
    switch (type) {
        case EAnnotationType.RenderContextAxisMarkerAnnotation:
            return "AxisMarkerAnnotation";
        case EAnnotationType.RenderContextBoxAnnotation:
            return "BoxAnnotation";
        case EAnnotationType.RenderContextLineAnnotation:
            return "LineAnnotation";
        case EAnnotationType.RenderContextHorizontalLineAnnotation:
            return "HorizontalLineAnnotation";
        case EAnnotationType.RenderContextVerticalLineAnnotation:
            return "VerticalLineAnnotation";
        case EAnnotationType.SVGTextAnnotation:
            return "TextAnnotation";
        case EAnnotationType.RenderContextNativeTextAnnotation:
            return "NativeTextAnnotation";
        case EAnnotationType.SVGCustomAnnotation:
            return "CustomAnnotation";
        case EAnnotationType.SVG:
            return "SvgAnnotation";
        case EAnnotationType.SvgLineAnnotation:
            return "SvgLineAnnotation";
        case EAnnotationType.HtmlCustomAnnotation:
            return "HtmlCustomAnnotation";
        case EAnnotationType.HtmlTextAnnotation:
            return "HtmlAnnotation";
        case EAnnotationType.RenderContextArcAnnotation:
            return "ArcAnnotation";
        case EAnnotationType.SVGPolarPointerAnnotation:
            return "PolarPointerAnnotation";
        case EAnnotationType.RenderContextLineArrowAnnotation:
            return "LineArrowAnnotation";
        case EAnnotationType.RenderContextPolarArcAnnotation:
            return "PolarArcAnnotation";
        // @ts-ignore
        case EAnnotationType.RenderContextCustomAnnotation:
            return "RenderContextCustomAnnotation";
        case EAnnotationType.CompositeAnnotation:
            return "CompositeAnnotation";
        default: {
            const handleInvalidType = (value: never): never => {
                throw new Error(`Invalid annotation type: ${value}`);
            };
            return handleInvalidType(type);
        }
    }
};

React Chart Editable Annotations

Overview

This example demonstrates how to create an interactive chart using SciChart.js integrated within a React application. It focuses on editable annotations including TextAnnotation, LineAnnotation, VerticalLineAnnotation, HorizontalLineAnnotation, BoxAnnotation, NativeTextAnnotation and CustomAnnotation SVG image annotations that users can drag, resize, and interact with dynamically. The strategy aligns with the guidelines from the SciChart React integration guide.

Technical Implementation

The chart is initialized using the <SciChartReact/> component via the initChart property, which provides a seamless way to integrate high-performance charts into React. The annotations are programmatically added to the SciChartSurface, featuring a variety of types such as horizontal and vertical line annotations, box annotations, and both standard and native text annotations. The annotation editability, combined with event handling for hover effects and tooltips provided by AnnotationHoverModifier, leverages the capabilities outlined in Editable Annotations documentation.

Features and Capabilities

The example provides real-time update and interaction capabilities, allowing users to click, drag, and resize annotations directly on the chart. It also includes advanced features such as responsive text scaling using NativeTextAnnotation and interactive tooltips, which enhance user engagement. These capabilities are complemented by performance optimizations through WebAssembly integration and best practices that ensure the chart remains highly responsive, as discussed in the Annotation Hover documentation.

Integration and Best Practices

Integrating SciChart.js with React is streamlined by using the <SciChartReact/> wrapper, which encapsulates chart initialization and lifecycle management. This approach enables developers to build highly interactive charts by following best practices detailed in React Charts with SciChart.js. Moreover, leveraging advanced configuration of text annotations for responsive design, as illustrated in the NativeTextAnnotation guide, further enhances the chart's usability and performance in complex applications.