d2/d2plugin/plugin_dagre.go

99 lines
2.1 KiB
Go
Raw Normal View History

2022-12-03 18:54:54 +00:00
//go:build !nodagre
package d2plugin
import (
"context"
2022-12-30 08:09:28 +00:00
"encoding/json"
2022-12-30 21:19:48 +00:00
"fmt"
2023-03-07 19:45:36 +00:00
"sync"
"oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/d2layouts/d2dagrelayout"
2022-12-30 05:09:53 +00:00
"oss.terrastruct.com/util-go/xmain"
)
var DagrePlugin = dagrePlugin{}
func init() {
2022-12-30 05:09:53 +00:00
plugins = append(plugins, &DagrePlugin)
}
2022-12-30 05:09:53 +00:00
type dagrePlugin struct {
2023-03-07 19:45:36 +00:00
mu sync.Mutex
2022-12-30 20:40:52 +00:00
opts *d2dagrelayout.ConfigurableOpts
2022-12-30 05:09:53 +00:00
}
2023-03-07 19:45:36 +00:00
func (p *dagrePlugin) Flags(context.Context) ([]PluginSpecificFlag, error) {
2022-12-30 08:09:28 +00:00
return []PluginSpecificFlag{
{
Name: "dagre-nodesep",
Type: "int64",
Default: int64(d2dagrelayout.DefaultOpts.NodeSep),
Usage: "number of pixels that separate nodes horizontally.",
Tag: "nodesep",
},
{
Name: "dagre-edgesep",
Type: "int64",
Default: int64(d2dagrelayout.DefaultOpts.EdgeSep),
Usage: "number of pixels that separate edges horizontally.",
Tag: "edgesep",
},
2022-12-30 19:33:32 +00:00
}, nil
2022-12-30 08:09:28 +00:00
}
func (p *dagrePlugin) HydrateOpts(opts []byte) error {
2023-03-07 19:45:36 +00:00
p.mu.Lock()
defer p.mu.Unlock()
2022-12-30 05:09:53 +00:00
if opts != nil {
2022-12-30 20:40:52 +00:00
var dagreOpts d2dagrelayout.ConfigurableOpts
2022-12-30 08:09:28 +00:00
err := json.Unmarshal(opts, &dagreOpts)
if err != nil {
2022-12-30 05:09:53 +00:00
return xmain.UsageErrorf("non-dagre layout options given for dagre")
}
p.opts = &dagreOpts
}
return nil
}
2023-03-07 19:45:36 +00:00
func (p *dagrePlugin) Info(ctx context.Context) (*PluginInfo, error) {
p.mu.Lock()
defer p.mu.Unlock()
2023-10-31 22:52:48 +00:00
opts := xmain.NewOpts(nil, nil)
2022-12-30 21:19:48 +00:00
flags, err := p.Flags(ctx)
if err != nil {
return nil, err
}
for _, f := range flags {
f.AddToOpts(opts)
}
return &PluginInfo{
Name: "dagre",
Type: "bundled",
2023-02-20 17:21:48 +00:00
Features: []PluginFeature{},
ShortHelp: "The directed graph layout library Dagre",
2022-12-30 21:19:48 +00:00
LongHelp: fmt.Sprintf(`dagre is a directed graph layout library for JavaScript.
2023-02-05 08:41:00 +00:00
See https://d2lang.com/tour/dagre for more.
2023-02-05 08:41:00 +00:00
Flags correspond to ones found at https://github.com/dagrejs/dagre/wiki.
2022-12-30 21:19:48 +00:00
Flags:
%s
`, opts.Defaults()),
}, nil
}
2023-03-07 19:45:36 +00:00
func (p *dagrePlugin) Layout(ctx context.Context, g *d2graph.Graph) error {
p.mu.Lock()
optsCopy := *p.opts
p.mu.Unlock()
return d2dagrelayout.Layout(ctx, g, &optsCopy)
}
2023-03-07 19:45:36 +00:00
func (p *dagrePlugin) PostProcess(ctx context.Context, in []byte) ([]byte, error) {
return in, nil
}