D2 Text-to-Diagram DSL
repository·master·Indexed 42 days ago
https://github.com/terrastruct/d2-docsA modern, open-source text-to-diagram Domain Specific Language (DSL) for creating software architecture diagrams. Features include the TALA orthogonal layout engine, animated SVG generation (v0.3.0+), ASCII rendering (v0.7.1+), and the ability to export diagrams to PowerPoint (.pptx). Supports advanced modeling techniques such as suspend/unsuspend for multiple views, C4-style zooming via layers and links, and structured legends using the d2-legend variable.
What's inside D2
- This repository contains the language documentation for D2, a modern, open-source text-to-diagram Domain Specific Language (DSL). The documentation is deployed at https://d2lang.com. For the core D2 language implementation and source code, visit the main repository at https://github.com/d2lang/d2.
Overview of the TALA layout engine
masterTALA is a specialized layout engine developed by Terrastruct, purpose-built for software architecture diagrams. Unlike traditional engines that are constrained to specific structures like trees, hierarchies, or radial layouts, TALA functions as a general orthogonal layout engine. This allows it to produce non-hierarchical diagrams that mimic human-drawn whiteboard layouts.
Key capabilities include:
- Position Locking: Use
topandleftproperties to lock specific positions. - Container Support: Provides first-class consideration for containers, including per-container
directionsettings. - Spatial Relationships: Use the
nearproperty to position a shape relative to another. - Symmetry and Routing: Prefers symmetrical layouts and uses a routing engine for grid cell connections (rather than just straight lines).
- Specialized Connections: Supports
sql_tableconnections that point to exact rows. - Dynamic Labeling: Automatically positions labels to avoid obstructing diagram elements.
- Position Locking: Use
What is D2
masterD2 (Declarative Diagramming) is a diagram scripting language that converts text descriptions into diagrams. Instead of manually drawing shapes and connections, you describe the structure and relationships of your diagram in a declarative syntax, and D2 generates the visual representation.Understand the D2 Roadmap and Priorities
masterD2's long-term goal is to reduce the effort required to create and maintain high-quality diagrams for software teams. The current development priorities are:
- Expand Layout Coverage: Increasing the variety of diagram types that can be automatically laid out.
- Minimize Aesthetic Effort: Making it easier to produce professional-looking diagrams through themes and granular customization.
- Developer Tooling Integration: Improving support for existing workflows, editor extensions, and programmatic manipulation.
What is TALA and when should I use it?
masterTALA is a novel autolayout algorithm optimized for software architecture diagrams. Unlike DAG-based engines (Dagre, ELK) that grow in a single direction, TALA is an orthogonal engine that aims for aesthetic qualities like symmetry, median distance, and clustering of similar nodes.
When to use TALA:
- For software architecture diagrams that require an orthogonal, whiteboard-like feel.
- When you need to mix manual node positioning with automatic layout (hybrid positioning).
- When you want to lock specific nodes to coordinates while letting the engine handle routing and other nodes.
Trade-offs to consider:
- Randomness: TALA uses multiple seeds (default is 3) to find the best layout. While the same seeds produce the same result, adding a single new node can cause the entire diagram layout to shift significantly, unlike Dagre or ELK which tend to accommodate new nodes locally.
- DAGs: TALA may not be as effective as Dagre or ELK for long, flowing directed acyclic graphs (DAGs).
- Performance: For very large diagrams, TALA's runtime scales nonlinearly and may take longer than other engines.
How shape overrides work in D2
masterIn D2, if you redeclare a shape, the new declaration is merged with the previous declaration. When multiple declarations exist, the latest explicit setting (such as alabel) takes priority over previous ones. This allows you to modify specific properties of an existing shape without redefining its entire structure.Understand 1:1 ratio shapes
masterCertain shapes in D2 maintain a 1:1 aspect ratio, meaning their width and height are always equal. This includes:
circlesquare
Behavioral rules for 1:1 shapes:
- Label scaling: If a long label makes the shape wider, D2 will automatically increase the height to maintain the ratio.
- Manual dimensions: If you manually set both
widthandheight, D2 will set both dimensions to the larger of the two values to preserve the 1:1 ratio.
# Example of a 1:1 shape MyCircle.shape: circle MyCircle.width: 100 MyCircle.height: 50 # Will be rendered as 100x100Define and use variables in D2
masterUse the
varskeyword to define variables that can be reused throughout your diagram. To reference a variable, use the substitution syntax${variable_name}.vars: my_var: hello shape: ${my_var}Reference a parent container using the underscore symbol
masterWhen working inside a container, you may need to reference an element or property that exists outside of it (in the parent scope). Use the underscore (
_) symbol to refer to the parent container.parent_container: { child: { # Refers to parent_container _ -> some_external_node } }How autoformat handles block string indentation
masterD2's autoformatter automatically corrects the indentation of block strings (strings starting with
|).If a block string's indentation is insufficient, the autoformatter identifies non-empty lines with insufficient indent and prepends them with the correct amount of indentation while respecting the existing common indent. This allows you to paste code into the first column after the block string marker without manually adjusting the indentation.
parent: { example_code: |go package fs type FS interface { Open(name string) (File, error) } | }How D2 Oracle works
masterD2 Oracle (
d2/d2oracle) is a Go package that provides an API for programmatically creating and manipulating D2 diagrams by operating on its Abstract Syntax Tree (AST).Key Concept: Immutability
All functions in
d2oracleare pure. They do not mutate the original graph; instead, they return a new modified graph. When chaining operations, you must always use the resulting graph from the previous call.Multi-board Diagrams
For diagrams containing multiple boards, most functions accept a
boardPath(a[]string) to specify which board to modify. For single-board diagrams, passnil.// Example of the required chaining pattern due to immutability g, _ = d2oracle.Create(g, nil, "a") g, _ = d2oracle.Set(g, "a.style.fill", nil, "red")D2 target use case: Software Documentation
masterD2 is a specialized tool for documenting software architecture. It is not a general-purpose visualization tool.
What D2 is for:
- Describing software systems via nodes and edges.
- Creating "whiteboard-fit" diagrams (simplified representations of systems).
What D2 is NOT for:
- General visualization (e.g., mind maps, Gantt charts, Sankey diagrams, or Venn diagrams).
- Large-scale graph theory visualization (e.g., diagrams with >1000 nodes where the goal is pattern recognition rather than understanding individual components).