Skip to content

Docs - Interactive Legend Example is in old React syntax #11572

@rebeccaalpert

Description

@rebeccaalpert

Describe the enhancement or change
This example in both v5 and v6 has old React syntax: https://v5-archive.patternfly.org/charts/legends/#interactive-legend

This was tripping up a new React dev on the Insights Roadmap team. We should update the demo code to be something like this:

import React from 'react';
import {
  Chart,
  ChartArea,
  ChartAxis,
  ChartGroup,
  ChartLegend,
  ChartLegendTooltip,
  ChartScatter,
  ChartThemeColor,
  createContainer,
  getInteractiveLegendEvents,
  getInteractiveLegendItemStyles,
} from '@patternfly/react-charts';

export const InteractiveLegendChart = () => {
  const [hiddenSeries, setHiddenSeries] = React.useState(new Set());

  const series = [
    {
      datapoints: [
        { x: '2015', y: 3 },
        { x: '2016', y: 4 },
        { x: '2017', y: 8 },
        { x: '2018', y: 6 },
      ],
      legendItem: { name: 'Cats' },
    },
    {
      datapoints: [
        { x: '2015', y: 2 },
        { x: '2016', y: 3 },
        { x: '2017', y: 4 },
        { x: '2018', y: 5 },
        { x: '2019', y: 6 },
      ],
      legendItem: { name: 'Dogs' },
    },
    {
      datapoints: [
        { x: '2015', y: 1 },
        { x: '2016', y: 2 },
        { x: '2017', y: 3 },
        { x: '2018', y: 2 },
        { x: '2019', y: 4 },
      ],
      legendItem: { name: 'Birds' },
    },
  ];

  // Returns groups of chart names associated with each data series
  const getChartNames = () => {
    const result = [];
    series.map((_, index) => {
      // Each group of chart names are hidden / shown together
      result.push([`area-${index}`, `scatter-${index}`]);
    });
    return result;
  };

  // Returns onMouseOver, onMouseOut, and onClick events for the interactive legend
  const getEvents = () =>
    getInteractiveLegendEvents({
      chartNames: getChartNames(),
      isHidden: isHidden,
      legendName: 'chart5-ChartLegend',
      onLegendClick: handleLegendClick,
    });

  // Returns legend data styled per hiddenSeries
  const getLegendData = () => {
    return series.map((s, index) => {
      return {
        childName: `area-${index}`, // Sync tooltip legend with the series associated with given chart name
        ...s.legendItem, // name property
        ...getInteractiveLegendItemStyles(hiddenSeries.has(index)), // hidden styles
      };
    });
  };

  // Hide each data series individually
  const handleLegendClick = (props) => {
    if (!hiddenSeries.delete(props.index)) {
      hiddenSeries.add(props.index);
    }
    setHiddenSeries(new Set(hiddenSeries));
  };

  // Returns true if data series is hidden
  const isHidden = (index) => {
    return hiddenSeries.has(index);
  };

  const isDataAvailable = () => {
    return hiddenSeries.size !== series.length;
  };

  // Note: Container order is important
  const CursorVoronoiContainer = createContainer('voronoi', 'cursor');

  const container = React.cloneElement(
    <CursorVoronoiContainer
      cursorDimension="x"
      labels={({ datum }) => (datum.childName.includes('area-') && datum.y !== null ? `${datum.y}` : null)}
      labelComponent={<ChartLegendTooltip legendData={getLegendData()} title={(datum) => datum.x} />}
      mouseFollowTooltips
      voronoiDimension="x"
      voronoiPadding={50}
    />,
    {
      disable: !isDataAvailable(),
    }
  );

  return (
    <div>
      <div className="area-chart-legend-bottom-responsive">
        <Chart
          ariaDesc="Average number of pets"
          ariaTitle="Area chart example"
          containerComponent={container}
          events={getEvents()}
          height={225}
          legendComponent={<ChartLegend name={'chart5-ChartLegend'} data={getLegendData()} />}
          legendPosition="bottom-left"
          name="chart5"
          padding={{
            bottom: 75, // Adjusted to accommodate legend
            left: 50,
            right: 50,
            top: 50,
          }}
          maxDomain={{ y: 9 }}
          themeColor={ChartThemeColor.multiUnordered}
          width={width}
        >
          <ChartAxis tickValues={['2015', '2016', '2017', '2018']} />
          <ChartAxis dependentAxis showGrid />
          <ChartGroup>
            {series.map((s, index) => {
              return (
                <ChartScatter
                  data={!hiddenSeries.has(index) ? s.datapoints : [{ y: null }]}
                  key={'scatter-' + index}
                  name={'scatter-' + index}
                  size={({ active }) => (active ? 5 : 3)}
                />
              );
            })}
          </ChartGroup>
          <ChartGroup>
            {series.map((s, index) => {
              return (
                <ChartArea
                  data={!hiddenSeries.has(index) ? s.datapoints : [{ y: null }]}
                  interpolation="monotoneX"
                  key={'area-' + index}
                  name={'area-' + index}
                />
              );
            })}
          </ChartGroup>
        </Chart>
      </div>
    </div>
  );
};

Is this request originating from a Red Hat product team? If so, which ones and is there any sort of deadline for this enhancement?

Any other information?

Metadata

Metadata

Assignees

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions