Skip to content

Commit f4a3ceb

Browse files
georgefstdhess
authored andcommitted
fix: Draw variable binding nodes closer to their parents
Signed-off-by: George Thomas <georgefsthomas@gmail.com>
1 parent 157effa commit f4a3ceb

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

src/components/TreeReactFlow/Types.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,27 @@ export const treeMap = <N1, N2, E>(
6363
: {}),
6464
});
6565

66+
// A generalisation of `treeMap`, where the mapping function is also passed
67+
// the node's subtrees and parent.
68+
export const treeMapWithExtraContext = <N1, N2, E>(
69+
t: Tree<N1, E> & { parent?: Tree<N1, E> },
70+
f: (t: Tree<N1, E> & { parent?: Tree<N1, E> }) => N2
71+
): Tree<N2, E> => ({
72+
node: f({ ...t }),
73+
childTrees: t.childTrees.map(([t1, e]) => [
74+
treeMapWithExtraContext({ ...t1, parent: t }, f),
75+
e,
76+
]),
77+
...(t.rightChild
78+
? {
79+
rightChild: (([t1, e]) => [
80+
treeMapWithExtraContext({ ...t1, parent: t }, f),
81+
e,
82+
])(t.rightChild),
83+
}
84+
: {}),
85+
});
86+
6687
export const treeNodes = <N, E>({
6788
node,
6889
rightChild,

src/components/TreeReactFlow/layoutTree.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ import {
66
import { WasmLayoutType } from "@zxch3n/tidy/wasm_dist";
77
import { unzip } from "fp-ts/lib/Array";
88
import { fst, mapFst, mapSnd } from "fp-ts/lib/Tuple";
9-
import { treeMap, Tree, Positioned, Padding } from "./Types";
9+
import {
10+
treeMap,
11+
Tree,
12+
Positioned,
13+
Padding,
14+
treeMapWithExtraContext,
15+
} from "./Types";
1016

1117
export type LayoutParams = {
1218
type: WasmLayoutType;
@@ -53,7 +59,25 @@ export const layoutTree = <
5359
const minY = Math.min(
5460
...nodes.map((n) => n.position.y - (n.data.padding?.top || 0))
5561
);
56-
const tree = treeMap(treeUnNormalized, (n) => ({
62+
// Ensure that where a node is a right-child with no children of its own,
63+
// that child is drawn close to its parent, rather than evenly distributed among its parents' siblings.
64+
// We should consider patching Tidy to allow us to do this sort of thing.
65+
// As it stands, this is a bit of a hack, but a self-contained and relatively harmless one,
66+
// which is extremely useful for positioning variable-binding nodes.
67+
const tree0 = treeMapWithExtraContext(treeUnNormalized, (t) => ({
68+
...t.node,
69+
position: {
70+
x:
71+
t.parent?.rightChild?.[1].target == t.node.id &&
72+
t.childTrees.length == 0
73+
? t.parent.node.position.x +
74+
p.margins.sibling +
75+
t.parent.node.data.width
76+
: t.node.position.x,
77+
y: t.node.position.y,
78+
},
79+
}));
80+
const tree = treeMap(tree0, (n) => ({
5781
...n,
5882
// Ensure top-left is at (0,0). This makes the result easier to work with.
5983
position: { x: n.position.x - minX, y: n.position.y - minY },

0 commit comments

Comments
 (0)