railroad-diagrams

Railroad-Diagram Generator, JS Version

This is a small library for generating railroad diagrams (like what JSON.org uses) using SVG, with both JS and Python ports. Here’s an online dingus for you to play with and get SVG code from!

(This is the README for the JS port; see the main README for other ports, and for more non-JS-specific information.)

Diagrams

To use the library, include railroad.css in your page, and import the railroad.js module in your script, then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence).

The constructors for each node are named exports in the module; the default export is an object of same-named functions that just call the constructors, so you can construct diagrams without having to spam new all over the place:

// Use the constructors
import {Diagram, Choice} from "./railroad.js";
const d = new Diagram("foo", new Choice(0, "bar", "baz"));

// Or use the functions that call the constructors for you
import rr from "./railroad.js";
const d = rr.Diagram("foo", rr.Choice(0, "bar", "baz"));

Alternately, you can call ComplexDiagram(); it’s identical to Diagram(), but has slightly different start/end shapes, same as what JSON.org does to distinguish between “leaf” types like number (ordinary Diagram()) and “container” types like Array (ComplexDiagram()).

The Diagram class also has a few methods:

Components

Components are either leaves or containers.

The leaves:

The containers:

After constructing a Diagram, call .format(...padding) on it, specifying 0-4 padding values (just like CSS) for some additional “breathing space” around the diagram (the paddings default to 20px).

The result can either be .toString()‘d for the markup, or .toSVG()‘d for an <svg> element, which can then be immediately inserted to the document. As a convenience, Diagram also has an .addTo(element) method, which immediately converts it to SVG and appends it to the referenced element with default paddings. element defaults to document.body.

Options

There are a few options you can tweak, in an Options object exported from the module. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart’s content. Note, though, that if you change the text sizes in the CSS, you’ll have to go adjust the options specifying the text metrics as well.