mcpField
D
d2

d2

github.com/itsjool開発040 回インストール28 週間前に更新
リポジトリ

d2 について

D2 の図コード作成と、図の種類の選択からテキストプレビューの確認、合意後の SVG 出力までを案内するスキルです。アーキテクチャ、プロセス、データなどの図を作成する用途に向きます。

主な機能

  1. 01図の種類を選ぶガイド
  2. 02D2 構文とスタイルのリファレンス
  3. 03検査結果から ASCII プレビューを作成
  4. 04確認後に SVG を出力
  5. 05アーキテクチャ、フロー、ER、UML のパターン

活用シーン

  1. 01システムアーキテクチャ図の下書き
  2. 02プロセスやリクエスト順序の整理
  3. 03データベース表やクラス関係のモデル化
  4. 04SVG 出力用の図の準備

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/itsjool/d2-mcp --skill d2

インストール後、Claude Code で/d2を入力して読み込まれたか確認します。

詳細

D2 図表言語

D2 は、SVG にコンパイルされる宣言型の図表スクリプト言語です。テキストから図表を作成できます。 ドキュメント:https://d2lang.com | プレイグラウンド:https://play.d2lang.com


図表の種類の選択

コードを書く前に、適切な図表の種類を選びます。

表示したい内容使用する D2 のパターン
システムのコンポーネントとその接続方法コンテナー+接続(アーキテクチャ)
リクエスト/レスポンスの流れ、API のやり取り、メッセージの順序shape: sequence_diagram
プロセス、アルゴリズム、または決定木図形+方向付き接続(フローチャート)
データベーステーブルと外部キーshape: sql_table(ER 図)
クラス階層、オブジェクトの関係shape: class(UML クラス図)
システムコンテキスト:ユーザー、システム、境界(C4)コンテナー+shape: c4-person+テーマ 303
状態機械またはライフサイクル図形+ラベル付き接続(状態図)
段階的な表示/ストーリーテリングsteps: {} と animate_interval
同じシステムの複数のビューlayers: {} または scenarios: {}
ダッシュボード/指標のグリッドgrid-rows/grid-columns を使ったコンテナー

デフォルトの図形: rectangle。フローの方向を制御するには、direction: right または direction: down を使用します。


ワークフロー:図表のリクエストへの対応

  1. 図表の種類を選ぶ(上の表を使用)

  2. D2 コードを作成する — 中核となる要素から始め、接続を追加し、最後にスタイルを追加する

  3. d2_inspect を呼び出し、その出力をもとに ASCII 図を描く:

    d2_inspect(d2_code=...)
    

    inspect の出力を使い、罫線文字(┌─┐│└┘├┤┬┴┼ ▶ ◀ ↓ ↑)で整った ASCII 図を手描きします。この ASCII 図は D2 レンダラーではなく、あなたが作成します。これにより、D2 の既知の ASCII 描画バグ(コンテナーをまたぐ接続、逆向きのエッジ、direction:right)を回避できます。

    描き方:

    • コンテナーはラベル付きボックスとして描きます:┌─ Control Plane ──────┐
    • 子図形は親ボックス内にインデントして配置します
    • 接続は、ラベルを付けたボックス間の矢印として描きます
    • コンテナーをまたぐ接続は、ボックス間を結ぶ矢印として示します
    • 順方向には →、逆方向には ←、双方向には ↔、無向には -- を使用します
    • シーケンス図では、アクターを列として描き、その間に矢印を配置します
    • ステップ/レイヤーでは、各ボードを個別のセクションとして示します

    結果をコードフェンスに入れ、構成が適切かユーザーに確認します:

    Here's the structure:
    
    ┌─ SaaS Cloud ─────────────────────────────┐
    │  ┌──────────────────┐                    │
    │  │  Control Plane   │                    │
    │  │  ┌─────────────┐ │                    │
    │  │  │ API Gateway │ │                    │
    │  │  └──────┬──────┘ │                    │
    │  │       route      │                    │
    │  │  ┌──────▼──────┐ │                    │
    │  │  │ gRPC Server │ │                    │
    │  │  └──────┬──────┘ │                    │
    │  └─────────┼────────┘                    │
    └────────────┼────────────────────────────-┘
                 │ mirror request →
    ┌─ Customer Edge ──────────────────────────┐
    │  ┌──────────────────┐                    │
    │  │  Data Plane Agent│                    │
    │  │  ┌─────────────┐ │                    │
    │  │  │ gRPC Client │ │                    │
    │  │  └─────────────┘ │                    │
    │  └──────────────────┘                    │
    └──────────────────────────────────────────┘
    
    Does this look right? I'll render the SVG if so.
    

    ルール:

    • 必ず最初に d2_inspect を呼び出し、記憶ではなく出力をもとに描きます
    • d2_render(ascii=true) は使用しないでください — D2 の ASCII レンダラーには既知のバグがあります
    • プレビューを省略して、いきなり SVG に進まないでください
    • ユーザーから変更の依頼があった場合は、D2 コードを更新し、再度 inspect を実行してから描き直します
  4. ユーザーが構成を確認した場合に限り、SVG をレンダリングする: d2_render(d2_code=..., skip_fonts=true)

  5. いずれかの手順で無効な場合は、 d2_validate を呼び出して行/列ごとの具体的なエラーを取得します

  6. 保存する場合: まず .d2 ソースを書き込み(即時)、最後に SVG をレンダリングします(レンダリング済み SVG の保存を参照)

  7. 反復する — フィードバックに基づいて調整し、ASCII を再レンダリングして確認してから、SVG をレンダリングします

