Merge pull request #1 from x-delfino/wasm-options-extended

Wasm options extended
This commit is contained in:
delfino 2025-02-14 22:53:30 +00:00 committed by GitHub
commit b81f10c39c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 279 additions and 151 deletions

View file

@ -2,6 +2,6 @@
#### Improvements 🧹
d2js: Support additional render options (`themeID`, `darkThemeID`, `center`, `pad`, `scale` and `forceAppendix`) [#2343](https://github.com/terrastruct/d2/pull/2343)
d2js: Support additional render options (`themeID`, `darkThemeID`, `center`, `pad`, `scale` and `forceAppendix`). Support `d2-config`. [#2343](https://github.com/terrastruct/d2/pull/2343)
#### Bugfixes ⛑️

View file

@ -154,6 +154,26 @@ func GetELKGraph(args []js.Value) (interface{}, error) {
return elk, nil
}
func layoutResolver() func(engine string) (d2graph.LayoutGraph, error) {
cached := make(map[string]d2graph.LayoutGraph)
return func(engine string) (d2graph.LayoutGraph, error) {
if c, ok := cached[engine]; ok {
return c, nil
}
var layout d2graph.LayoutGraph
switch engine {
case "dagre":
layout = d2dagrelayout.DefaultLayout
case "elk":
layout = d2elklayout.DefaultLayout
default:
return nil, &WASMError{Message: fmt.Sprintf("layout option '%s' not recognized", engine), Code: 400}
}
cached[engine] = layout
return layout, nil
}
}
func Compile(args []js.Value) (interface{}, error) {
if len(args) < 1 {
return nil, &WASMError{Message: "missing JSON argument", Code: 400}
@ -171,35 +191,29 @@ func Compile(args []js.Value) (interface{}, error) {
return nil, &WASMError{Message: "missing 'index' file in input fs", Code: 400}
}
fs, err := memfs.New(input.FS)
compileOpts := &d2lib.CompileOptions{
UTF16Pos: true,
LayoutResolver: layoutResolver(),
}
var err error
compileOpts.FS, err = memfs.New(input.FS)
if err != nil {
return nil, &WASMError{Message: fmt.Sprintf("invalid fs input: %s", err.Error()), Code: 400}
}
ruler, err := textmeasure.NewRuler()
compileOpts.Ruler, err = textmeasure.NewRuler()
if err != nil {
return nil, &WASMError{Message: fmt.Sprintf("text ruler cannot be initialized: %s", err.Error()), Code: 500}
}
ctx := log.WithDefault(context.Background())
layoutFunc := d2dagrelayout.DefaultLayout
if input.Opts != nil && input.Opts.Layout != nil {
switch *input.Opts.Layout {
case "dagre":
layoutFunc = d2dagrelayout.DefaultLayout
case "elk":
layoutFunc = d2elklayout.DefaultLayout
default:
return nil, &WASMError{Message: fmt.Sprintf("layout option '%s' not recognized", *input.Opts.Layout), Code: 400}
}
}
layoutResolver := func(engine string) (d2graph.LayoutGraph, error) {
return layoutFunc, nil
compileOpts.Layout = input.Opts.Layout
}
renderOpts := &d2svg.RenderOpts{}
var fontFamily *d2fonts.FontFamily
if input.Opts != nil && input.Opts.Sketch != nil && *input.Opts.Sketch {
fontFamily = go2.Pointer(d2fonts.HandDrawn)
compileOpts.FontFamily = go2.Pointer(d2fonts.HandDrawn)
renderOpts.Sketch = input.Opts.Sketch
}
if input.Opts != nil && input.Opts.Pad != nil {
@ -217,13 +231,9 @@ func Compile(args []js.Value) (interface{}, error) {
if input.Opts != nil && input.Opts.Scale != nil {
renderOpts.Scale = input.Opts.Scale
}
diagram, g, err := d2lib.Compile(ctx, input.FS["index"], &d2lib.CompileOptions{
UTF16Pos: true,
FS: fs,
Ruler: ruler,
LayoutResolver: layoutResolver,
FontFamily: fontFamily,
}, renderOpts)
ctx := log.WithDefault(context.Background())
diagram, g, err := d2lib.Compile(ctx, input.FS["index"], compileOpts, renderOpts)
if err != nil {
if pe, ok := err.(*d2parser.ParseError); ok {
errs, _ := json.Marshal(pe.Errors)
@ -238,6 +248,15 @@ func Compile(args []js.Value) (interface{}, error) {
FS: input.FS,
Diagram: *diagram,
Graph: *g,
Options: RenderOptions{
ThemeID: renderOpts.ThemeID,
DarkThemeID: renderOpts.DarkThemeID,
Sketch: renderOpts.Sketch,
Pad: renderOpts.Pad,
Center: renderOpts.Center,
Scale: renderOpts.Scale,
ForceAppendix: input.Opts.ForceAppendix,
},
}, nil
}

View file

@ -33,11 +33,10 @@ type BoardPositionResponse struct {
type CompileRequest struct {
FS map[string]string `json:"fs"`
Opts *RenderOptions `json:"options"`
Opts *CompileOptions `json:"options"`
}
type RenderOptions struct {
Layout *string `json:"layout"`
Pad *int64 `json:"pad"`
Sketch *bool `json:"sketch"`
Center *bool `json:"center"`
@ -47,10 +46,16 @@ type RenderOptions struct {
ForceAppendix *bool `json:"forceAppendix"`
}
type CompileOptions struct {
RenderOptions
Layout *string `json:"layout"`
}
type CompileResponse struct {
FS map[string]string `json:"fs"`
Diagram d2target.Diagram `json:"diagram"`
Graph d2graph.Graph `json:"graph"`
Options RenderOptions `json:"options"`
}
type CompletionResponse struct {

View file

@ -42,19 +42,44 @@ import { D2 } from '@terrastruct/d2';
const d2 = new D2();
const result = await d2.compile('x -> y');
const svg = await d2.render(result.diagram);
const svg = await d2.render(result.diagram, result.options);
```
Additional Configuration:
```javascript
import { D2 } from '@terrastruct/d2';
const d2 = new D2();
const result = await d2.compile('x -> y', {
sketch = true,
});
const svg = await d2.render(result.diagram, result.options);
```
## API Reference
### `new D2()`
Creates a new D2 instance.
### `compile(input: string, options?: CompileOptions): Promise<CompileResult>`
Compiles D2 markup into an intermediate representation.
Options:
### `render(diagram: Diagram, options?: RenderOptions): Promise<string>`
Renders a compiled diagram to SVG.
### `CompileOptions`
All `RenderOptions` properties in addition to:
- `layout`: Layout engine to use ('dagre' | 'elk') [default: 'dagre']
### `RenderOptions`
- `sketch`: Enable sketch mode [default: false]
- `themeID`: Theme ID to use [default: 0]
- `darkThemeID`: Theme ID to use when client is in dark mode
@ -63,8 +88,12 @@ Options:
- `scale`: Scale the output. E.g., 0.5 to halve the default size. The default will render SVG's that will fit to screen. Setting to 1 turns off SVG fitting to screen.
- `forceAppendix`: Adds an appendix for tooltips and links [default: false]
### `render(diagram: Diagram, options?: RenderOptions): Promise<string>`
Renders a compiled diagram to SVG.
### `CompileResult`
- `diagram`: `Diagram`: Compiled D2 diagram
- `options`: `RenderOptions`: Render options merged with configuration set in diagram
- `fs`
- `graph`
## Development

View file

@ -10,12 +10,14 @@
margin: 0;
font-family: system-ui, -apple-system, sans-serif;
}
.controls {
display: flex;
flex-direction: column;
gap: 12px;
width: 400px;
}
textarea {
width: 100%;
height: 300px;
@ -24,6 +26,7 @@
border-radius: 4px;
font-family: monospace;
}
.options-group {
display: flex;
flex-direction: column;
@ -32,34 +35,31 @@
border: 1px solid #eee;
border-radius: 4px;
}
.layout-toggle,
.sketch-toggle,
.center-toggle,
.appendix-toggle,
.theme-select,
.dark-theme-select,
.padding-input,
.scale-input {
.option:not(:has(.option-toggle-box:checked)) .option-select {
opacity: 0.5;
pointer-events: none;
}
.option {
display: flex;
gap: 16px;
align-items: center;
}
.radio-group {
display: flex;
gap: 12px;
}
.input-label,
.select-label,
.radio-label,
.checkbox-label {
.checkbox-label,
.select-label {
display: flex;
gap: 4px;
align-items: center;
cursor: pointer;
}
.number-input {
width: 3rem;
}
button {
padding: 8px 16px;
background: #0066cc;
@ -68,9 +68,11 @@
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #0052a3;
}
#output {
flex: 1;
overflow: auto;
@ -78,51 +80,107 @@
border-radius: 4px;
padding: 16px;
}
#output svg {
max-width: 100%;
max-height: 90vh;
}
</style>
</head>
<body>
<div class="controls">
<textarea id="input">x -> y</textarea>
<div class="options-group">
<div class="layout-toggle">
<span>Layout:</span>
<div class="radio-group">
<label class="radio-label">
<input type="radio" name="layout" value="dagre" checked />
Dagre
</label>
<label class="radio-label">
<input type="radio" name="layout" value="elk" />
ELK
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="layout-toggle" class="option-toggle-box" />
<span>Layout</span>
</label>
</div>
<div class="option-select">
<div class="radio-group">
<label class="radio-label">
<input type="radio" name="layout-select" value="dagre" checked />
Dagre
</label>
<label class="radio-label">
<input type="radio" name="layout-select" value="elk" />
ELK
</label>
</div>
</div>
</div>
<div class="sketch-toggle">
<label class="checkbox-label">
<input type="checkbox" id="sketch" />
Sketch mode
</label>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="sketch-toggle" class="option-toggle-box" />
<span>Sketch Mode</span>
</label>
</div>
<div class="option-select">
<div class="radio-group">
<label class="radio-label">
<input type="radio" name="sketch-select" value="true" checked />
Enabled
</label>
<label class="radio-label">
<input type="radio" name="sketch-select" value="false" />
Disabled
</label>
</div>
</div>
</div>
<div class="center-toggle">
<label class="checkbox-label">
<input type="checkbox" id="center" />
Centered
</label>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="center-toggle" class="option-toggle-box" />
<span>Centered</span>
</label>
</div>
<div class="option-select">
<div class="radio-group">
<label class="radio-label">
<input type="radio" name="center-select" value="true" checked />
Enabled
</label>
<label class="radio-label">
<input type="radio" name="center-select" value="false" />
Disabled
</label>
</div>
</div>
</div>
<div class="appendix-toggle">
<label class="checkbox-label">
<input type="checkbox" id="appendix" />
Force Appendix
</label>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="appendix-toggle" class="option-toggle-box" />
<span>Force Appendix</span>
</label>
</div>
<div class="option-select">
<div class="radio-group">
<label class="radio-label">
<input type="radio" name="appendix-select" value="true" checked />
Enabled
</label>
<label class="radio-label">
<input type="radio" name="appendix-select" value="false" />
Disabled
</label>
</div>
</div>
</div>
<div class="theme-select">
<label class="select-label">
<select id="theme" name="theme">
<option value="-1"></option>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="theme-toggle" class="option-toggle-box" />
<span>Theme</span>
</label>
</div>
<div class="option-select">
<select id="theme-select">
<option selected value="0">Default</option>
<option value="1">Neutral grey</option>
<option value="3">Flagship Terrastruct</option>
@ -141,14 +199,18 @@
<option value="300">Terminal</option>
<option value="301">Terminal grayscale</option>
</select>
Theme ID
</label>
</div>
</div>
<div class="dark-theme-select">
<label class="select-label">
<select id="dark-theme" name="dark-theme">
<option value="-1"></option>
<option value="0">Default</option>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="dark-theme-toggle" class="option-toggle-box" />
<span>Dark Theme</span>
</label>
</div>
<div class="option-select">
<select id="dark-theme-select">
<option selected value="0">Default</option>
<option value="1">Neutral grey</option>
<option value="3">Flagship Terrastruct</option>
<option value="4">Cool classics</option>
@ -166,20 +228,46 @@
<option value="300">Terminal</option>
<option value="301">Terminal grayscale</option>
</select>
Dark Theme ID
</label>
</div>
</div>
<div class="padding-input">
<label class="input-label">
<input type="number" id="padding" value="20" step="10" class="number-input" />
Padding
</label>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="pad-toggle" class="option-toggle-box" />
<span>Padding</span>
</label>
</div>
<div class="option-select">
<label class="input-label">
<input
type="number"
id="pad-input"
value="20"
step="10"
class="number-input"
/>
</label>
</div>
</div>
<div class="scale-input">
<label class="input-label">
<input type="number" id="scale" value="-1" step="1" class="number-input" />
Scale
</label>
<div class="option">
<div class="option-toggle">
<label class="checkbox-label">
<input type="checkbox" id="scale-toggle" class="option-toggle-box" />
<span>Scale</span>
</label>
</div>
<div class="option-select">
<label class="input-label">
<input
type="number"
id="scale-input"
value="1"
step="0.1"
min="0"
class="number-input"
/>
</label>
</div>
</div>
</div>
<button onclick="compile()">Compile</button>
@ -189,26 +277,34 @@
import { D2 } from "../dist/browser/index.js";
const d2 = new D2();
window.compile = async () => {
const notNegative = (value) => {
if (value < 0) {
return null;
} else return value;
};
const input = document.getElementById("input").value;
const layout = document.querySelector('input[name="layout"]:checked').value;
const sketch = document.getElementById("sketch").checked;
const center = document.getElementById("center").checked;
const themeSelector = document.getElementById("theme");
const themeId = notNegative(
Number(themeSelector.options[themeSelector.selectedIndex].value)
);
const darkThemeSelector = document.getElementById("dark-theme");
const darkThemeId = notNegative(
Number(darkThemeSelector.options[darkThemeSelector.selectedIndex].value)
);
const scale = notNegative(Number(document.getElementById("scale").value));
const pad = Number(document.getElementById("padding").value);
const forceAppendix = document.getElementById("appendix").checked;
const layout = document.getElementById("layout-toggle").checked
? document.querySelector('input[name="layout-select"]:checked').value
: null;
const sketch = document.getElementById("sketch-toggle").checked
? document.querySelector('input[name="sketch-select"]:checked').value == "true"
: null;
const center = document.getElementById("center-toggle").checked
? document.querySelector('input[name="center-select"]:checked').value == "true"
: null;
const forceAppendix = document.getElementById("appendix-toggle").checked
? document.querySelector('input[name="appendix-select"]:checked').value ==
"true"
: null;
const themeSelector = document.getElementById("theme-select");
const themeId = document.getElementById("theme-toggle").checked
? Number(themeSelector.options[themeSelector.selectedIndex].value)
: null;
const darkThemeSelector = document.getElementById("dark-theme-select");
const darkThemeId = document.getElementById("dark-theme-toggle").checked
? Number(darkThemeSelector.options[darkThemeSelector.selectedIndex].value)
: null;
const pad = document.getElementById("pad-toggle").checked
? Number(document.getElementById("pad-input").value)
: null;
const scale = document.getElementById("scale-toggle").checked
? Number(document.getElementById("scale-input").value)
: null;
try {
const result = await d2.compile(input, {
layout,
@ -220,15 +316,7 @@
center,
forceAppendix,
});
const svg = await d2.render(result.diagram, {
sketch,
themeId,
darkThemeId,
scale,
pad,
center,
forceAppendix,
});
const svg = await d2.render(result.diagram, result.options);
document.getElementById("output").innerHTML = svg;
} catch (err) {
console.error(err);

View file

@ -1,10 +1,5 @@
import { createWorker, loadFile } from "./platform.js";
const DEFAULT_OPTIONS = {
layout: "dagre",
sketch: false,
};
export class D2 {
constructor() {
this.ready = this.init();
@ -86,17 +81,15 @@ export class D2 {
}
async compile(input, options = {}) {
const opts = { ...DEFAULT_OPTIONS, ...options };
const request =
typeof input === "string"
? { fs: { index: input }, options: opts }
: { ...input, options: { ...opts, ...input.options } };
? { fs: { index: input }, options }
: { ...input, options: { ...options, ...input.options } };
return this.sendMessage("compile", request);
}
async render(diagram, options = {}) {
const opts = { ...DEFAULT_OPTIONS, ...options };
return this.sendMessage("render", { diagram, options: opts });
return this.sendMessage("render", { diagram, options });
}
async encode(script) {

View file

@ -1 +1 @@
export * from "./platform.node.js";
export * from "./platform.node.js";

View file

@ -30,12 +30,10 @@ export function setupMessageHandler(isNode, port, initWasm) {
// single-threaded WASM call cannot complete without giving control back
// So we compute it, store it here, then during elk layout, instead
// of computing again, we use this variable (and unset it for next call)
if (data.options.layout === "elk") {
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
const elkGraph2 = JSON.parse(elkGraph).data;
const layout = await elk.layout(elkGraph2);
globalThis.elkResult = layout;
}
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
const elkGraph2 = JSON.parse(elkGraph).data;
const layout = await elk.layout(elkGraph2);
globalThis.elkResult = layout;
const result = await d2.compile(JSON.stringify(data));
const response = JSON.parse(result);

View file

@ -27,12 +27,10 @@ export function setupMessageHandler(isNode, port, initWasm) {
case "compile":
try {
if (data.options.layout === "elk") {
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
const elkGraph2 = JSON.parse(elkGraph).data;
const layout = await elk.layout(elkGraph2);
globalThis.elkResult = layout;
}
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
const elkGraph2 = JSON.parse(elkGraph).data;
const layout = await elk.layout(elkGraph2);
globalThis.elkResult = layout;
const result = await d2.compile(JSON.stringify(data));
const response = JSON.parse(result);
if (response.error) throw new Error(response.error.message);

View file

@ -27,12 +27,10 @@ export function setupMessageHandler(isNode, port, initWasm) {
case "compile":
try {
if (data.options.layout === "elk") {
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
const elkGraph2 = JSON.parse(elkGraph).data;
const layout = await elk.layout(elkGraph2);
globalThis.elkResult = layout;
}
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
const elkGraph2 = JSON.parse(elkGraph).data;
const layout = await elk.layout(elkGraph2);
globalThis.elkResult = layout;
const result = await d2.compile(JSON.stringify(data));
const response = JSON.parse(result);
if (response.error) throw new Error(response.error.message);