rr-markdownmermaidtargets-r-package

static image of targets workflow, programatically


I'm trying to embed a static image of a targets workflow in an rmarkdown document. I tried to do this by using tar_mermaid, defining a target that writes the workflow in mermaid format mm <- tar_mermaid(); writeLines(mm, "target_mermaid.js") but the help for tar_mermaid says

You can visualize the graph by copying the text into a public online mermaid.js editor or a mermaid GitHub code chunk

I am looking for a programmatic way to either (1) embed the Javascript output in an (R)markdown file, or (2) render it (as SVG, PNG, whatever).

I thought as a shortcut that I could cut-and-paste into a markdown code chunk delimited by ```mermaid, or use cat(readLines("target_mermaid.js"), sep = "\n") in a chunk with results = "asis" but I guess that only works in Github markdown (I'm using Pandoc to render to HTML) ... ?

The visNetwork package has a visSave() function which can save to HTML (not quite what I wanted but better than what I've managed so far), and a visExport() function (which saves to PNG etc. but only by clicking in a web browser). Furthermore, targets wraps the visNetwork functions in a way that is (so far) hard for me to unravel (i.e., it doesn't return a visNetwork object, but automatically returns a widget ...)

For the time being I can go to https://mermaid.live, paste in the mermaid code, and export the PNG manually but I really want to do it programmatically (i.e. as part of my workflow, without manual steps involved).

enter image description here


Solution

  • @landau's suggestion to look here almost works, if I'm willing to use Quarto instead of Rmarkdown (GH Markdown is not an option). The cat() trick was the main thing I was missing. The .qmd file below gets most of the way there but has the following (cosmetic) issues:

    Any further advice would be welcome ...

    ---
    title: "targets/quarto/mermaid example"
    ---
    
    ```{r}
    suppressPackageStartupMessages(library("tidyverse"))
    library("targets")
    ```
    
    ```{r, results = "asis", echo = FALSE}
    cat(c("```{mermaid}", tar_mermaid(), "```"), sep = "\n")
    ```
    

    Beginning of document:

    
image of Quarto output, showing code chunks and tidyverse startup messages

    Zooming out:

    full view of Quarto output, showing an awkwardly sized corner of the targets network