ルール: skip_fonts のデフォルトは true です — ユーザーが埋め込みフォントを明示的に求めない限り、変更しないでください。実際にはシステムフォントと Source Sans Pro に違いはなく、フォントを省略するとレンダリング時間と SVG のサイズが約 500KB 削減されます。


基本構文

図形
# Bare identifier = rectangle by default
server

# With a display label (key vs label — connections use the KEY, not the label)
server: "API Server"

# Set shape type
db: {
  shape: cylinder
}

# Multiple on one line
web; app; db

# Inline style shorthand
cache: { shape: queue; style.fill: "#fce8e6" }

利用可能な図形の種類: rectangle(デフォルト)、square、circle、oval、diamond、hexagon、cloud、 cylinder、queue、package、parallelogram、document、page、step、 callout、stored_data、person、c4-person、 sql_table、class、sequence_diagram、image

接続
A -> B            # directed arrow
A <- B            # reverse
A -- B            # undirected line
A <-> B           # bidirectional

A -> B: label     # with label

# Chaining
A -> B -> C -> D

# Multiple connections (creates SEPARATE arrows — D2 never merges them)
A -> B: "first"
A -> B: "second"   # distinct second arrow, not an override

# Reference a specific connection (0-indexed) to style it
(A -> B)[0].style.stroke: red
コンテナー(ネスト)
cloud: {
  label: "AWS"
  vpc: {
    web: "Web Tier"
    app: "App Tier"
    web -> app
  }
}

# Cross-container connections: use _ to refer to the parent scope
cloud: {
  aws: {
    db
    db -> _.gcloud.backup    # _ = parent scope (cloud)
  }
  gcloud: {
    backup
  }
}
テキストと Markdown
explanation: |md
  ## Architecture Overview
  This diagram shows the **three-tier** architecture.
  - Web tier
  - App tier
  - Data tier
|

formula: |latex
  \frac{\partial f}{\partial x} = 2x
|

スタイルリファレンス

図形のスタイル
my_shape: {
  style: {
    fill: "#4a90d9"          # background color
    stroke: "#2c5f8a"        # border color
    stroke-width: 2
    stroke-dash: 5           # dashed border
    border-radius: 8         # rounded corners
    font-size: 14
    font-color: white
    opacity: 0.9
    shadow: true
    bold: true
    italic: false
    3d: true                 # rectangles/squares only
    multiple: true           # stacked visual — implies "many instances"
    double-border: true      # rectangles and ovals only
    text-transform: uppercase
  }
}
接続のスタイル
A -> B: {
  style: {
    stroke: red
    stroke-width: 3
    stroke-dash: 5
    animated: true           # flowing animation — use to show data/request flow
    bold: true
    font-color: "#666"
  }
}
矢印の先端
A -> B: {
  source-arrowhead: {
    shape: diamond
    style.filled: true
  }
  target-arrowhead: {
    shape: circle
  }
}

