File size: 1,430 Bytes
b9fe2b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useSelectTestingResult } from '@/hooks/knowledge-hooks';
import { Chart } from '@antv/g2';
import { useCallback, useEffect, useMemo, useRef } from 'react';

export function LabelWordCloud() {
  const domRef = useRef<HTMLDivElement>(null);
  let chartRef = useRef<Chart>();
  const { labels } = useSelectTestingResult();

  const list = useMemo(() => {
    if (!labels) {
      return [];
    }

    return Object.keys(labels).reduce<
      Array<{ text: string; name: string; value: number }>
    >((pre, cur) => {
      pre.push({ name: cur, text: cur, value: labels[cur] });

      return pre;
    }, []);
  }, [labels]);

  const renderWordCloud = useCallback(() => {
    if (domRef.current && list.length) {
      chartRef.current = new Chart({ container: domRef.current });

      chartRef.current.options({
        type: 'wordCloud',
        autoFit: true,
        layout: {
          fontSize: [6, 15],
        },
        data: {
          type: 'inline',
          value: list,
        },
        encode: { color: 'text' },
        legend: false,
        tooltip: {
          title: 'name', // title
          items: ['value'], // data item
        },
      });

      chartRef.current.render();
    }
  }, [list]);

  useEffect(() => {
    renderWordCloud();

    return () => {
      chartRef.current?.destroy();
    };
  }, [renderWordCloud]);

  return <div ref={domRef} className="w-full h-[13vh]"></div>;
}