All files / react/components/SideNav/Chart ScoreChart.jsx

68.6% Statements 59/86
47.22% Branches 17/36
59.09% Functions 13/22
68.6% Lines 59/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269          3x 3x 3x 3x   3x 1x 1x               1x       1x 1x         1x                                         1x 1x     1x 3x       1x 3x 2x   1x       1x   1x       1x           1x   1x       1x 3x         3x     1x   1x           1x                   9x 3x 6x 3x   3x   9x         9x 9x 3x   9x       9x 3x                                   1x 9x 3x 3x       1x                                           1x           1x             1x             1x       1x 1x 1x 1x       1x                                                     1x                   1x                       3x              
import React, { useState, useEffect } from 'react';
import { pie, arc } from 'd3-shape';
import { select, event } from 'd3-selection';
import PropTypes from 'prop-types';
 
const WIDTH = 210;
const HEIGHT = 210;
const RADIUS = Math.min(WIDTH, HEIGHT) / 2;
const GAP_VALUE = 2.5;
 
const ScoreChart = ({ performanceYear, chartData, linkCallback }) => {
  const [hasLegend, setHasLegend] = useState(false);
  const [titleMapping, setTitleMapping] = useState({
    quality: 'Quality Measures',
    aci: 'Advancing Care Info',
    pi: 'Promoting Interoperability',
    ia: 'Improvement Activities',
    cost: 'Cost',
  });
 
  const { categories } = chartData;
  let legendToggler;
  let legend;
 
  const getAdvancingCareLabel = () => {
    Iif (performanceYear > 2017) {
      setTitleMapping({ ...titleMapping, aci: 'Promoting Interoperability' });
    }
  };
 
  const redirectToCategory = (link, categoryId) => {
    if (!link) {
      return;
    }
 
    // track explicitly chart legends
    if (window.utag) {
      window.utag.track('link', {
        ga_event_category: 'SidebarNav',
        ga_event_action: `GoTo${categoryId}`,
        ga_event_label: categoryId,
      });
    }
 
    if (linkCallback) {
      linkCallback(link);
    } else {
      window.location.href = link;
    }
  };
 
  const draw = (chartData) => {
    const scorePie = pie().sort(null);
 
    // Removing invalid categories
    const categories = chartData.categories.filter(
      ({ maxContribution }) => !!maxContribution,
    );
 
    // Calculating the sum of valid categories in order to calculate ratios
    const categorySum = categories
      .map(({ maxContribution }) => maxContribution)
      .reduce((sum, current) => sum + current);
 
    Iif (!categorySum) {
      return;
    }
 
    select('.score-chart').selectAll('*').remove();
 
    const svg = select('.score-chart')
      .attr('width', WIDTH)
      .attr('height', HEIGHT);
 
    const chartArc = arc()
      .innerRadius(RADIUS - 1.5)
      .outerRadius(RADIUS - 25);
 
    // Preparing the data structure with ratios: [ FILLED, EMPTY, TRANSPARENT, FILLED, EMPTY, ... ]
    let data;
    Iif (categories.length === 0) {
      data = [];
    } else Iif (categories.length === 1) {
      const { value, maxContribution } = categories[0];
      data = [value || 0, maxContribution - value];
    } else {
      data = categories
        .map(({ value, maxContribution }) => [
          value || 0,
          maxContribution - value,
          GAP_VALUE * (categorySum / 100),
        ])
        .reduce((a, b) => a.concat(b), []);
    }
 
    svg.append('title').attr('id', 'titleID').text('Your submission score');
 
    svg
      .append('desc')
      .attr('id', 'descID')
      .text(`${chartData.finalScore} out of 100`);
 
    // Setting up the arcs
    let arcs = svg
      .append('g')
      .attr('class', 'arcs')
      .attr('role', 'presentation')
      .selectAll('g.arc')
      .data(scorePie(data))
      .enter()
      .append('g')
      .attr('class', (d, i) => {
        let role;
        if (i % 3 === 0) {
          role = 'filled';
        } else if (i % 3 === 1) {
          role = 'empty';
        } else {
          role = 'transparent';
        }
        return `arc ${categories[parseInt(i / 3)].name} ${role}`;
      })
      .attr('transform', `translate(${RADIUS}, ${RADIUS})`)
      // For accessibility, we add keyboard access to the filled slices
      .attr('tabindex', (d, i) => {
        let tabindex = -1;
        if (i % 3 === 0) {
          tabindex = 0;
        }
        return tabindex;
      })
      // IE for for focusable svg elements
      .attr('focusable', (d, i) => {
        if (i % 3 === 0) {
          return true;
        }
      })
      // For accessibility, we add keyboard access to the filled slices
      .on('keyup', (d, i) => {
        const code = event.keyCode || event.which;
        if (code === 13) {
          const { name, link } = categories[parseInt(i / 3)];
          redirectToCategory(link, name);
        }
      })
      // On click - go to category page
      .on('click', (d, i) => {
        const { name, link } = categories[parseInt(i / 3)];
        redirectToCategory(link, name);
      });
 
    // Add accessibility description
    arcs.append('desc').text((d, i) => {
      if (i % 3 === 0) {
        const { name, value, maxContribution } = categories[parseInt(i / 3)];
        return `${titleMapping[name]} ${value} out of ${maxContribution}`;
      }
    });
 
    arcs
      .append('path')
      .attr('d', chartArc)
      // On mouse over - show category tooltip
      .on('mouseover', (d, i) => {
        const { name, value, maxContribution } = categories[parseInt(i / 3)];
        select('.chart-tooltip')
          .style('opacity', 1)
          .text(`${titleMapping[name]} ${value}/${maxContribution}`);
      })
      // On mouse move - move category tooltip
      .on('mousemove', () => {
        select('.chart-tooltip')
          .style('top', event.clientY - HEIGHT + 10 + 'px')
          .style('left', event.clientX + 'px');
      })
      // On mouse out - hide category tooltip
      .on('mouseout', () => {
        select('.chart-tooltip').style('opacity', 0);
      });
 
    // Adding title and subtitle
    const text = svg
      .append('g')
      .attr('text-anchor', 'middle')
      .attr('transform', `translate(${WIDTH / 2}, ${HEIGHT / 2})`);
 
    // Adding title - X%
    text
      .append('text')
      .attr('y', 4)
      .attr('class', 'chart-title')
      .text(chartData.finalScore);
 
    // Adding subtitle - OUT OF 100
    text
      .append('text')
      .attr('y', 24)
      .attr('class', 'chart-subtitle')
      .text('OUT OF 100');
  };
 
  const toggleLegend = () => {
    setHasLegend(!hasLegend);
  };
 
  useEffect(() => {
    Eif (chartData?.finalScore) {
      draw(chartData);
      getAdvancingCareLabel();
    }
  }, [chartData?.finalScore]);
 
  Iif (hasLegend) {
    legendToggler = (
      <button className="open" type="button" aria-pressed="true">
        Hide Legend
        <svg
          className="right-icon rotated"
          aria-hidden="true"
          focusable="false"
        >
          <use xlinkHref="#chevron-down" />
        </svg>
      </button>
    );
    legend = categories.map(({ name, value, maxContribution, link }, index) => {
      return (
        <li key={name} className="legend-axis">
          <button onClick={() => redirectToCategory(link, name)}>
            <span className={`legend-axis-color ${name}`} />
            &nbsp;
            <span className="legend-axis-title">{titleMapping[name]}</span>
            &nbsp;
            <span className="legend-axis-value">{`${value}/${maxContribution}`}</span>
          </button>
        </li>
      );
    });
  } else {
    legendToggler = (
      <button type="button" aria-pressed="false">
        Show Legend
        <svg className="right-icon" aria-hidden="true" focusable="false">
          <use xlinkHref="#chevron-down" />
        </svg>
      </button>
    );
  }
 
  return (
    <div className="chart">
      <svg className="score-chart" focusable="false" />
      <div className="chart-tooltip off" />
      <div className="chart-legend-toggler" onClick={toggleLegend}>
        {legendToggler}
      </div>
      <ul className="chart-legend">{legend}</ul>
    </div>
  );
};
 
ScoreChart.propTypes = {
  chartData: PropTypes.object,
  linkCallback: PropTypes.func,
  performanceYear: PropTypes.number,
};
 
export default ScoreChart;