矢印の先端の形状:triangle(デフォルト)、arrow、diamond、circle、box、 cf-one、cf-many、cf-one-required、cf-many-required、cross

ER 接続では、カーディナリティ(カラスの足記法)を示すために cf-* の矢印の先端を使用します。


高度なスタイル設定

グロブを使ったグローバルスタイル
# Style all shapes
*.style.fill: "#f0f4ff"
*.style.stroke: "#3b5bdb"
*.style.border-radius: 6

# Style all connections
(* -> *)[*].style.stroke: "#888"
(* -> *)[*].style.animated: true

# Scoped glob — only shapes inside this container
cloud: {
  *.style.fill: "#e8f5e9"
}
再利用可能なスタイルクラス
classes: {
  important: {
    style: { stroke: red; stroke-width: 3; bold: true }
  }
  faded: {
    style: { opacity: 0.4 }
  }
  external: {
    style: { stroke-dash: 5; fill: "#f8f8f8" }
  }
}

# Apply to shapes
critical_db.class: important
legacy_service.class: faded

# Apply multiple (left-to-right, later class wins on conflicts)
service.class: [important; faded]

# Apply to connections
A -> B: { class: important }
変数と置換
vars: {
  primary: "#3b5bdb"
  secondary: "#74c0fc"
  accent: "#f06595"

  # In-file config (overridden by d2_render tool params)
  d2-config: {
    theme-id: 0
    theme-overrides: {
      B1: "#0057b8"   # brand primary — maps to the main accent color
      N7: "#1a1a2e"   # darkest neutral
    }
  }
}

server: {
  style.fill: ${primary}
  style.stroke: ${secondary}
}

色の上書きコード:N1~N7(ニュートラル)、B1~B6(ブランド)、AA2~AA5(アクセント A)、AB4~AB5(アクセント B)


図のパターン

アーキテクチャ/システム
*.style.border-radius: 6
*.style.font-size: 13
direction: right

internet: { shape: cloud; label: "Internet" }

frontend: {
  label: "Frontend\n(React)"
  icon: https://icons.terrastruct.com/dev/react.svg
  style.fill: "#e8f4fd"
}

api: { label: "API Gateway"; style.fill: "#fff3cd" }

services: {
  label: "Microservices"
  style.fill: "#f8f9fa"

  auth: "Auth Service"
  orders: "Orders Service"
  payments: "Payments Service"
}

db: { shape: cylinder; label: "PostgreSQL"; style.fill: "#d4edda" }
cache: { shape: queue; label: "Redis"; style.fill: "#fce8e6" }

internet -> frontend
frontend -> api: "HTTPS"
api -> services.auth: "JWT validate"
api -> services.orders
api -> services.payments
services.orders -> db
services.payments -> db
services.auth -> cache: "session"
フローチャート/プロセス
direction: down

start: { shape: circle; style.fill: "#4caf50"; style.font-color: white }
end_ok: { shape: circle; style.fill: "#4caf50"; style.font-color: white; label: "Done" }
end_err: { shape: circle; style.fill: "#f44336"; style.font-color: white; label: "Failed" }
validate: { shape: diamond; label: "Valid?" }
process: "Process Request"
notify: "Send Notification"
error: "Return Error"

start -> process
process -> validate
validate -> notify: "Yes"
validate -> error: "No"
notify -> end_ok
error -> end_err
シーケンス図
auth_flow: {
  shape: sequence_diagram

  # Declare actors in display order
  client
  gateway
  auth
  db

  client -> gateway: "POST /login"
  gateway -> auth: "validate(credentials)"
  auth -> db: "SELECT user WHERE email=?"
  db -> auth: "user record"

  # Note on a specific actor (no connections = annotation)
  auth."checks bcrypt hash"

  auth -> gateway: "JWT token"
  gateway -> client: "200 OK + token"

  # Group / fragment
  error_case: {
    gateway -> client: "401 Unauthorized"
  }
}

