Chart.tsx 8.45 KB
Newer Older
Yuge Zhang's avatar
Yuge Zhang 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
import React, { createRef } from 'react';
import cytoscape from 'cytoscape';
import dagre from 'cytoscape-dagre';
import lodash from 'lodash';
import { Graph, NodeTs } from './graphUtils';

cytoscape.use(dagre);

type ChartProps = {
  width: number,
  height: number,
  graph: Graph | undefined,
  activation: any,
  handleSelectionChange: (_: string) => void,
  onRefresh: () => void,
  onRefreshComplete: () => void,
  layout: boolean,
  onLayoutComplete: () => void,
}

const styles = [
  {
    selector: ':active',
    style: {
      'overlay-opacity': 0.1,
    }
  },
  {
    selector: 'node',
    style: {
      'shape': 'round-rectangle',
      'width': 'label',
      'height': 'label',
      'content': 'data(label)',
      'text-wrap': 'wrap',
      'text-valign': 'center',
      'text-halign': 'center',
      'font-family': '"Roboto", "Helvetica", "Arial", sans-serif',
      'font-size': 20,
      'padding-left': '8px',
      'padding-right': '8px',
      'padding-top': '8px',
      'padding-bottom': '8px',
      'background-color': '#000',
      'background-opacity': 0.02,
      'border-color': '#555',
      'border-width': '2px',
    }
  },
  {
    selector: 'node.op',
    style: {
      'background-color': '#fafafa',
      'background-opacity': 1,
    }
  },
  {
    selector: 'node:selected',
    style: {
      'border-width': '4px',
      'border-color': '#101010',
    }
  },
  {
    selector: 'edge',
    style: {
      'curve-style': 'bezier',
      'target-arrow-shape': 'triangle',
      'line-color': '#555',
      'target-arrow-color': '#555'
    }
  },
  {
    selector: 'node.compound',
    style: {
      'shape': 'roundrectangle',
      'text-valign': 'top',
      'padding-top': '30px',
      'padding-bottom': '10px',
      'padding-right': '10px',
      'padding-left': '10px',
    }
  }
];

export default class Chart extends React.Component<ChartProps> {
  container = createRef<HTMLDivElement>();
  zoom: any;
  collapseInstance: any;
  cyInstance: cytoscape.Core | null = null;
  expandSet: Set<string> = new Set<string>();
  elemWeight: Map<string, number> = new Map<string, number>();
  graphEl: any[] = [];
94
  private firstUpdate = true;
Yuge Zhang's avatar
Yuge Zhang committed
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

  componentDidMount() {
    this.cyInstance = cytoscape({
      container: this.container.current,
      elements: [],
      style: styles as any,
      wheelSensitivity: 0.1,
    });
    let singleClickedNodes = new Set<string>();
    this.cyInstance!.off('click');
    this.cyInstance!.on('click', (e: cytoscape.EventObject) => {
      if (e.target.id) {
        let nodeId = e.target.id();
        if (singleClickedNodes.has(nodeId)) {
          singleClickedNodes.delete(nodeId);
          e.target.trigger('dblclick');
        } else {
          singleClickedNodes.add(nodeId);
          setTimeout(() => { singleClickedNodes.delete(nodeId); }, 300);
        }
      }
    });
    this.cyInstance!.on('dblclick', (e: cytoscape.EventObject) => {
      const nodeId = e.target.id();
      const node = this.props.graph!.getNodeById(nodeId);
      if (node !== undefined && node.isParent()) {
        if (this.expandSet.has(nodeId)) {
          this.expandSet.delete(nodeId);
        } else {
          this.expandSet.add(nodeId);
        }
        this.renderGraph(false);
      }
    });
    this.cyInstance!.on('select', (e: cytoscape.EventObject) => {
      this.props.handleSelectionChange(e.target.id());
    });
    this.renderGraph(true);
  }

  componentDidUpdate(prevProps: ChartProps) {
    if (prevProps.graph === this.props.graph) {
      if (prevProps.width === this.props.width &&
        prevProps.height === this.props.height) {
        if (this.props.layout) {
          this.props.onLayoutComplete();
          this.reLayout();
        }
        if (prevProps.activation !== this.props.activation) {
          // perhaps only display step is changed
          this.applyMutableWeight();
        }
      } else {
        // something changed, re-render
        this.renderGraph(false);
      }
    } else {
      // re-calculate collapse
153
154
      this.renderGraph(true, this.firstUpdate);
      this.firstUpdate = false;
Yuge Zhang's avatar
Yuge Zhang committed
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
    }
  }

