D2 Text-to-Diagram DSL

repository·master·Indexed 42 days ago

https://github.com/terrastruct/d2-docs

A 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.

Tokens
39.2K
Snippets
187
Records
251
Agent score
54%

What's inside D2

  1. Overview of the TALA layout engine

    master

    TALA 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 top and left properties to lock specific positions.
    • Container Support: Provides first-class consideration for containers, including per-container direction settings.
    • Spatial Relationships: Use the near property 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_table connections that point to exact rows.
    • Dynamic Labeling: Automatically positions labels to avoid obstructing diagram elements.
  2. What is D2

    master
    D2 (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.
  3. Understand the D2 Roadmap and Priorities

    master

    D2'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:

    1. Expand Layout Coverage: Increasing the variety of diagram types that can be automatically laid out.
    2. Minimize Aesthetic Effort: Making it easier to produce professional-looking diagrams through themes and granular customization.
    3. Developer Tooling Integration: Improving support for existing workflows, editor extensions, and programmatic manipulation.
  4. What is TALA and when should I use it?

    master

    TALA 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.
  5. How shape overrides work in D2

    master
    In 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 a label) takes priority over previous ones. This allows you to modify specific properties of an existing shape without redefining its entire structure.
  6. Understand 1:1 ratio shapes

    master

    Certain shapes in D2 maintain a 1:1 aspect ratio, meaning their width and height are always equal. This includes:

    • circle
    • square

    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 width and height, 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 100x100
  7. Reference a parent container using the underscore symbol

    master

    When 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
      }
    }
  8. How autoformat handles block string indentation

    master

    D2'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)
    }
    |
    }
  9. How D2 Oracle works

    master

    D2 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 d2oracle are 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, pass nil.

    // Example of the required chaining pattern due to immutability
    g, _ = d2oracle.Create(g, nil, "a")
    g, _ = d2oracle.Set(g, "a.style.fill", nil, "red")
  10. D2 target use case: Software Documentation

    master

    D2 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).