シーケンス図の主なルール:

  • アクターは最初に参照された時点で自動的に作成されます。順序を制御するには、明示的に宣言してください
  • 図の中に接続のない単独の図形は、注記/注釈になります
  • グループ(名前付きの入れ子ブロック)は UML のフラグメントボックスを作成します
ER 図(SQL テーブル)
users: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  email: varchar(255) {constraint: [unique; not_null]}
  name: varchar(100)
  org_id: uuid {constraint: foreign_key}
  created_at: timestamptz
}

organizations: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  name: varchar(255) {constraint: not_null}
}

posts: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  author_id: uuid {constraint: foreign_key}
  title: varchar(255)
  body: text
}

# FK connections — connect column to column
users.org_id -> organizations.id
posts.author_id -> users.id

SQL テーブルに関する注記:

  • stroke はテーブル本体のスタイルを設定し、fill はヘッダー行のスタイルを設定します
  • 制約:primary_key、foreign_key、unique、not_null
  • 複数の制約:{constraint: [primary_key; not_null]}
UML クラス図
UserService: {
  shape: class

  # Fields: visibility + name: type
  # Quote the key if params contain ":", quote the value if it contains "[]"
  -db: Database
  "-users": "User[]"
  "#cache": Cache

  # Methods: visibility + name(params): return
  +getUser(): User
  "+createUser(data: UserInput)": User
  "-validateEmail(email: string)": bool
}

User: {
  shape: class
  +id: string
  +email: string
  +name: string
  +createdAt: Date
}

# Relationships as connections with labels
UserService -> User: uses
UserRepo -> User: manages

可視性:+ パブリック、- プライベート、# 保護

引用符のルール:

  • フィールド型に [] が含まれる場合は、値を引用符で囲みます:"-users": "User[]"
  • メソッドのパラメーターに : が含まれる場合は、キーを引用符で囲みます:"+method(id: string)": ReturnType
C4 アーキテクチャ

C4 図ではテーマ 303(C4)を使用してください。コンテナーに標準的な C4 の見た目を適用できます。

# Render with: theme_id=303
direction: right

vars: {
  d2-config: {
    theme-id: 303
  }
}

# Actors
user: {
  shape: c4-person
  label: "Customer"
  style.fill: "#08427b"
  style.font-color: white
}

# Systems
web_app: {
  label: "Web Application\n[React SPA]"
  style.fill: "#1168bd"
  style.font-color: white
}

api: {
  label: "API Server\n[Node.js / Express]"
  style.fill: "#1168bd"
  style.font-color: white
}

db: {
  shape: cylinder
  label: "Database\n[PostgreSQL]"
  style.fill: "#1168bd"
  style.font-color: white
}

external_payment: {
  label: "Payment Gateway\n[Stripe]"
  style.fill: "#999999"
  style.font-color: white
}

user -> web_app: "Uses [HTTPS]"
web_app -> api: "API calls [JSON/HTTPS]"
api -> db: "Reads/writes [SQL]"
api -> external_payment: "Charges card [HTTPS]"
ステートマシン
direction: right

# States
idle: { shape: rectangle; label: "Idle" }
loading: { shape: rectangle; label: "Loading"; style.fill: "#fff3cd" }
success: { shape: rectangle; label: "Success"; style.fill: "#d4edda" }
error: { shape: rectangle; label: "Error"; style.fill: "#f8d7da" }

# Terminal states with double-border
success: { style.double-border: true }

# Transitions
idle -> loading: "fetch()"
loading -> success: "onSuccess"
loading -> error: "onError"
error -> idle: "reset()"
success -> idle: "reset()"
グリッドダッシュボード
dashboard: {
  label: "System Health"
  grid-rows: 2
  grid-columns: 3
  grid-gap: 16

  cpu: { label: "CPU\n42%" }
  memory: { label: "Memory\n71%" }
  disk: { label: "Disk\n28%" }
  latency: { label: "p99 Latency\n180ms"; style.fill: "#fff3cd" }
  errors: { label: "Error Rate\n0.2%"; style.fill: "#d4edda" }
  uptime: { label: "Uptime\n99.97%"; style.fill: "#d4edda" }
}
アニメーション付きマルチステップ図