  private graphElements() {
    let graphElements: any[] = [];
    const { graph } = this.props;
    if (graph === undefined)
      return [];

    const collapseMap = new Map<string, string>();
    const traverse = (node: NodeTs, top: NodeTs | undefined) => {
      collapseMap.set(node.id, top === undefined ? node.id : top.id);
      if (node.id && (top === undefined || node === top)) {
        // not root and will display
        const isCompound = node.isParent() && this.expandSet.has(node.id);
        let data: any = {
          id: node.id,
          label: node.op ? node.op : node.tail,
        };
        if (node.parent !== undefined)
          data.parent = node.parent.id;
        const classes = [];
        if (isCompound) classes.push('compound');
        if (node.op) classes.push('op');
        graphElements.push({
          data: data,
          classes: classes
        });
      }
      for (const child of node.children)
        traverse(child, node.id && top === undefined && !this.expandSet.has(node.id) ? node : top);
    }
    traverse(graph.root, undefined);
    graph.edges.forEach(edge => {
      const [srcCollapse, trgCollapse] = [edge.source, edge.target].map((node) => collapseMap.get(node.id)!);
      if (edge.source !== edge.target && srcCollapse === trgCollapse) {
        return;
      }
      graphElements.push({
        data: {
          id: edge.id,
          source: srcCollapse,
          target: trgCollapse
        }
      });
    });
    return graphElements;
  }

  private applyMutableWeight() {
    const { graph, activation } = this.props;
    if (graph === undefined || activation === undefined)
      return;
    const weights = graph.weightFromMutables(activation);
    weights.forEach((weight, elem) => {
      if (this.elemWeight.get(elem) !== weight) {
        this.cyInstance!.getElementById(elem).style({
          opacity: 0.2 + 0.8 * weight
        });
      }
    });
    this.elemWeight = weights;
  }

  private graphElDifference(prev: any[], next: any[]): [Set<string>, any] {
    const tracedElements = new Set(prev.map(ele => ele.data.id));
    const prevMap = new Map(prev.map(ele => [ele.data.id, ele]));
    const nextMap = new Map(next.map(ele => [ele.data.id, ele]));
    const addedEles: any = [];
    nextMap.forEach((val, k) => {
      const prevEle = prevMap.get(k);
      if (prevEle === undefined) {
        addedEles.push(val);
      } else if (!lodash.isEqual(val, prevEle)) {
        tracedElements.delete(k);
        addedEles.push(val);
      } else {
        tracedElements.delete(k);
      }
    });
    return [tracedElements, addedEles];
  }

  private reLayout() {
    this.props.onRefresh();
    const _render = () => {
      const layout: any = {
        name: 'dagre'
      };
      this.cyInstance!.layout(layout).run();
      this.props.onRefreshComplete();
    };
    setTimeout(_render, 100);
  }

250
  private renderGraph(graphChanged: boolean, fit: boolean = false) {
Yuge Zhang's avatar
Yuge Zhang committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    const { graph } = this.props;
    if (graph === undefined)
      return;

    this.props.onRefresh();
    const _render = () => {
      if (graphChanged)
        this.expandSet = lodash.cloneDeep(graph.defaultExpandSet);
      const graphEl = this.graphElements();
      const [remove, add] = this.graphElDifference(this.graphEl, graphEl);
      const layout: any = {
        name: 'dagre'
      };
      if (graphEl.length > 100) {
        if (remove.size > 0) {
          const removedEles = this.cyInstance!.elements().filter(ele => remove.has(ele.id()));
          this.cyInstance!.remove(removedEles);
        }
        if (add.length > 0) {
          const eles = this.cyInstance!.add(add);
          this.cyInstance!.json({
            elements: graphEl
          });
274
275
276
          if (!fit) {
            layout.fit = false;
          }
Yuge Zhang's avatar
Yuge Zhang committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
          eles.layout(layout).run();
        }
      } else {
        this.cyInstance!.json({
          elements: graphEl
        });
        this.cyInstance!.layout(layout).run();
      }
      this.applyMutableWeight();
      this.graphEl = graphEl;
      this.props.onRefreshComplete();
    };
    if (graph.nodes.length > 100)
      setTimeout(_render, 100);
    else
      _render();
  }

  render() {
    return (
      <div className='container' ref={this.container}
        style={{
          left: 0,
          top: 0,
          position: 'absolute',
          width: this.props.width - 15,
          height: this.props.height,
          overflow: 'hidden'
        }}>
      </div>
    );
  }
}