TreeMap.tsx 5.24 KB
Newer Older
Maksym Tishchenko's avatar
Maksym Tishchenko committed
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
import * as React from 'react';

import { d3, DOM } from 'd3js';

interface IProps {
  nullLabel?: string;
  style: object;
  data: any;
}

/**
 * TreeMap based on https://observablehq.com/@d3/zoomable-treemap
 */
export const TreeMap = ({ nullLabel = 'NULL', style, data }: IProps) => {
  const chartRef = React.useRef(null);

  if (typeof window !== 'undefined' && d3) {
    const format = d3.format(',d');

    const name = (d) => d.data.term || d.data.name;
    const nameWithPath = (d) => d.ancestors().reverse().map(name).join(' / ');

    // useEffect
    React.useEffect(() => {
      // console.log('React effect!', chartRef, data);

      if (! data || ! chartRef.current) {
        return;
      }

      const headerHeight = 60;

      const width = chartRef.current.parentNode.getBoundingClientRect().width;
      let height = chartRef.current.parentNode.getBoundingClientRect().height;

      const svg = d3.select(chartRef.current)
        .attr('height', height)
        .attr('width', width)

      height -= headerHeight;
      const color = d3.scaleOrdinal(d3.quantize(d3.interpolateSpectral, data.children.length + 1));

      const tile = (node, x0, y0, x1, y1) => {
        d3.treemapBinary(node, 0, 0, width, height);
        for (const child of node.children) {
          child.x0 = x0 + child.x0 / width * (x1 - x0);
          child.x1 = x0 + child.x1 / width * (x1 - x0);
          child.y0 = y0 + child.y0 / height * (y1 - y0);
          child.y1 = y0 + child.y1 / height * (y1 - y0);
        }
      }

      const treemap = (data) => d3.treemap().tile(tile)(d3.hierarchy(data).sum((d) => d.count).sort((a, b) => b.count - a.count));

      const x = d3.scaleLinear().rangeRound([0, width]);
      const y = d3.scaleLinear().rangeRound([0, height]);

      svg
        .attr('viewBox', [0, -headerHeight - 0, width, height + headerHeight])
        .style('font', '14px sans-serif');

      const old = svg.selectAll('g');
      // console.log('SVG', svg, old);
      if (old) {
        // console.log('Removing', old);
        old.remove();
      }

      let group = svg.append('g')
        .call(render, treemap(data));

      group.exit().remove();

      function render(group, root) {
        const node = group
          .selectAll('g')
          .data(root.children.concat(root))
          .join('g');

        node.filter((d) => d === root ? d.parent : d.children)
          .attr('cursor', 'pointer')
          .on('click', (d) => d === root ? zoomout(root) : zoomin(d));

        node.append('title')
          .text((d) => `${nameWithPath(d)}\n${format(d.value)}`);

        node.append('rect')
          .attr('id', (d) => (d.leafUid = DOM.uid('leaf')).id)
          .attr('fill', (d) => d === root ? '#fff' : d.children ? '#ccc' : color(d.data.term))
          .attr('stroke', '#fff');

        node.append('clipPath')
          .attr('id', (d) => (d.clipUid = DOM.uid('clip')).id)
          .append('use')
          .attr('xlink:href', (d) => d.leafUid.href);

        node.append('text')
          .attr('clip-path', (d) => d.clipUid)
          .attr('font-weight', (d) => d === root ? 'bold' : null)
          .selectAll('tspan')
          .data((d) => [ (d === root ? nameWithPath(d) : name(d)) ].concat(format(d.value)))
          .join('tspan')
          .attr('x', 3)
          .attr('y', (d, i, nodes) => `${(i === nodes.length - 1 ? 1 : 0) * 0.3 + 1.1 + i * 0.9}em`)
          .attr('fill-opacity', (d, i, nodes) => i === nodes.length - 1 ? 0.7 : null)
          .attr('font-weight', (d, i, nodes) => i === nodes.length - 1 ? 'normal' : null)
          .text((d) => d);

        group.call(position, root);
      }

      function position(group, root) {
        group.selectAll('g')
          .attr('transform', (d) => d === root ? 'translate(0,-60)' : `translate(${x(d.x0)},${y(d.y0)})`)
          .select('rect')
          .attr('width', (d) => d === root ? width : x(d.x1) - x(d.x0))
          .attr('height', (d) => d === root ? 60 : y(d.y1) - y(d.y0));
      }

      // When zooming in, draw the new nodes on top, and fade them in.
      function zoomin(d) {
        const group0 = group.attr('pointer-events', 'none');
        const group1 = group = svg.append('g').call(render, d);

        x.domain([d.x0, d.x1]);
        y.domain([d.y0, d.y1]);

        svg.transition()
          .duration(750)
          .call((t) => group0.transition(t).remove()
            .call(position, d.parent))
          .call((t) => group1.transition(t)
            .attrTween('opacity', () => d3.interpolate(0, 1))
            .call(position, d));
      }

      // When zooming out, draw the old nodes on top, and fade them out.
      function zoomout(d) {
        const group0 = group.attr('pointer-events', 'none');
        const group1 = group = svg.insert('g', '*').call(render, d.parent);

        x.domain([d.parent.x0, d.parent.x1]);
        y.domain([d.parent.y0, d.parent.y1]);

        svg.transition()
          .duration(750)
          .call((t) => group0.transition(t).remove()
            .attrTween('opacity', () => d3.interpolate(1, 0))
            .call(position, d))
          .call((t) => group1.transition(t)
            .call(position, d.parent));
      }

    }, [ data ]);
  }

  console.log('Rendering TreeMap', style, chartRef);

  return (
    <svg style={ style } ref={ chartRef }></svg>
  );
};