steps を使うと、図を段階的に構成できます。animate_interval を指定してレンダリングすると、アニメーション SVG を生成できます。

steps: {
  s1: {
    user: "User"
  }
  s2: {
    user: "User"
    web: "Web Server"
    user -> web: "request"
  }
  s3: {
    user: "User"
    web: "Web Server"
    db: "Database"
    user -> web: "request"
    web -> db: "query"
  }
  s4: {
    user: "User"
    web: "Web Server"
    db: "Database"
    cache: "Redis"
    user -> web: "request"
    web -> db: "query"
    web -> cache: "cache hit"
  }
}

レンダリング:d2_render(d2_code=..., animate_interval=1500, target="*")

各ステップは前のステップを引き継ぎます。ベース図のバリエーションには scenarios を、互いに独立したビューには layers を使用します。


テーマ

用途に応じたおすすめ
用途おすすめのテーマID
技術ドキュメント、一般用途Neutral Default0
C4 アーキテクチャ図C4303
ダークモードのドキュメントDark Mauve200
鮮やか/カラフルFlagship Terrastruct3
紙/ホワイトボード風Origami302
ターミナル/等幅フォント風Terminal300
アクセシビリティ対応/色覚多様性に配慮Colorblind Clear8
プレゼンテーション(高コントラスト)Neutral Default または Flagship0 または 3
図ごとのライト/ダークモード

D2 では、1 つの SVG 内でライトモードとダークモードのブラウザー表示に別々のテーマを設定できます。

d2_render(d2_code=..., theme_id=0, dark_theme_id=200)

ブラウザーは prefers-color-scheme に基づいて自動的に切り替わります。ドキュメントサイトに SVG を埋め込む場合に使用してください。

テーマ一覧
ID名前特徴
0Neutral Defaultすっきりとしたプロフェッショナルなデザイン(デフォルトに最適)
1Neutral Grey控えめなモノクローム
3Flagship Terrastruct鮮やかでカラフル
4Cool Classicsブルーとグリーン
5Mixed Berry Blueパープルとブルー
6Grape Sodaパープルが主体
7Aubergine深みのあるパープル系
8Colorblind Clearアクセシブルなパレット
100Vanilla Nitro Cola温かみのあるニュートラルカラー
101Orange Creamsicleオレンジのアクセント
102Shirley Templeピンクとレッド
103Earth Tonesブラウンとタンカラー
104Everglade Green森林のグリーン
105Buttered Toast温かみのあるイエロー
200Dark Mauveダークモード
201Dark Flagship Terrastructカラフルなダークモード
300Terminal等幅フォント、ドット塗りのコンテナ
301Terminal Grayscaleターミナルスタイル、グレースケール
302Origami紙のような美しさ
303C4C4 アーキテクチャ図のスタイル

レイアウト

エンジン使用する場合備考
dagre常に — デフォルト高速で、ネストやコンテナをまたぐ接続を適切に処理します
elkユーザーが明示的に要求した場合WASM では非常に遅く(数分かかることがあります)、自分で選択しないでください。

デフォルトのルール:layout-engine は設定しないでください。 Dagre がデフォルトです。ELK はユーザーから要求された場合にのみ設定してください。

方向の制御:

direction: right    # top-level: up, down, left, right

# Per-container direction (ELK only — do not use unless user requests ELK)
container: {
  direction: right
  a -> b -> c
}

構成:レイヤー、シナリオ、ステップ

# Layers: independent views (no inheritance between layers)
layers: {
  overview: {
    web -> app -> db
  }
  detailed: {
    web: "Nginx" { shape: rectangle }
    web -> app: "HTTP/1.1"
    app -> db: "PostgreSQL wire protocol"
  }
}

# Scenarios: variations on a base diagram (inherit from root)
web -> app -> db

scenarios: {
  with_cache: {
    app -> cache: "read-through"
  }
  with_cdn: {
    cdn -> web
  }
}

# Steps: sequential, each step inherits the previous (use for animated storytelling)
steps: {
  s1: { user }
  s2: { user -> web }
  s3: { user -> web -> app }
  s4: { user -> web -> app -> db }
}

