├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── d2lang-cs.sln
├── docs
└── assets
│ └── img
│ ├── banner.png
│ ├── d2_logo.png
│ └── diagram.png
├── example
└── cli
│ ├── Program.cs
│ └── d2-sample-cli.csproj
├── src
├── D2Connection.cs
├── D2Diagram.cs
├── D2Shape.cs
├── D2Style.cs
├── D2Text.cs
├── Direction.cs
├── Shape.cs
├── Utils.cs
└── d2lang-cs.csproj
└── test
├── Tests.csproj
├── UnitTests.cs
└── Usings.cs
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: Stephanvs
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13 | custom: https://www.buymeacoffee.com/stephanvs
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
400 | .DS_Store
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Stephan van Stekelenburg
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # d2lang-cs
2 |
3 | 
4 |
5 | An unofficial interface for building [D2](https://github.com/terrastruct/d2) diagram files in C# and dotnet.
6 |
7 | # Installation
8 |
9 | ```bash
10 | dotnet add package d2lang-cs
11 | ```
12 |
13 | # Usage
14 |
15 | ```csharp
16 | using d2;
17 |
18 | var umbrella = new D2Shape("alphabet", "Alphabet Inc", Shape.Rectangle);
19 | var company = new D2Shape("google", null, Shape.Rectangle);
20 |
21 | company.Add(new D2Shape("gmail", "Gmail", Shape.Rectangle));
22 | company.Add(new D2Shape("meet", "Meet", Shape.Rectangle));
23 | company.Add(new D2Shape("deepmind", "DeepMind", Shape.Rectangle));
24 |
25 | company.Icon = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png";
26 |
27 | var connection = new D2Connection(company.Name, umbrella.Name, Direction.TO, "BELONGS_TO");
28 |
29 | var diagram = new D2Diagram(new[] { umbrella, company }, new[] { connection });
30 |
31 | Console.WriteLine(diagram.ToString());
32 | ```
33 |
34 | # D2 Output
35 | ```d2-lang
36 | alphabet: Alphabet Inc {
37 | shape: rectangle
38 | }
39 | google: {
40 | gmail: Gmail {
41 | shape: rectangle
42 | }
43 | meet: Meet {
44 | shape: rectangle
45 | }
46 | deepmind: DeepMind {
47 | shape: rectangle
48 | }
49 | icon: https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png
50 | shape: rectangle
51 | }
52 | google -> alphabet: BELONGS_TO
53 | ```
54 |
55 | # Diagram Output
56 | 
57 |
58 | # Documentation
59 | ## Supported
60 | - [x] Shapes (nodes)
61 | - [x] Connections (edges)
62 | - [x] Styles
63 | - [x] Containers (nodes/links in nodes)
64 | - [x] Arrow directions
65 | - [x] Markdown / latex / block strings / code in shapes
66 | - [x] Shape icons
67 | - [ ] SQL table shapes
68 | - [ ] Class shapes
69 | - [ ] Comments
70 |
71 | # Inspiration & Thanks
72 | - [Kreshnik/d2lang-js](https://github.com/Kreshnik/d2lang-js)
73 | - [MrBlenny/py-d2](https://github.com/MrBlenny/py-d2)
74 |
75 | # Thank me!
76 | If you like what I'm doing and you would like to thank me, please consider:
77 |
78 |
79 |
80 |
81 |
82 | Thank you for your support!
83 |
84 |
85 |
86 | Copyright © 2023 [Stephan van Stekelenburg](https://stephanvs.com) - Provided under [MIT License](LICENSE)
87 |
--------------------------------------------------------------------------------
/d2lang-cs.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.5.002.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "d2lang-cs", "src\d2lang-cs.csproj", "{BB0ABCF8-5B09-438A-9FCE-9CD3D70E4CBB}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "example", "example", "{5C588B55-FBDC-4C2F-B65F-14BB31282E33}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "d2-sample-cli", "example\cli\d2-sample-cli.csproj", "{327CF66B-11FC-460F-A018-F0A602482A03}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "test\Tests.csproj", "{BC01588F-4480-4AF0-A1C2-364A983E9F58}"
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {BB0ABCF8-5B09-438A-9FCE-9CD3D70E4CBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {BB0ABCF8-5B09-438A-9FCE-9CD3D70E4CBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {BB0ABCF8-5B09-438A-9FCE-9CD3D70E4CBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {BB0ABCF8-5B09-438A-9FCE-9CD3D70E4CBB}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {327CF66B-11FC-460F-A018-F0A602482A03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
25 | {327CF66B-11FC-460F-A018-F0A602482A03}.Debug|Any CPU.Build.0 = Debug|Any CPU
26 | {327CF66B-11FC-460F-A018-F0A602482A03}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {327CF66B-11FC-460F-A018-F0A602482A03}.Release|Any CPU.Build.0 = Release|Any CPU
28 | {BC01588F-4480-4AF0-A1C2-364A983E9F58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29 | {BC01588F-4480-4AF0-A1C2-364A983E9F58}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 | {BC01588F-4480-4AF0-A1C2-364A983E9F58}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {BC01588F-4480-4AF0-A1C2-364A983E9F58}.Release|Any CPU.Build.0 = Release|Any CPU
32 | EndGlobalSection
33 | GlobalSection(SolutionProperties) = preSolution
34 | HideSolutionNode = FALSE
35 | EndGlobalSection
36 | GlobalSection(ExtensibilityGlobals) = postSolution
37 | SolutionGuid = {10D35D6E-F298-4AA0-AC44-FEFFF3CA9EEB}
38 | EndGlobalSection
39 | GlobalSection(NestedProjects) = preSolution
40 | {327CF66B-11FC-460F-A018-F0A602482A03} = {5C588B55-FBDC-4C2F-B65F-14BB31282E33}
41 | EndGlobalSection
42 | EndGlobal
43 |
--------------------------------------------------------------------------------
/docs/assets/img/banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Stephanvs/d2lang-cs/664651a2f798a4abda0721eb795441ed24999887/docs/assets/img/banner.png
--------------------------------------------------------------------------------
/docs/assets/img/d2_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Stephanvs/d2lang-cs/664651a2f798a4abda0721eb795441ed24999887/docs/assets/img/d2_logo.png
--------------------------------------------------------------------------------
/docs/assets/img/diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Stephanvs/d2lang-cs/664651a2f798a4abda0721eb795441ed24999887/docs/assets/img/diagram.png
--------------------------------------------------------------------------------
/example/cli/Program.cs:
--------------------------------------------------------------------------------
1 | using d2;
2 |
3 | var umbrella = new D2Shape("alphabet", "Alphabet Inc", Shape.Rectangle);
4 | var company = new D2Shape("google", null, Shape.Rectangle);
5 |
6 | company.Add(new D2Shape("gmail", "Gmail", Shape.Rectangle));
7 | company.Add(new D2Shape("meet", "Meet", Shape.Rectangle));
8 | company.Add(new D2Shape("deepmind", "DeepMind", Shape.Rectangle));
9 |
10 | company.Icon = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png";
11 |
12 | var connection = new D2Connection(company.Name, umbrella.Name, Direction.TO, "BELONGS_TO");
13 |
14 | var diagram = new D2Diagram(new[] { umbrella, company }, new[] { connection });
15 |
16 | Console.WriteLine(diagram.ToString());
--------------------------------------------------------------------------------
/example/cli/d2-sample-cli.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | d2_sample_cli
7 | enable
8 | enable
9 | false
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/D2Connection.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public record class D2Connection(
4 | string First,
5 | string Second,
6 | Direction Direction,
7 | string? Label = ""
8 | )
9 | {
10 | internal IEnumerable Lines()
11 | {
12 | var @base = $"{First} {Direction} {Second}";
13 | if (!string.IsNullOrWhiteSpace(Label))
14 | {
15 | @base += $": {Label}";
16 | }
17 |
18 | return new List { @base };
19 | }
20 |
21 | public override string ToString()
22 | => string.Join(Environment.NewLine, Lines());
23 | }
--------------------------------------------------------------------------------
/src/D2Diagram.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public record class D2Diagram(
4 | IEnumerable Shapes,
5 | IEnumerable Connections
6 | )
7 | {
8 | public D2Diagram Add(D2Shape shape)
9 | => this with { Shapes = Shapes.Append(shape) };
10 | public D2Diagram Add(D2Connection connection)
11 | => this with { Connections = Connections.Append(connection) };
12 |
13 | internal IEnumerable Lines()
14 | {
15 | var shapes = Shapes.SelectMany(s => s.Lines()).ToList();
16 | var connections = Connections.SelectMany(c => c.Lines()).ToList();
17 |
18 | return shapes.Concat(connections);
19 | }
20 |
21 | public override string ToString()
22 | => string.Join(Environment.NewLine, Lines());
23 | }
--------------------------------------------------------------------------------
/src/D2Shape.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 |
3 | namespace d2;
4 |
5 | public record class D2Shape(
6 | string Name,
7 | string? Label,
8 | Shape? Shape = default,
9 | D2Style? Style = default,
10 | string? Near = default
11 | ) : IEnumerable, IEnumerable, IEnumerable
12 | {
13 | private readonly List _shapes = new();
14 | private readonly List _connections = new();
15 | private readonly List _texts = new();
16 |
17 | public string Icon { get; set; } = string.Empty;
18 |
19 | public void Add(D2Shape shape) => _shapes.Add(shape);
20 |
21 | public void Add(D2Connection connection) => _connections.Add(connection);
22 |
23 | public void Add(D2Text text) => _texts.Add(text);
24 |
25 | internal IEnumerable Lines()
26 | {
27 | var shapes = _shapes.SelectMany(s => s.Lines()).ToList();
28 | var connections = _connections.SelectMany(c => c.Lines()).ToList();
29 | var texts = _texts.SelectMany(t => t.Lines()).ToList();
30 |
31 | var properties = shapes.Concat(connections).Concat(texts).ToList();
32 |
33 | if (!string.IsNullOrWhiteSpace(Icon))
34 | {
35 | properties.Add($"icon: {Icon}");
36 | }
37 |
38 | if (Shape is not null)
39 | {
40 | properties.Add($"shape: {Shape}");
41 | }
42 |
43 | if (!string.IsNullOrEmpty(Near))
44 | {
45 | properties.Add($"near: {Near}");
46 | }
47 |
48 | if (Style is not null)
49 | {
50 | properties.AddRange(Style.Lines());
51 | }
52 |
53 | return Utils.AddLabelAndProperties(Name, Label, properties);
54 | }
55 |
56 | public override string ToString()
57 | => string.Join(Environment.NewLine, Lines());
58 |
59 | public IEnumerator GetEnumerator()
60 | => _shapes.GetEnumerator();
61 |
62 | IEnumerator IEnumerable.GetEnumerator()
63 | => GetEnumerator();
64 |
65 | IEnumerator IEnumerable.GetEnumerator()
66 | => _texts.GetEnumerator();
67 |
68 | IEnumerator IEnumerable.GetEnumerator()
69 | => _connections.GetEnumerator();
70 | }
71 |
--------------------------------------------------------------------------------
/src/D2Style.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public record class D2Style(
4 | string? Stroke,
5 | int? StrokeWidth,
6 | string? Fill,
7 | bool? Shadow,
8 | int? Opacity,
9 | int? StrokeDash,
10 | bool? ThreeD
11 | )
12 | {
13 | public IEnumerable Lines()
14 | {
15 | var styles = new List();
16 |
17 | if (Stroke is not null) styles.Add($"stroke: {Stroke}");
18 | if (StrokeWidth is not null) styles.Add($"stroke-width: {StrokeWidth}");
19 | if (Fill is not null) styles.Add($"fill: {Fill}");
20 | if (Shadow is not null) styles.Add($"shadow: {Utils.StringifyBoolean(Shadow)}");
21 | if (Opacity is not null) styles.Add($"opacity: {Opacity}");
22 | if (StrokeDash is not null) styles.Add($"stroke-dash: {StrokeDash}");
23 | if (ThreeD is not null) styles.Add($"3d: {Utils.StringifyBoolean(ThreeD)}");
24 |
25 | return styles.Count == 0
26 | ? new List()
27 | : Utils.AddLabelAndProperties("style", null, styles);
28 | }
29 |
30 | public override string ToString()
31 | => string.Join(Environment.NewLine, Lines());
32 | }
--------------------------------------------------------------------------------
/src/D2Text.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public record D2Text(
4 | string Property,
5 | string Text,
6 | string Format,
7 | int Pipes
8 | )
9 | {
10 | internal IEnumerable Lines()
11 | {
12 | var sep = "|".Repeat(Pipes);
13 |
14 | return new List()
15 | .Append($"{Property}:{sep}{Format}")
16 | .Concat(Text.Split(Environment.NewLine))
17 | .Append(sep);
18 | }
19 |
20 | public override string ToString()
21 | => string.Join(Environment.NewLine, Lines());
22 | }
--------------------------------------------------------------------------------
/src/Direction.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public abstract record Direction(string Value)
4 | {
5 | public readonly static To TO = new();
6 | public readonly static From FROM = new();
7 | public readonly static Both BOTH = new();
8 | public readonly static None NONE = new();
9 | public sealed override string ToString() => Value;
10 | }
11 |
12 | public sealed record To() : Direction("->");
13 | public sealed record From() : Direction("<-");
14 | public sealed record Both() : Direction("<->");
15 | public sealed record None() : Direction("--");
16 |
--------------------------------------------------------------------------------
/src/Shape.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public abstract record Shape(string Value)
4 | {
5 | public readonly static Rectangle Rectangle = new();
6 | public readonly static Square Square = new();
7 | public readonly static Page Page = new();
8 | public readonly static Parallelogram Parallelogram = new();
9 | public readonly static Document Document = new();
10 | public readonly static Cylinder Cylinder = new();
11 | public readonly static Queue Queue = new();
12 | public readonly static Package Package = new();
13 | public readonly static Step Step = new();
14 | public readonly static Callout Callout = new();
15 | public readonly static StoredData StoredData = new();
16 | public readonly static Person Person = new();
17 | public readonly static Diamond Diamond = new();
18 | public readonly static Oval Oval = new();
19 | public readonly static Circle Circle = new();
20 | public readonly static Hexagon Hexagon = new();
21 | public readonly static Cloud Cloud = new();
22 | public readonly static Text Text = new();
23 | public readonly static Code Code = new();
24 | public readonly static SqlTable SqlTable = new();
25 | public readonly static Image Image = new();
26 | public readonly static Class Class = new();
27 | public readonly static SequenceDiagram SequenceDiagram = new();
28 |
29 | public sealed override string ToString() => Value;
30 | }
31 |
32 | public sealed record Rectangle() : Shape("rectangle");
33 | public sealed record Square() : Shape("square");
34 | public sealed record Page() : Shape("page");
35 | public sealed record Parallelogram() : Shape("parallelogram");
36 | public sealed record Document() : Shape("document");
37 | public sealed record Cylinder() : Shape("cylinder");
38 | public sealed record Queue() : Shape("queue");
39 | public sealed record Package() : Shape("package");
40 | public sealed record Step() : Shape("step");
41 | public sealed record Callout() : Shape("callout");
42 | public sealed record StoredData() : Shape("stored_data");
43 | public sealed record Person() : Shape("person");
44 | public sealed record Diamond() : Shape("diamond");
45 | public sealed record Oval() : Shape("oval");
46 | public sealed record Circle() : Shape("circle");
47 | public sealed record Hexagon() : Shape("hexagon");
48 | public sealed record Cloud() : Shape("cloud");
49 | public sealed record Text() : Shape("text");
50 | public sealed record Code() : Shape("code");
51 | public sealed record SqlTable() : Shape("sql_table");
52 | public sealed record Image() : Shape("image");
53 | public sealed record Class() : Shape("class");
54 | public sealed record SequenceDiagram() : Shape("sequence_diagram");
55 |
--------------------------------------------------------------------------------
/src/Utils.cs:
--------------------------------------------------------------------------------
1 | namespace d2;
2 |
3 | public static class Utils
4 | {
5 | public static string StringifyBoolean(bool? value) => value switch
6 | {
7 | true => "true",
8 | _ => "false"
9 | };
10 |
11 | public static IEnumerable AddLabelAndProperties(
12 | string name,
13 | string? label,
14 | IEnumerable properties)
15 | {
16 | var hasProperties = properties?.Any() ?? false;
17 |
18 | string firstLine = name ?? string.Empty;
19 | if (label != null || hasProperties)
20 | {
21 | firstLine += ":";
22 | }
23 |
24 | if (label != null)
25 | {
26 | firstLine += $" {label}";
27 | }
28 |
29 | if (hasProperties)
30 | {
31 | firstLine += " {";
32 | }
33 |
34 | if (properties != null && hasProperties)
35 | {
36 | return new List { firstLine }
37 | .Concat(Indent(properties))
38 | .Append("}");
39 | }
40 |
41 | return new[] { firstLine };
42 | }
43 |
44 |
45 | public static IEnumerable Indent(IEnumerable items, int times = 2)
46 | {
47 | return items.Select(item => " ".Repeat(times) + item);
48 | }
49 |
50 | public static string Repeat(this string value, int times)
51 | {
52 | var result = string.Empty;
53 | for (var i = 0; i < times; i++)
54 | {
55 | result += value;
56 | }
57 | return result;
58 | }
59 | }
--------------------------------------------------------------------------------
/src/d2lang-cs.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | enable
7 | d2
8 | d2lang-cs
9 | 1.0.0
10 | Stephan van Stekelenburg
11 | https://github.com/Stephanvs/d2lang-cs.git
12 | https://github.com/Stephanvs/d2lang-cs
13 | D2;D2 Lang;Declarative Diagramming;Diagram;Text Diagram;Text to Diagram
14 | MIT
15 | D2 is A modern, open-source DSL designed specifically for software architecture diagrams.
16 | d2_logo.png
17 | README.md
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/test/Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | enable
7 |
8 | false
9 | true
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/test/UnitTests.cs:
--------------------------------------------------------------------------------
1 | namespace Tests;
2 |
3 | [TestClass]
4 | public class UnitTests
5 | {
6 | [TestMethod]
7 | public void TestDiagram()
8 | {
9 | var umbrella = new D2Shape("alphabet", "Alphabet Inc", Shape.Rectangle);
10 | var company = new D2Shape("google", "Google", Shape.Rectangle)
11 | {
12 | new D2Shape("gmail", "Gmail", Shape.Rectangle),
13 | new D2Shape("meet", "Meet", Shape.Rectangle),
14 | new D2Shape("deepmind", "DeepMind", Shape.Rectangle),
15 | };
16 |
17 | var connection = new D2Connection(company.Name, umbrella.Name, Direction.TO, "BELONGS_TO");
18 |
19 | var diagram = new D2Diagram(new[] { umbrella, company }, new[] { connection });
20 | var actual = diagram.ToString();
21 | var expected = @"alphabet: Alphabet Inc {
22 | shape: rectangle
23 | }
24 | google: Google {
25 | gmail: Gmail {
26 | shape: rectangle
27 | }
28 | meet: Meet {
29 | shape: rectangle
30 | }
31 | deepmind: DeepMind {
32 | shape: rectangle
33 | }
34 | shape: rectangle
35 | }
36 | google -> alphabet: BELONGS_TO";
37 |
38 | Assert.AreEqual(expected, actual);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/test/Usings.cs:
--------------------------------------------------------------------------------
1 | global using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | global using d2;
--------------------------------------------------------------------------------