Repository navigation
Expand file tree
/
Copy pathTreeAndDoc.tsx
More file actions
345 lines (312 loc) · 12.9 KB
/
Copy pathTreeAndDoc.tsx
File metadata and controls
345 lines (312 loc) · 12.9 KB
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
import { Id } from "./Data";
import { Doc, Indent, Level, OpenOp } from "./Doc";
import React, { Dispatch, FunctionComponent, useState } from "react";
import { InlineDocComponent } from "./InlineDoc";
import './TreeAndDoc.css';
import { Callout, Classes, Tag, Tooltip } from "@blueprintjs/core";
import {
decorators as TreebeardDecorators,
Treebeard,
TreebeardProps,
TreeNode as TreebeardTreeNode,
} from "react-treebeard";
import { State } from "./state";
// FormatterDecisions formatting stuff
type ExplorationNode = {
type: "exploration", parentId?: Id, id: Id, humanDescription: string, children: ReadonlyArray<LevelNode>,
startColumn: number, result?: ExplorationResult, incomingState?: State,
};
type LevelNode = {
type: "level", id: Id, parentId: Id, flat: string, toString: string, acceptedExplorationId: Id,
levelId: Id, children: ReadonlyArray<ExplorationNode>, incomingState: State, openOp: OpenOp,
evaluatedIndent: number
};
interface ExplorationResult {
outputLevel: Level;
finalState: State;
}
export type FormatterDecisions = ExplorationNode;
export interface ITreeState {
nodes: TreeNode[];
selectedNodeId?: string,
/** Treebeard's caching is broken as it mutates its props... Therefore, we force it to only render when we want it to. */
treeCacheBust: number,
}
/** Treebeard doesn't have typescript bindings, so have to manually specify them. */
interface TreeNode extends TreebeardTreeNode {
// Custom
data: NodeData,
}
type ExplorationNodeData = ExplorationNode & { parentLevelId?: Id };
type LevelNodeData = { levelId: Id, incomingState: State };
type NodeData = LevelNodeData | ExplorationNodeData;
/** A doc that should be displayed because it's currently being highlighted in the {@link DecisionTree}. */
type DisplayableLevel = { level: Level, startingColumn: number };
type Highlighted = DisplayableLevel | undefined;
export const TreeAndDoc: React.FC<{ formatterDecisions: FormatterDecisions, doc: Doc }> = props => {
const [highlighted, setHighlighted] = useState<Highlighted>();
const [highlightedLevelId, setHighlightedLevelId] = useState<Id>();
const [selected, setSelected] = useState<NodeData>();
function formatState(state: State) {
return <span>{JSON.stringify(state)}</span>
}
function formatNodeData(data: NodeData): JSX.Element | undefined {
if ("levelId" in data) {
return <table>
<tbody>
<tr>
<td><Tag intent={"primary"}>Incoming</Tag></td>
<td>{formatState(data.incomingState)}</td>
</tr>
</tbody>
</table>
}
if (data.result) {
// We always have an incoming state unless we're the root.
return <table>
<tbody>
<tr>
<td><Tag intent={"primary"}>Incoming</Tag></td>
<td>{formatState(data.incomingState!!)}</td>
</tr>
{data.result
? <tr>
<td><Tag intent={"success"}>Result</Tag></td>
<td>{formatState(data.result.finalState)}</td>
</tr>
: null}
</tbody>
</table>;
}
}
function nodeInfoBlock() {
const title = selected !== undefined
? "levelId" in selected ? "Level node" : "Exploration node"
: "<no node selected>";
return <Callout intent={"none"} title={title} className={"node-info"}>
{selected !== undefined ? formatNodeData(selected) : null}
</Callout>;
}
return <div className={"TreeAndDoc"}>
<div className={"column1"}>
{nodeInfoBlock()}
<DecisionTree
formatterDecisions={props.formatterDecisions}
highlightDoc={setHighlighted}
highlightLevelId={setHighlightedLevelId}
select={setSelected}/>
</div>
<div className={"InlineDocs"}>
<InlineDocComponent key={"entire-doc"} doc={props.doc} statingColumn={0} className={"InlineDoc"}
highlightedLevelId={highlightedLevelId}/>
{/* TODO grab this from `selected` */}
{highlighted !== undefined ? ([
<Callout intent={"primary"} title={"Rendered exploration output"}/>,
<InlineDocComponent key={"exploration"} doc={highlighted.level}
statingColumn={highlighted.startingColumn} className={"HighlightInlineDoc"}/>,
]) : null
}
</div>
</div>
};
interface DecisionTreeProps {
formatterDecisions: FormatterDecisions;
highlightDoc: Dispatch<Highlighted>;
highlightLevelId: Dispatch<Id | undefined>;
select: Dispatch<NodeData>;
}
export class DecisionTree extends React.PureComponent<DecisionTreeProps, ITreeState> {
public state: ITreeState = {
nodes: DecisionTree.createExplorationNode(this.props.formatterDecisions).children!!,
treeCacheBust: 0,
};
private static readonly duration = 50;
/** Default TreeBeard animations are too slow (300), sadly have to reimplement this to get a shorter duration. */
static Animations = {
toggle: function (_ref: { node: { toggled: boolean } }): { duration: number; animation: { rotateZ: number } } {
const toggled = _ref.node.toggled;
const duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DecisionTree.duration;
return {
animation: {
rotateZ: toggled ? 90 : 0,
},
duration: duration,
};
},
drawer: function () {
return (
/* props */
{
enter: {
animation: 'slideDown',
duration: DecisionTree.duration,
},
leave: {
animation: 'slideUp',
duration: DecisionTree.duration,
},
}
);
},
};
private static CastTreebeard<N extends TreeNode>(): FunctionComponent<TreebeardProps<N>> {
return Treebeard;
}
/**
* Treebeard isn't defined as a memoized thing so we need to.
* We use this memoization to indicate that only decorators.cacheBust should matter when determining up-to-dateness.
*/
private static MemoTreebeard: React.NamedExoticComponent<TreebeardProps<TreeNode>> = React.memo(
DecisionTree.CastTreebeard<TreeNode>(),
(prevProps, nextProps) =>
prevProps.decorators.cacheBust === nextProps.decorators.cacheBust);
public render() {
return <div className={`${Classes.ELEVATION_0} DecisionTree`}>
{/* Indicate which line is selected without refreshing the tree, because that is too slow. */}
{/* See https://medium.learnreact.com/the-style-tag-and-react-24d6dd3ca974 */}
<style dangerouslySetInnerHTML={{
__html: `
.node-${this.state.selectedNodeId} {
background-color: #2B95D6 !important
}
`,
}}/>
<DecisionTree.MemoTreebeard
data={this.state.nodes}
onToggle={this.onToggle}
animations={DecisionTree.Animations}
decorators={this.Decorators()}
/>
</div>;
}
private static createExplorationNode(node: ExplorationNode, parent?: LevelNode): TreeNode {
const onAcceptedPath = !parent || parent.acceptedExplorationId === node.id;
return {
id: node.id.toString(),
children: node.children.length > 0
? node.children.map(child => DecisionTree.createLevelNode(child, onAcceptedPath))
: undefined,
name: <div>
<Tooltip content={node.id.toString()}>
<span className={"explorationNode-description"}>{node.humanDescription}</span>
</Tooltip>
</div>,
toggled: onAcceptedPath,
active: onAcceptedPath,
data: {
...node,
parentLevelId: parent !== undefined ? parent.levelId : undefined,
},
};
}
private static createLevelNode(node: LevelNode, parentAccepted: boolean): TreeNode {
const indent = this.renderIndentTag(node.openOp.plusIndent, node.evaluatedIndent);
return {
id: node.id.toString(),
children: node.children.length > 0
? node.children.map(child => DecisionTree.createExplorationNode(child, node))
: undefined,
name: (
<div>
<Tooltip content={`Node ID: ${node.id.toString()}, Level ID: ${node.levelId.toString()}`}>
{node.openOp.debugName || node.id}
</Tooltip>
{" "}{indent}
</div>
),
toggled: true,
active: parentAccepted,
data: {
levelId: node.levelId,
incomingState: node.incomingState,
},
};
}
private static renderConstIndent(indent: Indent) {
switch (indent.type) {
case "const":
return <Tag intent={"success"}>+{indent.amount}</Tag>;
case "if":
throw Error(`Expected const indent but got ${indent}`)
}
}
/** Render an indent differently, depending on whether it was conditional or not. */
private static renderIndentTag(indent: Indent, evaluatedIndent?: number) {
switch (indent.type) {
case "const":
if (indent.amount === 0) {
return;
}
return <Tag intent={"success"}>+{indent.amount}</Tag>;
case "if":
return <Tooltip position={"bottom-right"} content={
<span>
thenIndent={this.renderConstIndent(indent.thenIndent)}{" "}
elseIndent={this.renderConstIndent(indent.elseIndent)}
</span>}>
<Tag intent={"warning"}>
{evaluatedIndent !== undefined ? `+${evaluatedIndent}` : '(unknown)'}
</Tag>
</Tooltip>
}
}
private onToggle = (nodeData: TreeNode, toggled: boolean) => {
nodeData.toggled = toggled;
this.setState(prevState => ({...prevState, treeCacheBust: prevState.treeCacheBust + 1}));
};
private highlightInlineDocLevel(id: Id) {
this.props.highlightLevelId(id);
}
private highlightLevel(nodeData: TreeNode) {
const data = nodeData.data;
if ("levelId" in data) {
this.highlightInlineDocLevel(data.levelId);
} else {
// It's an ExplorationNodeData
if (data.parentLevelId !== undefined) {
this.highlightInlineDocLevel(data.parentLevelId);
}
if (nodeData === this.state.nodes[0]) {
this.props.highlightDoc(undefined); // no point highlighting the root
} else if (data.result) {
// The exploration had a result
this.props.highlightDoc({
level: data.result.outputLevel,
startingColumn: data.startColumn,
});
} else {
this.props.highlightDoc(undefined);
}
}
this.props.select(data);
}
private onMouseEnter = (nodeData: TreeNode) => {
this.highlightLevel(nodeData);
this.setState(prevState => ({...prevState, selectedNodeId: nodeData.id}));
};
/**
* This is a hack to override the Container of {@link TreebeardDecorators} and still have access to the main
* component object, because we don't control what gets passed to this inner component via props.
*/
private Container = ((outer: DecisionTree) => class extends TreebeardDecorators.Container {
render() {
const {style, decorators, terminal, onClick, node} = this.props;
return (
<div
onClick={onClick}
className={`node-${node.id}`}
style={node.active ? {...style.container} : {...style.link}}
onMouseEnter={() => outer.onMouseEnter(node)}
>
{!terminal ? this.renderToggle() : null}
<decorators.Header node={node} style={style.header}/>
</div>
);
}
})(this);
private Decorators = () => Object.assign({}, TreebeardDecorators, {
Container: this.Container,
// Force the tree to re-render
cacheBust: this.state.treeCacheBust,
});
}