レイヤー/シナリオ/ステップをアニメーション表示するには、d2_render(d2_code=..., animate_interval=1500, target="*") を使用します。 1 つのボードをレンダリングするには、target="layers.production" を指定します。ボードとその子要素をレンダリングするには、target="layers.production.*" を指定します。


アイコン

# Icon from URL — Terrastruct's free icon library
server: {
  icon: https://icons.terrastruct.com/tech/server.svg
}

# Control icon position
server: {
  icon: https://icons.terrastruct.com/tech/server.svg
  icon.near: top-left    # top-left, top-center, top-right, center-left, center-right, bottom-*
}

# Standalone image shape
github: {
  shape: image
  icon: https://icons.terrastruct.com/social/github.svg
}

無料のアイコン:https://icons.terrastruct.com — AWS、GCP、Azure、開発ツール、テクノロジーのロゴが含まれています。


ツールチップとリンク

server: {
  tooltip: "Handles all API requests. SLA: 99.9%"
  link: https://docs.example.com/server
}

server -> db: {
  tooltip: "Uses PgBouncer connection pooling"
}

ツールチップとリンクは SVG に埋め込まれ、ブラウザーで開くと機能します。ツールチップのない図形でもツールチップの付録を必ずレンダリングするには、レンダリングオプションに forceAppendix: true を追加してください(現時点では d2_render ツールでは公開されていません。ファイル内の設定を使用するか、省略してください)。


グリッドレイアウト

dashboard: {
  grid-rows: 2
  grid-columns: 3
  grid-gap: 20           # gap between all cells
  vertical-gap: 10       # fine-tune vertical spacing
  horizontal-gap: 15     # fine-tune horizontal spacing

  widget_a: "Revenue"
  widget_b: "Users"
  widget_c: "Orders"
  widget_d: "Latency"
  widget_e: "Errors"
  widget_f: "Uptime"
}
  • 図形はセルに左から右、上から下の順に配置されます
  • グリッド項目間の接続も通常どおりレンダリングされます
  • グリッドコンテナで width/height を指定するには、ELK レイアウトが必要です

インポート

# Spread file contents into current scope
...@shared_styles.d2

# Assign file to a key
network: @network_diagram.d2

# Import specific object from file
db_schema: @schema.users

レンダリング済み SVG の保存

次の順番で保存します。まずソースを書き、その後に SVG を保存してください。

ステップ 1 — D2 ソースをすぐに書き込みます(レンダリング不要で、すぐに実行できます): Write ツールを使って、D2 コードを diagrams/<stem>.d2 に書き込みます。

ステップ 2 — 会話内のレンダリング結果の SVG を再利用します: すでに skip_fonts=true(デフォルト)でレンダリングした SVG が、保存に適した出力です。これを diagrams/<stem>.svg に書き込みます。2 回目のレンダリングは不要です。

フォントの埋め込み: skip_fonts=true はデフォルトであり、保存ファイルにも適しています。実際のところ、システムフォントは Source Sans Pro と見分けがつきません。ユーザーが埋め込みフォントを明示的に希望した場合に限り、skip_fonts=false でレンダリングしてください。その場合、ファイルサイズが約 500KB 増加し、処理にかなり時間がかかることを伝えてください。

ファイル名の規則:

  • ディレクトリ:プロジェクトのルートを基準とする diagrams/(ない場合は作成)
  • ファイル名の幹:YYYY-MM-DD_HH-MM_<slug> — ローカル時刻、24 時間表記、2~4 語の slug
  • 例:2025-06-01_14-32_auth-flow-sequence、2025-06-01_09-05_aws-three-tier

保存したら、ファイルのパスをユーザーに伝えてください。SVG はどのブラウザーでも開くことができ、ツールチップ、リンク、アニメーションを含め、完全なインタラクティブ機能を備えています。

HTML への埋め込み: <?xml?> 宣言を省略するには、no_xml_tag=true を追加します。


D2 の強み(Mermaid との比較)

