See this thread.

See _top-diagram.js for the code; feel free to modify it and use it (Apache v2 license). Look at the makeDiagram_top function at the bottom.