From ce40826d516fe927185aefd00c234951bd527429 Mon Sep 17 00:00:00 2001 From: Alexander Wang Date: Wed, 29 Jan 2025 16:25:30 -0700 Subject: [PATCH] ensure unique diagram hash based on appearance --- d2lib/d2.go | 9 ++++ docs/examples/lib/1-d2lib/d2lib_test.go | 56 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/d2lib/d2.go b/d2lib/d2.go index a50e1a226..39613caec 100644 --- a/d2lib/d2.go +++ b/d2lib/d2.go @@ -77,6 +77,15 @@ func Compile(ctx context.Context, input string, compileOpts *CompileOptions, ren d, err := compile(ctx, g, compileOpts, renderOpts) if d != nil { + if config == nil { + config = &d2target.Config{} + } + // These are fields that affect a diagram's appearance, so feed them back + // into diagram.Config to ensure the hash computed for CSS styling purposes + // is unique to its appearance + config.ThemeID = renderOpts.ThemeID + config.DarkThemeID = renderOpts.DarkThemeID + config.Sketch = renderOpts.Sketch d.Config = config } return d, g, err diff --git a/docs/examples/lib/1-d2lib/d2lib_test.go b/docs/examples/lib/1-d2lib/d2lib_test.go index 53b3d5bcc..30a1b923e 100644 --- a/docs/examples/lib/1-d2lib/d2lib_test.go +++ b/docs/examples/lib/1-d2lib/d2lib_test.go @@ -1,9 +1,65 @@ package main import ( + "context" "testing" + + "oss.terrastruct.com/d2/d2graph" + "oss.terrastruct.com/d2/d2layouts/d2dagrelayout" + "oss.terrastruct.com/d2/d2lib" + "oss.terrastruct.com/d2/d2renderers/d2svg" + "oss.terrastruct.com/d2/d2themes/d2themescatalog" + "oss.terrastruct.com/d2/lib/log" + "oss.terrastruct.com/d2/lib/textmeasure" + "oss.terrastruct.com/util-go/assert" + "oss.terrastruct.com/util-go/go2" ) func TestMain_(t *testing.T) { main() } + +func TestConfigHash(t *testing.T) { + var hash1, hash2 string + var err error + + { + ruler, _ := textmeasure.NewRuler() + layoutResolver := func(engine string) (d2graph.LayoutGraph, error) { + return d2dagrelayout.DefaultLayout, nil + } + renderOpts := &d2svg.RenderOpts{ + Pad: go2.Pointer(int64(5)), + ThemeID: &d2themescatalog.GrapeSoda.ID, + } + compileOpts := &d2lib.CompileOptions{ + LayoutResolver: layoutResolver, + Ruler: ruler, + } + ctx := log.WithDefault(context.Background()) + diagram, _, _ := d2lib.Compile(ctx, "x -> y", compileOpts, renderOpts) + hash1, err = diagram.HashID() + assert.Success(t, err) + } + + { + ruler, _ := textmeasure.NewRuler() + layoutResolver := func(engine string) (d2graph.LayoutGraph, error) { + return d2dagrelayout.DefaultLayout, nil + } + renderOpts := &d2svg.RenderOpts{ + Pad: go2.Pointer(int64(5)), + ThemeID: &d2themescatalog.NeutralGrey.ID, + } + compileOpts := &d2lib.CompileOptions{ + LayoutResolver: layoutResolver, + Ruler: ruler, + } + ctx := log.WithDefault(context.Background()) + diagram, _, _ := d2lib.Compile(ctx, "x -> y", compileOpts, renderOpts) + hash2, err = diagram.HashID() + assert.Success(t, err) + } + + assert.NotEqual(t, hash1, hash2) +}