Skip to content

Instantly share code, notes, and snippets.

@oliver-ni
Created August 7, 2023 01:07
Show Gist options
  • Select an option

  • Save oliver-ni/701eec83f6cc0b7e9464c2e67e607faa to your computer and use it in GitHub Desktop.

Select an option

Save oliver-ni/701eec83f6cc0b7e9464c2e67e607faa to your computer and use it in GitHub Desktop.

Revisions

  1. oliver-ni created this gist Aug 7, 2023.
    4 changes: 4 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    Make trees in Typst

    ![image](https://user-images.githubusercontent.com/20295134/258676405-ce7e3a05-487f-4501-ab21-f2782950c28d.png)
    ![image](https://user-images.githubusercontent.com/20295134/258676410-a5820408-6259-4df2-aed4-de51d3493f6d.png)
    29 changes: 29 additions & 0 deletions tree.typ
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    let tree(label, ..children) = style(styles => block(align(center, {
    let label = rect(align(center + horizon)[#label])
    let label_dim = measure(label, styles)

    let children_widths = children.pos().map(x => measure(x, styles).width)
    let all_children = stack(dir: ltr, spacing: 1em, ..children.pos())
    let all_children_dim = measure(all_children, styles)

    // If there are no children, stacking will result in excess space

    if children.pos().len() == 0 {
    label
    } else {
    stack(spacing: 1em, label, all_children)
    }

    // Draw lines

    let label_bottom = (all_children_dim.width / 2, label_dim.height)
    let x = 0em
    let y = label_dim.height + 1em

    for (i, child) in children.pos().enumerate() {
    let child_dim = measure(child, styles)
    let child_top = (x + child_dim.width / 2, y)
    place(top + left, line(start: label_bottom, end: child_top))
    x += child_dim.width + 1em
    }
    })))