Add graphviz display of line Traces.
[ustaxviewer.git] / src / FormView.tsx
1 // Copyright 2020 Blue Static <https://www.bluestatic.org>
2 // This program is free software licensed under the GNU General Public License,
3 // version 3.0. The full text of the license can be found in LICENSE.txt.
4 // SPDX-License-Identifier: GPL-3.0-only
5
6 import { createDependentEffect, createMemo, createState } from 'solid-js';
7 import { For, Show } from 'solid-js/dom';
8 import { TaxReturn, Form, Line } from 'ustaxlib/core';
9 import { Edge, getLastTraceList } from 'ustaxlib/core/Trace';
10 import { graphviz } from 'd3-graphviz';
11
12 const S = require('./FormView.css');
13
14 interface FormProps {
15 tr: TaxReturn;
16 form: Form<any>;
17 }
18
19 export default function FormView(props: FormProps) {
20 const lines = createMemo(() => {
21 const keys = Object.keys(props.form.lines);
22 keys.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
23 return keys.map(k => props.form.lines[k]);
24 });
25
26 return (
27 <>
28 <h2 class={S.formName}>Form {props.form.name}</h2>
29
30 <table class={S.table}>
31 <For each={lines()}>
32 {line => <LineView tr={props.tr} line={line} />}
33 </For>
34 </table>
35 </>
36 );
37 }
38
39 interface LineProps {
40 tr: TaxReturn;
41 line: Line<any>;
42 }
43
44 function LineView(props: LineProps) {
45 const { tr, line } = props;
46 const value = createMemo(() => {
47 try {
48 return JSON.stringify(line.value(tr), null, 1);
49 } catch (e) {
50 return <span class={S.error} title={e.stack}>{e.message}</span>;
51 }
52 });
53
54 const [ state, setState ] = createState({
55 trace: [] as readonly Edge[],
56 showTrace: false
57 });
58
59 createDependentEffect(() => setState('trace', getLastTraceList()), [value]);
60
61 const toggleTrace = () => setState('showTrace', !state.showTrace);
62
63 return (
64 <tr class={S.line}>
65 <th class={S.id} onclick={toggleTrace}>{line.id}</th>
66 <td class={S.description}>
67 {line.description}
68
69 <Show when={state.showTrace}>
70 <TraceViewer line={line} trace={state.trace} />
71 </Show>
72 </td>
73 <td class={S.value}>{value()}</td>
74 </tr>
75 );
76 }
77
78 interface TraceProps {
79 line: Line<any>;
80 trace: readonly Edge[];
81 }
82
83 function TraceViewer(props: TraceProps) {
84 const renderGraph = (ref) => {
85 let graph = '';
86 for (const edge of props.trace) {
87 graph += `"${edge[1]}" -> "${edge[0]}"; `;
88 }
89 graphviz(ref)
90 .renderDot(`digraph { ${graph} }`);
91 };
92 return (
93 <div class={S.traceViewer}>
94 <h2>Trace {props.line.id}</h2>
95 <div forwardRef={renderGraph}></div>
96 </div>
97 );
98 }