Generating Diagrams With D2

I was looking at D2 this evening and think it might be the thing I’ve been looking for as Mermaid hasn’t really done it for me. I knew D3, but it was nice to get know D2. Is there a D1? Oh well … let’s just do some D2:

https://github.com/terrastruct/d2

I tried the quickstart and it worked

# First, install D2
curl -fsSL https://d2lang.com/install.sh | sh -s --

echo 'x -> y -> z' > in.d2
d2 --watch in.d2 out.svg

And this worked

echo 'x -> y -> z' > in.d2
d2 in.d2 out.svg

So that’s a miracle. I went one further and tried to out a png and it brought playwright in and it worked

d2 in.d2 out.png

Oh neat, you can install your own fonts:

https://github.com/terrastruct/d2/tree/master/d2renderers/d2fonts

I tried it with this example

alphabet: Alphabet Inc {
  shape: rectangle
}
google: {
  gmail: Gmail {
    shape: rectangle
  }
  meet: Meet {
    shape: rectangle
  }
  deepmind: DeepMind {
    shape: rectangle
  }
  icon: https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png
  shape: rectangle
}
google -> alphabet: BELONGS_TO

Neat! It works in mkdocs https://github.com/landmaj/mkdocs-d2-plugin and there’s also a vscode extension https://github.com/terrastruct/d2-vscode

Fancy example is here https://terrastruct.com/blog/post/generate-diagrams-programmatically/

movie: {
  id: integer
  star: integer
  budget: integer
  profit: integer
  producer: integer
  dialogue: integer
}
movie.shape: sql_table
actor: {
  id: integer
  name: text
  native_lang: integer
}
actor.shape: sql_table
producer: {
  id: integer
  name: text
  native_lang: integer
}
producer.shape: sql_table
language: {
  id: integer
  name: text
}
language.shape: sql_table
movie.star -> actor.id
movie.producer -> producer.id
movie.dialogue -> language.id
producer.native_lang -> language.id
actor.native_lang -> language.id

It seems to be able to build unusually beautiful diagrams: https://terrastruct.com/blog/post/draw-software-architecture-diagrams/ which require their paid tala engine https://github.com/terrastruct/tala#installation

brew install terrastruct/tap/tala

Which you can run with this file

vars: {
  d2-config: {
    layout-engine: tala
  }
}
direction: down
a -> b -> c

b: {
  direction: right
  1 -> 2 -> 3
}

a: {
  direction: left
  foo -> bar
}

And get

Ah — now I understand. It’s not free.