D2 には Mermaid ではできない機能があります。適切な場面で活用してください。

  • コンテナーをまたぐ接続 — 異なるコンテナー内の図形を、親スコープを表す _ を使って接続します:aws.db -> _.gcloud.replica
  • アニメーション付き接続 — style.animated: true を設定すると、SVG 内の矢印が流れるように動きます(データフローの表示に最適です)
  • 複数ボードのアニメーション付き SVG — steps/scenarios/layers と animate_interval を組み合わせると、状態を切り替える 1 つの SVG が生成されます
  • ライトモード/ダークモードへの標準対応 — d2_render(theme_id=0, dark_theme_id=200) — ブラウザーが自動的に切り替えます
  • 変数によるブランドテーマ設定 — ブランドカラーを vars で一度定義し、全体で ${primary} を参照します
  • 再利用可能なスタイルクラス — .class のスタイルを一度定義し、CSS クラスのように複数の図形に適用します
  • グリッドレイアウト — D2 のみでダッシュボード形式のグリッドを配置できます
  • アイコンライブラリ — icons.terrastruct.com から SVG アイコンを直接図形に取り込めます
  • ツールチップの付録 — JavaScript を使わずに、SVG 内にリンクを含むホバーツールチップを埋め込めます

品質ガイドライン

  • まず構造を整え、スタイルは最後に追加します — 色を考える前に、図形と接続を適切に配置します
  • 図を見やすく保ちます — ノードは 40 個未満を目安とし、複雑なシステムは複数の図に分割します
  • 1 つの概念につき 1 つの図を作成します — 同じシステムのアーキテクチャ図とシーケンス図を別々に作るほうが、両方を 1 つの図で表そうとするより有用です
  • 平面的なグラフよりコンテナーを優先します — D2 の入れ子構造は強みです。関連するコンポーネントのグループ化に活用します
  • 接続に style.animated: true を使って、活発なデータフローを示します — 色だけで示すより、情報が伝わりやすくなります
  • ユーザーと一緒に反復します — レンダリングして見せ、「意図した内容が表現されていますか?」と確認し、調整します
  • 構文に自信がない場合は、d2_render の前に d2_validate を使います — 行と列を指定した具体的なエラーが返されます

よくある間違い

構造プレビューには d2_render(ascii=true) を使用しないでください: D2 の ASCII レンダラー(v0.7.1 で追加)には既知のバグがあります。コンテナー間の接続がある状態で direction: right を指定すると出力が乱れ、逆向きの矢印(返信、応答)は direction: down を指定しても経路が絡まります。Terrastruct は、このアプローチにはアーキテクチャ上の欠陥があることを認めており、現在書き直しが進められています。

代わりに d2_inspect を使用してください。レンダリングを行わず、コンパイル済みの図オブジェクトから信頼性の高いテキスト要約を生成します。

接続を繰り返しても統合されません:

A -> B: "label 1"
A -> B: "label 2"   # creates a SECOND distinct arrow, not an update

既存の接続を参照するには、(A -> B)[0].label: "label 1" を使用してください。

_ はルートではなく、親スコープです:

outer: {
  inner: {
    x -> _.y    # _ refers to outer, not root
  }
  y
}

クラスメソッドのパラメーターを引用符で囲む:

# WRONG — colon inside key breaks parsing
+createUser(data: UserInput): User

# CORRECT — quote the key when params contain ":"
"+createUser(data: UserInput)": User

WASM での ELK は非常に遅いです: ユーザーから明示的に求められない限り、vars.d2-config で layout-engine: elk を設定したり、d2_render に layout: "elk" を渡したりしないでください。レンダリングごとに数分かかる場合があります。

コンテナーの width/height には ELK が必要です: grid-rows/grid-columns は dagre で動作しますが、コンテナーに明示的に指定した width/height が反映されるのは ELK レイアウトのみです。

接続ではラベルではなくキーを使用します:

server: "API Server"   # label is "API Server", key is "server"
server -> db            # correct — uses the key
"API Server" -> db      # WRONG — this creates a new shape named "API Server"

会話内ではデフォルトで skip_fonts=true を使用します: 会話内で表示するためにレンダリングする場合は、必ず skip_fonts=true を渡してください。最終的な SVG をディスクに保存するときに限り、省略します(つまり、skip_fonts=false を使用します)。skip_fonts=true を指定せずにレンダリングするたびに、約 500KB の base64 フォントデータがコンテキストに追加されます。

コメント