chiru 0.7.0

A parser generator similar to antlr4.
Documentation
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
270
271
272
273
274
275
276
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{ name }}</title>
  <style>
    * {
      margin: 0 0;
    }

    *::-webkit-scrollbar {
      width: 5px;
      height: 5px;
    }

    /* 两个滚动条交接处 -- x轴和y轴 */
    *::-webkit-scrollbar-corner {
      background-color: transparent;
    }

    /* 滚动条滑块 */
    *::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: #49b1f5;
    }

    /* 滚动条轨道 */
    *::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 10px;
      background: #ededed;
    }

    *::-webkit-slider-container {
      /*可以修改容器的若干样式*/
      width: 5px;
      height: 5px;
    }

    input {
      width: 300px;
    }


    button {
      background-color: #49b1f5;
      border: none;
      color: white;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      border-radius: 4px;
    }
    
    button:hover {
      box-shadow: 0 6px 8px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
    }
  </style>
</head>

<body>
  <div style="overflow: hidden;">
    <div id="content"

      style="overflow-x: hidden; position: fixed; height: 100vh; overflow-y: auto;  background-color: rgb(244, 237, 237); width: 255px; z-index: 100;">
    </div>
    <div id="super" style="position: relative; overflow-y: visible; overflow-x: visible; margin-left: 255px; min-height: 100vh;">

      <div id="container"

        style="overflow: visible; height: 100%; background-color: transparent; display: flex;justify-content: center; z-index: 1;">
        <div id="tree" style="overflow: visible;"></div>
      </div>

      <!-- <div style="position: absolute; left: 0; top: 0;">
        <button id="reset">复位</button>
        <button id="switch">转换为 cluster</button>
        <input id="slider" type="range" min="0" max="550" step="1"  /> 
      </div> -->


    </div>
    <div style="position: absolute; left: 260px; top: 5px;">
      <button id="reset">复位(reset)</button>
      <button id="switch">转换为cluster (use cluster)</button>
      <span>
        dx
        <input id="slider" type="range" min="32" max="512" step="1" value="128" /> 
      </span>
      <span>
        dy
        <input id="slider2" type="range" min="32" max="512" step="1" value="96" /> 
      </span>
    </div>

  </div>

  <script type="module">
    {{ ast }}

    import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7/+esm";
    const maxScale = 4, minScale = 0.05;

    let config = {
      tree_or_cluster: d3.tree,
      current: ast, 
      scale: 1.0,
      isPointerdown: false,
      lastPointermove: { x: 0, y: 0 },
      x: 0, 
      y: 0,
      ast_width: 128,
      ast_height: 96,
    };

    const content = indentTree(ast);
    document.getElementById('content').appendChild(content);
    const tree = collapsibleTree(ast, { tree: config.tree_or_cluster, dx: config.ast_width, dy: config.ast_height });
    document.getElementById('tree').appendChild(tree);

    // 增加一些拖拽和缩放功能。
    bindEvents(document.getElementById('super'), document.getElementById('container'));
    document.getElementById('reset').addEventListener('click', e => reset());
    document.getElementById('switch').addEventListener('click', e => {
      // console.log(e.target.innerHTML, typeof e.target.innerHTML);
      if (e.target.innerHTML.endsWith('(use cluster)')) {
        config.tree_or_cluster = d3.cluster;
        e.target.innerHTML = '转换为 tree (use tree)';
        render();
      }
      else {
        config.tree_or_cluster = d3.tree;
        e.target.innerHTML = '转换为 cluster (use cluster)';
        render();
      }
    });

    document.getElementById('slider').onchange = (e) => {
      config.ast_width = e.target.value;
      render();
    };
    document.getElementById('slider2').onchange = (e) => {
      config.ast_height = e.target.value;
      render();
    };









    function indentTree(data, { nodeSize = 25, minWidth = 255 } = {}) {
      let width = minWidth;

      // 前序遍历? d.index用于计算布局,d.id用于更新
      const root = d3.hierarchy(data);

      root.descendants().forEach((d, i) => {
        d.id = i;
        d._children = d.children;
        d.y = i * nodeSize;

        // 如果需要在启动的时候就处于折叠状态,则将下面这行取消注释
        // d.children = null;

        // 计算最小尺寸, 假设一个字符占12个像素
        const tmp = d.depth * nodeSize + d.data.name.length * 13 + 6;
        width = tmp > width ? tmp : width;
      });

      const svg = d3.create("svg")
        .attr("viewBox", [-nodeSize / 2, -nodeSize * 3 / 2, width, 2 * nodeSize])
        .attr("font-family", "sans-serif")
        .attr("font-size", 18)
        .style("overflow", "visible");

      const gLink = svg.append("g")
        .attr("fill", "none")
        .attr("stroke", "#999");

      const gNode = svg.append("g");

      // bias_y 父节点的纵向偏移
      function update(source, bias_y) {

        // 前序遍历, 更新位置
        root.eachBefore((d, i) => {
          d.y = i * nodeSize;
        });

        const duration = 800;
        const nodes = root.descendants();
        const links = root.links();


        const transition = svg.transition()
          .duration(duration)
          .attr("viewBox", [-nodeSize / 2, -nodeSize * 3 / 2, width, (nodes.length + 1) * nodeSize])
          .tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));


        const node = gNode.selectAll("g").data(nodes, d => d.id);


        const nodeEnter = node.enter().append("g")
          .attr("transform", d => `translate(0, ${bias_y})`)
          .attr("fill-opacity", 0)
          .attr("stroke-opacity", 0);

        nodeEnter.append("circle")
          .attr("cx", d => d.depth * nodeSize)
          .attr("r", 5)
          .attr("fill", d => d._children ? null : "#999")
          .on("click", (event, d) => {
            d.children = d.children ? null : d._children;
            update(d, d.y);
          });

        nodeEnter.append("text")
          .attr("dy", "0.32em")
          .attr("x", d => d.depth * nodeSize + 8)
          .text(d => d.data.name)
          .attr("cursor", "pointer")
          .on("click", (event, d) => {
            config.current = d.data;
            render();
          })
          .clone(true).lower()
          .attr("stroke-linejoin", "round")
          .attr("stroke-width", 3)
          .attr("stroke", "white");

        node.merge(nodeEnter).transition(transition)
          .attr("transform", d => `translate(0, ${d.y})`)
          .attr("fill-opacity", 1)
          .attr("stroke-opacity", 1);

        node.exit().transition(transition).remove()
          .attr("transform", d => `translate(0, ${bias_y})`)
          .attr("fill-opacity", 0)
          .attr("stroke-opacity", 0);

        const link = gLink.selectAll("path")
          .data(links, d => d.target.id);

        const linkEnter = link.enter().append("path")
          .attr("d", d => `

          M${d.source.depth * nodeSize},${bias_y}

          V${bias_y}

          h${nodeSize}

        `);

        link.merge(linkEnter).transition(transition)
          .attr("d", d => `

          M${d.source.depth * nodeSize},${d.source.y}

          V${d.target.y}

          h${nodeSize}

        `);

        link.exit().transition(transition).remove()
          .attr("d", d => `

          M${d.source.depth * nodeSize},${bias_y}

          V${bias_y}

          h${nodeSize}`)
      }

      update(root, 0);
      return svg.node();
    }

    function collapsibleTree(data, {
      id = Array.isArray(data) ? d => d.id : null,
      parentId = Array.isArray(data) ? d => d.parentId : null,
      tree = d3.tree,
      r = 5,
      padding = 1,
      stroke = "#555",
      strokeWidth = 1.5,
      strokeOpacity = 0.4,
      curve = d3.curveBumpX,
      dx = 128,
      dy = 128,
      margin = { top: 40, right: 120, bottom: 10, left: 40 }
    } = {}) {

      const root = d3.hierarchy(data);
      const diagonal = d3.linkVertical(curve).x(d => d.x).y(d => d.y);
      const tree_func = tree().nodeSize([dx, dy]);


      root.descendants().forEach((d, i) => {
        d.id = i;
        d._children = d.children;
        // d.children = null;
      });

      const svg = d3.create("svg")
        // .attr("viewBox", [-margin.left, -margin.top, width, dx])
        .attr("font-size", 14)
        .style("overflow", "visible")
        .style("user-select", "none");

      const gLink = svg.append("g")
        .attr("fill", "none")
        .attr("stroke", "#555")
        .attr("stroke-opacity", 0.4)
        .attr("stroke-width", 1.5);

      const gNode = svg.append("g")
        // .attr("cursor", "pointer")
        .attr("pointer-events", "all");

      function update(source, from_x, from_y) {
        const duration = d3.event && d3.event.altKey ? 2500 : 300;

        const nodes = root.descendants().reverse();
        const links = root.links();

        // Compute the new tree layout.
        tree_func(root);

        let left = root;
        let right = root;
        let top = root;
        let bottom = root;
        root.eachBefore(node => {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.y < top.y) top = node;
          if (node.y > bottom.y) bottom = node;
        });

        // const height = right.x - left.x + margin.top + margin.bottom;
        const width = right.x - left.x + margin.left + margin.right;
        const height = bottom.y - top.y + margin.top + margin.bottom;

        const transition = svg.transition()
          .duration(duration)
          .attr('height', height)
          .attr('width', width)
          .attr("viewBox", [-margin.left + left.x, top.y - margin.top, width, height])
          .tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));

        // Update the nodes…
        const node = gNode.selectAll("g")
          .data(nodes, d => d.id);


        // Enter any new nodes at the parent's previous position.
        const nodeEnter = node.enter().append("g")
          .attr("transform", d => `translate(${from_x},${from_y})`)
          .attr("fill-opacity", 0)
          .attr("stroke-opacity", 0);

        nodeEnter.append("title")
        .text(d => d._children ? d.data.id: d.data.name);

        nodeEnter.append("text")
          .attr("y", 0)
          .attr('font-weight', 'bold')
          // .attr('font-style', d => d._children ? 'italic': 'normal')
          .attr("cursor", d => d._children ? "pointer" : "default")
          .attr('fill', d => d._children ? "#333" : "#999")
          .attr("text-anchor", "middle")
          .text(d => d._children ? d.data.name: d.data.text)
          .on("pointerdown", (event, d) => {
            d.children = d.children ? null : d._children;
            update(d, d.x, d.y);
          })
          .clone(true).lower()
          .attr("stroke-linejoin", "round")
          .attr("stroke-width", 3)
          .attr("stroke", "white");

        // Transition nodes to their new position.
        const nodeUpdate = node.merge(nodeEnter).transition(transition)
          .attr("transform", d => `translate(${d.x},${d.y})`)
          .attr("fill-opacity", 1)
          .attr("stroke-opacity", 1);

        // Transition exiting nodes to the parent's new position.
        const nodeExit = node.exit().transition(transition).remove()
          .attr("transform", d => `translate(${source.x},${source.y})`)
          .attr("fill-opacity", 0)
          .attr("stroke-opacity", 0);

        // Update the links…
        const link = gLink.selectAll("path")
          .data(links, d => d.target.id);

        // Enter any new links at the parent's previous position.
        const linkEnter = link.enter().append("path")
          .attr("d", d => {
            const o = { x: from_x, y: from_y };
            return diagonal({ source: o, target: o });
          });

        // Transition links to their new position.
        link.merge(linkEnter).transition(transition)
          .attr("d", diagonal);

        // Transition exiting nodes to the parent's new position.
        link.exit().transition(transition).remove()
          .attr("d", d => {
            const o = { x: source.x, y: source.y };
            return diagonal({ source: o, target: o });
          });
      }

      update(root, 0, 0);

      return svg.node();
    }

    function bindEvents(parent, element) {
      document.body.onresize = () => {
        // console.log('body resized!');
        setSize(element);
      }
      
      // 绑定滚轮缩放
      parent.addEventListener('wheel', (e) => {
        let ratio = 1.1;
        // 缩小
        if (e.deltaY > 0) {
          ratio = 1 / 1.1;
        }
        config.scale *= ratio;
        if (config.scale > maxScale) config.scale = maxScale;
        else if (config.scale < minScale) config.scale = minScale;

        // scale 后面不要有空格 translateX 里面一定要有单位
        const transform = `translateX(${config.x}px) translateY(${config.y}px) scale(${config.scale})`;
        element.style.transform = transform;

        // 预防执行默认的行为
        e.preventDefault();
      });

      // 绑定拖拽功能
      parent.addEventListener('pointerdown', (e) => {
        if (e.button == 0) {
          config.isPointerdown = true;
          element.setPointerCapture(e.pointerId);
          config.lastPointermove = { x: e.clientX, y: e.clientY };
          // e.preventDefault();
        }
      });

      parent.addEventListener('pointerup', (e) => {
        if (e.button == 0) {
          config.isPointerdown = false;
          e.preventDefault();
        }

      });

      parent.addEventListener('pointermove', (e) => {
        if (config.isPointerdown) {
          const current = { x: e.clientX, y: e.clientY };
          const dx = current.x - config.lastPointermove.x;
          const dy = current.y - config.lastPointermove.y;
          config.lastPointermove = { x: current.x, y: current.y };
          config.x += dx; config.y += dy;

          const transform = `translateX(${config.x}px) translateY(${config.y}px) scale(${config.scale})`;
          element.style.transform = transform;

          e.preventDefault();
        }

      });

      setSize(element);
    }

    function setSize(element) {
      if (element.scrollWidth > window.innerWidth || element.scrollHeight > window.innerHeight) {
        element.style.width = window.innerWidth + 'px';
        element.style.height = window.innerHeight + 'px';
      }
    }

    function reset() {
      config.scale = 1.0;
      config.isPointerdown = false, config.lastPointermove = { x: 0, y: 0 };
      config.x = 0, config.y = 0;
      // element.style.transform = 'translateX(0px) translateY(0px) scale(1)';
      const element = document.getElementById('container');
      element.style.transform = 'translateX(0px) translateY(0px) scale(1)';
      // console.log(element.style.transform);
    }

    function render() {
      const tree = collapsibleTree(config.current, { tree: config.tree_or_cluster, dx: config.ast_width, dy: config.ast_height });
      const dom = document.getElementById('tree');
      dom.innerHTML = '';
      dom.appendChild(tree);
      reset();
    }


  </script>

</body>

</html>