Compare commits
1 commit
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b884dad7e |
2297 changed files with 124035 additions and 408428 deletions
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
|
|
@ -17,7 +17,7 @@ jobs:
|
|||
env:
|
||||
GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: d2chaos
|
||||
|
|
|
|||
36
.github/workflows/daily.yml
vendored
36
.github/workflows/daily.yml
vendored
|
|
@ -8,41 +8,7 @@ concurrency:
|
|||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
npm-nightly:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # Needed for git history and version tags
|
||||
|
||||
- name: Check for changes
|
||||
id: check_changes
|
||||
run: |
|
||||
if [ $(git rev-list --count --since="24 hours ago" HEAD) -gt 0 ]; then
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
echo "Found changes in the last 24 hours, proceeding to publish d2js nightly"
|
||||
else
|
||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||
echo "No changes in the last 24 hours, skipping d2js nightly publish"
|
||||
fi
|
||||
|
||||
- uses: actions/setup-go@v4
|
||||
if: steps.check_changes.outputs.has_changes == 'true'
|
||||
with:
|
||||
go-version-file: ./go.mod
|
||||
cache: true
|
||||
|
||||
- name: Publish nightly version to NPM
|
||||
if: steps.check_changes.outputs.has_changes == 'true'
|
||||
run: |
|
||||
export NPM_VERSION=nightly
|
||||
COLOR=1 ./make.sh js
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
ci:
|
||||
needs: [npm-nightly]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
|
@ -54,7 +20,7 @@ jobs:
|
|||
env:
|
||||
GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: d2chaos
|
||||
|
|
|
|||
|
|
@ -5,4 +5,3 @@ d2renderers/d2latex/polyfills.js
|
|||
d2renderers/d2latex/setup.js
|
||||
d2renderers/d2sketch/rough.js
|
||||
lib/png/generate_png.js
|
||||
d2js
|
||||
|
|
|
|||
5
Makefile
5
Makefile
|
|
@ -1,7 +1,7 @@
|
|||
.POSIX:
|
||||
|
||||
.PHONY: all
|
||||
all: fmt gen js lint build test
|
||||
all: fmt gen lint build test
|
||||
|
||||
.PHONY: fmt
|
||||
fmt:
|
||||
|
|
@ -21,6 +21,3 @@ test: fmt
|
|||
.PHONY: race
|
||||
race: fmt
|
||||
prefix "$@" ./ci/test.sh --race ./...
|
||||
.PHONY: js
|
||||
js: gen
|
||||
cd d2js/js && NPM_VERSION="${NPM_VERSION}" prefix "$@" ./make.sh all
|
||||
|
|
|
|||
21
README.md
21
README.md
|
|
@ -4,13 +4,11 @@
|
|||
A modern diagram scripting language that turns text to diagrams.
|
||||
</h2>
|
||||
|
||||
[Docs](https://d2lang.com) | [Cheat sheet](./docs/assets/cheat_sheet.pdf) | [Comparisons](https://text-to-diagram.com) | [Playground](https://play.d2lang.com) | [IDE](https://app.terrastruct.com)
|
||||
[Docs](https://d2lang.com) | [Cheat sheet](./docs/assets/cheat_sheet.pdf) | [Comparisons](https://text-to-diagram.com) | [Playground](https://play.d2lang.com)
|
||||
|
||||
[](https://github.com/terrastruct/d2/actions/workflows/ci.yml)
|
||||
[](https://github.com/terrastruct/d2/actions/workflows/daily.yml)
|
||||
[](https://github.com/terrastruct/d2/releases)
|
||||
[](./CHANGELOG.md)
|
||||
[](https://www.npmjs.com/package/@terrastruct/d2)
|
||||
[](https://discord.gg/NF6X8K4eDq)
|
||||
[](https://twitter.com/terrastruct)
|
||||
[](./LICENSE.txt)
|
||||
|
|
@ -18,9 +16,6 @@
|
|||
<a href="https://play.d2lang.com">
|
||||
<img src="./docs/assets/playground_button.png" alt="D2 Playground button" width="200" />
|
||||
</a>
|
||||
<a href="https://app.terrastruct.com">
|
||||
<img src="./docs/assets/studio_button.png" alt="D2 Studio button" width="200" />
|
||||
</a>
|
||||
|
||||
https://user-images.githubusercontent.com/3120367/206125010-bd1fea8e-248a-43e7-8f85-0bbfca0c6e2a.mp4
|
||||
|
||||
|
|
@ -243,7 +238,7 @@ let us know and we'll be happy to include it here!
|
|||
|
||||
### Community plugins
|
||||
|
||||
- **Tree-sitter grammar**: [https://github.com/ravsii/tree-sitter-d2](https://github.com/ravsii/tree-sitter-d2)
|
||||
- **Tree-sitter grammar**: [https://git.pleshevski.ru/pleshevskiy/tree-sitter-d2](https://git.pleshevski.ru/pleshevskiy/tree-sitter-d2)
|
||||
- **Emacs major mode**: [https://github.com/andorsk/d2-mode](https://github.com/andorsk/d2-mode)
|
||||
- **Goldmark extension**: [https://github.com/FurqanSoftware/goldmark-d2](https://github.com/FurqanSoftware/goldmark-d2)
|
||||
- **Telegram bot**: [https://github.com/meinside/telegram-d2-bot](https://github.com/meinside/telegram-d2-bot)
|
||||
|
|
@ -265,17 +260,11 @@ let us know and we'll be happy to include it here!
|
|||
- **Logseq-D2**: [https://github.com/b-yp/logseq-d2](https://github.com/b-yp/logseq-d2)
|
||||
- **ent2d2**: [https://github.com/tmc/ent2d2](https://github.com/tmc/ent2d2)
|
||||
- **MkDocs Plugin**: [https://github.com/landmaj/mkdocs-d2-plugin](https://github.com/landmaj/mkdocs-d2-plugin)
|
||||
- **Remark Plugin**: [https://github.com/mech-a/remark-d2](https://github.com/mech-a/remark-d2)
|
||||
- **VitePress Plugin**: [https://github.com/BadgerHobbs/vitepress-plugin-d2](https://github.com/BadgerHobbs/vitepress-plugin-d2)
|
||||
- **Zed extension**: [https://github.com/gabeidx/zed-d2](https://github.com/gabeidx/zed-d2)
|
||||
- **Hexo blog extension**: [https://github.com/leverimmy/hexo-d2](https://github.com/leverimmy/hexo-d2)
|
||||
- **Rehype Plugin**: [https://github.com/stereobooster/beoe/tree/main/packages/rehype-d2](https://github.com/stereobooster/beoe/tree/main/packages/rehype-d2)
|
||||
|
||||
### Misc
|
||||
|
||||
- **Comparison site**: [https://github.com/terrastruct/text-to-diagram-site](https://github.com/terrastruct/text-to-diagram-site)
|
||||
- **Playground**: [https://github.com/terrastruct/d2-playground](https://github.com/terrastruct/d2-playground)
|
||||
- **IDE (paid)**: [https://app.terrastruct.com](https://app.terrastruct.com)
|
||||
- **Language docs**: [https://github.com/terrastruct/d2-docs](https://github.com/terrastruct/d2-docs)
|
||||
- **Hosted icons**: [https://icons.terrastruct.com](https://icons.terrastruct.com)
|
||||
|
||||
|
|
@ -301,12 +290,6 @@ Do you have or see an open-source project with `.d2` files? Please submit a PR a
|
|||
this selected list of featured projects using D2.
|
||||
|
||||
- [ElasticSearch](https://github.com/elastic/beats/blob/main/libbeat/publisher/queue/proxy/diagrams/broker.d2)
|
||||
- [Sourcegraph](https://handbook.sourcegraph.com/departments/engineering/managed-services/telemetry-gateway/#dev-architecture-diagram)
|
||||
- [Temporal](https://github.com/temporalio/temporal/blob/0be2681c994470c7c61ea88e4fcef89bb4024e58/docs/_assets/matching-context.d2)
|
||||
- [Tauri](https://v2.tauri.app/concept/inter-process-communication/)
|
||||
- Rust GUI framework (78.5k stars)
|
||||
- [Intellij](https://github.com/JetBrains/intellij-community/blob/45bcfc17a3f3e0d8548bc69e922d4ca97ac21b2b/platform/settings/docs/topics/overview.md)
|
||||
- [Coder](https://coder.com/blog/managing-templates-in-coder)
|
||||
- [UC
|
||||
Berkeley](https://github.com/ucb-bar/hammer/blob/2b5c04d7b7d9ee3c73575efcd7ee0698bd5bfa88/doc/Hammer-Use/hier.d2)
|
||||
- [Coronacheck](https://github.com/minvws/nl-covid19-coronacheck-app-ios/blob/e1567e9d1633b3273c537a105bff0e7d3a57ecfe/Diagrams/client-side-datamodel.d2)
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
OUTPUT_FILE="main.wasm"
|
||||
SOURCE_PACKAGE="./d2js"
|
||||
|
||||
echo "Building WASM file..."
|
||||
GOOS=js GOARCH=wasm go build -ldflags='-s -w' -trimpath -o "$OUTPUT_FILE" "$SOURCE_PACKAGE"
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "Build successful."
|
||||
|
||||
if [ -f "$OUTPUT_FILE" ]; then
|
||||
FILE_SIZE_BYTES=$(stat -f%z "$OUTPUT_FILE")
|
||||
FILE_SIZE_MB=$(echo "scale=2; $FILE_SIZE_BYTES / 1024 / 1024" | bc)
|
||||
|
||||
echo "File size of $OUTPUT_FILE: $FILE_SIZE_MB MB"
|
||||
else
|
||||
echo "File $OUTPUT_FILE not found!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Deleting $OUTPUT_FILE..."
|
||||
rm "$OUTPUT_FILE"
|
||||
echo "File deleted."
|
||||
else
|
||||
echo "Build failed."
|
||||
exit 1
|
||||
fi
|
||||
|
|
@ -241,9 +241,8 @@ create_windows_amd64() {
|
|||
'Name=instance-state-name,Values=pending,running,stopping,stopped' "Name=tag:Name,Values=$REMOTE_NAME" \
|
||||
| jq -r '.Reservations[].Instances[].State.Name')
|
||||
if [ -z "$state" ]; then
|
||||
# public AMIs are deprecated every few months so just search the latest Windows Server one for recreating
|
||||
sh_c aws ec2 run-instances \
|
||||
--image-id=ami-03ea14ccbeab7b2d5 \
|
||||
--image-id=ami-0c5300e833c2b32f3 \
|
||||
--count=1 \
|
||||
--instance-type=t3.medium \
|
||||
--security-groups=windows \
|
||||
|
|
@ -442,22 +441,19 @@ init_remote_windows() {
|
|||
header "$REMOTE_NAME"
|
||||
wait_remote_host_windows
|
||||
|
||||
# rsync was broken in this script last ran on 4/10/24.
|
||||
# had to upgrade with `pacman -Syyu rsync` after
|
||||
|
||||
init_ps1=$(cat <<EOF
|
||||
\$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
# Bootstrap PowerShell v7
|
||||
if ((\$PSVersionTable.PSVersion).Major -eq 5) {
|
||||
Invoke-WebRequest -Uri https://www.nuget.org/api/v2/package/Microsoft.UI.Xaml/2.8.6 -OutFile .\microsoft.ui.xaml.2.8.6.zip
|
||||
Expand-Archive -Force .\microsoft.ui.xaml.2.8.6.zip
|
||||
Add-AppxPackage .\microsoft.ui.xaml.2.8.6\tools\AppX\x64\Release\Microsoft.UI.Xaml.2.8.appx
|
||||
Invoke-WebRequest -Uri https://www.nuget.org/api/v2/package/Microsoft.UI.Xaml/2.7.3 -OutFile .\microsoft.ui.xaml.2.7.3.zip
|
||||
Expand-Archive -Force .\microsoft.ui.xaml.2.7.3.zip
|
||||
Add-AppxPackage .\microsoft.ui.xaml.2.7.3\tools\AppX\x64\Release\Microsoft.UI.Xaml.2.7.appx
|
||||
|
||||
Invoke-WebRequest -Uri https://github.com/microsoft/winget-cli/releases/download/v1.7.10861/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle -OutFile .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle
|
||||
Invoke-WebRequest -Uri https://github.com/microsoft/winget-cli/releases/download/v1.7.10861/30fe89a9836a4cfbbd3fedce72a58680_License1.xml -OutFile .\30fe89a9836a4cfbbd3fedce72a58680_License1.xml
|
||||
Invoke-WebRequest -Uri https://github.com/microsoft/winget-cli/releases/download/v1.3.2691/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle -OutFile .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle
|
||||
Invoke-WebRequest -Uri https://github.com/microsoft/winget-cli/releases/download/v1.3.2691/7bcb1a0ab33340daa57fa5b81faec616_License1.xml -OutFile .\7bcb1a0ab33340daa57fa5b81faec616_License1.xml
|
||||
Invoke-WebRequest -Uri https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx -OutFile Microsoft.VCLibs.x64.14.00.Desktop.appx
|
||||
Add-AppxProvisionedPackage -online -PackagePath .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle -LicensePath .\30fe89a9836a4cfbbd3fedce72a58680_License1.xml -DependencyPackagePath Microsoft.VCLibs.x64.14.00.Desktop.appx
|
||||
Add-AppxProvisionedPackage -online -PackagePath .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle -LicensePath .\7bcb1a0ab33340daa57fa5b81faec616_License1.xml -DependencyPackagePath Microsoft.VCLibs.x64.14.00.Desktop.appx
|
||||
Add-AppxPackage .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle
|
||||
|
||||
winget install --silent --accept-package-agreements --accept-source-agreements Microsoft.DotNet.SDK.7
|
||||
|
|
@ -555,7 +551,6 @@ EOF
|
|||
)
|
||||
|
||||
# Windows and AWS SSM both defeated me.
|
||||
# alixander: Step 3's output got mangled for me, so had to replace the line with `printf '%s\n' "$gen_init_ps1" > script` and then open it with vim
|
||||
FGCOLOR=3 bigheader "WARNING: WINDOWS INITIALIZATION MUST BE COMPLETED MANUALLY OVER RDP AND POWERSHELL!"
|
||||
|
||||
warn '1. Obtain Windows RDP password with:'
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ cd -- "$(dirname "$0")/../.."
|
|||
|
||||
help() {
|
||||
cat <<EOF
|
||||
usage: $0 [--rebuild] [--dry-run] [--run=regex] [--host-only] [--lockfile-force]
|
||||
usage: $0 [--rebuild] [--local] [--dry-run] [--run=regex] [--host-only] [--lockfile-force]
|
||||
[--install] [--uninstall]
|
||||
|
||||
$0 builds D2 release archives into ./ci/release/build/<version>/d2-<VERSION>-<OS>-<ARCH>.tar.gz
|
||||
|
|
@ -24,6 +24,14 @@ Flags:
|
|||
By default build.sh will avoid rebuilding finished assets if they already exist but if you
|
||||
changed something and need to force rebuild, use this flag.
|
||||
|
||||
--local
|
||||
By default build.sh uses \$CI_D2_LINUX_AMD64, \$CI_D2_LINUX_ARM64,
|
||||
\$CI_D2_MACOS_AMD64 and \$CI_D2_MACOS_ARM64 to build the release
|
||||
archives. It's required for now due to the following issue:
|
||||
https://github.com/terrastruct/d2/issues/31
|
||||
With --local, build.sh will cross compile locally. warning: This is only for testing
|
||||
purposes, do not use in production!
|
||||
|
||||
--host-only
|
||||
Use to build the release archive for the host OS-ARCH only. All logging is done to stderr
|
||||
so in a script you can read from stdout to get the path to the release archive.
|
||||
|
|
@ -67,6 +75,10 @@ main() {
|
|||
flag_noarg && shift "$FLAGSHIFT"
|
||||
REBUILD=1
|
||||
;;
|
||||
local)
|
||||
flag_noarg && shift "$FLAGSHIFT"
|
||||
LOCAL=1
|
||||
;;
|
||||
dry-run)
|
||||
flag_noarg && shift "$FLAGSHIFT"
|
||||
DRY_RUN=1
|
||||
|
|
@ -78,6 +90,7 @@ main() {
|
|||
host-only)
|
||||
flag_noarg && shift "$FLAGSHIFT"
|
||||
HOST_ONLY=1
|
||||
LOCAL=1
|
||||
;;
|
||||
version)
|
||||
flag_nonemptyarg && shift "$FLAGSHIFT"
|
||||
|
|
@ -91,11 +104,13 @@ main() {
|
|||
flag_noarg && shift "$FLAGSHIFT"
|
||||
INSTALL=1
|
||||
HOST_ONLY=1
|
||||
LOCAL=1
|
||||
;;
|
||||
uninstall)
|
||||
flag_noarg && shift "$FLAGSHIFT"
|
||||
UNINSTALL=1
|
||||
HOST_ONLY=1
|
||||
LOCAL=1
|
||||
;;
|
||||
push-docker)
|
||||
flag_noarg && shift "$FLAGSHIFT"
|
||||
|
|
@ -155,8 +170,45 @@ build() {
|
|||
return 0
|
||||
fi
|
||||
|
||||
build_local
|
||||
return 0
|
||||
if [ -n "${LOCAL-}" ]; then
|
||||
build_local
|
||||
return 0
|
||||
fi
|
||||
|
||||
case $OS in
|
||||
macos)
|
||||
case $ARCH in
|
||||
amd64)
|
||||
REMOTE_HOST=$CI_D2_MACOS_AMD64 build_remote_macos
|
||||
;;
|
||||
arm64)
|
||||
REMOTE_HOST=$CI_D2_MACOS_ARM64 build_remote_macos
|
||||
;;
|
||||
*)
|
||||
warn "no builder for OS=$OS ARCH=$ARCH, building locally..."
|
||||
build_local
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
linux)
|
||||
case $ARCH in
|
||||
amd64)
|
||||
REMOTE_HOST=$CI_D2_LINUX_AMD64 build_remote_linux
|
||||
;;
|
||||
arm64)
|
||||
REMOTE_HOST=$CI_D2_LINUX_ARM64 build_remote_linux
|
||||
;;
|
||||
*)
|
||||
warn "no builder for OS=$OS ARCH=$ARCH, building locally..."
|
||||
build_local
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
warn "no builder for OS=$OS, building locally..."
|
||||
build_local
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
build_local() {
|
||||
|
|
@ -169,6 +221,39 @@ build_local() {
|
|||
sh_c ./ci/release/_build.sh
|
||||
}
|
||||
|
||||
build_remote_macos() {(
|
||||
sh_c lockfile_ssh "$REMOTE_HOST" .d2-build-lock
|
||||
sh_c gitsync "$REMOTE_HOST" src/d2
|
||||
sh_c ssh "$REMOTE_HOST" "COLOR=${COLOR-} \
|
||||
TERM=${TERM-} \
|
||||
DRY_RUN=${DRY_RUN-} \
|
||||
HW_BUILD_DIR=$HW_BUILD_DIR \
|
||||
VERSION=$VERSION \
|
||||
OS=$OS \
|
||||
ARCH=$ARCH \
|
||||
ARCHIVE=$ARCHIVE \
|
||||
PATH=\\\"/usr/local/bin:/usr/local/sbin:/opt/homebrew/bin:/opt/homebrew/sbin\\\${PATH+:\\\$PATH}\\\" \
|
||||
./src/d2/ci/release/_build.sh"
|
||||
sh_c mkdir -p "$HW_BUILD_DIR"
|
||||
sh_c rsync --archive --human-readable "$REMOTE_HOST:src/d2/$ARCHIVE" "$ARCHIVE"
|
||||
)}
|
||||
|
||||
build_remote_linux() {(
|
||||
sh_c lockfile_ssh "$REMOTE_HOST" .d2-build-lock
|
||||
sh_c gitsync "$REMOTE_HOST" src/d2
|
||||
sh_c ssh "$REMOTE_HOST" "COLOR=${COLOR-} \
|
||||
TERM=${TERM-} \
|
||||
DRY_RUN=${DRY_RUN-} \
|
||||
HW_BUILD_DIR=$HW_BUILD_DIR \
|
||||
VERSION=$VERSION \
|
||||
OS=$OS \
|
||||
ARCH=$ARCH \
|
||||
ARCHIVE=$ARCHIVE \
|
||||
./src/d2/ci/release/build_in_docker.sh"
|
||||
sh_c mkdir -p "$HW_BUILD_DIR"
|
||||
sh_c rsync --archive --human-readable "$REMOTE_HOST:src/d2/$ARCHIVE" "$ARCHIVE"
|
||||
)}
|
||||
|
||||
build_docker() {
|
||||
if [ -n "${LOCAL-}" ]; then
|
||||
sh_c ./ci/release/docker/build.sh \
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ cd -- "$(dirname "$0")/../.."
|
|||
. ./ci/sub/lib.sh
|
||||
|
||||
tag="$(sh_c docker build \
|
||||
--build-arg GOVERSION="1.23.6.linux-$ARCH" \
|
||||
--build-arg GOVERSION="1.20.8.linux-$ARCH" \
|
||||
-qf ./ci/release/linux/Dockerfile ./ci/release/linux)"
|
||||
docker_run \
|
||||
-e DRY_RUN \
|
||||
|
|
|
|||
|
|
@ -1,11 +1,19 @@
|
|||
#### Features 🚀
|
||||
|
||||
- `cross` arrowhead shape is available [#2190](https://github.com/terrastruct/d2/pull/2190)
|
||||
- `style.underline` works on connections [#1836](https://github.com/terrastruct/d2/pull/1836)
|
||||
- `none` is added as an accepted value for `fill-pattern`. Previously there was no way to cancel the `fill-pattern` on select objects set by a theme that applies it (Origami) [#1882](https://github.com/terrastruct/d2/pull/1882)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- Dimensions can be set less than label dimensions [#1900](https://github.com/terrastruct/d2/pull/1900)
|
||||
- Boards no longer inherit `label` fields from parents [#1838](https://github.com/terrastruct/d2/pull/1838)
|
||||
- Prevents `near` targeting a child of a special object like grid cells, which wasn't doing anything [#1851](https://github.com/terrastruct/d2/pull/1851)
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
---
|
||||
|
||||
For the latest d2.js changes, see separate [changelog](https://github.com/terrastruct/d2/blob/master/d2js/js/CHANGELOG.md).
|
||||
- Theme flags on CLI apply to PDFs [#1894](https://github.com/terrastruct/d2/pull/1894)
|
||||
- Fixes styles in connections not overriding styles set by globs [#1857](https://github.com/terrastruct/d2/pull/1857)
|
||||
- Fixes `null` being set on a nested shape not working in certain cases when connections also pointed to that shape [#1830](https://github.com/terrastruct/d2/pull/1830)
|
||||
- Fixes edge case of bad import syntax crashing using d2 as a library [#1829](https://github.com/terrastruct/d2/pull/1829)
|
||||
- Fixes `style.fill` not applying to markdown [#1872](https://github.com/terrastruct/d2/pull/1872)
|
||||
- Fixes compiler erroring on certain styles when the shape's `shape` value is not all lowercase (e.g. `Circle`) [#1887](https://github.com/terrastruct/d2/pull/1887)
|
||||
|
|
|
|||
|
|
@ -3,7 +3,3 @@
|
|||
#### Improvements 🧹
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
---
|
||||
|
||||
For the latest d2.js changes, see separate [changelog](https://github.com/terrastruct/d2/blob/master/d2js/js/CHANGELOG.md).
|
||||
|
|
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
#### Features 🚀
|
||||
|
||||
- `style.underline` works on connections [#1836](https://github.com/terrastruct/d2/pull/1836)
|
||||
- `none` is added as an accepted value for `fill-pattern`. Previously there was no way to cancel the `fill-pattern` on select objects set by a theme that applies it (Origami) [#1882](https://github.com/terrastruct/d2/pull/1882)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- Dimensions can be set less than label dimensions [#1901](https://github.com/terrastruct/d2/pull/1901)
|
||||
- Boards no longer inherit `label` fields from parents [#1838](https://github.com/terrastruct/d2/pull/1838)
|
||||
- Prevents `near` targeting a child of a special object like grid cells, which wasn't doing anything [#1851](https://github.com/terrastruct/d2/pull/1851)
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Theme flags on CLI apply to PDFs [#1894](https://github.com/terrastruct/d2/pull/1894)
|
||||
- Fixes styles in connections not overriding styles set by globs [#1857](https://github.com/terrastruct/d2/pull/1857)
|
||||
- Fixes `null` being set on a nested shape not working in certain cases when connections also pointed to that shape [#1830](https://github.com/terrastruct/d2/pull/1830)
|
||||
- Fixes edge case of bad import syntax crashing using d2 as a library [#1829](https://github.com/terrastruct/d2/pull/1829)
|
||||
- Fixes `style.fill` not applying to markdown [#1872](https://github.com/terrastruct/d2/pull/1872)
|
||||
- Fixes compiler erroring on certain styles when the shape's `shape` value is not all lowercase (e.g. `Circle`) [#1887](https://github.com/terrastruct/d2/pull/1887)
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
D2 0.6.5 has a hotfix for 0.6.4 breaking plugin compatibility. Also includes 2 compiler fixes regarding substitutions/vars.
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Fix executable plugins that implement standalone router [#1910](https://github.com/terrastruct/d2/pull/1910)
|
||||
- Fix compiler error with multiple nested spread substitutions [#1913](https://github.com/terrastruct/d2/pull/1913)
|
||||
- Fix substitutions from imports into different scopes [#1914](https://github.com/terrastruct/d2/pull/1914)
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
#### Features 🚀
|
||||
|
||||
- Glob inverse filters are implemented (e.g. `*: {!&shape: circle; style.fill: red}` to turn all non-circles red) [#2008](https://github.com/terrastruct/d2/pull/2008)
|
||||
- Globs can be used in glob filter values, including checking for existence (e.g. `*: {&link: *; style.fill: red}` to turn all objects with a link red) [#2009](https://github.com/terrastruct/d2/pull/2009)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- Opacity 0 shapes no longer have a label mask which made any segment of connections going through them lower opacity [#1940](https://github.com/terrastruct/d2/pull/1940)
|
||||
- Bidirectional connections are now animated in opposite directions rather than one direction [#1939](https://github.com/terrastruct/d2/pull/1939)
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Local relative icons are relative to the d2 file instead of CLI invoke path [#1924](https://github.com/terrastruct/d2/pull/1924)
|
||||
- Custom label positions weren't being read when the width was smaller than the label [#1928](https://github.com/terrastruct/d2/pull/1928)
|
||||
- Using `shape: circle` for arrowheads no longer removes all arrowheads along path in sketch mode [#1942](https://github.com/terrastruct/d2/pull/1942)
|
||||
- Globs to null connections work [#1965](https://github.com/terrastruct/d2/pull/1965)
|
||||
- Edge globs setting styles inherit correctly in child boards [#1967](https://github.com/terrastruct/d2/pull/1967)
|
||||
- Board links imported with spread imports work [#1972](https://github.com/terrastruct/d2/pull/1972)
|
||||
- Fix importing a file with nested boards [#1998](https://github.com/terrastruct/d2/pull/1998)
|
||||
- Fix importing a file with underscores in links [#1999](https://github.com/terrastruct/d2/pull/1999)
|
||||
- Replace a panic with an error message resulting from invalid `link` usage [#2011](https://github.com/terrastruct/d2/pull/2011)
|
||||
- Fix globs not applying to scenarios on keys that were applied in earlier scenarios [#2021](https://github.com/terrastruct/d2/pull/2021)
|
||||
- Fix edge case of invalid SVG from code blocks [#2031](https://github.com/terrastruct/d2/pull/2031)
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
#### Features 🚀
|
||||
|
||||
- Vars: Variable definitions can refer to other variables in the current scope [#2052](https://github.com/terrastruct/d2/pull/2052)
|
||||
- Composition: Imported boards can use underscores to reference boards beyond its own scope (e.g. to a sibling board at the scope its imported to) [#2075](https://github.com/terrastruct/d2/pull/2075)
|
||||
- Autoformat: Reserved keywords are formatted to be lowercase [#2098](https://github.com/terrastruct/d2/pull/2098)
|
||||
- Misc: support for characters in the Latin-1 and geometric shapes unicode range [#2100](https://github.com/terrastruct/d2/pull/2100)
|
||||
- Imports: can now import from absolute file paths [#2113](https://github.com/terrastruct/d2/pull/2113)
|
||||
- Render: linear and radial gradients are now available for `fill`, `stroke` and `font-color` [#2120](https://github.com/terrastruct/d2/pull/2120)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- Sequence diagram: edge groups account for edge label heights [#2038](https://github.com/terrastruct/d2/pull/2038)
|
||||
- Sequence diagram: self-referential edges account for edge label heights [#2040](https://github.com/terrastruct/d2/pull/2040)
|
||||
- Sequence diagram: The spacing between self-referential edges and regular edges is uniform [#2043](https://github.com/terrastruct/d2/pull/2043)
|
||||
- Compiler: Error on multi-line labels in `sql_table` shapes [#2057](https://github.com/terrastruct/d2/pull/2057)
|
||||
- Sequence diagram: Image shape actors can use spans and notes [#2056](https://github.com/terrastruct/d2/issues/2056)
|
||||
- Globs: Filters work with default values (e.g. `&opacity: 1` will capture everything without opacity explicitly set) [#2090](https://github.com/terrastruct/d2/pull/2090)
|
||||
- Render: connection label fills have a bit of padding and border-radius for better aesthetics [#2094](https://github.com/terrastruct/d2/pull/2094)
|
||||
- Sequence diagram: the padding between message labels and message endpoints are slightly increased [#2096](https://github.com/terrastruct/d2/pull/2096)
|
||||
- Render: code syntax highlighter dependency upgrade caused some slight subtle color changes in code snippets [#2119](https://github.com/terrastruct/d2/pull/2119)
|
||||
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Sequence diagram: multi-line edge labels no longer can collide with other elements [#2049](https://github.com/terrastruct/d2/pull/2049)
|
||||
- Sequence diagram: long self-referential edge labels no longer can collide neighboring actors (or its own) lifeline edges [#2050](https://github.com/terrastruct/d2/pull/2050)
|
||||
- Sequence diagram: fixes layout when sequence diagrams are in children boards (e.g. a layer) [#1692](https://github.com/terrastruct/d2/issues/1692)
|
||||
- Globs: An edge case was fixed where globs used in edges were creating nodes when it shouldn't have [#2051](https://github.com/terrastruct/d2/pull/2051)
|
||||
- Render: Multi-line class labels/headers are rendered correctly [#2057](https://github.com/terrastruct/d2/pull/2057)
|
||||
- CLI: Watch mode uses correct backlinks (`_` usages) [#2058](https://github.com/terrastruct/d2/pull/2058)
|
||||
- Vars: Spread variables are inserted in place instead of appending to end of scope [#2062](https://github.com/terrastruct/d2/pull/2062)
|
||||
- Imports: fix local icon imports from files that are imported [#2066](https://github.com/terrastruct/d2/pull/2066)
|
||||
- CLI: fixes edge case of watch mode links to nested board that had more nested boards not working [#2070](https://github.com/terrastruct/d2/pull/2070)
|
||||
- CLI: fixes theme flag not being passed to GIF outputs [#2071](https://github.com/terrastruct/d2/pull/2071)
|
||||
- CLI: fixes scale flag not being passed to animated SVG outputs [#2071](https://github.com/terrastruct/d2/pull/2071)
|
||||
- CLI: pptx exports use theme flags correctly [#2099](https://github.com/terrastruct/d2/pull/2099)
|
||||
- Imports: importing files with url links is fixed [#2105](https://github.com/terrastruct/d2/pull/2105)
|
||||
- Composition: linking to invalid boards no longer produces an invalid link [#2118](https://github.com/terrastruct/d2/pull/2118)
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
#### Features 🚀
|
||||
|
||||
- Render: SVG files render in non-browser contexts (e.g. Inkscape, LaTeX) [#2147](https://github.com/terrastruct/d2/pull/2147)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- Lib: removes a dependency on external slog that was causing troubles with installation [#2137](https://github.com/terrastruct/d2/pull/2137)
|
||||
- CLI: attempts writing to path atomically, falling back to non-atomic if failed [#2141](https://github.com/terrastruct/d2/pull/2141)
|
||||
- Export: pptx has "created at" metadata removed, so successive runs yield the same result [#2169](https://github.com/terrastruct/d2/pull/2160)
|
||||
- Formatter: empty board keywords (e.g. `layers`) are removed [#2178](https://github.com/terrastruct/d2/pull/2178)
|
||||
- Render: a tooltip or link by itself will not expand width of shape [#2183](https://github.com/terrastruct/d2/pull/2183)
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Render: fixes edge case of a 3d shape with outside label being cut off [#2132](https://github.com/terrastruct/d2/pull/2132)
|
||||
- Composition: labels for boards set with shorthand `x: y` was not applied [#2182](https://github.com/terrastruct/d2/pull/2182)
|
||||
- Globs: double globs (`**`) were erroring when used with multiple scenario boards [#2195](https://github.com/terrastruct/d2/pull/2195)
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
#### Features 🚀
|
||||
|
||||
- Animations: `style.animated: true` is supported on shapes [#2250](https://github.com/terrastruct/d2/pull/2250)
|
||||
- Connections now support `link` [#1955](https://github.com/terrastruct/d2/pull/1955)
|
||||
- Vars: vars in markdown blocks are substituted [#2218](https://github.com/terrastruct/d2/pull/2218)
|
||||
- Markdown: Github-flavored tables work in `md` blocks [#2221](https://github.com/terrastruct/d2/pull/2221)
|
||||
- Render: adds box arrowheads [#2227](https://github.com/terrastruct/d2/issues/2227)
|
||||
- `d2 fmt` now supports a `--check` flag [#2253](https://github.com/terrastruct/d2/pull/2253)
|
||||
- CLI: PNG output to stdout is supported using `--stdout-format png -` [#2291](https://github.com/terrastruct/d2/pull/2291)
|
||||
- Globs: `&connected` and `&leaf` filters are implemented [#2299](https://github.com/terrastruct/d2/pull/2299)
|
||||
- CLI: add --no-xml-tag for direct HTML embedding [#2302](https://github.com/terrastruct/d2/pull/2302)
|
||||
- CLI: `play` cmd added for opening d2 input in online playground [#2242](https://github.com/terrastruct/d2/pull/2242)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- Composition: links pointing to own board are purged [#2203](https://github.com/terrastruct/d2/pull/2203)
|
||||
- Syntax: reserved keywords must be unquoted [#2231](https://github.com/terrastruct/d2/pull/2231)
|
||||
- Latex: Backslashes in Latex blocks do not escape [#2232](https://github.com/terrastruct/d2/pull/2232)
|
||||
- This is a breaking change. Previously Latex blocks required escaping the backslash. So
|
||||
for older D2 versions, you should remove the excess backslashes.
|
||||
- Links: non-http url scheme links are supported (e.g. `x.link: vscode://file/`) [#2237](https://github.com/terrastruct/d2/issues/2237)
|
||||
- Compiler: reserved keywords with missing values error instead of silently doing nothing [#2251](https://github.com/terrastruct/d2/pull/2251)
|
||||
- Render: SVG outputs conform to stricter HTML standards, e.g. no duplicate ids [#2273](https://github.com/terrastruct/d2/issues/2273)
|
||||
- Themes: theme names are consistently cased [#2322](https://github.com/terrastruct/d2/pull/2322)
|
||||
- Nears: constant nears avoid collision with edge routes [#2327](https://github.com/terrastruct/d2/pull/2327)
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Imports: fixes using substitutions in `icon` values [#2207](https://github.com/terrastruct/d2/pull/2207)
|
||||
- Markdown: fixes ampersands in URLs in markdown [#2219](https://github.com/terrastruct/d2/pull/2219)
|
||||
- Globs: fixes edge case where globs with imported boards would create empty boards [#2247](https://github.com/terrastruct/d2/pull/2247)
|
||||
- Sequence diagrams: fixes alignment of notes when self messages are above it [#2264](https://github.com/terrastruct/d2/pull/2264)
|
||||
- Null: fixes `null`ing a connection with absolute syntax [#2318](https://github.com/terrastruct/d2/issues/2318)
|
||||
- Gradients: works with connection fills [#2326](https://github.com/terrastruct/d2/pull/2326)
|
||||
- Latex: fixes backslashes doubling on successive parses [#2328](https://github.com/terrastruct/d2/pull/2328)
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
#### Features 🚀
|
||||
|
||||
- Icons:
|
||||
- connections can include icons [#12](https://github.com/terrastruct/d2/issues/12)
|
||||
- Syntax:
|
||||
- `suspend`/`unsuspend` to define models and instantiate them [#2394](https://github.com/terrastruct/d2/pull/2394)
|
||||
- Globs:
|
||||
- support for filtering edges based on properties of endpoint nodes (e.g., `&src.style.fill: blue`) [#2395](https://github.com/terrastruct/d2/pull/2395)
|
||||
- `level` filter implemented [#2473](https://github.com/terrastruct/d2/pull/2473)
|
||||
- Render:
|
||||
- markdown, latex, and code can be used as object labels [#2204](https://github.com/terrastruct/d2/pull/2204)
|
||||
- `shape: c4-person` to render a person shape like what the C4 model prescribes [#2397](https://github.com/terrastruct/d2/pull/2397)
|
||||
- Icons:
|
||||
- border-radius should work on icon [#2409](https://github.com/terrastruct/d2/issues/2409)
|
||||
- Misc:
|
||||
- Diagram legends are implemented [#2416](https://github.com/terrastruct/d2/pull/2416)
|
||||
|
||||
#### Improvements 🧹
|
||||
|
||||
- CLI:
|
||||
- Support `validate` command. [#2415](https://github.com/terrastruct/d2/pull/2415)
|
||||
- Watch mode ignores backup files (e.g. files created by certain editors like Helix). [#2131](https://github.com/terrastruct/d2/issues/2131)
|
||||
- Support for `--omit-version` flag. [#2377](https://github.com/terrastruct/d2/issues/2377)
|
||||
- Casing is ignored for plugin names [#2486](https://github.com/terrastruct/d2/pull/2486)
|
||||
- Compiler:
|
||||
- `link`s can be set to root path, e.g. `/xyz`. [#2357](https://github.com/terrastruct/d2/issues/2357)
|
||||
- When importing a file, attempt resolving substitutions at the imported file scope first [#2482](https://github.com/terrastruct/d2/pull/2482)
|
||||
- validate gradient color stops. [#2492](https://github.com/terrastruct/d2/pull/2492)
|
||||
- Parser:
|
||||
- impose max key length. It's almost certainly a mistake if an ID gets too long, e.g. missing quotes [#2465](https://github.com/terrastruct/d2/pull/2465)
|
||||
- Render:
|
||||
- horizontal padding added for connection labels [#2461](https://github.com/terrastruct/d2/pull/2461)
|
||||
|
||||
#### Bugfixes ⛑️
|
||||
|
||||
- Compiler:
|
||||
- fixes panic when `sql_shape` shape value had mixed casing [#2349](https://github.com/terrastruct/d2/pull/2349)
|
||||
- fixes panic when importing from a file with spread substitutions in `vars` [#2427](https://github.com/terrastruct/d2/pull/2427)
|
||||
- fixes support for `center` in `d2-config` [#2360](https://github.com/terrastruct/d2/pull/2360)
|
||||
- fixes panic when comment lines appear in arrays [#2378](https://github.com/terrastruct/d2/pull/2378)
|
||||
- fixes inconsistencies when objects were double quoted [#2390](https://github.com/terrastruct/d2/pull/2390)
|
||||
- fixes globs not applying to spread substitutions [#2426](https://github.com/terrastruct/d2/issues/2426)
|
||||
- fixes panic when classes were mixed with layers incorrectly [#2448](https://github.com/terrastruct/d2/pull/2448)
|
||||
- fixes panic when gradient colors are used in sketch mode [#2481](https://github.com/terrastruct/d2/pull/2487)
|
||||
- fixes panic using glob ampersand filters with composite values [#2489](https://github.com/terrastruct/d2/pull/2489)
|
||||
- fixes leaf ampersand filter when used with imports [#2494](https://github.com/terrastruct/d2/pull/2494)
|
||||
- Formatter:
|
||||
- fixes substitutions in quotes surrounded by text [#2462](https://github.com/terrastruct/d2/pull/2462)
|
||||
- CLI:
|
||||
- fetch and render remote images of mimetype octet-stream correctly [#2370](https://github.com/terrastruct/d2/pull/2370)
|
||||
- Composition:
|
||||
- spread importing scenarios/steps was not inheriting correctly [#2460](https://github.com/terrastruct/d2/pull/2460)
|
||||
- imported fields were not merging with current fields/edges [#2464](https://github.com/terrastruct/d2/pull/2464)
|
||||
- Markdown:
|
||||
- fixes nested var substitutions not working [#2456](https://github.com/terrastruct/d2/pull/2456)
|
||||
|
||||
---
|
||||
|
||||
For the latest d2.js changes, see separate [changelog](https://github.com/terrastruct/d2/blob/master/d2js/js/CHANGELOG.md).
|
||||
|
|
@ -5,9 +5,9 @@ ARG TARGETARCH
|
|||
|
||||
RUN apt-get update && apt-get install -y ca-certificates curl dumb-init sudo
|
||||
|
||||
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash -s - && \
|
||||
RUN curl -fsSL https://deb.nodesource.com/setup_19.x | bash -s - && \
|
||||
apt-get install -y nodejs
|
||||
RUN npx playwright@1.45.3 install --with-deps chromium
|
||||
RUN npx playwright@1.31.1 install --with-deps chromium
|
||||
|
||||
RUN adduser --gecos '' --disabled-password debian \
|
||||
&& echo "debian ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/nopasswd
|
||||
|
|
|
|||
|
|
@ -1,39 +0,0 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
cd -- "$(dirname "$0")/../.."
|
||||
. "./ci/sub/lib.sh"
|
||||
|
||||
VERSION=""
|
||||
|
||||
help() {
|
||||
cat <<EOF
|
||||
usage: $0 --version=<version>
|
||||
|
||||
Publishes the d2.js to NPM.
|
||||
|
||||
Flags:
|
||||
--version Version to publish (e.g., "0.1.2" or "nightly"). Note this is the js version, not related to the d2 version. A non-nightly version will publish to latest.
|
||||
EOF
|
||||
}
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--help|-h)
|
||||
help
|
||||
exit 0
|
||||
;;
|
||||
--version=*)
|
||||
VERSION="${arg#*=}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z "$VERSION" ]; then
|
||||
flag_errusage "--version is required"
|
||||
fi
|
||||
|
||||
FGCOLOR=6 header "Publishing JavaScript package to NPM (version: $VERSION)"
|
||||
|
||||
sh_c "NPM_VERSION=$VERSION ./make.sh js"
|
||||
|
||||
FGCOLOR=2 header 'NPM publish completed'
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
cd -- "$(dirname "$0")/../.."
|
||||
. "./ci/sub/lib.sh"
|
||||
|
||||
./ci/sub/release/release.sh "$@"
|
||||
|
|
|
|||
|
|
@ -8,17 +8,12 @@
|
|||
.Nm d2
|
||||
.Op Fl -watch Ar false
|
||||
.Op Fl -theme Em 0
|
||||
.Op Fl -salt Ar string
|
||||
.Ar file.d2
|
||||
.Op Ar file.svg | file.png
|
||||
.Nm d2
|
||||
.Ar layout Op Ar name
|
||||
.Nm d2
|
||||
.Ar fmt Ar file.d2 ...
|
||||
.Nm d2
|
||||
.Ar play Ar file.d2
|
||||
.Nm d2
|
||||
.Ar validate Ar file.d2
|
||||
.Sh DESCRIPTION
|
||||
.Nm
|
||||
compiles and renders
|
||||
|
|
@ -101,7 +96,7 @@ Path to .ttf file to use for the bold font. If none provided, Source Sans Pro Bo
|
|||
Pixels padded around the rendered diagram
|
||||
.Ns .
|
||||
.It Fl -animate-interval Ar 0
|
||||
If given, multiple boards are packaged as 1 SVG which transitions through each board at the interval (in milliseconds). Can only be used with SVG and GIF exports
|
||||
If given, multiple boards are packaged as 1 SVG which transitions through each board at the interval (in milliseconds). Can only be used with SVG exports
|
||||
.Ns .
|
||||
.It Fl -browser Ar true
|
||||
Browser executable that watch opens. Setting to 0 opens no browser
|
||||
|
|
@ -130,27 +125,12 @@ In watch mode, images used in icons are cached for subsequent compilations. This
|
|||
.It Fl -timeout Ar 120
|
||||
The maximum number of seconds that D2 runs for before timing out and exiting. When rendering a large diagram, it is recommended to increase this value
|
||||
.Ns .
|
||||
.It Fl -check Ar false
|
||||
Check that the specified files are formatted correctly
|
||||
.Ns .
|
||||
.It Fl -salt Ar string
|
||||
Add a salt value to ensure the output uses unique IDs. This is useful when generating multiple identical diagrams to be included in the same HTML doc, so that duplicate id's do not cause invalid HTML. The salt value is a string that will be appended to IDs in the output.
|
||||
.Ns .
|
||||
.It Fl h , -help
|
||||
Print usage information and exit
|
||||
.Ns .
|
||||
.It Fl v , -version
|
||||
Print version information and exit
|
||||
.Ns .
|
||||
.It Fl -stdout-format Ar string
|
||||
Set the output format when writing to stdout. Supported formats are: png, svg. Only used when output is set to stdout (-)
|
||||
.Ns .
|
||||
.It Fl -no-xml-tag Ar false
|
||||
Omit XML tag (<?xml ...?>) from output SVG files. Useful when generating SVGs for direct HTML embedding
|
||||
.Ns .
|
||||
.It Fl -omit-version Ar false
|
||||
omit D2 version from generated image
|
||||
.Ns .
|
||||
.El
|
||||
.Sh SUBCOMMANDS
|
||||
.Bl -tag -width Fl
|
||||
|
|
@ -165,64 +145,7 @@ Lists available themes
|
|||
.Ns .
|
||||
.It Ar fmt Ar file.d2 ...
|
||||
Format all passed files
|
||||
.It Ar play Ar file.d2
|
||||
Opens the file in playground, an online web viewer (https://play.d2lang.com)
|
||||
.It Ar validate Ar file.d2
|
||||
Validates file.d2
|
||||
.El
|
||||
.Sh ENVIRONMENT VARIABLES
|
||||
Many flags can also be set with environment variables.
|
||||
.Bl -tag -width Ds
|
||||
.It Ev Sy D2_WATCH
|
||||
See -w[atch] flag.
|
||||
.It Ev Sy D2_LAYOUT
|
||||
See -l[ayout] flag.
|
||||
.It Ev Sy D2_THEME
|
||||
See -t[heme] flag.
|
||||
.It Ev Sy D2_DARK_THEME
|
||||
See --dark-theme flag.
|
||||
.It Ev Sy D2_PAD
|
||||
See --pad flag.
|
||||
.It Ev Sy D2_CENTER
|
||||
See --center flag.
|
||||
.It Ev Sy D2_SKETCH
|
||||
See -s[ketch] flag.
|
||||
.It Ev Sy D2_BUNDLE
|
||||
See -b[undle] flag.
|
||||
.It Ev Sy D2_FORCE_APPENDIX
|
||||
See --force-appendix flag.
|
||||
.It Ev Sy D2_FONT_REGULAR
|
||||
See --font-regular flag.
|
||||
.It Ev Sy D2_FONT_ITALIC
|
||||
See --font-italic flag.
|
||||
.It Ev Sy D2_FONT_BOLD
|
||||
See --font-bold flag.
|
||||
.It Ev Sy D2_FONT_SEMIBOLD
|
||||
See --font-semibold flag.
|
||||
.It Ev Sy D2_ANIMATE_INTERVAL
|
||||
See --animate-interval flag.
|
||||
.It Ev Sy D2_TIMEOUT
|
||||
See --timeout flag.
|
||||
.It Ev Sy D2_CHECK
|
||||
See --check flag.
|
||||
.El
|
||||
.Bl -tag -width Ds
|
||||
.It Ev Sy DEBUG
|
||||
See -d[ebug] flag.
|
||||
.It Ev Sy IMG_CACHE
|
||||
See --img-cache flag.
|
||||
.It Ev Sy HOST
|
||||
See -h[ost] flag.
|
||||
.It Ev Sy PORT
|
||||
See -p[ort] flag.
|
||||
.It Ev Sy BROWSER
|
||||
See --browser flag.
|
||||
.It Ev Sy D2_STDOUT_FORMAT
|
||||
See --stdout-format flag.
|
||||
.It Ev Sy D2_NO_XML_TAG
|
||||
See --no-xml-tag flag.
|
||||
.It Ev Sy OMIT_VERSION
|
||||
See --omit-version
|
||||
.Ns .
|
||||
.El
|
||||
.Sh SEE ALSO
|
||||
.Xr d2plugin-tala 1
|
||||
|
|
|
|||
2
ci/sub
2
ci/sub
|
|
@ -1 +1 @@
|
|||
Subproject commit 2594100ac939644f134e24edac7c9bcd569b99f6
|
||||
Subproject commit 7a2914b504ed0dfca6d2dcd923b660052217cccb
|
||||
234
d2ast/d2ast.go
234
d2ast/d2ast.go
|
|
@ -49,14 +49,14 @@ type Node interface {
|
|||
// GetRange returns the range a node occupies in its file.
|
||||
GetRange() Range
|
||||
|
||||
Children() []Node
|
||||
// TODO: add Children() for walking AST
|
||||
// Children() []Node
|
||||
}
|
||||
|
||||
var _ Node = &Comment{}
|
||||
var _ Node = &BlockComment{}
|
||||
|
||||
var _ Node = &Null{}
|
||||
var _ Node = &Suspension{}
|
||||
var _ Node = &Boolean{}
|
||||
var _ Node = &Number{}
|
||||
var _ Node = &UnquotedString{}
|
||||
|
|
@ -167,8 +167,7 @@ func (r Range) Before(r2 Range) bool {
|
|||
type Position struct {
|
||||
Line int
|
||||
Column int
|
||||
// -1 is used as sentinel that a constructed position is missing byte offset (for LSP usage)
|
||||
Byte int
|
||||
Byte int
|
||||
}
|
||||
|
||||
var _ fmt.Stringer = Position{}
|
||||
|
|
@ -278,13 +277,7 @@ func (p Position) SubtractString(s string, byUTF16 bool) Position {
|
|||
}
|
||||
|
||||
func (p Position) Before(p2 Position) bool {
|
||||
if p.Byte != p2.Byte && p.Byte != -1 && p2.Byte != -1 {
|
||||
return p.Byte < p2.Byte
|
||||
}
|
||||
if p.Line != p2.Line {
|
||||
return p.Line < p2.Line
|
||||
}
|
||||
return p.Column < p2.Column
|
||||
return p.Byte < p2.Byte
|
||||
}
|
||||
|
||||
// MapNode is implemented by nodes that may be children of Maps.
|
||||
|
|
@ -330,7 +323,6 @@ type Scalar interface {
|
|||
|
||||
// See String for rest.
|
||||
var _ Scalar = &Null{}
|
||||
var _ Scalar = &Suspension{}
|
||||
var _ Scalar = &Boolean{}
|
||||
var _ Scalar = &Number{}
|
||||
|
||||
|
|
@ -340,7 +332,6 @@ type String interface {
|
|||
SetString(string)
|
||||
Copy() String
|
||||
_string()
|
||||
IsUnquoted() bool
|
||||
}
|
||||
|
||||
var _ String = &UnquotedString{}
|
||||
|
|
@ -351,7 +342,6 @@ var _ String = &BlockString{}
|
|||
func (c *Comment) node() {}
|
||||
func (c *BlockComment) node() {}
|
||||
func (n *Null) node() {}
|
||||
func (n *Suspension) node() {}
|
||||
func (b *Boolean) node() {}
|
||||
func (n *Number) node() {}
|
||||
func (s *UnquotedString) node() {}
|
||||
|
|
@ -370,7 +360,6 @@ func (i *EdgeIndex) node() {}
|
|||
func (c *Comment) Type() string { return "comment" }
|
||||
func (c *BlockComment) Type() string { return "block comment" }
|
||||
func (n *Null) Type() string { return "null" }
|
||||
func (n *Suspension) Type() string { return "suspension" }
|
||||
func (b *Boolean) Type() string { return "boolean" }
|
||||
func (n *Number) Type() string { return "number" }
|
||||
func (s *UnquotedString) Type() string { return "unquoted string" }
|
||||
|
|
@ -389,7 +378,6 @@ func (i *EdgeIndex) Type() string { return "edge index" }
|
|||
func (c *Comment) GetRange() Range { return c.Range }
|
||||
func (c *BlockComment) GetRange() Range { return c.Range }
|
||||
func (n *Null) GetRange() Range { return n.Range }
|
||||
func (n *Suspension) GetRange() Range { return n.Range }
|
||||
func (b *Boolean) GetRange() Range { return b.Range }
|
||||
func (n *Number) GetRange() Range { return n.Range }
|
||||
func (s *UnquotedString) GetRange() Range { return s.Range }
|
||||
|
|
@ -414,7 +402,6 @@ func (i *Import) mapNode() {}
|
|||
func (c *Comment) arrayNode() {}
|
||||
func (c *BlockComment) arrayNode() {}
|
||||
func (n *Null) arrayNode() {}
|
||||
func (n *Suspension) arrayNode() {}
|
||||
func (b *Boolean) arrayNode() {}
|
||||
func (n *Number) arrayNode() {}
|
||||
func (s *UnquotedString) arrayNode() {}
|
||||
|
|
@ -427,7 +414,6 @@ func (a *Array) arrayNode() {}
|
|||
func (m *Map) arrayNode() {}
|
||||
|
||||
func (n *Null) value() {}
|
||||
func (n *Suspension) value() {}
|
||||
func (b *Boolean) value() {}
|
||||
func (n *Number) value() {}
|
||||
func (s *UnquotedString) value() {}
|
||||
|
|
@ -439,7 +425,6 @@ func (m *Map) value() {}
|
|||
func (i *Import) value() {}
|
||||
|
||||
func (n *Null) scalar() {}
|
||||
func (n *Suspension) scalar() {}
|
||||
func (b *Boolean) scalar() {}
|
||||
func (n *Number) scalar() {}
|
||||
func (s *UnquotedString) scalar() {}
|
||||
|
|
@ -447,145 +432,10 @@ func (s *DoubleQuotedString) scalar() {}
|
|||
func (s *SingleQuotedString) scalar() {}
|
||||
func (s *BlockString) scalar() {}
|
||||
|
||||
func (c *Comment) Children() []Node { return nil }
|
||||
func (c *BlockComment) Children() []Node { return nil }
|
||||
func (n *Null) Children() []Node { return nil }
|
||||
func (n *Suspension) Children() []Node { return nil }
|
||||
func (b *Boolean) Children() []Node { return nil }
|
||||
func (n *Number) Children() []Node { return nil }
|
||||
func (s *SingleQuotedString) Children() []Node { return nil }
|
||||
func (s *BlockString) Children() []Node { return nil }
|
||||
func (ei *EdgeIndex) Children() []Node { return nil }
|
||||
|
||||
func (s *UnquotedString) Children() []Node {
|
||||
var children []Node
|
||||
for _, box := range s.Value {
|
||||
if box.Substitution != nil {
|
||||
children = append(children, box.Substitution)
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (s *DoubleQuotedString) Children() []Node {
|
||||
var children []Node
|
||||
for _, box := range s.Value {
|
||||
if box.Substitution != nil {
|
||||
children = append(children, box.Substitution)
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (s *Substitution) Children() []Node {
|
||||
var children []Node
|
||||
for _, sb := range s.Path {
|
||||
if sb != nil {
|
||||
if child := sb.Unbox(); child != nil {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (i *Import) Children() []Node {
|
||||
var children []Node
|
||||
for _, sb := range i.Path {
|
||||
if sb != nil {
|
||||
if child := sb.Unbox(); child != nil {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (a *Array) Children() []Node {
|
||||
var children []Node
|
||||
for _, box := range a.Nodes {
|
||||
if child := box.Unbox(); child != nil {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (m *Map) Children() []Node {
|
||||
var children []Node
|
||||
for _, box := range m.Nodes {
|
||||
if child := box.Unbox(); child != nil {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (k *Key) Children() []Node {
|
||||
var children []Node
|
||||
if k.Key != nil {
|
||||
children = append(children, k.Key)
|
||||
}
|
||||
for _, edge := range k.Edges {
|
||||
if edge != nil {
|
||||
children = append(children, edge)
|
||||
}
|
||||
}
|
||||
if k.EdgeIndex != nil {
|
||||
children = append(children, k.EdgeIndex)
|
||||
}
|
||||
if k.EdgeKey != nil {
|
||||
children = append(children, k.EdgeKey)
|
||||
}
|
||||
if scalar := k.Primary.Unbox(); scalar != nil {
|
||||
children = append(children, scalar)
|
||||
}
|
||||
if value := k.Value.Unbox(); value != nil {
|
||||
children = append(children, value)
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (kp *KeyPath) Children() []Node {
|
||||
var children []Node
|
||||
for _, sb := range kp.Path {
|
||||
if sb != nil {
|
||||
if child := sb.Unbox(); child != nil {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func (e *Edge) Children() []Node {
|
||||
var children []Node
|
||||
if e.Src != nil {
|
||||
children = append(children, e.Src)
|
||||
}
|
||||
if e.Dst != nil {
|
||||
children = append(children, e.Dst)
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
func Walk(node Node, fn func(Node) bool) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
if !fn(node) {
|
||||
return
|
||||
}
|
||||
for _, child := range node.Children() {
|
||||
Walk(child, fn)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: mistake, move into parse.go
|
||||
func (n *Null) ScalarString() string { return "" }
|
||||
func (n *Suspension) ScalarString() string { return "" }
|
||||
func (b *Boolean) ScalarString() string { return strconv.FormatBool(b.Value) }
|
||||
func (n *Number) ScalarString() string { return n.Raw }
|
||||
func (n *Null) ScalarString() string { return "" }
|
||||
func (b *Boolean) ScalarString() string { return strconv.FormatBool(b.Value) }
|
||||
func (n *Number) ScalarString() string { return n.Raw }
|
||||
func (s *UnquotedString) ScalarString() string {
|
||||
if len(s.Value) == 0 {
|
||||
return ""
|
||||
|
|
@ -622,11 +472,6 @@ func (s *DoubleQuotedString) _string() {}
|
|||
func (s *SingleQuotedString) _string() {}
|
||||
func (s *BlockString) _string() {}
|
||||
|
||||
func (s *UnquotedString) IsUnquoted() bool { return true }
|
||||
func (s *DoubleQuotedString) IsUnquoted() bool { return false }
|
||||
func (s *SingleQuotedString) IsUnquoted() bool { return false }
|
||||
func (s *BlockString) IsUnquoted() bool { return false }
|
||||
|
||||
type Comment struct {
|
||||
Range Range `json:"range"`
|
||||
Value string `json:"value"`
|
||||
|
|
@ -641,11 +486,6 @@ type Null struct {
|
|||
Range Range `json:"range"`
|
||||
}
|
||||
|
||||
type Suspension struct {
|
||||
Range Range `json:"range"`
|
||||
Value bool `json:"value"`
|
||||
}
|
||||
|
||||
type Boolean struct {
|
||||
Range Range `json:"range"`
|
||||
Value bool `json:"value"`
|
||||
|
|
@ -820,9 +660,6 @@ func (mk1 *Key) D2OracleEquals(mk2 *Key) bool {
|
|||
if mk1.Ampersand != mk2.Ampersand {
|
||||
return false
|
||||
}
|
||||
if mk1.NotAmpersand != mk2.NotAmpersand {
|
||||
return false
|
||||
}
|
||||
if (mk1.Key == nil) != (mk2.Key == nil) {
|
||||
return false
|
||||
}
|
||||
|
|
@ -902,9 +739,6 @@ func (mk1 *Key) Equals(mk2 *Key) bool {
|
|||
if mk1.Ampersand != mk2.Ampersand {
|
||||
return false
|
||||
}
|
||||
if mk1.NotAmpersand != mk2.NotAmpersand {
|
||||
return false
|
||||
}
|
||||
if (mk1.Key == nil) != (mk2.Key == nil) {
|
||||
return false
|
||||
}
|
||||
|
|
@ -1028,27 +862,15 @@ func (mk *Key) HasTripleGlob() bool {
|
|||
return true
|
||||
}
|
||||
}
|
||||
if mk.EdgeIndex != nil && mk.EdgeIndex.Glob {
|
||||
return true
|
||||
}
|
||||
if mk.EdgeKey.HasTripleGlob() {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (mk *Key) HasMultiGlob() bool {
|
||||
if mk.Key.HasMultiGlob() {
|
||||
return true
|
||||
}
|
||||
for _, e := range mk.Edges {
|
||||
if e.Src.HasMultiGlob() || e.Dst.HasMultiGlob() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if mk.EdgeKey.HasMultiGlob() {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (mk *Key) SupportsGlobFilters() bool {
|
||||
if mk.Key.HasGlob() && len(mk.Edges) == 0 {
|
||||
return true
|
||||
|
|
@ -1080,22 +902,7 @@ func MakeKeyPath(a []string) *KeyPath {
|
|||
return kp
|
||||
}
|
||||
|
||||
func MakeKeyPathString(a []String) *KeyPath {
|
||||
kp := &KeyPath{}
|
||||
for _, el := range a {
|
||||
kp.Path = append(kp.Path, MakeValueBox(RawString(el.ScalarString(), true)).StringBox())
|
||||
}
|
||||
return kp
|
||||
}
|
||||
|
||||
func (kp *KeyPath) IDA() (ida []String) {
|
||||
for _, el := range kp.Path {
|
||||
ida = append(ida, el.Unbox())
|
||||
}
|
||||
return ida
|
||||
}
|
||||
|
||||
func (kp *KeyPath) StringIDA() (ida []string) {
|
||||
func (kp *KeyPath) IDA() (ida []string) {
|
||||
for _, el := range kp.Path {
|
||||
ida = append(ida, el.Unbox().ScalarString())
|
||||
}
|
||||
|
|
@ -1384,7 +1191,6 @@ func (ab ArrayNodeBox) Unbox() ArrayNode {
|
|||
// ValueBox is used to box Value for JSON persistence.
|
||||
type ValueBox struct {
|
||||
Null *Null `json:"null,omitempty"`
|
||||
Suspension *Suspension `json:"suspension,omitempty"`
|
||||
Boolean *Boolean `json:"boolean,omitempty"`
|
||||
Number *Number `json:"number,omitempty"`
|
||||
UnquotedString *UnquotedString `json:"unquoted_string,omitempty"`
|
||||
|
|
@ -1400,8 +1206,6 @@ func (vb ValueBox) Unbox() Value {
|
|||
switch {
|
||||
case vb.Null != nil:
|
||||
return vb.Null
|
||||
case vb.Suspension != nil:
|
||||
return vb.Suspension
|
||||
case vb.Boolean != nil:
|
||||
return vb.Boolean
|
||||
case vb.Number != nil:
|
||||
|
|
@ -1430,8 +1234,6 @@ func MakeValueBox(v Value) ValueBox {
|
|||
switch v := v.(type) {
|
||||
case *Null:
|
||||
vb.Null = v
|
||||
case *Suspension:
|
||||
vb.Suspension = v
|
||||
case *Boolean:
|
||||
vb.Boolean = v
|
||||
case *Number:
|
||||
|
|
@ -1457,7 +1259,6 @@ func MakeValueBox(v Value) ValueBox {
|
|||
func (vb ValueBox) ScalarBox() ScalarBox {
|
||||
var sb ScalarBox
|
||||
sb.Null = vb.Null
|
||||
sb.Suspension = vb.Suspension
|
||||
sb.Boolean = vb.Boolean
|
||||
sb.Number = vb.Number
|
||||
sb.UnquotedString = vb.UnquotedString
|
||||
|
|
@ -1480,7 +1281,6 @@ func (vb ValueBox) StringBox() *StringBox {
|
|||
// TODO: implement ScalarString()
|
||||
type ScalarBox struct {
|
||||
Null *Null `json:"null,omitempty"`
|
||||
Suspension *Suspension `json:"suspension,omitempty"`
|
||||
Boolean *Boolean `json:"boolean,omitempty"`
|
||||
Number *Number `json:"number,omitempty"`
|
||||
UnquotedString *UnquotedString `json:"unquoted_string,omitempty"`
|
||||
|
|
@ -1493,8 +1293,6 @@ func (sb ScalarBox) Unbox() Scalar {
|
|||
switch {
|
||||
case sb.Null != nil:
|
||||
return sb.Null
|
||||
case sb.Suspension != nil:
|
||||
return sb.Suspension
|
||||
case sb.Boolean != nil:
|
||||
return sb.Boolean
|
||||
case sb.Number != nil:
|
||||
|
|
@ -1583,7 +1381,7 @@ func RawString(s string, inKey bool) String {
|
|||
return &SingleQuotedString{Value: s}
|
||||
}
|
||||
}
|
||||
} else if s == "null" || s == "suspend" || s == "unsuspend" || strings.ContainsAny(s, UnquotedValueSpecials) {
|
||||
} else if s == "null" || strings.ContainsAny(s, UnquotedValueSpecials) {
|
||||
if !strings.ContainsRune(s, '"') && !strings.ContainsRune(s, '$') {
|
||||
return FlatDoubleQuotedString(s)
|
||||
}
|
||||
|
|
@ -1617,9 +1415,9 @@ func (s *Substitution) IDA() (ida []string) {
|
|||
return ida
|
||||
}
|
||||
|
||||
func (i *Import) IDA() (ida []String) {
|
||||
func (i *Import) IDA() (ida []string) {
|
||||
for _, el := range i.Path[1:] {
|
||||
ida = append(ida, el.Unbox())
|
||||
ida = append(ida, el.Unbox().ScalarString())
|
||||
}
|
||||
return ida
|
||||
}
|
||||
|
|
@ -1630,7 +1428,3 @@ func (i *Import) PathWithPre() string {
|
|||
}
|
||||
return path.Join(i.Pre, i.Path[0].Unbox().ScalarString())
|
||||
}
|
||||
|
||||
func (i *Import) Dir() string {
|
||||
return path.Dir(i.PathWithPre())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,200 +0,0 @@
|
|||
package d2ast
|
||||
|
||||
import "oss.terrastruct.com/d2/lib/label"
|
||||
|
||||
// All reserved keywords. See init below.
|
||||
var ReservedKeywords map[string]struct{}
|
||||
|
||||
// Non Style/Holder keywords.
|
||||
var SimpleReservedKeywords = map[string]struct{}{
|
||||
"label": {},
|
||||
"shape": {},
|
||||
"icon": {},
|
||||
"constraint": {},
|
||||
"tooltip": {},
|
||||
"link": {},
|
||||
"near": {},
|
||||
"width": {},
|
||||
"height": {},
|
||||
"direction": {},
|
||||
"top": {},
|
||||
"left": {},
|
||||
"grid-rows": {},
|
||||
"grid-columns": {},
|
||||
"grid-gap": {},
|
||||
"vertical-gap": {},
|
||||
"horizontal-gap": {},
|
||||
"class": {},
|
||||
"vars": {},
|
||||
}
|
||||
|
||||
// ReservedKeywordHolders are reserved keywords that are meaningless on its own and must hold composites
|
||||
var ReservedKeywordHolders = map[string]struct{}{
|
||||
"style": {},
|
||||
}
|
||||
|
||||
// CompositeReservedKeywords are reserved keywords that can hold composites
|
||||
var CompositeReservedKeywords = map[string]struct{}{
|
||||
"source-arrowhead": {},
|
||||
"target-arrowhead": {},
|
||||
"classes": {},
|
||||
"constraint": {},
|
||||
"label": {},
|
||||
"icon": {},
|
||||
}
|
||||
|
||||
// StyleKeywords are reserved keywords which cannot exist outside of the "style" keyword
|
||||
var StyleKeywords = map[string]struct{}{
|
||||
"opacity": {},
|
||||
"stroke": {},
|
||||
"fill": {},
|
||||
"fill-pattern": {},
|
||||
"stroke-width": {},
|
||||
"stroke-dash": {},
|
||||
"border-radius": {},
|
||||
|
||||
// Only for text
|
||||
"font": {},
|
||||
"font-size": {},
|
||||
"font-color": {},
|
||||
"bold": {},
|
||||
"italic": {},
|
||||
"underline": {},
|
||||
"text-transform": {},
|
||||
|
||||
// Only for shapes
|
||||
"shadow": {},
|
||||
"multiple": {},
|
||||
"double-border": {},
|
||||
|
||||
// Only for squares
|
||||
"3d": {},
|
||||
|
||||
// Only for edges
|
||||
"animated": {},
|
||||
"filled": {},
|
||||
}
|
||||
|
||||
// TODO maybe autofmt should allow other values, and transform them to conform
|
||||
// e.g. left-center becomes center-left
|
||||
var NearConstantsArray = []string{
|
||||
"top-left",
|
||||
"top-center",
|
||||
"top-right",
|
||||
|
||||
"center-left",
|
||||
"center-right",
|
||||
|
||||
"bottom-left",
|
||||
"bottom-center",
|
||||
"bottom-right",
|
||||
}
|
||||
var NearConstants map[string]struct{}
|
||||
|
||||
// LabelPositionsArray are the values that labels and icons can set `near` to
|
||||
var LabelPositionsArray = []string{
|
||||
"top-left",
|
||||
"top-center",
|
||||
"top-right",
|
||||
|
||||
"center-left",
|
||||
"center-center",
|
||||
"center-right",
|
||||
|
||||
"bottom-left",
|
||||
"bottom-center",
|
||||
"bottom-right",
|
||||
|
||||
"outside-top-left",
|
||||
"outside-top-center",
|
||||
"outside-top-right",
|
||||
|
||||
"outside-left-top",
|
||||
"outside-left-center",
|
||||
"outside-left-bottom",
|
||||
|
||||
"outside-right-top",
|
||||
"outside-right-center",
|
||||
"outside-right-bottom",
|
||||
|
||||
"outside-bottom-left",
|
||||
"outside-bottom-center",
|
||||
"outside-bottom-right",
|
||||
}
|
||||
var LabelPositions map[string]struct{}
|
||||
|
||||
var LabelPositionsMapping = map[string]label.Position{
|
||||
"top-left": label.InsideTopLeft,
|
||||
"top-center": label.InsideTopCenter,
|
||||
"top-right": label.InsideTopRight,
|
||||
|
||||
"center-left": label.InsideMiddleLeft,
|
||||
"center-center": label.InsideMiddleCenter,
|
||||
"center-right": label.InsideMiddleRight,
|
||||
|
||||
"bottom-left": label.InsideBottomLeft,
|
||||
"bottom-center": label.InsideBottomCenter,
|
||||
"bottom-right": label.InsideBottomRight,
|
||||
|
||||
"outside-top-left": label.OutsideTopLeft,
|
||||
"outside-top-center": label.OutsideTopCenter,
|
||||
"outside-top-right": label.OutsideTopRight,
|
||||
|
||||
"outside-left-top": label.OutsideLeftTop,
|
||||
"outside-left-center": label.OutsideLeftMiddle,
|
||||
"outside-left-bottom": label.OutsideLeftBottom,
|
||||
|
||||
"outside-right-top": label.OutsideRightTop,
|
||||
"outside-right-center": label.OutsideRightMiddle,
|
||||
"outside-right-bottom": label.OutsideRightBottom,
|
||||
|
||||
"outside-bottom-left": label.OutsideBottomLeft,
|
||||
"outside-bottom-center": label.OutsideBottomCenter,
|
||||
"outside-bottom-right": label.OutsideBottomRight,
|
||||
}
|
||||
|
||||
var FillPatterns = []string{
|
||||
"none",
|
||||
"dots",
|
||||
"lines",
|
||||
"grain",
|
||||
"paper",
|
||||
}
|
||||
|
||||
var TextTransforms = []string{"none", "uppercase", "lowercase", "capitalize"}
|
||||
|
||||
// BoardKeywords contains the keywords that create new boards.
|
||||
var BoardKeywords = map[string]struct{}{
|
||||
"layers": {},
|
||||
"scenarios": {},
|
||||
"steps": {},
|
||||
}
|
||||
|
||||
func init() {
|
||||
ReservedKeywords = make(map[string]struct{})
|
||||
for k, v := range SimpleReservedKeywords {
|
||||
ReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range StyleKeywords {
|
||||
ReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range ReservedKeywordHolders {
|
||||
CompositeReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range BoardKeywords {
|
||||
CompositeReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range CompositeReservedKeywords {
|
||||
ReservedKeywords[k] = v
|
||||
}
|
||||
|
||||
NearConstants = make(map[string]struct{}, len(NearConstantsArray))
|
||||
for _, k := range NearConstantsArray {
|
||||
NearConstants[k] = struct{}{}
|
||||
}
|
||||
|
||||
LabelPositions = make(map[string]struct{}, len(LabelPositionsArray))
|
||||
for _, k := range LabelPositionsArray {
|
||||
LabelPositions[k] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
|
@ -269,7 +269,7 @@ func (gs *dslGenState) randStr(n int, inKey bool) string {
|
|||
func (gs *dslGenState) randShape() string {
|
||||
for {
|
||||
s := shapes[gs.rand.Intn(len(shapes))]
|
||||
if s != d2target.ShapeImage && s != d2target.ShapeText {
|
||||
if s != d2target.ShapeImage {
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package d2chaos_test
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime/debug"
|
||||
|
|
@ -89,14 +90,14 @@ func TestD2Chaos(t *testing.T) {
|
|||
|
||||
func test(t *testing.T, textPath, text string) {
|
||||
t.Logf("writing d2 to %v (%d bytes)", textPath, len(text))
|
||||
err := os.WriteFile(textPath, []byte(text), 0644)
|
||||
err := ioutil.WriteFile(textPath, []byte(text), 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
goencText := fmt.Sprintf("%#v", text)
|
||||
t.Logf("writing d2.goenc to %v (%d bytes)", textPath+".goenc", len(goencText))
|
||||
err = os.WriteFile(textPath+".goenc", []byte(goencText), 0644)
|
||||
err = ioutil.WriteFile(textPath+".goenc", []byte(goencText), 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
@ -114,7 +115,7 @@ func test(t *testing.T, textPath, text string) {
|
|||
}
|
||||
}()
|
||||
|
||||
ctx := log.WithTB(context.Background(), t)
|
||||
ctx := log.WithTB(context.Background(), t, nil)
|
||||
|
||||
ruler, err := textmeasure.NewRuler()
|
||||
assert.Nil(t, err)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
package d2cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type exportExtension string
|
||||
|
|
@ -16,24 +14,6 @@ const SVG exportExtension = ".svg"
|
|||
|
||||
var SUPPORTED_EXTENSIONS = []exportExtension{SVG, PNG, PDF, PPTX, GIF}
|
||||
|
||||
var STDOUT_FORMAT_MAP = map[string]exportExtension{
|
||||
"png": PNG,
|
||||
"svg": SVG,
|
||||
}
|
||||
|
||||
var SUPPORTED_STDOUT_FORMATS = []string{"png", "svg"}
|
||||
|
||||
func getOutputFormat(stdoutFormatFlag *string, outputPath string) (exportExtension, error) {
|
||||
if stdoutFormatFlag != nil && *stdoutFormatFlag != "" {
|
||||
format := strings.ToLower(*stdoutFormatFlag)
|
||||
if ext, ok := STDOUT_FORMAT_MAP[format]; ok {
|
||||
return ext, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s is not a supported format. Supported formats are: %s", *stdoutFormatFlag, SUPPORTED_STDOUT_FORMATS)
|
||||
}
|
||||
return getExportExtension(outputPath), nil
|
||||
}
|
||||
|
||||
func getExportExtension(outputPath string) exportExtension {
|
||||
ext := filepath.Ext(outputPath)
|
||||
for _, kext := range SUPPORTED_EXTENSIONS {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import (
|
|||
|
||||
func TestOutputFormat(t *testing.T) {
|
||||
type testCase struct {
|
||||
stdoutFormatFlag string
|
||||
outputPath string
|
||||
extension exportExtension
|
||||
supportsDarkTheme bool
|
||||
|
|
@ -42,15 +41,6 @@ func TestOutputFormat(t *testing.T) {
|
|||
requiresAnimationInterval: false,
|
||||
requiresPngRender: false,
|
||||
},
|
||||
{
|
||||
stdoutFormatFlag: "png",
|
||||
outputPath: "-",
|
||||
extension: PNG,
|
||||
supportsDarkTheme: false,
|
||||
supportsAnimation: false,
|
||||
requiresAnimationInterval: false,
|
||||
requiresPngRender: true,
|
||||
},
|
||||
{
|
||||
outputPath: "/out.png",
|
||||
extension: PNG,
|
||||
|
|
@ -88,8 +78,7 @@ func TestOutputFormat(t *testing.T) {
|
|||
for _, tc := range testCases {
|
||||
tc := tc
|
||||
t.Run(tc.outputPath, func(t *testing.T) {
|
||||
extension, err := getOutputFormat(&tc.stdoutFormatFlag, tc.outputPath)
|
||||
assert.NoError(t, err)
|
||||
extension := getExportExtension(tc.outputPath)
|
||||
assert.Equal(t, tc.extension, extension)
|
||||
assert.Equal(t, tc.supportsAnimation, extension.supportsAnimation())
|
||||
assert.Equal(t, tc.supportsDarkTheme, extension.supportsDarkTheme())
|
||||
|
|
|
|||
24
d2cli/fmt.go
24
d2cli/fmt.go
|
|
@ -12,10 +12,9 @@ import (
|
|||
|
||||
"oss.terrastruct.com/d2/d2format"
|
||||
"oss.terrastruct.com/d2/d2parser"
|
||||
"oss.terrastruct.com/d2/lib/log"
|
||||
)
|
||||
|
||||
func fmtCmd(ctx context.Context, ms *xmain.State, check bool) (err error) {
|
||||
func fmtCmd(ctx context.Context, ms *xmain.State) (err error) {
|
||||
defer xdefer.Errorf(&err, "failed to fmt")
|
||||
|
||||
ms.Opts = xmain.NewOpts(ms.Env, ms.Opts.Flags.Args()[1:])
|
||||
|
|
@ -23,8 +22,6 @@ func fmtCmd(ctx context.Context, ms *xmain.State, check bool) (err error) {
|
|||
return xmain.UsageErrorf("fmt must be passed at least one file to be formatted")
|
||||
}
|
||||
|
||||
unformattedCount := 0
|
||||
|
||||
for _, inputPath := range ms.Opts.Args {
|
||||
if inputPath != "-" {
|
||||
inputPath = ms.AbsPath(inputPath)
|
||||
|
|
@ -46,25 +43,10 @@ func fmtCmd(ctx context.Context, ms *xmain.State, check bool) (err error) {
|
|||
|
||||
output := []byte(d2format.Format(m))
|
||||
if !bytes.Equal(output, input) {
|
||||
if check {
|
||||
unformattedCount += 1
|
||||
log.Warn(ctx, inputPath)
|
||||
} else {
|
||||
if err := ms.WritePath(inputPath, output); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ms.WritePath(inputPath, output); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if unformattedCount > 0 {
|
||||
pluralFiles := "file"
|
||||
if unformattedCount > 1 {
|
||||
pluralFiles = "files"
|
||||
}
|
||||
|
||||
return xmain.ExitErrorf(1, "found %d unformatted %s. Run d2 fmt to fix.", unformattedCount, pluralFiles)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,8 +22,6 @@ Usage:
|
|||
%[1]s [--watch=false] [--theme=0] file.d2 [file.svg | file.png]
|
||||
%[1]s layout [name]
|
||||
%[1]s fmt file.d2 ...
|
||||
%[1]s play [--theme=0] [--sketch] file.d2
|
||||
%[1]s validate file.d2
|
||||
|
||||
%[1]s compiles and renders file.d2 to file.svg | file.png
|
||||
It defaults to file.svg if an output path is not provided.
|
||||
|
|
@ -40,8 +38,6 @@ Subcommands:
|
|||
%[1]s layout [name] - Display long help for a particular layout engine, including its configuration options
|
||||
%[1]s themes - Lists available themes
|
||||
%[1]s fmt file.d2 ... - Format passed files
|
||||
%[1]s play file.d2 - Opens the file in playground, an online web viewer (https://play.d2lang.com)
|
||||
%[1]s validate file.d2 - Validates file.d2
|
||||
|
||||
See more docs and the source code at https://oss.terrastruct.com/d2.
|
||||
Hosted icons at https://icons.terrastruct.com.
|
||||
|
|
@ -59,7 +55,7 @@ func layoutCmd(ctx context.Context, ms *xmain.State, ps []d2plugin.Plugin) error
|
|||
}
|
||||
}
|
||||
|
||||
func themesCmd(_ context.Context, ms *xmain.State) {
|
||||
func themesCmd(ctx context.Context, ms *xmain.State) {
|
||||
fmt.Fprintf(ms.Stdout, "Available themes:\n%s", d2themescatalog.CLIString())
|
||||
}
|
||||
|
||||
|
|
|
|||
242
d2cli/main.go
242
d2cli/main.go
|
|
@ -5,8 +5,8 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
|
|
@ -36,7 +36,7 @@ import (
|
|||
"oss.terrastruct.com/d2/d2themes/d2themescatalog"
|
||||
"oss.terrastruct.com/d2/lib/background"
|
||||
"oss.terrastruct.com/d2/lib/imgbundler"
|
||||
"oss.terrastruct.com/d2/lib/log"
|
||||
ctxlog "oss.terrastruct.com/d2/lib/log"
|
||||
"oss.terrastruct.com/d2/lib/pdf"
|
||||
"oss.terrastruct.com/d2/lib/png"
|
||||
"oss.terrastruct.com/d2/lib/pptx"
|
||||
|
|
@ -45,12 +45,17 @@ import (
|
|||
timelib "oss.terrastruct.com/d2/lib/time"
|
||||
"oss.terrastruct.com/d2/lib/version"
|
||||
"oss.terrastruct.com/d2/lib/xgif"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"cdr.dev/slog/sloggers/sloghuman"
|
||||
)
|
||||
|
||||
func Run(ctx context.Context, ms *xmain.State) (err error) {
|
||||
ctx = log.WithDefault(ctx)
|
||||
// :(
|
||||
ctx = DiscardSlog(ctx)
|
||||
|
||||
// These should be kept up-to-date with the d2 man page
|
||||
watchFlag, err := ms.Opts.Bool("D2_WATCH", "watch", "w", false, "watch for changes to input and live reload. Use $HOST and $PORT to specify the listening address.\n(default localhost:0, which will open on a randomly available local port).")
|
||||
watchFlag, err := ms.Opts.Bool("D2_WATCH", "watch", "w", false, "watch for changes to input and live reload. Use $HOST and $PORT to specify the listening address.\n(default localhost:0, which is will open on a randomly available local port).")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -103,11 +108,6 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stdoutFormatFlag := ms.Opts.String("", "stdout-format", "", "", "output format when writing to stdout (svg, png). Usage: d2 input.d2 --stdout-format png - > output.png")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
browserFlag := ms.Opts.String("BROWSER", "browser", "", "", "browser executable that watch opens. Setting to 0 opens no browser.")
|
||||
centerFlag, err := ms.Opts.Bool("D2_CENTER", "center", "c", false, "center the SVG in the containing viewbox, such as your browser screen")
|
||||
if err != nil {
|
||||
|
|
@ -124,23 +124,6 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
fontBoldFlag := ms.Opts.String("D2_FONT_BOLD", "font-bold", "", "", "path to .ttf file to use for the bold font. If none provided, Source Sans Pro Bold is used.")
|
||||
fontSemiboldFlag := ms.Opts.String("D2_FONT_SEMIBOLD", "font-semibold", "", "", "path to .ttf file to use for the semibold font. If none provided, Source Sans Pro Semibold is used.")
|
||||
|
||||
checkFlag, err := ms.Opts.Bool("D2_CHECK", "check", "", false, "check that the specified files are formatted correctly.")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
noXMLTagFlag, err := ms.Opts.Bool("D2_NO_XML_TAG", "no-xml-tag", "", false, "omit XML tag (<?xml ...?>) from output SVG files. Useful when generating SVGs for direct HTML embedding")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
saltFlag := ms.Opts.String("", "salt", "", "", "Add a salt value to ensure the output uses unique IDs. This is useful when generating multiple identical diagrams to be included in the same HTML doc, so that duplicate IDs do not cause invalid HTML. The salt value is a string that will be appended to IDs in the output.")
|
||||
|
||||
omitVersionFlag, err := ms.Opts.Bool("OMIT_VERSION", "omit-version", "", false, "omit D2 version from generated image")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
plugins, err := d2plugin.ListPlugins(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -175,11 +158,7 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
themesCmd(ctx, ms)
|
||||
return nil
|
||||
case "fmt":
|
||||
return fmtCmd(ctx, ms, *checkFlag)
|
||||
case "play":
|
||||
return playCmd(ctx, ms)
|
||||
case "validate":
|
||||
return validateCmd(ctx, ms)
|
||||
return fmtCmd(ctx, ms)
|
||||
case "version":
|
||||
if len(ms.Opts.Flags.Args()) > 1 {
|
||||
return xmain.UsageErrorf("version subcommand accepts no arguments")
|
||||
|
|
@ -190,7 +169,6 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
}
|
||||
|
||||
if *debugFlag {
|
||||
ctx = log.Leveled(ctx, slog.LevelDebug)
|
||||
ms.Env.Setenv("DEBUG", "1")
|
||||
}
|
||||
if *imgCacheFlag {
|
||||
|
|
@ -239,12 +217,7 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
if filepath.Ext(outputPath) == ".ppt" {
|
||||
return xmain.UsageErrorf("D2 does not support ppt exports, did you mean \"pptx\"?")
|
||||
}
|
||||
|
||||
outputFormat, err := getOutputFormat(stdoutFormatFlag, outputPath)
|
||||
if err != nil {
|
||||
return xmain.UsageErrorf("%v", err)
|
||||
}
|
||||
|
||||
outputFormat := getExportExtension(outputPath)
|
||||
if outputPath != "-" {
|
||||
outputPath = ms.AbsPath(outputPath)
|
||||
if *animateIntervalFlag > 0 && !outputFormat.supportsAnimation() {
|
||||
|
|
@ -334,9 +307,6 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
ThemeID: themeFlag,
|
||||
DarkThemeID: darkThemeFlag,
|
||||
Scale: scale,
|
||||
NoXMLTag: noXMLTagFlag,
|
||||
Salt: saltFlag,
|
||||
OmitVersion: omitVersionFlag,
|
||||
}
|
||||
|
||||
if *watchFlag {
|
||||
|
|
@ -359,7 +329,6 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
forceAppendix: *forceAppendixFlag,
|
||||
pw: pw,
|
||||
fontFamily: fontFamily,
|
||||
outputFormat: outputFormat,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -384,13 +353,13 @@ func Run(ctx context.Context, ms *xmain.State) (err error) {
|
|||
if err != nil {
|
||||
return xmain.UsageErrorf("invalid target: %s", *targetFlag)
|
||||
}
|
||||
boardPath = key.StringIDA()
|
||||
boardPath = key.IDA()
|
||||
}
|
||||
|
||||
ctx, cancel := timelib.WithTimeout(ctx, time.Minute*2)
|
||||
defer cancel()
|
||||
|
||||
_, written, err := compile(ctx, ms, plugins, nil, layoutFlag, renderOpts, fontFamily, *animateIntervalFlag, inputPath, outputPath, boardPath, noChildren, *bundleFlag, *forceAppendixFlag, pw.Page, outputFormat)
|
||||
_, written, err := compile(ctx, ms, plugins, nil, layoutFlag, renderOpts, fontFamily, *animateIntervalFlag, inputPath, outputPath, boardPath, noChildren, *bundleFlag, *forceAppendixFlag, pw.Page)
|
||||
if err != nil {
|
||||
if written {
|
||||
return fmt.Errorf("failed to fully compile (partial render written) %s: %w", ms.HumanPath(inputPath), err)
|
||||
|
|
@ -465,7 +434,7 @@ func RouterResolver(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plu
|
|||
}
|
||||
}
|
||||
|
||||
func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs fs.FS, layout *string, renderOpts d2svg.RenderOpts, fontFamily *d2fonts.FontFamily, animateInterval int64, inputPath, outputPath string, boardPath []string, noChildren, bundle, forceAppendix bool, page playwright.Page, ext exportExtension) (_ []byte, written bool, _ error) {
|
||||
func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs fs.FS, layout *string, renderOpts d2svg.RenderOpts, fontFamily *d2fonts.FontFamily, animateInterval int64, inputPath, outputPath string, boardPath []string, noChildren, bundle, forceAppendix bool, page playwright.Page) (_ []byte, written bool, _ error) {
|
||||
start := time.Now()
|
||||
input, err := ms.ReadPath(inputPath)
|
||||
if err != nil {
|
||||
|
|
@ -490,7 +459,7 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
if os.Getenv("D2_LSP_MODE") == "1" {
|
||||
// only the parse result is needed if running d2 for lsp,
|
||||
// if this, "fails", the AST is still valid and can be sent
|
||||
// to vscode extension
|
||||
// to vscode extention
|
||||
ast, err := d2lib.Parse(ctx, string(input), opts)
|
||||
|
||||
type LspOutputData struct {
|
||||
|
|
@ -511,13 +480,13 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
}, time.Second*5)
|
||||
defer cancel()
|
||||
|
||||
rootDiagram, g, err := d2lib.Compile(ctx, string(input), opts, &renderOpts)
|
||||
diagram, g, err := d2lib.Compile(ctx, string(input), opts, &renderOpts)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
cancel()
|
||||
|
||||
diagram := rootDiagram.GetBoard(boardPath)
|
||||
diagram = diagram.GetBoard(boardPath)
|
||||
if diagram == nil {
|
||||
return nil, false, fmt.Errorf(`render target "%s" not found`, strings.Join(boardPath, "."))
|
||||
}
|
||||
|
|
@ -530,7 +499,7 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
plugin, _ := d2plugin.FindPlugin(ctx, plugins, *opts.Layout)
|
||||
|
||||
if animateInterval > 0 {
|
||||
masterID, err := diagram.HashID(renderOpts.Salt)
|
||||
masterID, err := diagram.HashID()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -557,9 +526,10 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
return nil, false, err
|
||||
}
|
||||
|
||||
ext := getExportExtension(outputPath)
|
||||
switch ext {
|
||||
case GIF:
|
||||
svg, pngs, err := renderPNGsForGIF(ctx, ms, plugin, renderOpts, ruler, page, inputPath, diagram)
|
||||
svg, pngs, err := renderPNGsForGIF(ctx, ms, plugin, renderOpts, ruler, page, diagram)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -571,7 +541,7 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
err = Write(ms, outputPath, out)
|
||||
err = ms.WritePath(outputPath, out)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -583,7 +553,7 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
path := []pdf.BoardTitle{
|
||||
{Name: diagram.Root.Label, BoardID: "root"},
|
||||
}
|
||||
pdf, err := renderPDF(ctx, ms, plugin, renderOpts, inputPath, outputPath, page, ruler, diagram, nil, path, pageMap, diagram.Root.Label != "")
|
||||
pdf, err := renderPDF(ctx, ms, plugin, renderOpts, outputPath, page, ruler, diagram, nil, path, pageMap, diagram.Root.Label != "")
|
||||
if err != nil {
|
||||
return pdf, false, err
|
||||
}
|
||||
|
|
@ -604,7 +574,7 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
path := []pptx.BoardTitle{
|
||||
{Name: "root", BoardID: "root", LinkToSlide: boardIdToIndex["root"] + 1},
|
||||
}
|
||||
svg, err := renderPPTX(ctx, ms, p, plugin, renderOpts, ruler, inputPath, outputPath, page, diagram, path, boardIdToIndex)
|
||||
svg, err := renderPPTX(ctx, ms, p, plugin, renderOpts, ruler, outputPath, page, diagram, path, boardIdToIndex)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -619,11 +589,11 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
compileDur := time.Since(start)
|
||||
if animateInterval <= 0 {
|
||||
// Rename all the "root.layers.x" to the paths that the boards get output to
|
||||
linkToOutput, err := resolveLinks("root", outputPath, rootDiagram)
|
||||
linkToOutput, err := resolveLinks("root", outputPath, diagram)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
err = relink("root", rootDiagram, linkToOutput)
|
||||
err = relink("root", diagram, linkToOutput)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -632,9 +602,9 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
var boards [][]byte
|
||||
var err error
|
||||
if noChildren {
|
||||
boards, err = renderSingle(ctx, ms, compileDur, plugin, renderOpts, inputPath, outputPath, bundle, forceAppendix, page, ruler, diagram, ext)
|
||||
boards, err = renderSingle(ctx, ms, compileDur, plugin, renderOpts, inputPath, outputPath, bundle, forceAppendix, page, ruler, diagram)
|
||||
} else {
|
||||
boards, err = render(ctx, ms, compileDur, plugin, renderOpts, inputPath, outputPath, bundle, forceAppendix, page, ruler, diagram, ext)
|
||||
boards, err = render(ctx, ms, compileDur, plugin, renderOpts, inputPath, outputPath, bundle, forceAppendix, page, ruler, diagram)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
|
|
@ -647,15 +617,11 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs
|
|||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
out, err = plugin.PostProcess(ctx, out)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
err = os.MkdirAll(filepath.Dir(outputPath), 0755)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
err = Write(ms, outputPath, out)
|
||||
err = ms.WritePath(outputPath, out)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -773,7 +739,7 @@ func relink(currDiagramPath string, d *d2target.Diagram, linkToOutput map[string
|
|||
return nil
|
||||
}
|
||||
|
||||
func render(ctx context.Context, ms *xmain.State, compileDur time.Duration, plugin d2plugin.Plugin, opts d2svg.RenderOpts, inputPath, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram, ext exportExtension) ([][]byte, error) {
|
||||
func render(ctx context.Context, ms *xmain.State, compileDur time.Duration, plugin d2plugin.Plugin, opts d2svg.RenderOpts, inputPath, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram) ([][]byte, error) {
|
||||
if diagram.Name != "" {
|
||||
ext := filepath.Ext(outputPath)
|
||||
outputPath = strings.TrimSuffix(outputPath, ext)
|
||||
|
|
@ -819,21 +785,21 @@ func render(ctx context.Context, ms *xmain.State, compileDur time.Duration, plug
|
|||
|
||||
var boards [][]byte
|
||||
for _, dl := range diagram.Layers {
|
||||
childrenBoards, err := render(ctx, ms, compileDur, plugin, opts, inputPath, layersOutputPath, bundle, forceAppendix, page, ruler, dl, ext)
|
||||
childrenBoards, err := render(ctx, ms, compileDur, plugin, opts, inputPath, layersOutputPath, bundle, forceAppendix, page, ruler, dl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boards = append(boards, childrenBoards...)
|
||||
}
|
||||
for _, dl := range diagram.Scenarios {
|
||||
childrenBoards, err := render(ctx, ms, compileDur, plugin, opts, inputPath, scenariosOutputPath, bundle, forceAppendix, page, ruler, dl, ext)
|
||||
childrenBoards, err := render(ctx, ms, compileDur, plugin, opts, inputPath, scenariosOutputPath, bundle, forceAppendix, page, ruler, dl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boards = append(boards, childrenBoards...)
|
||||
}
|
||||
for _, dl := range diagram.Steps {
|
||||
childrenBoards, err := render(ctx, ms, compileDur, plugin, opts, inputPath, stepsOutputPath, bundle, forceAppendix, page, ruler, dl, ext)
|
||||
childrenBoards, err := render(ctx, ms, compileDur, plugin, opts, inputPath, stepsOutputPath, bundle, forceAppendix, page, ruler, dl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -842,7 +808,7 @@ func render(ctx context.Context, ms *xmain.State, compileDur time.Duration, plug
|
|||
|
||||
if !diagram.IsFolderOnly {
|
||||
start := time.Now()
|
||||
out, err := _render(ctx, ms, plugin, opts, inputPath, boardOutputPath, bundle, forceAppendix, page, ruler, diagram, ext)
|
||||
out, err := _render(ctx, ms, plugin, opts, boardOutputPath, bundle, forceAppendix, page, ruler, diagram)
|
||||
if err != nil {
|
||||
return boards, err
|
||||
}
|
||||
|
|
@ -856,9 +822,9 @@ func render(ctx context.Context, ms *xmain.State, compileDur time.Duration, plug
|
|||
return boards, nil
|
||||
}
|
||||
|
||||
func renderSingle(ctx context.Context, ms *xmain.State, compileDur time.Duration, plugin d2plugin.Plugin, opts d2svg.RenderOpts, inputPath, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram, outputFormat exportExtension) ([][]byte, error) {
|
||||
func renderSingle(ctx context.Context, ms *xmain.State, compileDur time.Duration, plugin d2plugin.Plugin, opts d2svg.RenderOpts, inputPath, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram) ([][]byte, error) {
|
||||
start := time.Now()
|
||||
out, err := _render(ctx, ms, plugin, opts, inputPath, outputPath, bundle, forceAppendix, page, ruler, diagram, outputFormat)
|
||||
out, err := _render(ctx, ms, plugin, opts, outputPath, bundle, forceAppendix, page, ruler, diagram)
|
||||
if err != nil {
|
||||
return [][]byte{}, err
|
||||
}
|
||||
|
|
@ -869,56 +835,49 @@ func renderSingle(ctx context.Context, ms *xmain.State, compileDur time.Duration
|
|||
return [][]byte{out}, nil
|
||||
}
|
||||
|
||||
func _render(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts d2svg.RenderOpts, inputPath, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram, outputFormat exportExtension) ([]byte, error) {
|
||||
toPNG := outputFormat == PNG
|
||||
|
||||
func _render(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts d2svg.RenderOpts, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram) ([]byte, error) {
|
||||
toPNG := getExportExtension(outputPath) == PNG
|
||||
var scale *float64
|
||||
if opts.Scale != nil {
|
||||
scale = opts.Scale
|
||||
} else if toPNG {
|
||||
scale = go2.Pointer(1.)
|
||||
}
|
||||
renderOpts := &d2svg.RenderOpts{
|
||||
svg, err := d2svg.Render(diagram, &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
MasterID: opts.MasterID,
|
||||
ThemeID: opts.ThemeID,
|
||||
DarkThemeID: opts.DarkThemeID,
|
||||
MasterID: opts.MasterID,
|
||||
ThemeOverrides: opts.ThemeOverrides,
|
||||
DarkThemeOverrides: opts.DarkThemeOverrides,
|
||||
NoXMLTag: opts.NoXMLTag,
|
||||
Salt: opts.Salt,
|
||||
Scale: scale,
|
||||
OmitVersion: opts.OmitVersion,
|
||||
}
|
||||
svg, err := d2svg.Render(diagram, renderOpts)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if opts.MasterID == "" {
|
||||
svg, err = plugin.PostProcess(ctx, svg)
|
||||
if err != nil {
|
||||
return svg, err
|
||||
}
|
||||
svg, err = plugin.PostProcess(ctx, svg)
|
||||
if err != nil {
|
||||
return svg, err
|
||||
}
|
||||
|
||||
cacheImages := ms.Env.Getenv("IMG_CACHE") == "1"
|
||||
l := simplelog.FromCmdLog(ms.Log)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, inputPath, svg, cacheImages)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, svg, cacheImages)
|
||||
if bundle {
|
||||
var bundleErr2 error
|
||||
svg, bundleErr2 = imgbundler.BundleRemote(ctx, l, svg, cacheImages)
|
||||
bundleErr = multierr.Combine(bundleErr, bundleErr2)
|
||||
}
|
||||
if forceAppendix && !toPNG {
|
||||
svg = appendix.Append(diagram, renderOpts, ruler, svg)
|
||||
svg = appendix.Append(diagram, ruler, svg)
|
||||
}
|
||||
|
||||
out := svg
|
||||
if toPNG {
|
||||
svg := appendix.Append(diagram, renderOpts, ruler, svg)
|
||||
svg := appendix.Append(diagram, ruler, svg)
|
||||
|
||||
if !bundle {
|
||||
var bundleErr2 error
|
||||
|
|
@ -945,7 +904,7 @@ func _render(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts
|
|||
if err != nil {
|
||||
return svg, err
|
||||
}
|
||||
err = Write(ms, outputPath, out)
|
||||
err = ms.WritePath(outputPath, out)
|
||||
if err != nil {
|
||||
return svg, err
|
||||
}
|
||||
|
|
@ -956,7 +915,7 @@ func _render(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts
|
|||
return svg, nil
|
||||
}
|
||||
|
||||
func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts d2svg.RenderOpts, inputPath, outputPath string, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram, doc *pdf.GoFPDF, boardPath []pdf.BoardTitle, pageMap map[string]int, includeNav bool) (svg []byte, err error) {
|
||||
func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts d2svg.RenderOpts, outputPath string, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram, doc *pdf.GoFPDF, boardPath []pdf.BoardTitle, pageMap map[string]int, includeNav bool) (svg []byte, err error) {
|
||||
var isRoot bool
|
||||
if doc == nil {
|
||||
doc = pdf.Init()
|
||||
|
|
@ -976,18 +935,13 @@ func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opt
|
|||
scale = go2.Pointer(1.)
|
||||
}
|
||||
|
||||
renderOpts := &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
Scale: scale,
|
||||
ThemeID: opts.ThemeID,
|
||||
DarkThemeID: opts.DarkThemeID,
|
||||
ThemeOverrides: opts.ThemeOverrides,
|
||||
DarkThemeOverrides: opts.DarkThemeOverrides,
|
||||
OmitVersion: opts.OmitVersion,
|
||||
}
|
||||
svg, err = d2svg.Render(diagram, renderOpts)
|
||||
svg, err = d2svg.Render(diagram, &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
Scale: scale,
|
||||
ThemeID: opts.ThemeID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -999,13 +953,13 @@ func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opt
|
|||
|
||||
cacheImages := ms.Env.Getenv("IMG_CACHE") == "1"
|
||||
l := simplelog.FromCmdLog(ms.Log)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, inputPath, svg, cacheImages)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, svg, cacheImages)
|
||||
svg, bundleErr2 := imgbundler.BundleRemote(ctx, l, svg, cacheImages)
|
||||
bundleErr = multierr.Combine(bundleErr, bundleErr2)
|
||||
if bundleErr != nil {
|
||||
return svg, bundleErr
|
||||
}
|
||||
svg = appendix.Append(diagram, renderOpts, ruler, svg)
|
||||
svg = appendix.Append(diagram, ruler, svg)
|
||||
|
||||
pngImg, err := ConvertSVG(ms, page, svg)
|
||||
if err != nil {
|
||||
|
|
@ -1032,7 +986,7 @@ func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opt
|
|||
Name: dl.Root.Label,
|
||||
BoardID: strings.Join([]string{boardPath[len(boardPath)-1].BoardID, LAYERS, dl.Name}, "."),
|
||||
})
|
||||
_, err := renderPDF(ctx, ms, plugin, opts, inputPath, "", page, ruler, dl, doc, path, pageMap, includeNav)
|
||||
_, err := renderPDF(ctx, ms, plugin, opts, "", page, ruler, dl, doc, path, pageMap, includeNav)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1042,7 +996,7 @@ func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opt
|
|||
Name: dl.Root.Label,
|
||||
BoardID: strings.Join([]string{boardPath[len(boardPath)-1].BoardID, SCENARIOS, dl.Name}, "."),
|
||||
})
|
||||
_, err := renderPDF(ctx, ms, plugin, opts, inputPath, "", page, ruler, dl, doc, path, pageMap, includeNav)
|
||||
_, err := renderPDF(ctx, ms, plugin, opts, "", page, ruler, dl, doc, path, pageMap, includeNav)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1052,7 +1006,7 @@ func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opt
|
|||
Name: dl.Root.Label,
|
||||
BoardID: strings.Join([]string{boardPath[len(boardPath)-1].BoardID, STEPS, dl.Name}, "."),
|
||||
})
|
||||
_, err := renderPDF(ctx, ms, plugin, opts, inputPath, "", page, ruler, dl, doc, path, pageMap, includeNav)
|
||||
_, err := renderPDF(ctx, ms, plugin, opts, "", page, ruler, dl, doc, path, pageMap, includeNav)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1068,7 +1022,7 @@ func renderPDF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opt
|
|||
return svg, nil
|
||||
}
|
||||
|
||||
func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Presentation, plugin d2plugin.Plugin, opts d2svg.RenderOpts, ruler *textmeasure.Ruler, inputPath, outputPath string, page playwright.Page, diagram *d2target.Diagram, boardPath []pptx.BoardTitle, boardIDToIndex map[string]int) ([]byte, error) {
|
||||
func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Presentation, plugin d2plugin.Plugin, opts d2svg.RenderOpts, ruler *textmeasure.Ruler, outputPath string, page playwright.Page, diagram *d2target.Diagram, boardPath []pptx.BoardTitle, boardIDToIndex map[string]int) ([]byte, error) {
|
||||
var svg []byte
|
||||
if !diagram.IsFolderOnly {
|
||||
// gofpdf will print the png img with a slight filter
|
||||
|
|
@ -1084,18 +1038,12 @@ func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Present
|
|||
|
||||
var err error
|
||||
|
||||
renderOpts := &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
Scale: scale,
|
||||
ThemeID: opts.ThemeID,
|
||||
DarkThemeID: opts.DarkThemeID,
|
||||
ThemeOverrides: opts.ThemeOverrides,
|
||||
DarkThemeOverrides: opts.DarkThemeOverrides,
|
||||
OmitVersion: opts.OmitVersion,
|
||||
}
|
||||
svg, err = d2svg.Render(diagram, renderOpts)
|
||||
svg, err = d2svg.Render(diagram, &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
Scale: scale,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1107,14 +1055,14 @@ func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Present
|
|||
|
||||
cacheImages := ms.Env.Getenv("IMG_CACHE") == "1"
|
||||
l := simplelog.FromCmdLog(ms.Log)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, inputPath, svg, cacheImages)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, svg, cacheImages)
|
||||
svg, bundleErr2 := imgbundler.BundleRemote(ctx, l, svg, cacheImages)
|
||||
bundleErr = multierr.Combine(bundleErr, bundleErr2)
|
||||
if bundleErr != nil {
|
||||
return nil, bundleErr
|
||||
}
|
||||
|
||||
svg = appendix.Append(diagram, renderOpts, ruler, svg)
|
||||
svg = appendix.Append(diagram, ruler, svg)
|
||||
|
||||
pngImg, err := ConvertSVG(ms, page, svg)
|
||||
if err != nil {
|
||||
|
|
@ -1172,7 +1120,7 @@ func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Present
|
|||
BoardID: boardID,
|
||||
LinkToSlide: boardIDToIndex[boardID] + 1,
|
||||
})
|
||||
_, err := renderPPTX(ctx, ms, presentation, plugin, opts, ruler, inputPath, "", page, dl, path, boardIDToIndex)
|
||||
_, err := renderPPTX(ctx, ms, presentation, plugin, opts, ruler, "", page, dl, path, boardIDToIndex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1184,7 +1132,7 @@ func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Present
|
|||
BoardID: boardID,
|
||||
LinkToSlide: boardIDToIndex[boardID] + 1,
|
||||
})
|
||||
_, err := renderPPTX(ctx, ms, presentation, plugin, opts, ruler, inputPath, "", page, dl, path, boardIDToIndex)
|
||||
_, err := renderPPTX(ctx, ms, presentation, plugin, opts, ruler, "", page, dl, path, boardIDToIndex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1196,7 +1144,7 @@ func renderPPTX(ctx context.Context, ms *xmain.State, presentation *pptx.Present
|
|||
BoardID: boardID,
|
||||
LinkToSlide: boardIDToIndex[boardID] + 1,
|
||||
})
|
||||
_, err := renderPPTX(ctx, ms, presentation, plugin, opts, ruler, inputPath, "", page, dl, path, boardIDToIndex)
|
||||
_, err := renderPPTX(ctx, ms, presentation, plugin, opts, ruler, "", page, dl, path, boardIDToIndex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1220,6 +1168,11 @@ func getFileName(path string) string {
|
|||
return strings.TrimSuffix(filepath.Base(path), ext)
|
||||
}
|
||||
|
||||
// TODO: remove after removing slog
|
||||
func DiscardSlog(ctx context.Context) context.Context {
|
||||
return ctxlog.With(ctx, slog.Make(sloghuman.Sink(io.Discard)))
|
||||
}
|
||||
|
||||
func populateLayoutOpts(ctx context.Context, ms *xmain.State, ps []d2plugin.Plugin) error {
|
||||
pluginFlags, err := d2plugin.ListPluginFlags(ctx, ps)
|
||||
if err != nil {
|
||||
|
|
@ -1323,7 +1276,7 @@ func buildBoardIDToIndex(diagram *d2target.Diagram, dictionary map[string]int, p
|
|||
return dictionary
|
||||
}
|
||||
|
||||
func renderPNGsForGIF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts d2svg.RenderOpts, ruler *textmeasure.Ruler, page playwright.Page, inputPath string, diagram *d2target.Diagram) (svg []byte, pngs [][]byte, err error) {
|
||||
func renderPNGsForGIF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, opts d2svg.RenderOpts, ruler *textmeasure.Ruler, page playwright.Page, diagram *d2target.Diagram) (svg []byte, pngs [][]byte, err error) {
|
||||
if !diagram.IsFolderOnly {
|
||||
|
||||
var scale *float64
|
||||
|
|
@ -1332,18 +1285,12 @@ func renderPNGsForGIF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plug
|
|||
} else {
|
||||
scale = go2.Pointer(1.)
|
||||
}
|
||||
renderOpts := &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
Scale: scale,
|
||||
ThemeID: opts.ThemeID,
|
||||
DarkThemeID: opts.DarkThemeID,
|
||||
ThemeOverrides: opts.ThemeOverrides,
|
||||
DarkThemeOverrides: opts.DarkThemeOverrides,
|
||||
OmitVersion: opts.OmitVersion,
|
||||
}
|
||||
svg, err = d2svg.Render(diagram, renderOpts)
|
||||
svg, err = d2svg.Render(diagram, &d2svg.RenderOpts{
|
||||
Pad: opts.Pad,
|
||||
Sketch: opts.Sketch,
|
||||
Center: opts.Center,
|
||||
Scale: scale,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
|
@ -1355,14 +1302,14 @@ func renderPNGsForGIF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plug
|
|||
|
||||
cacheImages := ms.Env.Getenv("IMG_CACHE") == "1"
|
||||
l := simplelog.FromCmdLog(ms.Log)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, inputPath, svg, cacheImages)
|
||||
svg, bundleErr := imgbundler.BundleLocal(ctx, l, svg, cacheImages)
|
||||
svg, bundleErr2 := imgbundler.BundleRemote(ctx, l, svg, cacheImages)
|
||||
bundleErr = multierr.Combine(bundleErr, bundleErr2)
|
||||
if bundleErr != nil {
|
||||
return nil, nil, bundleErr
|
||||
}
|
||||
|
||||
svg = appendix.Append(diagram, renderOpts, ruler, svg)
|
||||
svg = appendix.Append(diagram, ruler, svg)
|
||||
|
||||
pngImg, err := ConvertSVG(ms, page, svg)
|
||||
if err != nil {
|
||||
|
|
@ -1372,21 +1319,21 @@ func renderPNGsForGIF(ctx context.Context, ms *xmain.State, plugin d2plugin.Plug
|
|||
}
|
||||
|
||||
for _, dl := range diagram.Layers {
|
||||
_, layerPNGs, err := renderPNGsForGIF(ctx, ms, plugin, opts, ruler, page, inputPath, dl)
|
||||
_, layerPNGs, err := renderPNGsForGIF(ctx, ms, plugin, opts, ruler, page, dl)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pngs = append(pngs, layerPNGs...)
|
||||
}
|
||||
for _, dl := range diagram.Scenarios {
|
||||
_, scenarioPNGs, err := renderPNGsForGIF(ctx, ms, plugin, opts, ruler, page, inputPath, dl)
|
||||
_, scenarioPNGs, err := renderPNGsForGIF(ctx, ms, plugin, opts, ruler, page, dl)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pngs = append(pngs, scenarioPNGs...)
|
||||
}
|
||||
for _, dl := range diagram.Steps {
|
||||
_, stepsPNGs, err := renderPNGsForGIF(ctx, ms, plugin, opts, ruler, page, inputPath, dl)
|
||||
_, stepsPNGs, err := renderPNGsForGIF(ctx, ms, plugin, opts, ruler, page, dl)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
|
@ -1414,15 +1361,6 @@ func AnimatePNGs(ms *xmain.State, pngs [][]byte, animIntervalMs int) ([]byte, er
|
|||
return xgif.AnimatePNGs(pngs, animIntervalMs)
|
||||
}
|
||||
|
||||
func Write(ms *xmain.State, path string, out []byte) error {
|
||||
err := ms.AtomicWritePath(path, out)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
ms.Log.Debug.Printf("atomic write failed: %s, trying non-atomic write", err.Error())
|
||||
return ms.WritePath(path, out)
|
||||
}
|
||||
|
||||
func init() {
|
||||
log.Init()
|
||||
ctxlog.Init()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,75 +0,0 @@
|
|||
package d2cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"oss.terrastruct.com/d2/lib/urlenc"
|
||||
"oss.terrastruct.com/util-go/xbrowser"
|
||||
"oss.terrastruct.com/util-go/xmain"
|
||||
)
|
||||
|
||||
func playCmd(ctx context.Context, ms *xmain.State) error {
|
||||
if len(ms.Opts.Flags.Args()) != 2 {
|
||||
return xmain.UsageErrorf("play must be passed one argument: either a filepath or '-' for stdin")
|
||||
}
|
||||
filepath := ms.Opts.Flags.Args()[1]
|
||||
|
||||
theme, err := ms.Opts.Flags.GetInt64("theme")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sketch, err := ms.Opts.Flags.GetBool("sketch")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var sketchNumber int
|
||||
if sketch {
|
||||
sketchNumber = 1
|
||||
} else {
|
||||
sketchNumber = 0
|
||||
}
|
||||
|
||||
fileRaw, err := readInput(filepath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
encoded, err := urlenc.Encode(fileRaw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://play.d2lang.com/?script=%s&sketch=%d&theme=%d&", encoded, sketchNumber, theme)
|
||||
openBrowser(ctx, ms, url)
|
||||
return nil
|
||||
}
|
||||
|
||||
func readInput(filepath string) (string, error) {
|
||||
if filepath == "-" {
|
||||
data, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading from stdin: %w", err)
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filepath)
|
||||
if err != nil {
|
||||
return "", xmain.UsageErrorf(err.Error())
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func openBrowser(ctx context.Context, ms *xmain.State, url string) {
|
||||
ms.Log.Info.Printf("opening playground: %s", url)
|
||||
|
||||
err := xbrowser.Open(ctx, ms.Env, url)
|
||||
if err != nil {
|
||||
ms.Log.Warn.Printf("failed to open browser to %v: %v", url, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -27,7 +27,7 @@ function init(reconnectDelay) {
|
|||
const parsedXML = new DOMParser().parseFromString(msg.svg, "text/xml");
|
||||
d2SVG.replaceChildren(parsedXML.documentElement);
|
||||
changeFavicon("/static/favicon.ico");
|
||||
const svgEl = d2SVG.querySelector(".d2-svg");
|
||||
const svgEl = d2SVG.querySelector("#d2-svg");
|
||||
// just use inner SVG in watch mode
|
||||
svgEl.parentElement.replaceWith(svgEl);
|
||||
let width = parseInt(svgEl.getAttribute("width"), 10);
|
||||
|
|
|
|||
|
|
@ -1,41 +0,0 @@
|
|||
package d2cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"oss.terrastruct.com/d2/d2lib"
|
||||
"oss.terrastruct.com/util-go/xdefer"
|
||||
"oss.terrastruct.com/util-go/xmain"
|
||||
)
|
||||
|
||||
func validateCmd(ctx context.Context, ms *xmain.State) (err error) {
|
||||
defer xdefer.Errorf(&err, "")
|
||||
|
||||
ms.Opts = xmain.NewOpts(ms.Env, ms.Opts.Flags.Args()[1:])
|
||||
if len(ms.Opts.Args) == 0 {
|
||||
return xmain.UsageErrorf("input argument required")
|
||||
}
|
||||
|
||||
inputPath := ms.Opts.Args[0]
|
||||
if inputPath != "-" {
|
||||
inputPath = ms.AbsPath(inputPath)
|
||||
}
|
||||
|
||||
input, err := ms.ReadPath(inputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = d2lib.Parse(ctx, string(input), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if inputPath == "-" {
|
||||
inputPath = "Input"
|
||||
}
|
||||
|
||||
fmt.Printf("Success! [%s] is valid D2.\n", inputPath)
|
||||
return nil
|
||||
}
|
||||
|
|
@ -17,9 +17,9 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"nhooyr.io/websocket"
|
||||
"nhooyr.io/websocket/wsjson"
|
||||
|
||||
"oss.terrastruct.com/util-go/xbrowser"
|
||||
|
||||
|
|
@ -57,7 +57,6 @@ type watcherOpts struct {
|
|||
forceAppendix bool
|
||||
pw png.Playwright
|
||||
fontFamily *d2fonts.FontFamily
|
||||
outputFormat exportExtension
|
||||
}
|
||||
|
||||
type watcher struct {
|
||||
|
|
@ -264,12 +263,6 @@ func (w *watcher) watchLoop(ctx context.Context) error {
|
|||
return errors.New("fsnotify watcher closed")
|
||||
}
|
||||
w.ms.Log.Debug.Printf("received file system event %v", ev)
|
||||
|
||||
if isTemp, reason := isBackupFile(ev.Name); isTemp {
|
||||
w.ms.Log.Debug.Printf("skipping event for %q: detected as %s", w.ms.HumanPath(ev.Name), reason)
|
||||
continue
|
||||
}
|
||||
|
||||
mt, err := w.ensureAddWatch(ctx, ev.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -355,11 +348,6 @@ func (w *watcher) ensureAddWatch(ctx context.Context, path string) (time.Time, e
|
|||
}
|
||||
|
||||
func (w *watcher) addWatch(ctx context.Context, path string) (time.Time, error) {
|
||||
if isTemp, reason := isBackupFile(path); isTemp {
|
||||
w.ms.Log.Debug.Printf("skipping watch for %q: detected as %s", w.ms.HumanPath(path), reason)
|
||||
return time.Time{}, nil
|
||||
}
|
||||
|
||||
err := w.fw.Add(path)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
|
|
@ -442,7 +430,7 @@ func (w *watcher) compileLoop(ctx context.Context) error {
|
|||
if w.boardPath != "" {
|
||||
boardPath = strings.Split(w.boardPath, string(os.PathSeparator))
|
||||
}
|
||||
svg, _, err := compile(ctx, w.ms, w.plugins, &fs, w.layout, w.renderOpts, w.fontFamily, w.animateInterval, w.inputPath, w.outputPath, boardPath, false, w.bundle, w.forceAppendix, w.pw.Page, w.outputFormat)
|
||||
svg, _, err := compile(ctx, w.ms, w.plugins, &fs, w.layout, w.renderOpts, w.fontFamily, w.animateInterval, w.inputPath, w.outputPath, boardPath, false, w.bundle, w.forceAppendix, w.pw.Page)
|
||||
w.boardpathMu.Unlock()
|
||||
errs := ""
|
||||
if err != nil {
|
||||
|
|
@ -532,11 +520,6 @@ func (w *watcher) handleRoot(hw http.ResponseWriter, r *http.Request) {
|
|||
if idx := strings.LastIndexByte(boardPath, '.'); idx != -1 {
|
||||
boardPath = boardPath[:idx]
|
||||
}
|
||||
// if path is "/index", we just want "/"
|
||||
boardPath = strings.TrimSuffix(boardPath, "/index")
|
||||
if boardPath == "index" {
|
||||
boardPath = ""
|
||||
}
|
||||
recompile := false
|
||||
if boardPath != w.boardPath {
|
||||
w.boardPath = boardPath
|
||||
|
|
@ -682,41 +665,3 @@ func (tfs *trackedFS) Open(name string) (fs.File, error) {
|
|||
}
|
||||
return f, err
|
||||
}
|
||||
|
||||
func isBackupFile(path string) (bool, string) {
|
||||
ext := filepath.Ext(path)
|
||||
baseName := filepath.Base(path)
|
||||
|
||||
// This list is based off of https://github.com/gohugoio/hugo/blob/master/commands/hugobuilder.go#L795
|
||||
switch {
|
||||
case strings.HasSuffix(ext, "~"):
|
||||
return true, "generic backup file (~)"
|
||||
case ext == ".swp":
|
||||
return true, "vim swap file"
|
||||
case ext == ".swx":
|
||||
return true, "vim swap file"
|
||||
case ext == ".tmp":
|
||||
return true, "generic temp file"
|
||||
case ext == ".DS_Store":
|
||||
return true, "OSX thumbnail"
|
||||
case ext == ".bck":
|
||||
return true, "Helix backup"
|
||||
case baseName == "4913":
|
||||
return true, "vim temp file"
|
||||
case strings.HasPrefix(ext, ".goutputstream"):
|
||||
return true, "GNOME temp file"
|
||||
case strings.HasSuffix(ext, "jb_old___"):
|
||||
return true, "IntelliJ old backup"
|
||||
case strings.HasSuffix(ext, "jb_tmp___"):
|
||||
return true, "IntelliJ temp file"
|
||||
case strings.HasSuffix(ext, "jb_bak___"):
|
||||
return true, "IntelliJ backup"
|
||||
case strings.HasPrefix(ext, ".sb-"):
|
||||
return true, "Byword temp file"
|
||||
case strings.HasPrefix(baseName, ".#"):
|
||||
return true, "Emacs lock file"
|
||||
case strings.HasPrefix(baseName, "#"):
|
||||
return true, "Emacs temp file"
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -8,7 +8,6 @@ import (
|
|||
|
||||
"oss.terrastruct.com/util-go/go2"
|
||||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2parser"
|
||||
"oss.terrastruct.com/d2/d2renderers/d2fonts"
|
||||
|
|
@ -16,7 +15,6 @@ import (
|
|||
"oss.terrastruct.com/d2/d2themes"
|
||||
"oss.terrastruct.com/d2/lib/color"
|
||||
"oss.terrastruct.com/d2/lib/geo"
|
||||
"oss.terrastruct.com/d2/lib/label"
|
||||
)
|
||||
|
||||
func Export(ctx context.Context, g *d2graph.Graph, fontFamily *d2fonts.FontFamily) (*d2target.Diagram, error) {
|
||||
|
|
@ -47,26 +45,6 @@ func Export(ctx context.Context, g *d2graph.Graph, fontFamily *d2fonts.FontFamil
|
|||
diagram.Connections[i] = toConnection(g.Edges[i], g.Theme)
|
||||
}
|
||||
|
||||
if g.Legend != nil {
|
||||
legend := &d2target.Legend{}
|
||||
|
||||
if len(g.Legend.Objects) > 0 {
|
||||
legend.Shapes = make([]d2target.Shape, len(g.Legend.Objects))
|
||||
for i, obj := range g.Legend.Objects {
|
||||
legend.Shapes[i] = toShape(obj, g)
|
||||
}
|
||||
}
|
||||
|
||||
if len(g.Legend.Edges) > 0 {
|
||||
legend.Connections = make([]d2target.Connection, len(g.Legend.Edges))
|
||||
for i, edge := range g.Legend.Edges {
|
||||
legend.Connections[i] = toConnection(edge, g.Theme)
|
||||
}
|
||||
}
|
||||
|
||||
diagram.Legend = legend
|
||||
}
|
||||
|
||||
return diagram, nil
|
||||
}
|
||||
|
||||
|
|
@ -99,46 +77,6 @@ func applyTheme(shape *d2target.Shape, obj *d2graph.Object, theme *d2themes.Them
|
|||
if theme.SpecialRules.Mono {
|
||||
shape.FontFamily = "mono"
|
||||
}
|
||||
if theme.SpecialRules.C4 && len(obj.ChildrenArray) > 0 {
|
||||
if obj.Style.Fill == nil {
|
||||
shape.Fill = "transparent"
|
||||
}
|
||||
if obj.Style.Stroke == nil {
|
||||
shape.Stroke = color.AA2
|
||||
}
|
||||
if obj.Style.StrokeDash == nil {
|
||||
shape.StrokeDash = 5
|
||||
}
|
||||
if obj.Style.FontColor == nil {
|
||||
shape.Color = color.N1
|
||||
}
|
||||
}
|
||||
if theme.SpecialRules.C4 && obj.Level() == 1 && len(obj.ChildrenArray) == 0 &&
|
||||
obj.Shape.Value != d2target.ShapePerson && obj.Shape.Value != d2target.ShapeC4Person {
|
||||
if obj.Style.Fill == nil {
|
||||
shape.Fill = color.B6
|
||||
}
|
||||
if obj.Style.Stroke == nil {
|
||||
shape.Stroke = color.B5
|
||||
}
|
||||
}
|
||||
if theme.SpecialRules.C4 && (obj.Shape.Value == d2target.ShapePerson || obj.Shape.Value == d2target.ShapeC4Person) {
|
||||
if obj.Style.Fill == nil {
|
||||
shape.Fill = color.B2
|
||||
}
|
||||
if obj.Style.Stroke == nil {
|
||||
shape.Stroke = color.B1
|
||||
}
|
||||
}
|
||||
if theme.SpecialRules.C4 && obj.Level() > 1 && len(obj.ChildrenArray) == 0 &&
|
||||
obj.Shape.Value != d2target.ShapePerson && obj.Shape.Value != d2target.ShapeC4Person {
|
||||
if obj.Style.Fill == nil {
|
||||
shape.Fill = color.B4
|
||||
}
|
||||
if obj.Style.Stroke == nil {
|
||||
shape.Stroke = color.B3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -194,9 +132,6 @@ func applyStyles(shape *d2target.Shape, obj *d2graph.Object) {
|
|||
if obj.Style.DoubleBorder != nil {
|
||||
shape.DoubleBorder, _ = strconv.ParseBool(obj.Style.DoubleBorder.Value)
|
||||
}
|
||||
if obj.IconStyle.BorderRadius != nil {
|
||||
shape.IconBorderRadius, _ = strconv.Atoi(obj.IconStyle.BorderRadius.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func toShape(obj *d2graph.Object, g *d2graph.Graph) d2target.Shape {
|
||||
|
|
@ -209,7 +144,6 @@ func toShape(obj *d2graph.Object, g *d2graph.Graph) d2target.Shape {
|
|||
shape.Pos = d2target.NewPoint(int(obj.TopLeft.X), int(obj.TopLeft.Y))
|
||||
shape.Width = int(obj.Width)
|
||||
shape.Height = int(obj.Height)
|
||||
shape.Language = obj.Language
|
||||
|
||||
text := obj.Text()
|
||||
shape.Bold = text.IsBold
|
||||
|
|
@ -228,18 +162,12 @@ func toShape(obj *d2graph.Object, g *d2graph.Graph) d2target.Shape {
|
|||
applyStyles(shape, obj)
|
||||
applyTheme(shape, obj, g.Theme)
|
||||
shape.Color = text.GetColor(shape.Italic)
|
||||
if g.Theme != nil && g.Theme.SpecialRules.C4 {
|
||||
if obj.Style.FontColor == nil {
|
||||
if len(obj.ChildrenArray) > 0 {
|
||||
shape.Color = color.N1
|
||||
} else {
|
||||
shape.Color = color.N7
|
||||
}
|
||||
}
|
||||
}
|
||||
applyStyles(shape, obj)
|
||||
|
||||
switch strings.ToLower(obj.Shape.Value) {
|
||||
switch obj.Shape.Value {
|
||||
case d2target.ShapeCode, d2target.ShapeText:
|
||||
shape.Language = obj.Language
|
||||
shape.Label = obj.Label.Value
|
||||
case d2target.ShapeClass:
|
||||
shape.Class = *obj.Class
|
||||
// The label is the header for classes and tables, which is set in client to be 4 px larger than the object's set font size
|
||||
|
|
@ -266,9 +194,6 @@ func toShape(obj *d2graph.Object, g *d2graph.Graph) d2target.Shape {
|
|||
if obj.Tooltip != nil {
|
||||
shape.Tooltip = obj.Tooltip.Value
|
||||
}
|
||||
if obj.Style.Animated != nil {
|
||||
shape.Animated, _ = strconv.ParseBool(obj.Style.Animated.Value)
|
||||
}
|
||||
if obj.Link != nil {
|
||||
shape.Link = obj.Link.Value
|
||||
shape.PrettyLink = toPrettyLink(g, obj.Link.Value)
|
||||
|
|
@ -407,18 +332,7 @@ func toConnection(edge *d2graph.Edge, theme *d2themes.Theme) d2target.Connection
|
|||
if edge.Tooltip != nil {
|
||||
connection.Tooltip = edge.Tooltip.Value
|
||||
}
|
||||
if edge.Icon != nil {
|
||||
connection.Icon = edge.Icon
|
||||
if edge.IconPosition != nil {
|
||||
connection.IconPosition = (d2ast.LabelPositionsMapping[edge.IconPosition.Value]).String()
|
||||
} else {
|
||||
connection.IconPosition = label.InsideMiddleCenter.String()
|
||||
}
|
||||
}
|
||||
|
||||
if edge.IconStyle.BorderRadius != nil {
|
||||
connection.IconBorderRadius, _ = strconv.ParseFloat(edge.IconStyle.BorderRadius.Value, 64)
|
||||
}
|
||||
connection.Icon = edge.Icon
|
||||
|
||||
if edge.Style.Italic != nil {
|
||||
connection.Italic, _ = strconv.ParseBool(edge.Style.Italic.Value)
|
||||
|
|
@ -440,9 +354,6 @@ func toConnection(edge *d2graph.Edge, theme *d2themes.Theme) d2target.Connection
|
|||
if edge.Style.Font != nil {
|
||||
connection.FontFamily = edge.Style.Font.Value
|
||||
}
|
||||
if edge.Link != nil {
|
||||
connection.Link = edge.Link.Value
|
||||
}
|
||||
connection.Label = text.Text
|
||||
connection.LabelWidth = text.Dimensions.Width
|
||||
connection.LabelHeight = text.Dimensions.Height
|
||||
|
|
@ -466,17 +377,5 @@ func toConnection(edge *d2graph.Edge, theme *d2themes.Theme) d2target.Connection
|
|||
connection.Src = edge.Src.AbsID()
|
||||
connection.Dst = edge.Dst.AbsID()
|
||||
|
||||
if theme != nil && theme.SpecialRules.C4 {
|
||||
if edge.Style.StrokeDash == nil {
|
||||
connection.StrokeDash = 5
|
||||
}
|
||||
if edge.Style.Stroke == nil {
|
||||
connection.Stroke = color.AA4
|
||||
}
|
||||
if edge.Style.FontColor == nil {
|
||||
connection.Color = color.N2
|
||||
}
|
||||
}
|
||||
|
||||
return *connection
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,12 @@ package d2exporter_test
|
|||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cdr.dev/slog"
|
||||
|
||||
tassert "github.com/stretchr/testify/assert"
|
||||
|
||||
"oss.terrastruct.com/util-go/assert"
|
||||
|
|
@ -39,7 +40,6 @@ func TestExport(t *testing.T) {
|
|||
t.Run("connection", testConnection)
|
||||
t.Run("label", testLabel)
|
||||
t.Run("theme", testTheme)
|
||||
t.Run("legend", testLegend)
|
||||
}
|
||||
|
||||
func testShape(t *testing.T) {
|
||||
|
|
@ -205,30 +205,6 @@ func testTheme(t *testing.T) {
|
|||
runa(t, tcs)
|
||||
}
|
||||
|
||||
func testLegend(t *testing.T) {
|
||||
tcs := []testCase{
|
||||
{
|
||||
name: "basic_legend",
|
||||
dsl: `vars: {
|
||||
d2-legend: {
|
||||
legend: {
|
||||
l1: Rectangles {shape: rectangle}
|
||||
l2: Ovals {shape: oval}
|
||||
l1 -> l2: Connection
|
||||
}
|
||||
}
|
||||
}
|
||||
x: {shape: rectangle}
|
||||
y: {shape: oval}
|
||||
x -> y: connects
|
||||
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
runa(t, tcs)
|
||||
}
|
||||
|
||||
func runa(t *testing.T, tcs []testCase) {
|
||||
for _, tc := range tcs {
|
||||
tc := tc
|
||||
|
|
@ -242,7 +218,7 @@ func runa(t *testing.T, tcs []testCase) {
|
|||
|
||||
func run(t *testing.T, tc testCase) {
|
||||
ctx := context.Background()
|
||||
ctx = log.WithTB(ctx, t)
|
||||
ctx = log.WithTB(ctx, t, nil)
|
||||
ctx = log.Leveled(ctx, slog.LevelDebug)
|
||||
|
||||
g, config, err := d2compiler.Compile("", strings.NewReader(tc.dsl), &d2compiler.CompileOptions{
|
||||
|
|
@ -301,7 +277,7 @@ func run(t *testing.T, tc testCase) {
|
|||
// TestHashID tests that 2 diagrams with different theme configs do not equal each other
|
||||
func TestHashID(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = log.WithTB(ctx, t)
|
||||
ctx = log.WithTB(ctx, t, nil)
|
||||
ctx = log.Leveled(ctx, slog.LevelDebug)
|
||||
|
||||
aString := `
|
||||
|
|
@ -328,10 +304,10 @@ a -> b
|
|||
db, err := compile(ctx, bString)
|
||||
assert.JSON(t, nil, err)
|
||||
|
||||
hashA, err := da.HashID(nil)
|
||||
hashA, err := da.HashID()
|
||||
assert.JSON(t, nil, err)
|
||||
|
||||
hashB, err := db.HashID(nil)
|
||||
hashB, err := db.HashID()
|
||||
assert.JSON(t, nil, err)
|
||||
|
||||
assert.NotEqual(t, hashA, hashB)
|
||||
|
|
|
|||
|
|
@ -42,12 +42,6 @@ func (p *printer) node(n d2ast.Node) {
|
|||
p.blockComment(n)
|
||||
case *d2ast.Null:
|
||||
p.sb.WriteString("null")
|
||||
case *d2ast.Suspension:
|
||||
if n.Value {
|
||||
p.sb.WriteString("suspend")
|
||||
} else {
|
||||
p.sb.WriteString("unsuspend")
|
||||
}
|
||||
case *d2ast.Boolean:
|
||||
p.sb.WriteString(strconv.FormatBool(n.Value))
|
||||
case *d2ast.Number:
|
||||
|
|
@ -127,7 +121,7 @@ func (p *printer) blockComment(bc *d2ast.BlockComment) {
|
|||
}
|
||||
|
||||
func (p *printer) interpolationBoxes(boxes []d2ast.InterpolationBox, isDoubleString bool) {
|
||||
for i, b := range boxes {
|
||||
for _, b := range boxes {
|
||||
if b.Substitution != nil {
|
||||
p.substitution(b.Substitution)
|
||||
continue
|
||||
|
|
@ -140,17 +134,6 @@ func (p *printer) interpolationBoxes(boxes []d2ast.InterpolationBox, isDoubleStr
|
|||
s = escapeUnquotedValue(*b.String, p.inKey)
|
||||
}
|
||||
b.StringRaw = &s
|
||||
} else if i > 0 && boxes[i-1].Substitution != nil {
|
||||
// If this string follows a substitution, we need to make sure to use
|
||||
// the actual string content, not the raw value which might be incorrect
|
||||
s := *b.String
|
||||
b.StringRaw = &s
|
||||
}
|
||||
if !isDoubleString {
|
||||
if _, ok := d2ast.ReservedKeywords[strings.ToLower(*b.StringRaw)]; ok {
|
||||
s := strings.ToLower(*b.StringRaw)
|
||||
b.StringRaw = &s
|
||||
}
|
||||
}
|
||||
p.sb.WriteString(*b.StringRaw)
|
||||
}
|
||||
|
|
@ -304,18 +287,11 @@ func (p *printer) _map(m *d2ast.Map) {
|
|||
if nb.IsBoardNode() {
|
||||
switch nb.MapKey.Key.Path[0].Unbox().ScalarString() {
|
||||
case "layers":
|
||||
// remove useless
|
||||
if nb.MapKey.Value.Map != nil && len(nb.MapKey.Value.Map.Nodes) > 0 {
|
||||
layerNodes = append(layerNodes, nb)
|
||||
}
|
||||
layerNodes = append(layerNodes, nb)
|
||||
case "scenarios":
|
||||
if nb.MapKey.Value.Map != nil && len(nb.MapKey.Value.Map.Nodes) > 0 {
|
||||
scenarioNodes = append(scenarioNodes, nb)
|
||||
}
|
||||
scenarioNodes = append(scenarioNodes, nb)
|
||||
case "steps":
|
||||
if nb.MapKey.Value.Map != nil && len(nb.MapKey.Value.Map.Nodes) > 0 {
|
||||
stepNodes = append(stepNodes, nb)
|
||||
}
|
||||
stepNodes = append(stepNodes, nb)
|
||||
}
|
||||
prev = n
|
||||
continue
|
||||
|
|
@ -357,14 +333,12 @@ func (p *printer) _map(m *d2ast.Map) {
|
|||
n := boards[i].Unbox()
|
||||
// if this board is the very first line of the file, don't add an extra newline
|
||||
if n.GetRange().Start.Line != 0 {
|
||||
p.sb.WriteByte('\n')
|
||||
p.newline()
|
||||
}
|
||||
// if scope only has boards, don't newline the first board
|
||||
if i != 0 || len(m.Nodes) > len(boards) {
|
||||
p.sb.WriteByte('\n')
|
||||
p.newline()
|
||||
}
|
||||
|
||||
p.sb.WriteString(p.indentStr)
|
||||
p.node(n)
|
||||
prev = n
|
||||
}
|
||||
|
|
@ -384,9 +358,6 @@ func (p *printer) _map(m *d2ast.Map) {
|
|||
func (p *printer) mapKey(mk *d2ast.Key) {
|
||||
if mk.Ampersand {
|
||||
p.sb.WriteByte('&')
|
||||
} else if mk.NotAmpersand {
|
||||
p.sb.WriteByte('!')
|
||||
p.sb.WriteByte('&')
|
||||
}
|
||||
if mk.Key != nil {
|
||||
p.key(mk.Key)
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ x -> y
|
|||
exp: `x -> y
|
||||
`,
|
||||
},
|
||||
|
||||
{
|
||||
name: "complex",
|
||||
in: `
|
||||
|
|
@ -152,7 +153,7 @@ meow
|
|||
diagram: int {constraint: foreign_key}
|
||||
}
|
||||
meow <- diagrams.id
|
||||
|
||||
|
||||
steps: {
|
||||
shape: sql_table
|
||||
id: {type: int; constraint: primary_key}
|
||||
|
|
@ -664,8 +665,8 @@ x: @"x/../file"
|
|||
b: {
|
||||
e
|
||||
scenarios: {
|
||||
p: {
|
||||
x
|
||||
p: {
|
||||
x
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -677,14 +678,14 @@ x: @"x/../file"
|
|||
exp: `layers: {
|
||||
b: {
|
||||
e
|
||||
|
||||
|
||||
scenarios: {
|
||||
p: {
|
||||
x
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
steps: {
|
||||
a
|
||||
}
|
||||
|
|
@ -762,7 +763,7 @@ only-layers: {
|
|||
X
|
||||
Y
|
||||
}
|
||||
|
||||
|
||||
layers: {
|
||||
Z
|
||||
}
|
||||
|
|
@ -772,10 +773,10 @@ layers: {
|
|||
Test super nested: {
|
||||
base-layer
|
||||
last-layer
|
||||
|
||||
|
||||
layers: {
|
||||
layer-board
|
||||
|
||||
|
||||
layers: {
|
||||
grand-child-layer: {
|
||||
grand-child-board
|
||||
|
|
@ -788,7 +789,7 @@ layers: {
|
|||
scenarios: {
|
||||
scenario-1: {
|
||||
non-step
|
||||
|
||||
|
||||
steps: {
|
||||
step-1: {
|
||||
Test
|
||||
|
|
@ -828,83 +829,6 @@ mybox: {
|
|||
mybox: {
|
||||
label: prefix${test}suffix
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "not-filter",
|
||||
in: `jacob: {
|
||||
shape: circle
|
||||
}
|
||||
jeremy: {
|
||||
shape: rectangle
|
||||
}
|
||||
*: {
|
||||
!&shape: rectangle
|
||||
label: I'm not a rectangle
|
||||
}`,
|
||||
exp: `jacob: {
|
||||
shape: circle
|
||||
}
|
||||
jeremy: {
|
||||
shape: rectangle
|
||||
}
|
||||
*: {
|
||||
!&shape: rectangle
|
||||
label: I'm not a rectangle
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "lowercase-reserved",
|
||||
in: `jacob: {
|
||||
SHAPE: circle
|
||||
}
|
||||
jeremy.SHAPE: rectangle
|
||||
alice.STYLE.fill: red
|
||||
bob.style.FILL: red
|
||||
carmen.STYLE.FILL: red
|
||||
coop: {
|
||||
STYLE: {
|
||||
FILL: blue
|
||||
}
|
||||
}
|
||||
`,
|
||||
exp: `jacob: {
|
||||
shape: circle
|
||||
}
|
||||
jeremy.shape: rectangle
|
||||
alice.style.fill: red
|
||||
bob.style.fill: red
|
||||
carmen.style.fill: red
|
||||
coop: {
|
||||
style: {
|
||||
fill: blue
|
||||
}
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "remove-empty-boards",
|
||||
in: `k
|
||||
|
||||
layers
|
||||
scenarios: {}
|
||||
steps: asdf
|
||||
`,
|
||||
exp: `k
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "vars",
|
||||
in: `vars: {
|
||||
a: "a"
|
||||
b: "X${a})"
|
||||
}
|
||||
`,
|
||||
exp: `vars: {
|
||||
a: "a"
|
||||
b: "X${a})"
|
||||
}
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,7 +49,6 @@ type Graph struct {
|
|||
BaseAST *d2ast.Map `json:"-"`
|
||||
|
||||
Root *Object `json:"root"`
|
||||
Legend *Legend `json:"legend,omitempty"`
|
||||
Edges []*Edge `json:"edges"`
|
||||
Objects []*Object `json:"objects"`
|
||||
|
||||
|
|
@ -61,16 +60,6 @@ type Graph struct {
|
|||
|
||||
// Object.Level uses the location of a nested graph
|
||||
RootLevel int `json:"rootLevel,omitempty"`
|
||||
|
||||
// Currently this holds data embedded from source code configuration variables
|
||||
// Plugins only have access to exported graph, so this data structure allows
|
||||
// carrying arbitrary metadata that any plugin might handle
|
||||
Data map[string]interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
type Legend struct {
|
||||
Objects []*Object `json:"objects,omitempty"`
|
||||
Edges []*Edge `json:"edges,omitempty"`
|
||||
}
|
||||
|
||||
func NewGraph() *Graph {
|
||||
|
|
@ -90,66 +79,6 @@ func (g *Graph) RootBoard() *Graph {
|
|||
return g
|
||||
}
|
||||
|
||||
func (g *Graph) IDA() []string {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var parts []string
|
||||
|
||||
current := g
|
||||
for current != nil {
|
||||
if current.Name != "" {
|
||||
parts = append(parts, current.Name)
|
||||
}
|
||||
current = current.Parent
|
||||
}
|
||||
|
||||
for i := 0; i < len(parts)/2; i++ {
|
||||
j := len(parts) - 1 - i
|
||||
parts[i], parts[j] = parts[j], parts[i]
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return []string{"root"}
|
||||
}
|
||||
|
||||
parts = append([]string{"root"}, parts...)
|
||||
|
||||
if g.Parent != nil {
|
||||
var containerName string
|
||||
if len(g.Parent.Layers) > 0 {
|
||||
for _, l := range g.Parent.Layers {
|
||||
if l == g {
|
||||
containerName = "layers"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(g.Parent.Scenarios) > 0 {
|
||||
for _, s := range g.Parent.Scenarios {
|
||||
if s == g {
|
||||
containerName = "scenarios"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(g.Parent.Steps) > 0 {
|
||||
for _, s := range g.Parent.Steps {
|
||||
if s == g {
|
||||
containerName = "steps"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if containerName != "" {
|
||||
parts = append(parts[:1], append([]string{containerName}, parts[1:]...)...)
|
||||
}
|
||||
}
|
||||
|
||||
return parts
|
||||
}
|
||||
|
||||
type LayoutGraph func(context.Context, *Graph) error
|
||||
type RouteEdges func(context.Context, *Graph, []*Edge) error
|
||||
|
||||
|
|
@ -196,11 +125,10 @@ type Attributes struct {
|
|||
Label Scalar `json:"label"`
|
||||
LabelDimensions d2target.TextDimensions `json:"labelDimensions"`
|
||||
|
||||
Style Style `json:"style"`
|
||||
Icon *url.URL `json:"icon,omitempty"`
|
||||
IconStyle Style `json:"iconStyle"`
|
||||
Tooltip *Scalar `json:"tooltip,omitempty"`
|
||||
Link *Scalar `json:"link,omitempty"`
|
||||
Style Style `json:"style"`
|
||||
Icon *url.URL `json:"icon,omitempty"`
|
||||
Tooltip *Scalar `json:"tooltip,omitempty"`
|
||||
Link *Scalar `json:"link,omitempty"`
|
||||
|
||||
WidthAttr *Scalar `json:"width,omitempty"`
|
||||
HeightAttr *Scalar `json:"height,omitempty"`
|
||||
|
|
@ -269,7 +197,6 @@ type Reference struct {
|
|||
Scope *d2ast.Map `json:"-"`
|
||||
ScopeObj *Object `json:"-"`
|
||||
ScopeAST *d2ast.Map `json:"-"`
|
||||
IsVar bool `json:"-"`
|
||||
}
|
||||
|
||||
func (r Reference) MapKeyEdgeDest() bool {
|
||||
|
|
@ -325,24 +252,24 @@ func (s *Style) Apply(key, value string) error {
|
|||
if s.Stroke == nil {
|
||||
break
|
||||
}
|
||||
if !color.ValidColor(value) {
|
||||
return errors.New(`expected "stroke" to be a valid named color ("orange"), a hex code ("#f0ff3a"), or a gradient ("linear-gradient(red, blue)")`)
|
||||
if !go2.Contains(color.NamedColors, strings.ToLower(value)) && !color.ColorHexRegex.MatchString(value) {
|
||||
return errors.New(`expected "stroke" to be a valid named color ("orange") or a hex code ("#f0ff3a")`)
|
||||
}
|
||||
s.Stroke.Value = value
|
||||
case "fill":
|
||||
if s.Fill == nil {
|
||||
break
|
||||
}
|
||||
if !color.ValidColor(value) {
|
||||
return errors.New(`expected "fill" to be a valid named color ("orange"), a hex code ("#f0ff3a"), or a gradient ("linear-gradient(red, blue)")`)
|
||||
if !go2.Contains(color.NamedColors, strings.ToLower(value)) && !color.ColorHexRegex.MatchString(value) {
|
||||
return errors.New(`expected "fill" to be a valid named color ("orange") or a hex code ("#f0ff3a")`)
|
||||
}
|
||||
s.Fill.Value = value
|
||||
case "fill-pattern":
|
||||
if s.FillPattern == nil {
|
||||
break
|
||||
}
|
||||
if !go2.Contains(d2ast.FillPatterns, strings.ToLower(value)) {
|
||||
return fmt.Errorf(`expected "fill-pattern" to be one of: %s`, strings.Join(d2ast.FillPatterns, ", "))
|
||||
if !go2.Contains(FillPatterns, strings.ToLower(value)) {
|
||||
return fmt.Errorf(`expected "fill-pattern" to be one of: %s`, strings.Join(FillPatterns, ", "))
|
||||
}
|
||||
s.FillPattern.Value = value
|
||||
case "stroke-width":
|
||||
|
|
@ -420,8 +347,8 @@ func (s *Style) Apply(key, value string) error {
|
|||
if s.FontColor == nil {
|
||||
break
|
||||
}
|
||||
if !color.ValidColor(value) {
|
||||
return errors.New(`expected "font-color" to be a valid named color ("orange"), a hex code ("#f0ff3a"), or a gradient ("linear-gradient(red, blue)")`)
|
||||
if !go2.Contains(color.NamedColors, strings.ToLower(value)) && !color.ColorHexRegex.MatchString(value) {
|
||||
return errors.New(`expected "font-color" to be a valid named color ("orange") or a hex code ("#f0ff3a")`)
|
||||
}
|
||||
s.FontColor.Value = value
|
||||
case "animated":
|
||||
|
|
@ -482,8 +409,8 @@ func (s *Style) Apply(key, value string) error {
|
|||
if s.TextTransform == nil {
|
||||
break
|
||||
}
|
||||
if !go2.Contains(d2ast.TextTransforms, strings.ToLower(value)) {
|
||||
return fmt.Errorf(`expected "text-transform" to be one of (%s)`, strings.Join(d2ast.TextTransforms, ", "))
|
||||
if !go2.Contains(textTransforms, strings.ToLower(value)) {
|
||||
return fmt.Errorf(`expected "text-transform" to be one of (%s)`, strings.Join(textTransforms, ", "))
|
||||
}
|
||||
s.TextTransform.Value = value
|
||||
default:
|
||||
|
|
@ -571,7 +498,7 @@ func (obj *Object) GetFill() string {
|
|||
return color.AB5
|
||||
}
|
||||
|
||||
if strings.EqualFold(shape, d2target.ShapePerson) || strings.EqualFold(shape, d2target.ShapeC4Person) {
|
||||
if strings.EqualFold(shape, d2target.ShapePerson) {
|
||||
return color.B3
|
||||
}
|
||||
if strings.EqualFold(shape, d2target.ShapeDiamond) {
|
||||
|
|
@ -701,10 +628,7 @@ func (obj *Object) Text() *d2target.MText {
|
|||
}
|
||||
}
|
||||
|
||||
func (obj *Object) newObject(ids d2ast.String) *Object {
|
||||
id := d2format.Format(&d2ast.KeyPath{
|
||||
Path: []*d2ast.StringBox{d2ast.MakeValueBox(d2ast.RawString(ids.ScalarString(), true)).StringBox()},
|
||||
})
|
||||
func (obj *Object) newObject(id string) *Object {
|
||||
idval := id
|
||||
k, _ := d2parser.ParseKey(id)
|
||||
if k != nil && len(k.Path) > 0 {
|
||||
|
|
@ -717,6 +641,9 @@ func (obj *Object) newObject(ids d2ast.String) *Object {
|
|||
Label: Scalar{
|
||||
Value: idval,
|
||||
},
|
||||
Shape: Scalar{
|
||||
Value: d2target.ShapeRectangle,
|
||||
},
|
||||
},
|
||||
|
||||
Graph: obj.Graph,
|
||||
|
|
@ -740,7 +667,7 @@ func (obj *Object) HasChild(ids []string) (*Object, bool) {
|
|||
return obj, true
|
||||
}
|
||||
if len(ids) == 1 && ids[0] != "style" {
|
||||
_, ok := d2ast.ReservedKeywords[ids[0]]
|
||||
_, ok := ReservedKeywords[ids[0]]
|
||||
if ok {
|
||||
return obj, true
|
||||
}
|
||||
|
|
@ -854,7 +781,7 @@ func (obj *Object) FindEdges(mk *d2ast.Key) ([]*Edge, bool) {
|
|||
return ea, true
|
||||
}
|
||||
|
||||
func (obj *Object) ensureChildEdge(ida []d2ast.String) *Object {
|
||||
func (obj *Object) ensureChildEdge(ida []string) *Object {
|
||||
for i := range ida {
|
||||
switch obj.Shape.Value {
|
||||
case d2target.ShapeClass, d2target.ShapeSQLTable:
|
||||
|
|
@ -870,12 +797,12 @@ func (obj *Object) ensureChildEdge(ida []d2ast.String) *Object {
|
|||
|
||||
// EnsureChild grabs the child by ids or creates it if it does not exist including all
|
||||
// intermediate nodes.
|
||||
func (obj *Object) EnsureChild(ida []d2ast.String) *Object {
|
||||
func (obj *Object) EnsureChild(ida []string) *Object {
|
||||
seq := obj.OuterSequenceDiagram()
|
||||
if seq != nil {
|
||||
for _, c := range seq.ChildrenArray {
|
||||
if c.ID == ida[0].ScalarString() {
|
||||
if obj.ID == ida[0].ScalarString() {
|
||||
if c.ID == ida[0] {
|
||||
if obj.ID == ida[0] {
|
||||
// In cases of a.a where EnsureChild is called on the parent a, the second a should
|
||||
// be created as a child of a and not as a child of the diagram. This is super
|
||||
// unfortunate code but alas.
|
||||
|
|
@ -891,11 +818,9 @@ func (obj *Object) EnsureChild(ida []d2ast.String) *Object {
|
|||
return obj
|
||||
}
|
||||
|
||||
_, is := d2ast.ReservedKeywordHolders[ida[0].ScalarString()]
|
||||
is = is && ida[0].IsUnquoted()
|
||||
_, is := ReservedKeywordHolders[ida[0]]
|
||||
if len(ida) == 1 && !is {
|
||||
_, ok := d2ast.ReservedKeywords[ida[0].ScalarString()]
|
||||
ok = ok && ida[0].IsUnquoted()
|
||||
_, ok := ReservedKeywords[ida[0]]
|
||||
if ok {
|
||||
return obj
|
||||
}
|
||||
|
|
@ -904,14 +829,11 @@ func (obj *Object) EnsureChild(ida []d2ast.String) *Object {
|
|||
id := ida[0]
|
||||
ida = ida[1:]
|
||||
|
||||
if id.ScalarString() == "_" && id.IsUnquoted() {
|
||||
if id == "_" {
|
||||
return obj.Parent.EnsureChild(ida)
|
||||
}
|
||||
|
||||
head := d2format.Format(&d2ast.KeyPath{
|
||||
Path: []*d2ast.StringBox{d2ast.MakeValueBox(d2ast.RawString(id.ScalarString(), true)).StringBox()},
|
||||
})
|
||||
child, ok := obj.Children[strings.ToLower(head)]
|
||||
child, ok := obj.Children[strings.ToLower(id)]
|
||||
if !ok {
|
||||
child = obj.newObject(id)
|
||||
}
|
||||
|
|
@ -949,16 +871,14 @@ func (obj *Object) GetLabelSize(mtexts []*d2target.MText, ruler *textmeasure.Rul
|
|||
|
||||
var dims *d2target.TextDimensions
|
||||
switch shapeType {
|
||||
case d2target.ShapeClass:
|
||||
dims = GetTextDimensions(mtexts, ruler, obj.Text(), go2.Pointer(d2fonts.SourceCodePro))
|
||||
default:
|
||||
case d2target.ShapeText:
|
||||
if obj.Language == "latex" {
|
||||
width, height, err := d2latex.Measure(obj.Text().Text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dims = d2target.NewTextDimensions(width, height)
|
||||
} else if obj.Language != "" && shapeType != d2target.ShapeCode {
|
||||
} else if obj.Language != "" {
|
||||
var err error
|
||||
dims, err = getMarkdownDimensions(mtexts, ruler, obj.Text(), fontFamily)
|
||||
if err != nil {
|
||||
|
|
@ -967,6 +887,12 @@ func (obj *Object) GetLabelSize(mtexts []*d2target.MText, ruler *textmeasure.Rul
|
|||
} else {
|
||||
dims = GetTextDimensions(mtexts, ruler, obj.Text(), fontFamily)
|
||||
}
|
||||
|
||||
case d2target.ShapeClass:
|
||||
dims = GetTextDimensions(mtexts, ruler, obj.Text(), go2.Pointer(d2fonts.SourceCodePro))
|
||||
|
||||
default:
|
||||
dims = GetTextDimensions(mtexts, ruler, obj.Text(), fontFamily)
|
||||
}
|
||||
|
||||
if shapeType == d2target.ShapeSQLTable && obj.Label.Value == "" {
|
||||
|
|
@ -1060,7 +986,7 @@ func (obj *Object) GetDefaultSize(mtexts []*d2target.MText, ruler *textmeasure.R
|
|||
}
|
||||
if anyRowText != nil {
|
||||
rowHeight := GetTextDimensions(mtexts, ruler, anyRowText, go2.Pointer(d2fonts.SourceCodePro)).Height + d2target.VerticalPadding
|
||||
dims.Height = rowHeight*(len(obj.Class.Fields)+len(obj.Class.Methods)) + go2.Max(2*rowHeight, labelDims.Height+2*label.PADDING)
|
||||
dims.Height = rowHeight * (len(obj.Class.Fields) + len(obj.Class.Methods) + 2)
|
||||
} else {
|
||||
dims.Height = 2*go2.Max(12, labelDims.Height) + d2target.VerticalPadding
|
||||
}
|
||||
|
|
@ -1194,7 +1120,7 @@ func (obj *Object) IsConstantNear() bool {
|
|||
if isKey {
|
||||
return false
|
||||
}
|
||||
_, isConst := d2ast.NearConstants[keyPath[0]]
|
||||
_, isConst := NearConstants[keyPath[0]]
|
||||
return isConst
|
||||
}
|
||||
|
||||
|
|
@ -1306,10 +1232,10 @@ func (e *Edge) AbsID() string {
|
|||
return fmt.Sprintf("%s(%s %s %s)[%d]", commonKey, strings.Join(srcIDA, "."), e.ArrowString(), strings.Join(dstIDA, "."), e.Index)
|
||||
}
|
||||
|
||||
func (obj *Object) Connect(srcID, dstID []d2ast.String, srcArrow, dstArrow bool, label string) (*Edge, error) {
|
||||
for _, id := range [][]d2ast.String{srcID, dstID} {
|
||||
func (obj *Object) Connect(srcID, dstID []string, srcArrow, dstArrow bool, label string) (*Edge, error) {
|
||||
for _, id := range [][]string{srcID, dstID} {
|
||||
for _, p := range id {
|
||||
if _, ok := d2ast.ReservedKeywords[p.ScalarString()]; ok && p.IsUnquoted() {
|
||||
if _, ok := ReservedKeywords[p]; ok {
|
||||
return nil, errors.New("cannot connect to reserved keyword")
|
||||
}
|
||||
}
|
||||
|
|
@ -1337,7 +1263,7 @@ func (obj *Object) Connect(srcID, dstID []d2ast.String, srcArrow, dstArrow bool,
|
|||
return e, nil
|
||||
}
|
||||
|
||||
func addSQLTableColumnIndices(e *Edge, srcID, dstID []d2ast.String, obj, src, dst *Object) {
|
||||
func addSQLTableColumnIndices(e *Edge, srcID, dstID []string, obj, src, dst *Object) {
|
||||
if src.Shape.Value == d2target.ShapeSQLTable {
|
||||
if src == dst {
|
||||
// Ignore edge to column inside table.
|
||||
|
|
@ -1347,7 +1273,7 @@ func addSQLTableColumnIndices(e *Edge, srcID, dstID []d2ast.String, obj, src, ds
|
|||
srcAbsID := src.AbsIDArray()
|
||||
if len(objAbsID)+len(srcID) > len(srcAbsID) {
|
||||
for i, d2col := range src.SQLTable.Columns {
|
||||
if d2col.Name.Label == srcID[len(srcID)-1].ScalarString() {
|
||||
if d2col.Name.Label == srcID[len(srcID)-1] {
|
||||
d2col.Reference = dst.AbsID()
|
||||
e.SrcTableColumnIndex = new(int)
|
||||
*e.SrcTableColumnIndex = i
|
||||
|
|
@ -1361,7 +1287,7 @@ func addSQLTableColumnIndices(e *Edge, srcID, dstID []d2ast.String, obj, src, ds
|
|||
dstAbsID := dst.AbsIDArray()
|
||||
if len(objAbsID)+len(dstID) > len(dstAbsID) {
|
||||
for i, d2col := range dst.SQLTable.Columns {
|
||||
if d2col.Name.Label == dstID[len(dstID)-1].ScalarString() {
|
||||
if d2col.Name.Label == dstID[len(dstID)-1] {
|
||||
d2col.Reference = dst.AbsID()
|
||||
e.DstTableColumnIndex = new(int)
|
||||
*e.DstTableColumnIndex = i
|
||||
|
|
@ -1502,12 +1428,12 @@ func (g *Graph) SetDimensions(mtexts []*d2target.MText, ruler *textmeasure.Ruler
|
|||
// user-specified label/icon positions
|
||||
if obj.HasLabel() && obj.Attributes.LabelPosition != nil {
|
||||
scalar := *obj.Attributes.LabelPosition
|
||||
position := d2ast.LabelPositionsMapping[scalar.Value]
|
||||
position := LabelPositionsMapping[scalar.Value]
|
||||
obj.LabelPosition = go2.Pointer(position.String())
|
||||
}
|
||||
if obj.Icon != nil && obj.Attributes.IconPosition != nil {
|
||||
scalar := *obj.Attributes.IconPosition
|
||||
position := d2ast.LabelPositionsMapping[scalar.Value]
|
||||
position := LabelPositionsMapping[scalar.Value]
|
||||
obj.IconPosition = go2.Pointer(position.String())
|
||||
}
|
||||
|
||||
|
|
@ -1612,8 +1538,11 @@ func (g *Graph) SetDimensions(mtexts []*d2target.MText, ruler *textmeasure.Ruler
|
|||
switch shapeType {
|
||||
case shape.TABLE_TYPE, shape.CLASS_TYPE, shape.CODE_TYPE:
|
||||
default:
|
||||
if obj.Link != nil && obj.Tooltip != nil {
|
||||
paddingX += 64
|
||||
if obj.Link != nil {
|
||||
paddingX += 32
|
||||
}
|
||||
if obj.Tooltip != nil {
|
||||
paddingX += 32
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1744,6 +1673,205 @@ func Key(k *d2ast.KeyPath) []string {
|
|||
return d2format.KeyPath(k)
|
||||
}
|
||||
|
||||
// All reserved keywords. See init below.
|
||||
var ReservedKeywords map[string]struct{}
|
||||
|
||||
// Non Style/Holder keywords.
|
||||
var SimpleReservedKeywords = map[string]struct{}{
|
||||
"label": {},
|
||||
"desc": {},
|
||||
"shape": {},
|
||||
"icon": {},
|
||||
"constraint": {},
|
||||
"tooltip": {},
|
||||
"link": {},
|
||||
"near": {},
|
||||
"width": {},
|
||||
"height": {},
|
||||
"direction": {},
|
||||
"top": {},
|
||||
"left": {},
|
||||
"grid-rows": {},
|
||||
"grid-columns": {},
|
||||
"grid-gap": {},
|
||||
"vertical-gap": {},
|
||||
"horizontal-gap": {},
|
||||
"class": {},
|
||||
"vars": {},
|
||||
}
|
||||
|
||||
// ReservedKeywordHolders are reserved keywords that are meaningless on its own and must hold composites
|
||||
var ReservedKeywordHolders = map[string]struct{}{
|
||||
"style": {},
|
||||
"source-arrowhead": {},
|
||||
"target-arrowhead": {},
|
||||
}
|
||||
|
||||
// CompositeReservedKeywords are reserved keywords that can hold composites
|
||||
var CompositeReservedKeywords = map[string]struct{}{
|
||||
"classes": {},
|
||||
"constraint": {},
|
||||
"label": {},
|
||||
"icon": {},
|
||||
}
|
||||
|
||||
// StyleKeywords are reserved keywords which cannot exist outside of the "style" keyword
|
||||
var StyleKeywords = map[string]struct{}{
|
||||
"opacity": {},
|
||||
"stroke": {},
|
||||
"fill": {},
|
||||
"fill-pattern": {},
|
||||
"stroke-width": {},
|
||||
"stroke-dash": {},
|
||||
"border-radius": {},
|
||||
|
||||
// Only for text
|
||||
"font": {},
|
||||
"font-size": {},
|
||||
"font-color": {},
|
||||
"bold": {},
|
||||
"italic": {},
|
||||
"underline": {},
|
||||
"text-transform": {},
|
||||
|
||||
// Only for shapes
|
||||
"shadow": {},
|
||||
"multiple": {},
|
||||
"double-border": {},
|
||||
|
||||
// Only for squares
|
||||
"3d": {},
|
||||
|
||||
// Only for edges
|
||||
"animated": {},
|
||||
"filled": {},
|
||||
}
|
||||
|
||||
// TODO maybe autofmt should allow other values, and transform them to conform
|
||||
// e.g. left-center becomes center-left
|
||||
var NearConstantsArray = []string{
|
||||
"top-left",
|
||||
"top-center",
|
||||
"top-right",
|
||||
|
||||
"center-left",
|
||||
"center-right",
|
||||
|
||||
"bottom-left",
|
||||
"bottom-center",
|
||||
"bottom-right",
|
||||
}
|
||||
var NearConstants map[string]struct{}
|
||||
|
||||
// LabelPositionsArray are the values that labels and icons can set `near` to
|
||||
var LabelPositionsArray = []string{
|
||||
"top-left",
|
||||
"top-center",
|
||||
"top-right",
|
||||
|
||||
"center-left",
|
||||
"center-center",
|
||||
"center-right",
|
||||
|
||||
"bottom-left",
|
||||
"bottom-center",
|
||||
"bottom-right",
|
||||
|
||||
"outside-top-left",
|
||||
"outside-top-center",
|
||||
"outside-top-right",
|
||||
|
||||
"outside-left-top",
|
||||
"outside-left-center",
|
||||
"outside-left-bottom",
|
||||
|
||||
"outside-right-top",
|
||||
"outside-right-center",
|
||||
"outside-right-bottom",
|
||||
|
||||
"outside-bottom-left",
|
||||
"outside-bottom-center",
|
||||
"outside-bottom-right",
|
||||
}
|
||||
var LabelPositions map[string]struct{}
|
||||
|
||||
// convert to label.Position
|
||||
var LabelPositionsMapping = map[string]label.Position{
|
||||
"top-left": label.InsideTopLeft,
|
||||
"top-center": label.InsideTopCenter,
|
||||
"top-right": label.InsideTopRight,
|
||||
|
||||
"center-left": label.InsideMiddleLeft,
|
||||
"center-center": label.InsideMiddleCenter,
|
||||
"center-right": label.InsideMiddleRight,
|
||||
|
||||
"bottom-left": label.InsideBottomLeft,
|
||||
"bottom-center": label.InsideBottomCenter,
|
||||
"bottom-right": label.InsideBottomRight,
|
||||
|
||||
"outside-top-left": label.OutsideTopLeft,
|
||||
"outside-top-center": label.OutsideTopCenter,
|
||||
"outside-top-right": label.OutsideTopRight,
|
||||
|
||||
"outside-left-top": label.OutsideLeftTop,
|
||||
"outside-left-center": label.OutsideLeftMiddle,
|
||||
"outside-left-bottom": label.OutsideLeftBottom,
|
||||
|
||||
"outside-right-top": label.OutsideRightTop,
|
||||
"outside-right-center": label.OutsideRightMiddle,
|
||||
"outside-right-bottom": label.OutsideRightBottom,
|
||||
|
||||
"outside-bottom-left": label.OutsideBottomLeft,
|
||||
"outside-bottom-center": label.OutsideBottomCenter,
|
||||
"outside-bottom-right": label.OutsideBottomRight,
|
||||
}
|
||||
|
||||
var FillPatterns = []string{
|
||||
"none",
|
||||
"dots",
|
||||
"lines",
|
||||
"grain",
|
||||
"paper",
|
||||
}
|
||||
|
||||
var textTransforms = []string{"none", "uppercase", "lowercase", "capitalize"}
|
||||
|
||||
// BoardKeywords contains the keywords that create new boards.
|
||||
var BoardKeywords = map[string]struct{}{
|
||||
"layers": {},
|
||||
"scenarios": {},
|
||||
"steps": {},
|
||||
}
|
||||
|
||||
func init() {
|
||||
ReservedKeywords = make(map[string]struct{})
|
||||
for k, v := range SimpleReservedKeywords {
|
||||
ReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range StyleKeywords {
|
||||
ReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range ReservedKeywordHolders {
|
||||
CompositeReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range BoardKeywords {
|
||||
CompositeReservedKeywords[k] = v
|
||||
}
|
||||
for k, v := range CompositeReservedKeywords {
|
||||
ReservedKeywords[k] = v
|
||||
}
|
||||
|
||||
NearConstants = make(map[string]struct{}, len(NearConstantsArray))
|
||||
for _, k := range NearConstantsArray {
|
||||
NearConstants[k] = struct{}{}
|
||||
}
|
||||
|
||||
LabelPositions = make(map[string]struct{}, len(LabelPositionsArray))
|
||||
for _, k := range LabelPositionsArray {
|
||||
LabelPositions[k] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Graph) GetBoard(name string) *Graph {
|
||||
for _, l := range g.Layers {
|
||||
if l.Name == name {
|
||||
|
|
@ -1773,11 +1901,6 @@ func (g *Graph) SortObjectsByAST() {
|
|||
}
|
||||
r1 := o1.References[0]
|
||||
r2 := o2.References[0]
|
||||
// If they are variable substitutions, leave them alone, as their
|
||||
// references reflect where the variable is, not where the substitution is
|
||||
if r1.IsVar || r2.IsVar {
|
||||
return i < j
|
||||
}
|
||||
return r1.Key.Path[r1.KeyPathIndex].Unbox().GetRange().Before(r2.Key.Path[r2.KeyPathIndex].Unbox().GetRange())
|
||||
})
|
||||
g.Objects = objects
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
package d2graph
|
||||
|
||||
import (
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
)
|
||||
import "oss.terrastruct.com/d2/d2target"
|
||||
|
||||
func (obj *Object) IsSequenceDiagram() bool {
|
||||
return obj != nil && obj.Shape.Value == d2target.ShapeSequenceDiagram
|
||||
|
|
|
|||
|
|
@ -10,11 +10,10 @@ import (
|
|||
)
|
||||
|
||||
type SerializedGraph struct {
|
||||
Root SerializedObject `json:"root"`
|
||||
Edges []SerializedEdge `json:"edges"`
|
||||
Objects []SerializedObject `json:"objects"`
|
||||
RootLevel int `json:"rootLevel"`
|
||||
Data map[string]interface{} `json:"data,omitempty"`
|
||||
Root SerializedObject `json:"root"`
|
||||
Edges []SerializedEdge `json:"edges"`
|
||||
Objects []SerializedObject `json:"objects"`
|
||||
RootLevel int `json:"rootLevel"`
|
||||
}
|
||||
|
||||
type SerializedObject map[string]interface{}
|
||||
|
|
@ -28,9 +27,8 @@ func DeserializeGraph(bytes []byte, g *Graph) error {
|
|||
return err
|
||||
}
|
||||
|
||||
g.Data = sg.Data
|
||||
var root Object
|
||||
Convert(sg.Root, &root)
|
||||
convert(sg.Root, &root)
|
||||
g.Root = &root
|
||||
root.Graph = g
|
||||
g.RootLevel = sg.RootLevel
|
||||
|
|
@ -40,7 +38,7 @@ func DeserializeGraph(bytes []byte, g *Graph) error {
|
|||
var objects []*Object
|
||||
for _, so := range sg.Objects {
|
||||
var o Object
|
||||
if err := Convert(so, &o); err != nil {
|
||||
if err := convert(so, &o); err != nil {
|
||||
return err
|
||||
}
|
||||
o.Graph = g
|
||||
|
|
@ -69,7 +67,7 @@ func DeserializeGraph(bytes []byte, g *Graph) error {
|
|||
var edges []*Edge
|
||||
for _, se := range sg.Edges {
|
||||
var e Edge
|
||||
if err := Convert(se, &e); err != nil {
|
||||
if err := convert(se, &e); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -97,7 +95,6 @@ func SerializeGraph(g *Graph) ([]byte, error) {
|
|||
}
|
||||
sg.Root = root
|
||||
sg.RootLevel = g.RootLevel
|
||||
sg.Data = g.Data
|
||||
|
||||
var sobjects []SerializedObject
|
||||
for _, o := range g.Objects {
|
||||
|
|
@ -111,7 +108,7 @@ func SerializeGraph(g *Graph) ([]byte, error) {
|
|||
|
||||
var sedges []SerializedEdge
|
||||
for _, e := range g.Edges {
|
||||
se, err := ToSerializedEdge(e)
|
||||
se, err := toSerializedEdge(e)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -124,7 +121,7 @@ func SerializeGraph(g *Graph) ([]byte, error) {
|
|||
|
||||
func toSerializedObject(o *Object) (SerializedObject, error) {
|
||||
var so SerializedObject
|
||||
if err := Convert(o, &so); err != nil {
|
||||
if err := convert(o, &so); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
|
@ -141,9 +138,9 @@ func toSerializedObject(o *Object) (SerializedObject, error) {
|
|||
return so, nil
|
||||
}
|
||||
|
||||
func ToSerializedEdge(e *Edge) (SerializedEdge, error) {
|
||||
func toSerializedEdge(e *Edge) (SerializedEdge, error) {
|
||||
var se SerializedEdge
|
||||
if err := Convert(e, &se); err != nil {
|
||||
if err := convert(e, &se); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
|
@ -157,7 +154,7 @@ func ToSerializedEdge(e *Edge) (SerializedEdge, error) {
|
|||
return se, nil
|
||||
}
|
||||
|
||||
func Convert[T, Q any](from T, to *Q) error {
|
||||
func convert[T, Q any](from T, to *Q) error {
|
||||
b, err := json.Marshal(from)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
|||
822
d2ir/compile.go
822
d2ir/compile.go
File diff suppressed because it is too large
Load diff
|
|
@ -28,7 +28,6 @@ func TestCompile(t *testing.T) {
|
|||
t.Run("imports", testCompileImports)
|
||||
t.Run("patterns", testCompilePatterns)
|
||||
t.Run("filters", testCompileFilters)
|
||||
t.Run("vars", testCompileVars)
|
||||
}
|
||||
|
||||
type testCase struct {
|
||||
|
|
@ -195,23 +194,6 @@ func testCompileFields(t *testing.T) {
|
|||
assert.String(t, `[1; 2; 3; 4]`, f.Composite.String())
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "quoted",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `my_table: {
|
||||
shape: sql_table
|
||||
width: 200
|
||||
height: 200
|
||||
"shape": string
|
||||
"icon": string
|
||||
"width": int
|
||||
"height": int
|
||||
}`)
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 0, 0, "sql_table", "my_table.shape")
|
||||
assertQuery(t, m, 0, 0, "string", `my_table."shape"`)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "null",
|
||||
run: func(t testing.TB) {
|
||||
|
|
@ -593,7 +575,7 @@ classes: {
|
|||
}
|
||||
}
|
||||
`)
|
||||
assert.ErrorString(t, err, `TestCompile/classes/nonroot.d2:2:3: classes must be declared at a board root scope`)
|
||||
assert.ErrorString(t, err, `TestCompile/classes/nonroot.d2:2:3: classes is only allowed at a board root`)
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -716,32 +698,3 @@ layers: {
|
|||
}
|
||||
runa(t, tca)
|
||||
}
|
||||
|
||||
func testCompileVars(t *testing.T) {
|
||||
t.Parallel()
|
||||
tca := []testCase{
|
||||
{
|
||||
name: "spread-in-place",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `vars: {
|
||||
person-shape: {
|
||||
grid-columns: 1
|
||||
grid-rows: 2
|
||||
grid-gap: 0
|
||||
head
|
||||
body
|
||||
}
|
||||
}
|
||||
|
||||
dora: {
|
||||
...${person-shape}
|
||||
body
|
||||
}
|
||||
`)
|
||||
assert.Success(t, err)
|
||||
assert.Equal(t, "grid-columns", m.Fields[1].Map().Fields[0].Name.ScalarString())
|
||||
},
|
||||
},
|
||||
}
|
||||
runa(t, tca)
|
||||
}
|
||||
|
|
|
|||
467
d2ir/d2ir.go
467
d2ir/d2ir.go
|
|
@ -11,6 +11,7 @@ import (
|
|||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2format"
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2parser"
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
)
|
||||
|
|
@ -166,17 +167,16 @@ func (s *Scalar) Equal(n2 Node) bool {
|
|||
}
|
||||
|
||||
type Map struct {
|
||||
parent Node
|
||||
importAST d2ast.Node
|
||||
Fields []*Field `json:"fields"`
|
||||
Edges []*Edge `json:"edges"`
|
||||
parent Node
|
||||
Fields []*Field `json:"fields"`
|
||||
Edges []*Edge `json:"edges"`
|
||||
|
||||
globs []*globContext
|
||||
}
|
||||
|
||||
func (m *Map) initRoot() {
|
||||
m.parent = &Field{
|
||||
Name: d2ast.FlatUnquotedString("root"),
|
||||
Name: "root",
|
||||
References: []*FieldReference{{
|
||||
Context_: &RefContext{
|
||||
ScopeMap: m,
|
||||
|
|
@ -185,20 +185,6 @@ func (m *Map) initRoot() {
|
|||
}
|
||||
}
|
||||
|
||||
func (m *Map) ImportAST() d2ast.Node {
|
||||
return m.importAST
|
||||
}
|
||||
|
||||
func (m *Map) SetImportAST(node d2ast.Node) {
|
||||
m.importAST = node
|
||||
for _, f := range m.Fields {
|
||||
f.SetImportAST(node)
|
||||
}
|
||||
for _, e := range m.Edges {
|
||||
e.SetImportAST(node)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Map) Copy(newParent Node) Node {
|
||||
tmp := *m
|
||||
m = &tmp
|
||||
|
|
@ -277,9 +263,6 @@ func NodeBoardKind(n Node) BoardKind {
|
|||
}
|
||||
f = ParentField(n)
|
||||
case *Map:
|
||||
if n == nil {
|
||||
return ""
|
||||
}
|
||||
var ok bool
|
||||
f, ok = n.parent.(*Field)
|
||||
if !ok {
|
||||
|
|
@ -293,7 +276,7 @@ func NodeBoardKind(n Node) BoardKind {
|
|||
if f == nil {
|
||||
return ""
|
||||
}
|
||||
switch f.Name.ScalarString() {
|
||||
switch f.Name {
|
||||
case "layers":
|
||||
return BoardLayer
|
||||
case "scenarios":
|
||||
|
|
@ -305,22 +288,11 @@ func NodeBoardKind(n Node) BoardKind {
|
|||
}
|
||||
}
|
||||
|
||||
type Importable interface {
|
||||
ImportAST() d2ast.Node
|
||||
SetImportAST(d2ast.Node)
|
||||
}
|
||||
|
||||
var _ Importable = &Edge{}
|
||||
var _ Importable = &Field{}
|
||||
var _ Importable = &Map{}
|
||||
|
||||
type Field struct {
|
||||
// *Map.
|
||||
parent Node
|
||||
importAST d2ast.Node
|
||||
suspended bool
|
||||
parent Node
|
||||
|
||||
Name d2ast.String `json:"name"`
|
||||
Name string `json:"name"`
|
||||
|
||||
// Primary_ to avoid clashing with Primary(). We need to keep it exported for
|
||||
// encoding/json to marshal it so cannot prefix _ instead.
|
||||
|
|
@ -330,17 +302,6 @@ type Field struct {
|
|||
References []*FieldReference `json:"references,omitempty"`
|
||||
}
|
||||
|
||||
func (f *Field) ImportAST() d2ast.Node {
|
||||
return f.importAST
|
||||
}
|
||||
|
||||
func (f *Field) SetImportAST(node d2ast.Node) {
|
||||
f.importAST = node
|
||||
if f.Map() != nil {
|
||||
f.Map().SetImportAST(node)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Field) Copy(newParent Node) Node {
|
||||
tmp := *f
|
||||
f = &tmp
|
||||
|
|
@ -378,11 +339,11 @@ func (f *Field) LastRef() Reference {
|
|||
}
|
||||
|
||||
type EdgeID struct {
|
||||
SrcPath []d2ast.String `json:"src_path"`
|
||||
SrcArrow bool `json:"src_arrow"`
|
||||
SrcPath []string `json:"src_path"`
|
||||
SrcArrow bool `json:"src_arrow"`
|
||||
|
||||
DstPath []d2ast.String `json:"dst_path"`
|
||||
DstArrow bool `json:"dst_arrow"`
|
||||
DstPath []string `json:"dst_path"`
|
||||
DstArrow bool `json:"dst_arrow"`
|
||||
|
||||
// If nil, then any EdgeID with equal src/dst/arrows matches.
|
||||
Index *int `json:"index"`
|
||||
|
|
@ -410,8 +371,8 @@ func (eid *EdgeID) Copy() *EdgeID {
|
|||
tmp := *eid
|
||||
eid = &tmp
|
||||
|
||||
eid.SrcPath = append([]d2ast.String(nil), eid.SrcPath...)
|
||||
eid.DstPath = append([]d2ast.String(nil), eid.DstPath...)
|
||||
eid.SrcPath = append([]string(nil), eid.SrcPath...)
|
||||
eid.DstPath = append([]string(nil), eid.DstPath...)
|
||||
return eid
|
||||
}
|
||||
|
||||
|
|
@ -429,7 +390,7 @@ func (eid *EdgeID) Match(eid2 *EdgeID) bool {
|
|||
return false
|
||||
}
|
||||
for i, s := range eid.SrcPath {
|
||||
if !strings.EqualFold(s.ScalarString(), eid2.SrcPath[i].ScalarString()) {
|
||||
if !strings.EqualFold(s, eid2.SrcPath[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -441,7 +402,7 @@ func (eid *EdgeID) Match(eid2 *EdgeID) bool {
|
|||
return false
|
||||
}
|
||||
for i, s := range eid.DstPath {
|
||||
if !strings.EqualFold(s.ScalarString(), eid2.DstPath[i].ScalarString()) {
|
||||
if !strings.EqualFold(s, eid2.DstPath[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -451,21 +412,21 @@ func (eid *EdgeID) Match(eid2 *EdgeID) bool {
|
|||
|
||||
// resolve resolves both underscores and commons in eid.
|
||||
// It returns the new eid, containing map adjusted for underscores and common ida.
|
||||
func (eid *EdgeID) resolve(m *Map) (_ *EdgeID, _ *Map, common []d2ast.String, _ error) {
|
||||
func (eid *EdgeID) resolve(m *Map) (_ *EdgeID, _ *Map, common []string, _ error) {
|
||||
eid = eid.Copy()
|
||||
maxUnderscores := go2.Max(countUnderscores(eid.SrcPath), countUnderscores(eid.DstPath))
|
||||
for i := 0; i < maxUnderscores; i++ {
|
||||
if eid.SrcPath[0].ScalarString() == "_" && eid.SrcPath[0].IsUnquoted() {
|
||||
if eid.SrcPath[0] == "_" {
|
||||
eid.SrcPath = eid.SrcPath[1:]
|
||||
} else {
|
||||
mf := ParentField(m)
|
||||
eid.SrcPath = append([]d2ast.String{mf.Name}, eid.SrcPath...)
|
||||
eid.SrcPath = append([]string{mf.Name}, eid.SrcPath...)
|
||||
}
|
||||
if eid.DstPath[0].ScalarString() == "_" && eid.DstPath[0].IsUnquoted() {
|
||||
if eid.DstPath[0] == "_" {
|
||||
eid.DstPath = eid.DstPath[1:]
|
||||
} else {
|
||||
mf := ParentField(m)
|
||||
eid.DstPath = append([]d2ast.String{mf.Name}, eid.DstPath...)
|
||||
eid.DstPath = append([]string{mf.Name}, eid.DstPath...)
|
||||
}
|
||||
m = ParentMap(m)
|
||||
if m == nil {
|
||||
|
|
@ -474,7 +435,7 @@ func (eid *EdgeID) resolve(m *Map) (_ *EdgeID, _ *Map, common []d2ast.String, _
|
|||
}
|
||||
|
||||
for len(eid.SrcPath) > 1 && len(eid.DstPath) > 1 {
|
||||
if !strings.EqualFold(eid.SrcPath[0].ScalarString(), eid.DstPath[0].ScalarString()) || strings.Contains(eid.SrcPath[0].ScalarString(), "*") {
|
||||
if !strings.EqualFold(eid.SrcPath[0], eid.DstPath[0]) || eid.SrcPath[0] == "*" {
|
||||
return eid, m, common, nil
|
||||
}
|
||||
common = append(common, eid.SrcPath[0])
|
||||
|
|
@ -487,9 +448,7 @@ func (eid *EdgeID) resolve(m *Map) (_ *EdgeID, _ *Map, common []d2ast.String, _
|
|||
|
||||
type Edge struct {
|
||||
// *Map
|
||||
parent Node
|
||||
importAST d2ast.Node
|
||||
suspended bool
|
||||
parent Node
|
||||
|
||||
ID *EdgeID `json:"edge_id"`
|
||||
|
||||
|
|
@ -499,17 +458,6 @@ type Edge struct {
|
|||
References []*EdgeReference `json:"references,omitempty"`
|
||||
}
|
||||
|
||||
func (e *Edge) ImportAST() d2ast.Node {
|
||||
return e.importAST
|
||||
}
|
||||
|
||||
func (e *Edge) SetImportAST(node d2ast.Node) {
|
||||
e.importAST = node
|
||||
if e.Map() != nil {
|
||||
e.Map().SetImportAST(node)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Edge) Copy(newParent Node) Node {
|
||||
tmp := *e
|
||||
e = &tmp
|
||||
|
|
@ -650,41 +598,7 @@ func (rc *RefContext) EdgeIndex() int {
|
|||
func (rc *RefContext) Equal(rc2 *RefContext) bool {
|
||||
// We intentionally ignore edges here because the same glob can produce multiple RefContexts that should be treated the same with only the edge as the difference.
|
||||
// Same with ScopeMap.
|
||||
if !(rc.Key.Equals(rc2.Key) && rc.Scope == rc2.Scope && rc.ScopeAST == rc2.ScopeAST) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if suspension values match for suspension operations
|
||||
// We don't want these two to equal
|
||||
// 1. *: suspend
|
||||
// 2. *: unsuspend
|
||||
hasSuspension1 := (rc.Key.Primary.Suspension != nil || rc.Key.Value.Suspension != nil)
|
||||
hasSuspension2 := (rc2.Key.Primary.Suspension != nil || rc2.Key.Value.Suspension != nil)
|
||||
|
||||
if hasSuspension1 || hasSuspension2 {
|
||||
var val1, val2 bool
|
||||
if rc.Key.Primary.Suspension != nil {
|
||||
val1 = rc.Key.Primary.Suspension.Value
|
||||
} else if rc.Key.Value.Suspension != nil {
|
||||
val1 = rc.Key.Value.Suspension.Value
|
||||
}
|
||||
|
||||
if rc2.Key.Primary.Suspension != nil {
|
||||
val2 = rc2.Key.Primary.Suspension.Value
|
||||
} else if rc2.Key.Value.Suspension != nil {
|
||||
val2 = rc2.Key.Value.Suspension.Value
|
||||
}
|
||||
|
||||
if hasSuspension1 && hasSuspension2 && val1 != val2 {
|
||||
return false
|
||||
}
|
||||
|
||||
if hasSuspension1 != hasSuspension2 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
return rc.Key.Equals(rc2.Key) && rc.Scope == rc2.Scope && rc.ScopeAST == rc2.ScopeAST
|
||||
}
|
||||
|
||||
func (m *Map) FieldCountRecursive() int {
|
||||
|
|
@ -705,44 +619,13 @@ func (m *Map) FieldCountRecursive() int {
|
|||
return acc
|
||||
}
|
||||
|
||||
func (c *compiler) IsContainer(m *Map) bool {
|
||||
func (m *Map) IsContainer() bool {
|
||||
if m == nil {
|
||||
return false
|
||||
}
|
||||
// Check references as the fields and edges may not be compiled yet
|
||||
f := m.Parent().(*Field)
|
||||
for _, ref := range f.References {
|
||||
if ref.Primary() && ref.Context_.Key != nil && ref.Context_.Key.Value.Map != nil {
|
||||
for _, n := range ref.Context_.Key.Value.Map.Nodes {
|
||||
if n.MapKey == nil {
|
||||
if n.Import != nil {
|
||||
impn, ok := c.peekImport(n.Import)
|
||||
if ok {
|
||||
for _, f := range impn.Fields {
|
||||
_, isReserved := d2ast.ReservedKeywords[f.Name.ScalarString()]
|
||||
if !(isReserved && f.Name.IsUnquoted()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(n.MapKey.Edges) > 0 {
|
||||
return true
|
||||
}
|
||||
if n.MapKey.Key != nil {
|
||||
_, isReserved := d2ast.ReservedKeywords[n.MapKey.Key.Path[0].Unbox().ScalarString()]
|
||||
if !(isReserved && f.Name.IsUnquoted()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range m.Fields {
|
||||
_, isReserved := d2ast.ReservedKeywords[f.Name.ScalarString()]
|
||||
if !(isReserved && f.Name.IsUnquoted()) {
|
||||
_, isReserved := d2graph.ReservedKeywords[f.Name]
|
||||
if !isReserved {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
|
@ -769,9 +652,9 @@ func (m *Map) EdgeCountRecursive() int {
|
|||
|
||||
func (m *Map) GetClassMap(name string) *Map {
|
||||
root := RootMap(m)
|
||||
classes := root.Map().GetField(d2ast.FlatUnquotedString("classes"))
|
||||
classes := root.Map().GetField("classes")
|
||||
if classes != nil && classes.Map() != nil {
|
||||
class := classes.Map().GetField(d2ast.FlatUnquotedString(name))
|
||||
class := classes.Map().GetField(name)
|
||||
if class != nil && class.Map() != nil {
|
||||
return class.Map()
|
||||
}
|
||||
|
|
@ -779,8 +662,8 @@ func (m *Map) GetClassMap(name string) *Map {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (m *Map) GetField(ida ...d2ast.String) *Field {
|
||||
for len(ida) > 0 && ida[0].ScalarString() == "_" && ida[0].IsUnquoted() {
|
||||
func (m *Map) GetField(ida ...string) *Field {
|
||||
for len(ida) > 0 && ida[0] == "_" {
|
||||
m = ParentMap(m)
|
||||
if m == nil {
|
||||
return nil
|
||||
|
|
@ -789,7 +672,7 @@ func (m *Map) GetField(ida ...d2ast.String) *Field {
|
|||
return m.getField(ida)
|
||||
}
|
||||
|
||||
func (m *Map) getField(ida []d2ast.String) *Field {
|
||||
func (m *Map) getField(ida []string) *Field {
|
||||
if len(ida) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -797,22 +680,14 @@ func (m *Map) getField(ida []d2ast.String) *Field {
|
|||
s := ida[0]
|
||||
rest := ida[1:]
|
||||
|
||||
if s.ScalarString() == "_" && s.IsUnquoted() {
|
||||
if s == "_" {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, f := range m.Fields {
|
||||
if f.Name == nil {
|
||||
if !strings.EqualFold(f.Name, s) {
|
||||
continue
|
||||
}
|
||||
if !strings.EqualFold(f.Name.ScalarString(), s.ScalarString()) {
|
||||
continue
|
||||
}
|
||||
if _, isReserved := d2ast.ReservedKeywords[strings.ToLower(s.ScalarString())]; isReserved {
|
||||
if f.Name.IsUnquoted() != s.IsUnquoted() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(rest) == 0 {
|
||||
return f
|
||||
}
|
||||
|
|
@ -826,7 +701,7 @@ func (m *Map) getField(ida []d2ast.String) *Field {
|
|||
// EnsureField is a bit of a misnomer. It's more of a Query/Ensure combination function at this point.
|
||||
func (m *Map) EnsureField(kp *d2ast.KeyPath, refctx *RefContext, create bool, c *compiler) ([]*Field, error) {
|
||||
i := 0
|
||||
for kp.Path[i].Unbox().ScalarString() == "_" && kp.Path[i].Unbox().IsUnquoted() {
|
||||
for kp.Path[i].Unbox().ScalarString() == "_" {
|
||||
m = ParentMap(m)
|
||||
if m == nil {
|
||||
return nil, d2parser.Errorf(kp.Path[i].Unbox(), "invalid underscore: no parent")
|
||||
|
|
@ -859,10 +734,10 @@ func (m *Map) ensureField(i int, kp *d2ast.KeyPath, refctx *RefContext, create b
|
|||
filter := func(f *Field, passthrough bool) bool {
|
||||
if gctx != nil {
|
||||
var ks string
|
||||
if refctx.Key.HasMultiGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(IDA(f)))
|
||||
if refctx.Key.HasTripleGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(IDA(f)))
|
||||
} else {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(BoardIDA(f)))
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(BoardIDA(f)))
|
||||
}
|
||||
if !kp.HasGlob() {
|
||||
if !passthrough {
|
||||
|
|
@ -916,10 +791,7 @@ func (m *Map) ensureField(i int, kp *d2ast.KeyPath, refctx *RefContext, create b
|
|||
return nil
|
||||
}
|
||||
for _, f := range m.Fields {
|
||||
if f.Name == nil {
|
||||
continue
|
||||
}
|
||||
if matchPattern(f.Name.ScalarString(), us.Pattern) {
|
||||
if matchPattern(f.Name, us.Pattern) {
|
||||
if i == len(kp.Path)-1 {
|
||||
faAppend(f)
|
||||
} else {
|
||||
|
|
@ -941,37 +813,31 @@ func (m *Map) ensureField(i int, kp *d2ast.KeyPath, refctx *RefContext, create b
|
|||
return nil
|
||||
}
|
||||
|
||||
head := kp.Path[i].Unbox()
|
||||
headString := head.ScalarString()
|
||||
head := kp.Path[i].Unbox().ScalarString()
|
||||
|
||||
if _, ok := d2ast.ReservedKeywords[strings.ToLower(head.ScalarString())]; ok && head.IsUnquoted() {
|
||||
headString = strings.ToLower(head.ScalarString())
|
||||
if _, ok := d2ast.CompositeReservedKeywords[headString]; !ok && i < len(kp.Path)-1 {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), fmt.Sprintf(`"%s" must be the last part of the key`, headString))
|
||||
if _, ok := d2graph.ReservedKeywords[strings.ToLower(head)]; ok {
|
||||
head = strings.ToLower(head)
|
||||
if _, ok := d2graph.CompositeReservedKeywords[head]; !ok && i < len(kp.Path)-1 {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), fmt.Sprintf(`"%s" must be the last part of the key`, head))
|
||||
}
|
||||
}
|
||||
|
||||
if headString == "_" && head.IsUnquoted() {
|
||||
if head == "_" {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), `parent "_" can only be used in the beginning of paths, e.g. "_.x"`)
|
||||
}
|
||||
|
||||
if headString == "classes" && head.IsUnquoted() && NodeBoardKind(m) == "" {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), "%s must be declared at a board root scope", headString)
|
||||
if head == "classes" && NodeBoardKind(m) == "" {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), "%s is only allowed at a board root", head)
|
||||
}
|
||||
|
||||
if findBoardKeyword(head) != -1 && head.IsUnquoted() && NodeBoardKind(m) == "" {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), "%s must be declared at a board root scope", headString)
|
||||
if findBoardKeyword(head) != -1 && NodeBoardKind(m) == "" {
|
||||
return d2parser.Errorf(kp.Path[i].Unbox(), "%s is only allowed at a board root", head)
|
||||
}
|
||||
|
||||
for _, f := range m.Fields {
|
||||
if !(f.Name != nil && strings.EqualFold(f.Name.ScalarString(), head.ScalarString())) {
|
||||
if !strings.EqualFold(f.Name, head) {
|
||||
continue
|
||||
}
|
||||
if _, isReserved := d2ast.ReservedKeywords[strings.ToLower(f.Name.ScalarString())]; isReserved {
|
||||
if f.Name.IsUnquoted() != head.IsUnquoted() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Don't add references for fake common KeyPath from trimCommon in CreateEdge.
|
||||
if refctx != nil {
|
||||
|
|
@ -1006,14 +872,14 @@ func (m *Map) ensureField(i int, kp *d2ast.KeyPath, refctx *RefContext, create b
|
|||
return nil
|
||||
}
|
||||
shape := ParentShape(m)
|
||||
if _, ok := d2ast.ReservedKeywords[strings.ToLower(head.ScalarString())]; !(ok && head.IsUnquoted()) && len(c.globRefContextStack) > 0 {
|
||||
if _, ok := d2graph.ReservedKeywords[strings.ToLower(head)]; !ok && len(c.globRefContextStack) > 0 {
|
||||
if shape == d2target.ShapeClass || shape == d2target.ShapeSQLTable {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
f := &Field{
|
||||
parent: m,
|
||||
Name: kp.Path[i].Unbox(),
|
||||
Name: head,
|
||||
}
|
||||
defer func() {
|
||||
if i < kp.FirstGlob() {
|
||||
|
|
@ -1021,10 +887,10 @@ func (m *Map) ensureField(i int, kp *d2ast.KeyPath, refctx *RefContext, create b
|
|||
}
|
||||
for _, grefctx := range c.globRefContextStack {
|
||||
var ks string
|
||||
if grefctx.Key.HasMultiGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(IDA(f)))
|
||||
if grefctx.Key.HasTripleGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(IDA(f)))
|
||||
} else {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(BoardIDA(f)))
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(BoardIDA(f)))
|
||||
}
|
||||
gctx2 := c.getGlobContext(grefctx)
|
||||
gctx2.appliedFields[ks] = struct{}{}
|
||||
|
|
@ -1061,25 +927,9 @@ func (m *Map) DeleteEdge(eid *EdgeID) *Edge {
|
|||
return nil
|
||||
}
|
||||
|
||||
resolvedEID, resolvedM, common, err := eid.resolve(m)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(common) > 0 {
|
||||
f := resolvedM.GetField(common...)
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
if f.Map() == nil {
|
||||
return nil
|
||||
}
|
||||
return f.Map().DeleteEdge(resolvedEID)
|
||||
}
|
||||
|
||||
for i, e := range resolvedM.Edges {
|
||||
if e.ID.Match(resolvedEID) {
|
||||
resolvedM.Edges = append(resolvedM.Edges[:i], resolvedM.Edges[i+1:]...)
|
||||
for i, e := range m.Edges {
|
||||
if e.ID.Match(eid) {
|
||||
m.Edges = append(m.Edges[:i], m.Edges[i+1:]...)
|
||||
return e
|
||||
}
|
||||
}
|
||||
|
|
@ -1095,7 +945,7 @@ func (m *Map) DeleteField(ida ...string) *Field {
|
|||
rest := ida[1:]
|
||||
|
||||
for i, f := range m.Fields {
|
||||
if !strings.EqualFold(f.Name.ScalarString(), s) {
|
||||
if !strings.EqualFold(f.Name, s) {
|
||||
continue
|
||||
}
|
||||
if len(rest) == 0 {
|
||||
|
|
@ -1121,11 +971,11 @@ func (m *Map) DeleteField(ida ...string) *Field {
|
|||
// If a field was deleted from a keyword-holder keyword and that holder is empty,
|
||||
// then that holder becomes meaningless and should be deleted too
|
||||
parent := ParentField(f)
|
||||
for keywordHolder := range d2ast.ReservedKeywordHolders {
|
||||
if parent != nil && parent.Name.ScalarString() == keywordHolder && parent.Name.IsUnquoted() && len(parent.Map().Fields) == 0 {
|
||||
for keywordHolder := range d2graph.ReservedKeywordHolders {
|
||||
if parent != nil && parent.Name == keywordHolder && len(parent.Map().Fields) == 0 {
|
||||
keywordHolderParentMap := ParentMap(parent)
|
||||
for i, f := range keywordHolderParentMap.Fields {
|
||||
if f.Name.ScalarString() == keywordHolder && f.Name.IsUnquoted() {
|
||||
if f.Name == keywordHolder {
|
||||
keywordHolderParentMap.Fields = append(keywordHolderParentMap.Fields[:i], keywordHolderParentMap.Fields[i+1:]...)
|
||||
break
|
||||
}
|
||||
|
|
@ -1183,7 +1033,7 @@ func (m *Map) getEdges(eid *EdgeID, refctx *RefContext, gctx *globContext, ea *[
|
|||
}
|
||||
|
||||
if len(common) > 0 {
|
||||
commonKP := d2ast.MakeKeyPathString(common)
|
||||
commonKP := d2ast.MakeKeyPath(common)
|
||||
lastMatch := 0
|
||||
for i, el := range commonKP.Path {
|
||||
for j := lastMatch; j < len(refctx.Edge.Src.Path); j++ {
|
||||
|
|
@ -1234,10 +1084,10 @@ func (m *Map) getEdges(eid *EdgeID, refctx *RefContext, gctx *globContext, ea *[
|
|||
for _, e := range ea2 {
|
||||
if gctx != nil {
|
||||
var ks string
|
||||
if refctx.Key.HasMultiGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(IDA(e)))
|
||||
if refctx.Key.HasTripleGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(IDA(e)))
|
||||
} else {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(BoardIDA(e)))
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(BoardIDA(e)))
|
||||
}
|
||||
if _, ok := gctx.appliedEdges[ks]; ok {
|
||||
continue
|
||||
|
|
@ -1279,7 +1129,7 @@ func (m *Map) createEdge(eid *EdgeID, refctx *RefContext, gctx *globContext, c *
|
|||
return d2parser.Errorf(refctx.Edge, err.Error())
|
||||
}
|
||||
if len(common) > 0 {
|
||||
commonKP := d2ast.MakeKeyPathString(common)
|
||||
commonKP := d2ast.MakeKeyPath(common)
|
||||
lastMatch := 0
|
||||
for i, el := range commonKP.Path {
|
||||
for j := lastMatch; j < len(refctx.Edge.Src.Path); j++ {
|
||||
|
|
@ -1347,7 +1197,7 @@ func (m *Map) createEdge(eid *EdgeID, refctx *RefContext, gctx *globContext, c *
|
|||
|
||||
if refctx.Edge.Src.HasMultiGlob() {
|
||||
// If src has a double glob we only select leafs, those without children.
|
||||
if c.IsContainer(src.Map()) {
|
||||
if src.Map().IsContainer() {
|
||||
continue
|
||||
}
|
||||
if NodeBoardKind(src) != "" || ParentBoard(src) != ParentBoard(dst) {
|
||||
|
|
@ -1356,7 +1206,7 @@ func (m *Map) createEdge(eid *EdgeID, refctx *RefContext, gctx *globContext, c *
|
|||
}
|
||||
if refctx.Edge.Dst.HasMultiGlob() {
|
||||
// If dst has a double glob we only select leafs, those without children.
|
||||
if c.IsContainer(dst.Map()) {
|
||||
if dst.Map().IsContainer() {
|
||||
continue
|
||||
}
|
||||
if NodeBoardKind(dst) != "" || ParentBoard(src) != ParentBoard(dst) {
|
||||
|
|
@ -1368,11 +1218,11 @@ func (m *Map) createEdge(eid *EdgeID, refctx *RefContext, gctx *globContext, c *
|
|||
eid2.SrcPath = RelIDA(m, src)
|
||||
eid2.DstPath = RelIDA(m, dst)
|
||||
|
||||
es, err := m.createEdge2(eid2, refctx, gctx, c, src, dst)
|
||||
e, err := m.createEdge2(eid2, refctx, gctx, c, src, dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range es {
|
||||
if e != nil {
|
||||
*ea = append(*ea, e)
|
||||
}
|
||||
}
|
||||
|
|
@ -1380,7 +1230,7 @@ func (m *Map) createEdge(eid *EdgeID, refctx *RefContext, gctx *globContext, c *
|
|||
return nil
|
||||
}
|
||||
|
||||
func (m *Map) createEdge2(eid *EdgeID, refctx *RefContext, gctx *globContext, c *compiler, src, dst *Field) ([]*Edge, error) {
|
||||
func (m *Map) createEdge2(eid *EdgeID, refctx *RefContext, gctx *globContext, c *compiler, src, dst *Field) (*Edge, error) {
|
||||
if NodeBoardKind(src) != "" {
|
||||
return nil, d2parser.Errorf(refctx.Edge.Src, "cannot create edges between boards")
|
||||
}
|
||||
|
|
@ -1391,45 +1241,6 @@ func (m *Map) createEdge2(eid *EdgeID, refctx *RefContext, gctx *globContext, c
|
|||
return nil, d2parser.Errorf(refctx.Edge, "cannot create edges between boards")
|
||||
}
|
||||
|
||||
eid, m, common, err := eid.resolve(m)
|
||||
if err != nil {
|
||||
return nil, d2parser.Errorf(refctx.Edge, err.Error())
|
||||
}
|
||||
if len(common) > 0 {
|
||||
commonKP := d2ast.MakeKeyPathString(common)
|
||||
lastMatch := 0
|
||||
for i, el := range commonKP.Path {
|
||||
for j := lastMatch; j < len(refctx.Edge.Src.Path); j++ {
|
||||
realEl := refctx.Edge.Src.Path[j]
|
||||
if el.ScalarString() == realEl.ScalarString() {
|
||||
commonKP.Path[i] = realEl
|
||||
lastMatch += j + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
fa, err := m.EnsureField(commonKP, nil, true, c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var edges []*Edge
|
||||
for _, f := range fa {
|
||||
if _, ok := f.Composite.(*Array); ok {
|
||||
return nil, d2parser.Errorf(refctx.Edge.Src, "cannot index into array")
|
||||
}
|
||||
if f.Map() == nil {
|
||||
f.Composite = &Map{
|
||||
parent: f,
|
||||
}
|
||||
}
|
||||
edges2, err := f.Map().createEdge2(eid, refctx, gctx, c, src, dst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
edges = append(edges, edges2...)
|
||||
}
|
||||
return edges, nil
|
||||
}
|
||||
|
||||
eid.Index = nil
|
||||
eid.Glob = true
|
||||
ea := m.GetEdges(eid, nil, nil)
|
||||
|
|
@ -1452,10 +1263,10 @@ func (m *Map) createEdge2(eid *EdgeID, refctx *RefContext, gctx *globContext, c
|
|||
e2 := e.Copy(e.Parent()).(*Edge)
|
||||
e2.ID = e2.ID.Copy()
|
||||
e2.ID.Index = nil
|
||||
if refctx.Key.HasMultiGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(IDA(e2)))
|
||||
if refctx.Key.HasTripleGlob() {
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(IDA(e2)))
|
||||
} else {
|
||||
ks = d2format.Format(d2ast.MakeKeyPathString(BoardIDA(e2)))
|
||||
ks = d2format.Format(d2ast.MakeKeyPath(BoardIDA(e2)))
|
||||
}
|
||||
if _, ok := gctx.appliedEdges[ks]; ok {
|
||||
return nil, nil
|
||||
|
|
@ -1465,7 +1276,7 @@ func (m *Map) createEdge2(eid *EdgeID, refctx *RefContext, gctx *globContext, c
|
|||
|
||||
m.Edges = append(m.Edges, e)
|
||||
|
||||
return []*Edge{e}, nil
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func (s *Scalar) AST() d2ast.Node {
|
||||
|
|
@ -1476,7 +1287,7 @@ func (f *Field) AST() d2ast.Node {
|
|||
k := &d2ast.Key{
|
||||
Key: &d2ast.KeyPath{
|
||||
Path: []*d2ast.StringBox{
|
||||
d2ast.MakeValueBox(f.Name).StringBox(),
|
||||
d2ast.MakeValueBox(d2ast.RawString(f.Name, true)).StringBox(),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -1485,14 +1296,7 @@ func (f *Field) AST() d2ast.Node {
|
|||
k.Primary = d2ast.MakeValueBox(f.Primary_.AST().(d2ast.Value)).ScalarBox()
|
||||
}
|
||||
if f.Composite != nil {
|
||||
value := f.Composite.AST().(d2ast.Value)
|
||||
if m, ok := value.(*d2ast.Map); ok {
|
||||
path := m.Range.Path
|
||||
// Treat it as multi-line, but not file-map (line 0)
|
||||
m.Range = d2ast.MakeRange(",1:0:0-2:0:0")
|
||||
m.Range.Path = path
|
||||
}
|
||||
k.Value = d2ast.MakeValueBox(value)
|
||||
k.Value = d2ast.MakeValueBox(f.Composite.AST().(d2ast.Value))
|
||||
}
|
||||
|
||||
return k
|
||||
|
|
@ -1501,11 +1305,11 @@ func (f *Field) AST() d2ast.Node {
|
|||
func (e *Edge) AST() d2ast.Node {
|
||||
astEdge := &d2ast.Edge{}
|
||||
|
||||
astEdge.Src = d2ast.MakeKeyPathString(e.ID.SrcPath)
|
||||
astEdge.Src = d2ast.MakeKeyPath(e.ID.SrcPath)
|
||||
if e.ID.SrcArrow {
|
||||
astEdge.SrcArrow = "<"
|
||||
}
|
||||
astEdge.Dst = d2ast.MakeKeyPathString(e.ID.DstPath)
|
||||
astEdge.Dst = d2ast.MakeKeyPath(e.ID.DstPath)
|
||||
if e.ID.DstArrow {
|
||||
astEdge.DstArrow = ">"
|
||||
}
|
||||
|
|
@ -1524,7 +1328,7 @@ func (e *Edge) AST() d2ast.Node {
|
|||
return k
|
||||
}
|
||||
|
||||
func (e *Edge) IDString() d2ast.String {
|
||||
func (e *Edge) IDString() string {
|
||||
ast := e.AST().(*d2ast.Key)
|
||||
if e.ID.Index != nil {
|
||||
ast.EdgeIndex = &d2ast.EdgeIndex{
|
||||
|
|
@ -1533,8 +1337,7 @@ func (e *Edge) IDString() d2ast.String {
|
|||
}
|
||||
ast.Primary = d2ast.ScalarBox{}
|
||||
ast.Value = d2ast.ValueBox{}
|
||||
formatted := d2format.Format(ast)
|
||||
return d2ast.FlatUnquotedString(formatted)
|
||||
return d2format.Format(ast)
|
||||
}
|
||||
|
||||
func (a *Array) AST() d2ast.Node {
|
||||
|
|
@ -1552,14 +1355,11 @@ func (m *Map) AST() d2ast.Node {
|
|||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
astMap := &d2ast.Map{
|
||||
Range: d2ast.MakeRange(",0:0:0-1:0:0"),
|
||||
}
|
||||
if m.parent != nil && NodeBoardKind(m) != "" {
|
||||
f, ok := m.parent.(*Field)
|
||||
if ok {
|
||||
astMap.Range.Path = f.Name.GetRange().Path
|
||||
}
|
||||
astMap := &d2ast.Map{}
|
||||
if m.Root() {
|
||||
astMap.Range = d2ast.MakeRange(",0:0:0-1:0:0")
|
||||
} else {
|
||||
astMap.Range = d2ast.MakeRange(",1:0:0-2:0:0")
|
||||
}
|
||||
for _, f := range m.Fields {
|
||||
astMap.Nodes = append(astMap.Nodes, d2ast.MakeMapNodeBox(f.AST().(d2ast.MapNode)))
|
||||
|
|
@ -1572,7 +1372,7 @@ func (m *Map) AST() d2ast.Node {
|
|||
|
||||
func (m *Map) appendFieldReferences(i int, kp *d2ast.KeyPath, refctx *RefContext, c *compiler) {
|
||||
sb := kp.Path[i]
|
||||
f := m.GetField(sb.Unbox())
|
||||
f := m.GetField(sb.Unbox().ScalarString())
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -1631,12 +1431,9 @@ func IsVar(n Node) bool {
|
|||
if NodeBoardKind(n) != "" {
|
||||
return false
|
||||
}
|
||||
if f, ok := n.(*Field); ok && f.Name.ScalarString() == "vars" && f.Name.IsUnquoted() {
|
||||
if f, ok := n.(*Field); ok && f.Name == "vars" {
|
||||
return true
|
||||
}
|
||||
if n == (*Map)(nil) {
|
||||
return false
|
||||
}
|
||||
n = n.Parent()
|
||||
}
|
||||
}
|
||||
|
|
@ -1670,7 +1467,7 @@ func ParentShape(n Node) string {
|
|||
f, ok := n.(*Field)
|
||||
if ok {
|
||||
if f.Map() != nil {
|
||||
shapef := f.Map().GetField(d2ast.FlatUnquotedString("shape"))
|
||||
shapef := f.Map().GetField("shape")
|
||||
if shapef != nil && shapef.Primary() != nil {
|
||||
return shapef.Primary().Value.ScalarString()
|
||||
}
|
||||
|
|
@ -1683,30 +1480,30 @@ func ParentShape(n Node) string {
|
|||
}
|
||||
}
|
||||
|
||||
func countUnderscores(p []d2ast.String) int {
|
||||
func countUnderscores(p []string) int {
|
||||
for i, el := range p {
|
||||
if el.ScalarString() != "_" || !el.IsUnquoted() {
|
||||
if el != "_" {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func findBoardKeyword(ida ...d2ast.String) int {
|
||||
func findBoardKeyword(ida ...string) int {
|
||||
for i := range ida {
|
||||
if _, ok := d2ast.BoardKeywords[strings.ToLower(ida[i].ScalarString())]; ok && ida[i].IsUnquoted() {
|
||||
if _, ok := d2graph.BoardKeywords[ida[i]]; ok {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func findProhibitedEdgeKeyword(ida ...d2ast.String) int {
|
||||
func findProhibitedEdgeKeyword(ida ...string) int {
|
||||
for i := range ida {
|
||||
if _, ok := d2ast.SimpleReservedKeywords[ida[i].ScalarString()]; ok && ida[i].IsUnquoted() {
|
||||
if _, ok := d2graph.SimpleReservedKeywords[ida[i]]; ok {
|
||||
return i
|
||||
}
|
||||
if _, ok := d2ast.ReservedKeywordHolders[ida[i].ScalarString()]; ok && ida[i].IsUnquoted() {
|
||||
if _, ok := d2graph.ReservedKeywordHolders[ida[i]]; ok {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
|
@ -1750,7 +1547,7 @@ func parentPrimaryKey(n Node) *d2ast.Key {
|
|||
}
|
||||
|
||||
// BoardIDA returns the absolute path to n from the nearest board root.
|
||||
func BoardIDA(n Node) (ida []d2ast.String) {
|
||||
func BoardIDA(n Node) (ida []string) {
|
||||
for {
|
||||
switch n := n.(type) {
|
||||
case *Field:
|
||||
|
|
@ -1771,7 +1568,7 @@ func BoardIDA(n Node) (ida []d2ast.String) {
|
|||
}
|
||||
|
||||
// IDA returns the absolute path to n.
|
||||
func IDA(n Node) (ida []d2ast.String) {
|
||||
func IDA(n Node) (ida []string) {
|
||||
for {
|
||||
switch n := n.(type) {
|
||||
case *Field:
|
||||
|
|
@ -1792,7 +1589,7 @@ func IDA(n Node) (ida []d2ast.String) {
|
|||
}
|
||||
|
||||
// RelIDA returns the path to n relative to p.
|
||||
func RelIDA(p, n Node) (ida []d2ast.String) {
|
||||
func RelIDA(p, n Node) (ida []string) {
|
||||
for {
|
||||
switch n := n.(type) {
|
||||
case *Field:
|
||||
|
|
@ -1802,7 +1599,7 @@ func RelIDA(p, n Node) (ida []d2ast.String) {
|
|||
return ida
|
||||
}
|
||||
case *Edge:
|
||||
ida = append(ida, d2ast.FlatUnquotedString(n.String()))
|
||||
ida = append(ida, n.String())
|
||||
}
|
||||
n = n.Parent()
|
||||
f, fok := n.(*Field)
|
||||
|
|
@ -1814,11 +1611,11 @@ func RelIDA(p, n Node) (ida []d2ast.String) {
|
|||
}
|
||||
}
|
||||
|
||||
func reverseIDA[T any](slice []T) {
|
||||
for i := 0; i < len(slice)/2; i++ {
|
||||
tmp := slice[i]
|
||||
slice[i] = slice[len(slice)-i-1]
|
||||
slice[len(slice)-i-1] = tmp
|
||||
func reverseIDA(ida []string) {
|
||||
for i := 0; i < len(ida)/2; i++ {
|
||||
tmp := ida[i]
|
||||
ida[i] = ida[len(ida)-i-1]
|
||||
ida[len(ida)-i-1] = tmp
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1893,7 +1690,7 @@ func (m *Map) Equal(n2 Node) bool {
|
|||
}
|
||||
|
||||
func (m *Map) InClass(key *d2ast.Key) bool {
|
||||
classes := m.Map().GetField(d2ast.FlatUnquotedString("classes"))
|
||||
classes := m.Map().GetField("classes")
|
||||
if classes == nil || classes.Map() == nil {
|
||||
return false
|
||||
}
|
||||
|
|
@ -1921,7 +1718,7 @@ func (m *Map) IsClass() bool {
|
|||
if parentBoard.Map() == nil {
|
||||
return false
|
||||
}
|
||||
classes := parentBoard.Map().GetField(d2ast.FlatUnquotedString("classes"))
|
||||
classes := parentBoard.Map().GetField("classes")
|
||||
if classes == nil || classes.Map() == nil {
|
||||
return false
|
||||
}
|
||||
|
|
@ -1933,51 +1730,3 @@ func (m *Map) IsClass() bool {
|
|||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *Map) FindBoardRoot(path []string) *Map {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
if len(path) == 0 {
|
||||
return m
|
||||
}
|
||||
|
||||
layersf := m.GetField(d2ast.FlatUnquotedString("layers"))
|
||||
scenariosf := m.GetField(d2ast.FlatUnquotedString("scenarios"))
|
||||
stepsf := m.GetField(d2ast.FlatUnquotedString("steps"))
|
||||
|
||||
if layersf != nil && layersf.Map() != nil {
|
||||
for _, f := range layersf.Map().Fields {
|
||||
if f.Name.ScalarString() == path[0] {
|
||||
if len(path) == 1 {
|
||||
return f.Map()
|
||||
}
|
||||
return f.Map().FindBoardRoot(path[1:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if scenariosf != nil && scenariosf.Map() != nil {
|
||||
for _, f := range scenariosf.Map().Fields {
|
||||
if f.Name.ScalarString() == path[0] {
|
||||
if len(path) == 1 {
|
||||
return f.Map()
|
||||
}
|
||||
return f.Map().FindBoardRoot(path[1:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if stepsf != nil && stepsf.Map() != nil {
|
||||
for _, f := range stepsf.Map().Fields {
|
||||
if f.Name.ScalarString() == path[0] {
|
||||
if len(path) == 1 {
|
||||
return f.Map()
|
||||
}
|
||||
return f.Map().FindBoardRoot(path[1:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ func TestCopy(t *testing.T) {
|
|||
|
||||
const keyStr = `Absence makes the heart grow frantic.`
|
||||
f := &d2ir.Field{
|
||||
Name: d2ast.FlatUnquotedString(keyStr),
|
||||
Name: keyStr,
|
||||
|
||||
Primary_: s,
|
||||
Composite: a,
|
||||
|
|
@ -48,10 +48,10 @@ func TestCopy(t *testing.T) {
|
|||
}
|
||||
|
||||
m = m.Copy(nil).(*d2ir.Map)
|
||||
f.Name = d2ast.FlatUnquotedString(`Many a wife thinks her husband is the world's greatest lover.`)
|
||||
f.Name = `Many a wife thinks her husband is the world's greatest lover.`
|
||||
|
||||
assert.Equal(t, m, m.Fields[0].Parent())
|
||||
assert.Equal(t, keyStr, m.Fields[0].Name.ScalarString())
|
||||
assert.Equal(t, keyStr, m.Fields[0].Name)
|
||||
assert.Equal(t, m.Fields[0], m.Fields[0].Primary_.Parent())
|
||||
assert.Equal(t, m.Fields[0], m.Fields[0].Composite.(*d2ir.Array).Parent())
|
||||
|
||||
|
|
|
|||
|
|
@ -175,6 +175,7 @@ x -> y: hi
|
|||
}
|
||||
|
||||
a
|
||||
# if i remove this line, the glob applies as expected
|
||||
b
|
||||
b.label: a
|
||||
`)
|
||||
|
|
@ -224,25 +225,6 @@ classes: {
|
|||
assertQuery(t, m, 9, 3, nil, "")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not-basic",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `jacob: {
|
||||
shape: circle
|
||||
}
|
||||
jeremy: {
|
||||
shape: rectangle
|
||||
}
|
||||
*: {
|
||||
!&shape: rectangle
|
||||
label: I'm not a rectangle
|
||||
}`)
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 2, 0, nil, "jacob")
|
||||
assertQuery(t, m, 1, 0, nil, "jeremy")
|
||||
assertQuery(t, m, 0, 0, "I'm not a rectangle", "jacob.label")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
runa(t, tca)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import (
|
|||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
|
|
@ -18,13 +17,17 @@ func (c *compiler) pushImportStack(imp *d2ast.Import) (string, bool) {
|
|||
return "", false
|
||||
}
|
||||
if len(c.importStack) > 0 {
|
||||
if path.IsAbs(impPath) {
|
||||
c.errorf(imp, "import paths must be relative")
|
||||
return "", false
|
||||
}
|
||||
|
||||
if path.Ext(impPath) != ".d2" {
|
||||
impPath += ".d2"
|
||||
}
|
||||
|
||||
if !filepath.IsAbs(impPath) {
|
||||
impPath = path.Join(path.Dir(c.importStack[len(c.importStack)-1]), impPath)
|
||||
}
|
||||
// Imports are always relative to the importing file.
|
||||
impPath = path.Join(path.Dir(c.importStack[len(c.importStack)-1]), impPath)
|
||||
}
|
||||
|
||||
for i, p := range c.importStack {
|
||||
|
|
@ -79,11 +82,16 @@ func (c *compiler) __import(imp *d2ast.Import) (*Map, bool) {
|
|||
|
||||
// Only get immediate imports.
|
||||
if len(c.importStack) == 2 {
|
||||
if _, ok := c.seenImports[impPath]; !ok {
|
||||
if _, ok := c.importCache[impPath]; !ok {
|
||||
c.imports = append(c.imports, imp.PathWithPre())
|
||||
}
|
||||
}
|
||||
|
||||
ir, ok := c.importCache[impPath]
|
||||
if ok {
|
||||
return ir, true
|
||||
}
|
||||
|
||||
var f fs.File
|
||||
var err error
|
||||
if c.fs == nil {
|
||||
|
|
@ -105,68 +113,13 @@ func (c *compiler) __import(imp *d2ast.Import) (*Map, bool) {
|
|||
return nil, false
|
||||
}
|
||||
|
||||
ir := &Map{}
|
||||
ir = &Map{}
|
||||
ir.initRoot()
|
||||
ir.parent.(*Field).References[0].Context_.Scope = ast
|
||||
|
||||
c.compileMap(ir, ast, ast)
|
||||
|
||||
// We attempt to resolve variables in the imported file scope first
|
||||
// But ignore errors, in case the variable is meant to be resolved at the
|
||||
// importer
|
||||
savedErrors := make([]d2ast.Error, len(c.err.Errors))
|
||||
copy(savedErrors, c.err.Errors)
|
||||
c.compileSubstitutions(ir, nil)
|
||||
c.err.Errors = savedErrors
|
||||
|
||||
c.seenImports[impPath] = struct{}{}
|
||||
|
||||
return ir, true
|
||||
}
|
||||
|
||||
func (c *compiler) peekImport(imp *d2ast.Import) (*Map, bool) {
|
||||
impPath := imp.PathWithPre()
|
||||
if impPath == "" && imp.Range != (d2ast.Range{}) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if len(c.importStack) > 0 {
|
||||
if path.Ext(impPath) != ".d2" {
|
||||
impPath += ".d2"
|
||||
}
|
||||
|
||||
if !filepath.IsAbs(impPath) {
|
||||
impPath = path.Join(path.Dir(c.importStack[len(c.importStack)-1]), impPath)
|
||||
}
|
||||
}
|
||||
|
||||
var f fs.File
|
||||
var err error
|
||||
if c.fs == nil {
|
||||
f, err = os.Open(impPath)
|
||||
} else {
|
||||
f, err = c.fs.Open(impPath)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Use a separate parse error to avoid polluting the main one
|
||||
localErr := &d2parser.ParseError{}
|
||||
ast, err := d2parser.Parse(impPath, f, &d2parser.ParseOptions{
|
||||
UTF16Pos: c.utf16Pos,
|
||||
ParseError: localErr,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
ir := &Map{}
|
||||
ir.initRoot()
|
||||
ir.parent.(*Field).References[0].Context_.Scope = ast
|
||||
|
||||
c.compileMap(ir, ast, ast)
|
||||
c.importCache[impPath] = ir
|
||||
|
||||
return ir, true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,23 +211,6 @@ label: meow`,
|
|||
assert.Success(t, err)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "nested-scope",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compileFS(t, "index.d2", map[string]string{
|
||||
"index.d2": `...@second
|
||||
`,
|
||||
"second.d2": `elem: {
|
||||
...@third
|
||||
}`,
|
||||
"third.d2": `third: {
|
||||
elem
|
||||
}`,
|
||||
})
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 3, 0, nil, "")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
runa(t, tca)
|
||||
|
|
@ -252,6 +235,15 @@ label: meow`,
|
|||
assert.ErrorString(t, err, `index.d2:1:1: failed to import "../x.d2": open ../x.d2: invalid argument`)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "absolute",
|
||||
run: func(t testing.TB) {
|
||||
_, err := compileFS(t, "index.d2", map[string]string{
|
||||
"index.d2": "...@/x.d2",
|
||||
})
|
||||
assert.ErrorString(t, err, `index.d2:1:1: import paths must be relative`)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "parse",
|
||||
run: func(t testing.TB) {
|
||||
|
|
|
|||
|
|
@ -21,39 +21,6 @@ func OverlayMap(base, overlay *Map) {
|
|||
}
|
||||
}
|
||||
|
||||
func ExpandSubstitution(m, resolved *Map, placeholder *Field) {
|
||||
fi := -1
|
||||
for i := 0; i < len(m.Fields); i++ {
|
||||
if m.Fields[i] == placeholder {
|
||||
fi = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for _, of := range resolved.Fields {
|
||||
bf := m.GetField(of.Name)
|
||||
if bf == nil {
|
||||
m.Fields = append(m.Fields[:fi], append([]*Field{of.Copy(m).(*Field)}, m.Fields[fi:]...)...)
|
||||
fi++
|
||||
continue
|
||||
}
|
||||
OverlayField(bf, of)
|
||||
}
|
||||
|
||||
// NOTE this doesn't expand edges in place, and just appends
|
||||
// I suppose to do this, there needs to be an edge placeholder too on top of the field placeholder
|
||||
// Will wait to see if a problem
|
||||
for _, oe := range resolved.Edges {
|
||||
bea := m.GetEdges(oe.ID, nil, nil)
|
||||
if len(bea) == 0 {
|
||||
m.Edges = append(m.Edges, oe.Copy(m).(*Edge))
|
||||
continue
|
||||
}
|
||||
be := bea[0]
|
||||
OverlayEdge(be, oe)
|
||||
}
|
||||
}
|
||||
|
||||
func OverlayField(bf, of *Field) {
|
||||
if of.Primary_ != nil {
|
||||
bf.Primary_ = of.Primary_.Copy(bf).(*Scalar)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
)
|
||||
|
||||
func (m *Map) multiGlob(pattern []string) ([]*Field, bool) {
|
||||
|
|
@ -21,14 +22,11 @@ func (m *Map) multiGlob(pattern []string) ([]*Field, bool) {
|
|||
|
||||
func (m *Map) _doubleGlob(fa *[]*Field) {
|
||||
for _, f := range m.Fields {
|
||||
if f.Name == nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := d2ast.ReservedKeywords[f.Name.ScalarString()]; ok && f.Name.IsUnquoted() {
|
||||
if f.Name.ScalarString() == "layers" {
|
||||
if _, ok := d2graph.ReservedKeywords[f.Name]; ok {
|
||||
if f.Name == "layers" {
|
||||
continue
|
||||
}
|
||||
if _, ok := d2ast.BoardKeywords[f.Name.ScalarString()]; !ok {
|
||||
if _, ok := d2graph.BoardKeywords[f.Name]; !ok {
|
||||
continue
|
||||
}
|
||||
// We don't ever want to append layers, scenarios or steps directly.
|
||||
|
|
@ -48,8 +46,8 @@ func (m *Map) _doubleGlob(fa *[]*Field) {
|
|||
|
||||
func (m *Map) _tripleGlob(fa *[]*Field) {
|
||||
for _, f := range m.Fields {
|
||||
if _, ok := d2ast.ReservedKeywords[f.Name.ScalarString()]; ok && f.Name.IsUnquoted() {
|
||||
if _, ok := d2ast.BoardKeywords[f.Name.ScalarString()]; !ok {
|
||||
if _, ok := d2graph.ReservedKeywords[f.Name]; ok {
|
||||
if _, ok := d2graph.BoardKeywords[f.Name]; !ok {
|
||||
continue
|
||||
}
|
||||
// We don't ever want to append layers, scenarios or steps directly.
|
||||
|
|
@ -71,7 +69,7 @@ func matchPattern(s string, pattern []string) bool {
|
|||
if len(pattern) == 0 {
|
||||
return true
|
||||
}
|
||||
if _, ok := d2ast.ReservedKeywords[s]; ok {
|
||||
if _, ok := d2graph.ReservedKeywords[s]; ok {
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -157,24 +157,6 @@ sh*.an* -> sh*.an*`)
|
|||
assertQuery(t, m, 0, 0, nil, "shared.(animal -> animate)[0]")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edge/4",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `app_a: {
|
||||
x
|
||||
}
|
||||
|
||||
app_b: {
|
||||
y
|
||||
}
|
||||
|
||||
app_*.x -> app_*.y`)
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 6, 4, nil, "")
|
||||
assertQuery(t, m, 2, 1, nil, "app_a")
|
||||
assertQuery(t, m, 2, 1, nil, "app_b")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edge-glob-index",
|
||||
run: func(t testing.TB) {
|
||||
|
|
@ -328,79 +310,6 @@ layers.x: { wrapper.p }
|
|||
assertQuery(t, m, 0, 0, nil, "layers.x.wrapper.p")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edge-glob-null",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `a -> b
|
||||
(* -> *)[*]: null
|
||||
x -> y
|
||||
`)
|
||||
assert.Success(t, err)
|
||||
// 4 fields and 0 edges
|
||||
assertQuery(t, m, 4, 0, nil, "")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "field-glob-style-inherit",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `*.style.opacity: 0
|
||||
x: {
|
||||
style.opacity: 1
|
||||
}
|
||||
|
||||
scenarios: {
|
||||
1: {
|
||||
x
|
||||
}
|
||||
}
|
||||
`)
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 0, 0, 1, "x.style.opacity")
|
||||
assertQuery(t, m, 0, 0, 1, "scenarios.1.x.style.opacity")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edge-glob-style-inherit/1",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `(* -> *)[*].style.opacity: 0
|
||||
x -> y: {
|
||||
style.opacity: 1
|
||||
}
|
||||
|
||||
scenarios: {
|
||||
1: {
|
||||
x
|
||||
}
|
||||
}
|
||||
`)
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 0, 0, 1, "(x -> y)[0].style.opacity")
|
||||
assertQuery(t, m, 0, 0, 1, "scenarios.1.(x -> y)[0].style.opacity")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edge-glob-style-inherit/2",
|
||||
run: func(t testing.TB) {
|
||||
m, err := compile(t, `*.style.opacity: 0
|
||||
(* -> *)[*].style.opacity: 0
|
||||
x -> y
|
||||
|
||||
steps: {
|
||||
1: {
|
||||
x.style.opacity: 1
|
||||
}
|
||||
2: {
|
||||
(x -> y)[0].style.opacity: 1
|
||||
}
|
||||
3: {
|
||||
y.style.opacity: 1
|
||||
}
|
||||
}
|
||||
`)
|
||||
assert.Success(t, err)
|
||||
assertQuery(t, m, 0, 0, 1, "steps.3.(x -> y)[0].style.opacity")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "double-glob/edge/1",
|
||||
run: func(t testing.TB) {
|
||||
|
|
|
|||
|
|
@ -1,71 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package d2wasm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"runtime/debug"
|
||||
"syscall/js"
|
||||
)
|
||||
|
||||
type D2API struct {
|
||||
exports map[string]js.Func
|
||||
}
|
||||
|
||||
func NewD2API() *D2API {
|
||||
return &D2API{
|
||||
exports: make(map[string]js.Func),
|
||||
}
|
||||
}
|
||||
|
||||
func (api *D2API) Register(name string, fn func(args []js.Value) (interface{}, error)) {
|
||||
api.exports[name] = wrapWASMCall(fn)
|
||||
}
|
||||
|
||||
func (api *D2API) ExportTo(target js.Value) {
|
||||
d2Namespace := make(map[string]interface{})
|
||||
for name, fn := range api.exports {
|
||||
d2Namespace[name] = fn
|
||||
}
|
||||
target.Set("d2", js.ValueOf(d2Namespace))
|
||||
}
|
||||
|
||||
func wrapWASMCall(fn func(args []js.Value) (interface{}, error)) js.Func {
|
||||
return js.FuncOf(func(this js.Value, args []js.Value) (result any) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
resp := WASMResponse{
|
||||
Error: &WASMError{
|
||||
Message: fmt.Sprintf("panic recovered: %v\n%s", r, debug.Stack()),
|
||||
Code: 500,
|
||||
},
|
||||
}
|
||||
jsonResp, _ := json.Marshal(resp)
|
||||
result = string(jsonResp)
|
||||
}
|
||||
}()
|
||||
|
||||
data, err := fn(args)
|
||||
if err != nil {
|
||||
wasmErr, ok := err.(*WASMError)
|
||||
if !ok {
|
||||
wasmErr = &WASMError{
|
||||
Message: err.Error(),
|
||||
Code: 500,
|
||||
}
|
||||
}
|
||||
resp := WASMResponse{
|
||||
Error: wasmErr,
|
||||
}
|
||||
jsonResp, _ := json.Marshal(resp)
|
||||
return string(jsonResp)
|
||||
}
|
||||
|
||||
resp := WASMResponse{
|
||||
Data: data,
|
||||
}
|
||||
jsonResp, _ := json.Marshal(resp)
|
||||
return string(jsonResp)
|
||||
})
|
||||
}
|
||||
|
|
@ -1,544 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package d2wasm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall/js"
|
||||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2compiler"
|
||||
"oss.terrastruct.com/d2/d2format"
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2layouts/d2dagrelayout"
|
||||
"oss.terrastruct.com/d2/d2layouts/d2elklayout"
|
||||
"oss.terrastruct.com/d2/d2lib"
|
||||
"oss.terrastruct.com/d2/d2lsp"
|
||||
"oss.terrastruct.com/d2/d2oracle"
|
||||
"oss.terrastruct.com/d2/d2parser"
|
||||
"oss.terrastruct.com/d2/d2renderers/d2animate"
|
||||
"oss.terrastruct.com/d2/d2renderers/d2fonts"
|
||||
"oss.terrastruct.com/d2/d2renderers/d2svg"
|
||||
"oss.terrastruct.com/d2/d2renderers/d2svg/appendix"
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
"oss.terrastruct.com/d2/lib/log"
|
||||
"oss.terrastruct.com/d2/lib/memfs"
|
||||
"oss.terrastruct.com/d2/lib/textmeasure"
|
||||
"oss.terrastruct.com/d2/lib/urlenc"
|
||||
"oss.terrastruct.com/d2/lib/version"
|
||||
)
|
||||
|
||||
const DEFAULT_INPUT_PATH = "index"
|
||||
|
||||
func GetParentID(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing id argument", Code: 400}
|
||||
}
|
||||
|
||||
id := args[0].String()
|
||||
mk, err := d2parser.ParseMapKey(id)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 400}
|
||||
}
|
||||
|
||||
if len(mk.Edges) > 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if mk.Key != nil {
|
||||
if len(mk.Key.Path) == 1 {
|
||||
return "root", nil
|
||||
}
|
||||
mk.Key.Path = mk.Key.Path[:len(mk.Key.Path)-1]
|
||||
return strings.Join(mk.Key.StringIDA(), "."), nil
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func GetObjOrder(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing dsl argument", Code: 400}
|
||||
}
|
||||
|
||||
dsl := args[0].String()
|
||||
g, _, err := d2compiler.Compile("", strings.NewReader(dsl), &d2compiler.CompileOptions{
|
||||
UTF16Pos: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 400}
|
||||
}
|
||||
|
||||
objOrder, err := d2oracle.GetObjOrder(g, nil)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"order": objOrder,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func GetRefRanges(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 4 {
|
||||
return nil, &WASMError{Message: "missing required arguments", Code: 400}
|
||||
}
|
||||
|
||||
var fs map[string]string
|
||||
if err := json.Unmarshal([]byte(args[0].String()), &fs); err != nil {
|
||||
return nil, &WASMError{Message: "invalid fs argument", Code: 400}
|
||||
}
|
||||
|
||||
file := args[1].String()
|
||||
key := args[2].String()
|
||||
|
||||
var boardPath []string
|
||||
if err := json.Unmarshal([]byte(args[3].String()), &boardPath); err != nil {
|
||||
return nil, &WASMError{Message: "invalid boardPath argument", Code: 400}
|
||||
}
|
||||
|
||||
ranges, importRanges, err := d2lsp.GetRefRanges(file, fs, boardPath, key)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
|
||||
return RefRangesResponse{
|
||||
Ranges: ranges,
|
||||
ImportRanges: importRanges,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func GetELKGraph(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing JSON argument", Code: 400}
|
||||
}
|
||||
var input CompileRequest
|
||||
if err := json.Unmarshal([]byte(args[0].String()), &input); err != nil {
|
||||
return nil, &WASMError{Message: "invalid JSON input", Code: 400}
|
||||
}
|
||||
|
||||
if input.FS == nil {
|
||||
return nil, &WASMError{Message: "missing 'fs' field in input JSON", Code: 400}
|
||||
}
|
||||
|
||||
inputPath := DEFAULT_INPUT_PATH
|
||||
|
||||
if input.InputPath != nil {
|
||||
inputPath = *input.InputPath
|
||||
}
|
||||
|
||||
if _, ok := input.FS[inputPath]; !ok {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("missing '%s' file in input fs", inputPath), Code: 400}
|
||||
}
|
||||
|
||||
fs, err := memfs.New(input.FS)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("invalid fs input: %s", err.Error()), Code: 400}
|
||||
}
|
||||
|
||||
g, _, err := d2compiler.Compile(inputPath, strings.NewReader(input.FS[inputPath]), &d2compiler.CompileOptions{
|
||||
UTF16Pos: true,
|
||||
FS: fs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 400}
|
||||
}
|
||||
|
||||
ruler, err := textmeasure.NewRuler()
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("text ruler cannot be initialized: %s", err.Error()), Code: 500}
|
||||
}
|
||||
err = g.SetDimensions(nil, ruler, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
elk, err := d2elklayout.ConvertGraph(context.Background(), g, nil)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 400}
|
||||
}
|
||||
return elk, nil
|
||||
}
|
||||
|
||||
func Compile(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing JSON argument", Code: 400}
|
||||
}
|
||||
var input CompileRequest
|
||||
if err := json.Unmarshal([]byte(args[0].String()), &input); err != nil {
|
||||
return nil, &WASMError{Message: "invalid JSON input", Code: 400}
|
||||
}
|
||||
|
||||
if input.FS == nil {
|
||||
return nil, &WASMError{Message: "missing 'fs' field in input JSON", Code: 400}
|
||||
}
|
||||
|
||||
compileOpts := &d2lib.CompileOptions{
|
||||
UTF16Pos: true,
|
||||
}
|
||||
|
||||
inputPath := DEFAULT_INPUT_PATH
|
||||
|
||||
if input.InputPath != nil {
|
||||
inputPath = *input.InputPath
|
||||
}
|
||||
|
||||
if _, ok := input.FS[inputPath]; !ok {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("missing '%s' file in input fs", inputPath), Code: 400}
|
||||
}
|
||||
|
||||
compileOpts.InputPath = inputPath
|
||||
|
||||
compileOpts.LayoutResolver = func(engine string) (d2graph.LayoutGraph, error) {
|
||||
switch engine {
|
||||
case "dagre":
|
||||
return d2dagrelayout.DefaultLayout, nil
|
||||
case "elk":
|
||||
return d2elklayout.DefaultLayout, nil
|
||||
default:
|
||||
return nil, &WASMError{Message: fmt.Sprintf("layout option '%s' not recognized", engine), Code: 400}
|
||||
}
|
||||
}
|
||||
|
||||
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}
|
||||
}
|
||||
|
||||
var fontRegular []byte
|
||||
var fontItalic []byte
|
||||
var fontBold []byte
|
||||
var fontSemibold []byte
|
||||
if input.Opts != nil && (input.Opts.FontRegular != nil) {
|
||||
fontRegular = *input.Opts.FontRegular
|
||||
}
|
||||
if input.Opts != nil && (input.Opts.FontItalic != nil) {
|
||||
fontItalic = *input.Opts.FontItalic
|
||||
}
|
||||
if input.Opts != nil && (input.Opts.FontBold != nil) {
|
||||
fontBold = *input.Opts.FontBold
|
||||
}
|
||||
if input.Opts != nil && (input.Opts.FontSemibold != nil) {
|
||||
fontSemibold = *input.Opts.FontSemibold
|
||||
}
|
||||
if fontRegular != nil || fontItalic != nil || fontBold != nil || fontSemibold != nil {
|
||||
fontFamily, err := d2fonts.AddFontFamily("custom", fontRegular, fontItalic, fontBold, fontSemibold)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("custom fonts could not be initialized: %s", err.Error()), Code: 400}
|
||||
}
|
||||
compileOpts.FontFamily = fontFamily
|
||||
}
|
||||
|
||||
compileOpts.Ruler, err = textmeasure.NewRuler()
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("text ruler cannot be initialized: %s", err.Error()), Code: 500}
|
||||
}
|
||||
|
||||
if input.Opts != nil && input.Opts.Layout != nil {
|
||||
compileOpts.Layout = input.Opts.Layout
|
||||
}
|
||||
|
||||
renderOpts := &d2svg.RenderOpts{}
|
||||
if input.Opts != nil && input.Opts.Sketch != nil {
|
||||
renderOpts.Sketch = input.Opts.Sketch
|
||||
}
|
||||
if input.Opts != nil && input.Opts.Pad != nil {
|
||||
renderOpts.Pad = input.Opts.Pad
|
||||
}
|
||||
if input.Opts != nil && input.Opts.Center != nil {
|
||||
renderOpts.Center = input.Opts.Center
|
||||
}
|
||||
if input.Opts != nil && input.Opts.ThemeID != nil {
|
||||
renderOpts.ThemeID = input.Opts.ThemeID
|
||||
}
|
||||
if input.Opts != nil && input.Opts.DarkThemeID != nil {
|
||||
renderOpts.DarkThemeID = input.Opts.DarkThemeID
|
||||
}
|
||||
if input.Opts != nil && input.Opts.Scale != nil {
|
||||
renderOpts.Scale = input.Opts.Scale
|
||||
}
|
||||
|
||||
ctx := log.WithDefault(context.Background())
|
||||
diagram, g, err := d2lib.Compile(ctx, input.FS[inputPath], compileOpts, renderOpts)
|
||||
if err != nil {
|
||||
if pe, ok := err.(*d2parser.ParseError); ok {
|
||||
errs, _ := json.Marshal(pe.Errors)
|
||||
return nil, &WASMError{Message: string(errs), Code: 400}
|
||||
}
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
|
||||
input.FS[inputPath] = d2format.Format(g.AST)
|
||||
|
||||
return CompileResponse{
|
||||
FS: input.FS,
|
||||
InputPath: inputPath,
|
||||
Diagram: *diagram,
|
||||
Graph: *g,
|
||||
RenderOptions: RenderOptions{
|
||||
ThemeID: renderOpts.ThemeID,
|
||||
DarkThemeID: renderOpts.DarkThemeID,
|
||||
Sketch: renderOpts.Sketch,
|
||||
Pad: renderOpts.Pad,
|
||||
Center: renderOpts.Center,
|
||||
Scale: renderOpts.Scale,
|
||||
ForceAppendix: input.Opts.ForceAppendix,
|
||||
Target: input.Opts.Target,
|
||||
AnimateInterval: input.Opts.AnimateInterval,
|
||||
Salt: input.Opts.Salt,
|
||||
NoXMLTag: input.Opts.NoXMLTag,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func Render(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing JSON argument", Code: 400}
|
||||
}
|
||||
var input RenderRequest
|
||||
if err := json.Unmarshal([]byte(args[0].String()), &input); err != nil {
|
||||
return nil, &WASMError{Message: "invalid JSON input", Code: 400}
|
||||
}
|
||||
|
||||
if input.Diagram == nil {
|
||||
return nil, &WASMError{Message: "missing 'diagram' field in input JSON", Code: 400}
|
||||
}
|
||||
|
||||
animateInterval := 0
|
||||
if input.Opts != nil && input.Opts.AnimateInterval != nil && *input.Opts.AnimateInterval > 0 {
|
||||
animateInterval = int(*input.Opts.AnimateInterval)
|
||||
}
|
||||
|
||||
var boardPath []string
|
||||
noChildren := true
|
||||
|
||||
if input.Opts.Target != nil {
|
||||
switch *input.Opts.Target {
|
||||
case "*":
|
||||
noChildren = false
|
||||
case "":
|
||||
default:
|
||||
target := *input.Opts.Target
|
||||
if strings.HasSuffix(target, ".*") {
|
||||
target = target[:len(target)-2]
|
||||
noChildren = false
|
||||
}
|
||||
key, err := d2parser.ParseKey(target)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("target '%s' not recognized", target), Code: 400}
|
||||
}
|
||||
boardPath = key.StringIDA()
|
||||
}
|
||||
if !noChildren && animateInterval <= 0 {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("target '%s' only supported for animated SVGs", *input.Opts.Target), Code: 500}
|
||||
}
|
||||
}
|
||||
|
||||
diagram := input.Diagram.GetBoard(boardPath)
|
||||
if diagram == nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("render target '%s' not found", strings.Join(boardPath, ".")), Code: 400}
|
||||
}
|
||||
if noChildren {
|
||||
diagram.Layers = nil
|
||||
diagram.Scenarios = nil
|
||||
diagram.Steps = nil
|
||||
}
|
||||
|
||||
renderOpts := &d2svg.RenderOpts{}
|
||||
|
||||
if input.Opts != nil && input.Opts.Salt != nil {
|
||||
renderOpts.Salt = input.Opts.Salt
|
||||
}
|
||||
|
||||
if animateInterval > 0 {
|
||||
masterID, err := diagram.HashID(renderOpts.Salt)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("cannot process animate interval: %s", err.Error()), Code: 500}
|
||||
}
|
||||
renderOpts.MasterID = masterID
|
||||
}
|
||||
|
||||
ruler, err := textmeasure.NewRuler()
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("text ruler cannot be initialized: %s", err.Error()), Code: 500}
|
||||
}
|
||||
|
||||
if input.Opts != nil && input.Opts.Sketch != nil {
|
||||
renderOpts.Sketch = input.Opts.Sketch
|
||||
}
|
||||
if input.Opts != nil && input.Opts.Pad != nil {
|
||||
renderOpts.Pad = input.Opts.Pad
|
||||
}
|
||||
if input.Opts != nil && input.Opts.Center != nil {
|
||||
renderOpts.Center = input.Opts.Center
|
||||
}
|
||||
if input.Opts != nil && input.Opts.ThemeID != nil {
|
||||
renderOpts.ThemeID = input.Opts.ThemeID
|
||||
}
|
||||
if input.Opts != nil && input.Opts.DarkThemeID != nil {
|
||||
renderOpts.DarkThemeID = input.Opts.DarkThemeID
|
||||
}
|
||||
if input.Opts != nil && input.Opts.Scale != nil {
|
||||
renderOpts.Scale = input.Opts.Scale
|
||||
}
|
||||
if input.Opts != nil && input.Opts.NoXMLTag != nil {
|
||||
renderOpts.NoXMLTag = input.Opts.NoXMLTag
|
||||
}
|
||||
|
||||
forceAppendix := input.Opts != nil && input.Opts.ForceAppendix != nil && *input.Opts.ForceAppendix
|
||||
|
||||
var boards [][]byte
|
||||
if noChildren {
|
||||
var board []byte
|
||||
board, err = renderSingleBoard(renderOpts, forceAppendix, ruler, diagram)
|
||||
boards = [][]byte{board}
|
||||
} else {
|
||||
boards, err = renderBoards(renderOpts, forceAppendix, ruler, diagram)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("render failed: %s", err.Error()), Code: 500}
|
||||
}
|
||||
|
||||
var out []byte
|
||||
if len(boards) > 0 {
|
||||
out = boards[0]
|
||||
if animateInterval > 0 {
|
||||
out, err = d2animate.Wrap(diagram, boards, *renderOpts, animateInterval)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("animation failed: %s", err.Error()), Code: 500}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func renderSingleBoard(opts *d2svg.RenderOpts, forceAppendix bool, ruler *textmeasure.Ruler, diagram *d2target.Diagram) ([]byte, error) {
|
||||
out, err := d2svg.Render(diagram, opts)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: fmt.Sprintf("render failed: %s", err.Error()), Code: 500}
|
||||
}
|
||||
if forceAppendix {
|
||||
out = appendix.Append(diagram, opts, ruler, out)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func renderBoards(opts *d2svg.RenderOpts, forceAppendix bool, ruler *textmeasure.Ruler, diagram *d2target.Diagram) ([][]byte, error) {
|
||||
var boards [][]byte
|
||||
for _, dl := range diagram.Layers {
|
||||
childrenBoards, err := renderBoards(opts, forceAppendix, ruler, dl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boards = append(boards, childrenBoards...)
|
||||
}
|
||||
for _, dl := range diagram.Scenarios {
|
||||
childrenBoards, err := renderBoards(opts, forceAppendix, ruler, dl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boards = append(boards, childrenBoards...)
|
||||
}
|
||||
for _, dl := range diagram.Steps {
|
||||
childrenBoards, err := renderBoards(opts, forceAppendix, ruler, dl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boards = append(boards, childrenBoards...)
|
||||
}
|
||||
|
||||
if !diagram.IsFolderOnly {
|
||||
out, err := renderSingleBoard(opts, forceAppendix, ruler, diagram)
|
||||
if err != nil {
|
||||
return boards, err
|
||||
}
|
||||
boards = append([][]byte{out}, boards...)
|
||||
}
|
||||
return boards, nil
|
||||
}
|
||||
|
||||
func GetBoardAtPosition(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 3 {
|
||||
return nil, &WASMError{Message: "missing required arguments", Code: 400}
|
||||
}
|
||||
|
||||
dsl := args[0].String()
|
||||
line := args[1].Int()
|
||||
column := args[2].Int()
|
||||
|
||||
boardPath, err := d2lsp.GetBoardAtPosition(dsl, d2ast.Position{
|
||||
Line: line,
|
||||
Column: column,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
|
||||
return BoardPositionResponse{BoardPath: boardPath}, nil
|
||||
}
|
||||
|
||||
func Encode(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing script argument", Code: 400}
|
||||
}
|
||||
|
||||
script := args[0].String()
|
||||
encoded, err := urlenc.Encode(script)
|
||||
// should never happen
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
|
||||
return map[string]string{"result": encoded}, nil
|
||||
}
|
||||
|
||||
func Decode(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 1 {
|
||||
return nil, &WASMError{Message: "missing script argument", Code: 400}
|
||||
}
|
||||
|
||||
script := args[0].String()
|
||||
script, err := urlenc.Decode(script)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
return map[string]string{"result": script}, nil
|
||||
}
|
||||
|
||||
func GetVersion(args []js.Value) (interface{}, error) {
|
||||
return version.Version, nil
|
||||
}
|
||||
|
||||
func GetCompletions(args []js.Value) (interface{}, error) {
|
||||
if len(args) < 3 {
|
||||
return nil, &WASMError{Message: "missing required arguments", Code: 400}
|
||||
}
|
||||
|
||||
text := args[0].String()
|
||||
line := args[1].Int()
|
||||
column := args[2].Int()
|
||||
|
||||
completions, err := d2lsp.GetCompletionItems(text, line, column)
|
||||
if err != nil {
|
||||
return nil, &WASMError{Message: err.Error(), Code: 500}
|
||||
}
|
||||
|
||||
// Convert to map for JSON serialization
|
||||
items := make([]map[string]interface{}, len(completions))
|
||||
for i, completion := range completions {
|
||||
items[i] = map[string]interface{}{
|
||||
"label": completion.Label,
|
||||
"kind": int(completion.Kind),
|
||||
"detail": completion.Detail,
|
||||
"insertText": completion.InsertText,
|
||||
}
|
||||
}
|
||||
|
||||
return CompletionResponse{
|
||||
Items: items,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package d2wasm
|
||||
|
||||
import (
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
)
|
||||
|
||||
type WASMResponse struct {
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Error *WASMError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type WASMError struct {
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
}
|
||||
|
||||
func (e *WASMError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
type RefRangesResponse struct {
|
||||
Ranges []d2ast.Range `json:"ranges"`
|
||||
ImportRanges []d2ast.Range `json:"importRanges"`
|
||||
}
|
||||
|
||||
type BoardPositionResponse struct {
|
||||
BoardPath []string `json:"boardPath"`
|
||||
}
|
||||
|
||||
type CompileRequest struct {
|
||||
FS map[string]string `json:"fs"`
|
||||
InputPath *string `json:"inputPath"`
|
||||
Opts *CompileOptions `json:"options"`
|
||||
}
|
||||
|
||||
type RenderOptions struct {
|
||||
Pad *int64 `json:"pad"`
|
||||
Sketch *bool `json:"sketch"`
|
||||
Center *bool `json:"center"`
|
||||
ThemeID *int64 `json:"themeID"`
|
||||
DarkThemeID *int64 `json:"darkThemeID"`
|
||||
Scale *float64 `json:"scale"`
|
||||
ForceAppendix *bool `json:"forceAppendix"`
|
||||
Target *string `json:"target"`
|
||||
AnimateInterval *int64 `json:"animateInterval"`
|
||||
Salt *string `json:"salt"`
|
||||
NoXMLTag *bool `json:"noXMLTag"`
|
||||
}
|
||||
|
||||
type CompileOptions struct {
|
||||
RenderOptions
|
||||
Layout *string `json:"layout"`
|
||||
FontRegular *[]byte `json:"FontRegular"`
|
||||
FontItalic *[]byte `json:"FontItalic"`
|
||||
FontBold *[]byte `json:"FontBold"`
|
||||
FontSemibold *[]byte `json:"FontSemibold"`
|
||||
}
|
||||
|
||||
type CompileResponse struct {
|
||||
FS map[string]string `json:"fs"`
|
||||
InputPath string `json:"inputPath"`
|
||||
Diagram d2target.Diagram `json:"diagram"`
|
||||
Graph d2graph.Graph `json:"graph"`
|
||||
RenderOptions RenderOptions `json:"renderOptions"`
|
||||
}
|
||||
|
||||
type CompletionResponse struct {
|
||||
Items []map[string]interface{} `json:"items"`
|
||||
}
|
||||
|
||||
type RenderRequest struct {
|
||||
Diagram *d2target.Diagram `json:"diagram"`
|
||||
Opts *RenderOptions `json:"options"`
|
||||
}
|
||||
32
d2js/js.go
32
d2js/js.go
|
|
@ -1,32 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"syscall/js"
|
||||
|
||||
"oss.terrastruct.com/d2/d2js/d2wasm"
|
||||
)
|
||||
|
||||
func main() {
|
||||
api := d2wasm.NewD2API()
|
||||
|
||||
api.Register("getCompletions", d2wasm.GetCompletions)
|
||||
api.Register("getParentID", d2wasm.GetParentID)
|
||||
api.Register("getObjOrder", d2wasm.GetObjOrder)
|
||||
api.Register("getRefRanges", d2wasm.GetRefRanges)
|
||||
api.Register("getELKGraph", d2wasm.GetELKGraph)
|
||||
api.Register("compile", d2wasm.Compile)
|
||||
api.Register("render", d2wasm.Render)
|
||||
api.Register("getBoardAtPosition", d2wasm.GetBoardAtPosition)
|
||||
api.Register("encode", d2wasm.Encode)
|
||||
api.Register("decode", d2wasm.Decode)
|
||||
api.Register("version", d2wasm.GetVersion)
|
||||
|
||||
api.ExportTo(js.Global())
|
||||
|
||||
if cb := js.Global().Get("onWasmInitialized"); !cb.IsUndefined() {
|
||||
cb.Invoke()
|
||||
}
|
||||
select {}
|
||||
}
|
||||
28
d2js/js/.gitignore
vendored
28
d2js/js/.gitignore
vendored
|
|
@ -1,28 +0,0 @@
|
|||
node_modules
|
||||
.npm
|
||||
bun.lockb
|
||||
|
||||
src/wasm-loader.browser.js
|
||||
wasm/d2.wasm
|
||||
dist/
|
||||
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
coverage/
|
||||
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
*.tmp
|
||||
*.temp
|
||||
.cache/
|
||||
|
|
@ -1 +0,0 @@
|
|||
src/platform.browser.js
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
# Changelog
|
||||
|
||||
All notable changes to only the d2.js package will be documented in this file. **Does not
|
||||
include changes to the main d2 project.**
|
||||
|
||||
## Next
|
||||
|
||||
- Fix TypeScript signatures
|
||||
|
||||
## [0.1.22]
|
||||
### March 20, 2025
|
||||
|
||||
- Support `d2-config`. Support additional options. [#2343](https://github.com/terrastruct/d2/pull/2343)
|
||||
- `themeID`
|
||||
- `darkThemeID`
|
||||
- `center`
|
||||
- `pad`
|
||||
- `scale`
|
||||
- `forceAppendix`
|
||||
- `target`
|
||||
- `animateInterval`
|
||||
- `salt`
|
||||
- `noXMLTag`
|
||||
- Support relative imports. Improve elk error handling [#2382](https://github.com/terrastruct/d2/pull/2382)
|
||||
- Support fonts (`fontRegular`, `fontItalic`, `fontBold`, `fontSemiBold`) [#2384](https://github.com/terrastruct/d2/pull/2384)
|
||||
- Add TypeScript signatures
|
||||
|
||||
## [0.1.21]
|
||||
### January 12, 2025
|
||||
|
||||
First public release
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
.POSIX:
|
||||
.PHONY: all
|
||||
all: fmt build test cleanup
|
||||
|
||||
.PHONY: fmt
|
||||
fmt: node_modules
|
||||
prefix "$@" ../../ci/sub/bin/fmt.sh
|
||||
prefix "$@" rm -f yarn.lock
|
||||
|
||||
.PHONY: build
|
||||
build: fmt
|
||||
prefix "$@" ./ci/build.sh
|
||||
|
||||
.PHONY: dev
|
||||
dev: build
|
||||
prefix "$@" git checkout -- src/platform.js src/worker.js
|
||||
prefix "$@" bun run dev
|
||||
|
||||
.PHONY: test
|
||||
test: build
|
||||
prefix "$@" bun test:all
|
||||
|
||||
.PHONY: node_modules
|
||||
node_modules:
|
||||
prefix "$@" bun install $${CI:+--frozen-lockfile}
|
||||
|
||||
.PHONY: cleanup
|
||||
cleanup: test
|
||||
prefix "$@" git checkout -- src/platform.js src/worker.js
|
||||
|
|
@ -1,193 +0,0 @@
|
|||
# D2.js
|
||||
|
||||
[](https://www.npmjs.com/package/@terrastruct/d2)
|
||||
[](https://mozilla.org/MPL/2.0/)
|
||||
|
||||
D2.js is a JavaScript wrapper around D2, the modern diagram scripting language. It enables running D2 directly in browsers and Node environments through WebAssembly.
|
||||
|
||||
## Features
|
||||
|
||||
- 🌐 **Universal** - Works in both browser and Node environments
|
||||
- 🚀 **Modern** - Built with ESM modules, with CJS fallback
|
||||
- 🔄 **Isomorphic** - Same API everywhere
|
||||
- ⚡ **Fast** - Powered by WebAssembly for near-native performance
|
||||
- 📦 **Lightweight** - Minimal wrapper around the core D2 engine
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm install @terrastruct/d2
|
||||
|
||||
# yarn
|
||||
yarn add @terrastruct/d2
|
||||
|
||||
# pnpm
|
||||
pnpm add @terrastruct/d2
|
||||
|
||||
# bun
|
||||
bun add @terrastruct/d2
|
||||
```
|
||||
|
||||
### Nightly
|
||||
|
||||
Use the `@nightly` tag to get the version that is built by daily CI on the master branch.
|
||||
|
||||
For example,
|
||||
|
||||
```bash
|
||||
yarn add @terrastruct/d2@nightly
|
||||
```
|
||||
|
||||
A demo using the nightly build is hosted [here](https://alixander-d2js.web.val.run/).
|
||||
|
||||
## Usage
|
||||
|
||||
D2.js uses webworkers to call a WASM file.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```javascript
|
||||
// Same for Node or browser
|
||||
import { D2 } from '@terrastruct/d2';
|
||||
// Or using a CDN
|
||||
// import { D2 } from 'https://esm.sh/@terrastruct/d2';
|
||||
|
||||
const d2 = new D2();
|
||||
|
||||
const result = await d2.compile('x -> y');
|
||||
const svg = await d2.render(result.diagram, result.renderOptions);
|
||||
```
|
||||
|
||||
Configuring render options (see [CompileOptions](#compileoptions) for all available options):
|
||||
|
||||
```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.renderOptions);
|
||||
```
|
||||
|
||||
### Imports
|
||||
|
||||
In order to support [imports](https://d2lang.com/tour/imports), a mapping of D2 file paths to their content can be passed to the compiler.
|
||||
|
||||
```javascript
|
||||
import { D2 } from '@terrastruct/d2';
|
||||
|
||||
const d2 = new D2();
|
||||
|
||||
const fs = {
|
||||
"project.d2": "a: @import",
|
||||
"import.d2": "x: {shape: circle}",
|
||||
}
|
||||
|
||||
const result = await d2.compile({
|
||||
fs,
|
||||
inputPath: "project.d2",
|
||||
options: {
|
||||
sketch: true
|
||||
}
|
||||
});
|
||||
const svg = await d2.render(result.diagram, result.renderOptions);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `new D2()`
|
||||
|
||||
Creates a new D2 instance.
|
||||
|
||||
### `compile(input: string | CompileRequest, options?: CompileOptions): Promise<CompileResult>`
|
||||
|
||||
Compiles D2 markup into an intermediate representation. It compile options are provided in both `input` and `options`, the latter will take precedence.
|
||||
|
||||
### `render(diagram: Diagram, options?: RenderOptions): Promise<string>`
|
||||
|
||||
Renders a compiled diagram to SVG.
|
||||
|
||||
### `CompileOptions`
|
||||
|
||||
All [RenderOptions](#renderoptions) properties in addition to:
|
||||
|
||||
- `layout`: Layout engine to use ('dagre' | 'elk') [default: 'dagre']
|
||||
- `fontRegular` A byte array containing .ttf file to use for the regular font. If none provided, Source Sans Pro Regular is used.
|
||||
- `fontItalic` A byte array containing .ttf file to use for the italic font. If none provided, Source Sans Pro Italic is used.
|
||||
- `fontBold` A byte array containing .ttf file to use for the bold font. If none provided, Source Sans Pro Bold is used.
|
||||
- `fontSemibold` A byte array containing .ttf file to use for the semibold font. If none provided, Source Sans Pro Semibold is used.
|
||||
|
||||
### `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
|
||||
- `center`: Center the SVG in the containing viewbox [default: false]
|
||||
- `pad`: Pixels padded around the rendered diagram [default: 100]
|
||||
- `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]
|
||||
- `target`: Target board/s to render. If target ends with '*', it will be rendered with all of its scenarios, steps, and layers. Otherwise, only the target board will be rendered. E.g. `target: 'layers.x.*'` to render layer 'x' with all of its children. Pass '*' to render all scenarios, steps, and layers. By default, only the root board is rendered. Multi-board outputs are currently only supported for animated SVGs and so `animateInterval` must be set to a value greater than 0 when targeting multiple boards.
|
||||
- `animateInterval`: If given, multiple boards are packaged as 1 SVG which transitions through each board at the interval (in milliseconds).
|
||||
- `salt`: Add a salt value to ensure the output uses unique IDs. This is useful when generating multiple identical diagrams to be included in the same HTML doc, so that duplicate IDs do not cause invalid HTML. The salt value is a string that will be appended to IDs in the output.
|
||||
- `noXMLTag`: Omit XML tag `(<?xml ...?>)` from output SVG files. Useful when generating SVGs for direct HTML embedding.
|
||||
|
||||
### `CompileRequest`
|
||||
|
||||
- `fs`: A mapping of D2 file paths to their content
|
||||
- `inputPath`: The path of the entry D2 file [default: index]
|
||||
- `options`: The [CompileOptions](#compileoptions) to pass to the compiler
|
||||
|
||||
### `CompileResult`
|
||||
|
||||
- `diagram`: `Diagram`: Compiled D2 diagram
|
||||
- `options`: `RenderOptions`: Render options merged with configuration set in diagram
|
||||
- `fs`
|
||||
- `graph`
|
||||
|
||||
## Development
|
||||
|
||||
D2.js uses Bun, so install this first.
|
||||
|
||||
### Building from source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/terrastruct/d2.git
|
||||
cd d2/d2js/js
|
||||
./make.sh all
|
||||
```
|
||||
|
||||
If you change the main D2 source code, you should regenerate the WASM file:
|
||||
```bash
|
||||
./make.sh build
|
||||
```
|
||||
|
||||
### Running the dev server
|
||||
|
||||
You can browse the examples by running the dev server:
|
||||
|
||||
```bash
|
||||
./make.sh dev
|
||||
```
|
||||
|
||||
Visit `http://localhost:3000` to see the example page.
|
||||
|
||||
### Publishing
|
||||
|
||||
TODO stable release publishing.
|
||||
|
||||
Nightly builds are automated by CI by running:
|
||||
|
||||
```bash
|
||||
PUBLISH=1 ./make.sh build
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome!
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the Mozilla Public License Version 2.0.
|
||||
107
d2js/js/build.js
107
d2js/js/build.js
|
|
@ -1,107 +0,0 @@
|
|||
import { build } from "bun";
|
||||
import { copyFile, mkdir, writeFile, readFile, rm } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
const __dirname = new URL(".", import.meta.url).pathname;
|
||||
const ROOT_DIR = resolve(__dirname);
|
||||
const SRC_DIR = resolve(ROOT_DIR, "src");
|
||||
|
||||
await rm("./dist", { recursive: true, force: true });
|
||||
await mkdir("./dist/browser", { recursive: true });
|
||||
await mkdir("./dist/node-esm", { recursive: true });
|
||||
await mkdir("./dist/node-cjs", { recursive: true });
|
||||
|
||||
const wasmBinary = await readFile("./wasm/d2.wasm");
|
||||
const wasmExecJs = await readFile("./wasm/wasm_exec.js", "utf8");
|
||||
|
||||
await writeFile(
|
||||
join(SRC_DIR, "wasm-loader.browser.js"),
|
||||
`export const wasmBinary = Uint8Array.from(atob("${Buffer.from(wasmBinary).toString(
|
||||
"base64"
|
||||
)}"), c => c.charCodeAt(0));
|
||||
export const wasmExecJs = ${JSON.stringify(wasmExecJs)};`
|
||||
);
|
||||
|
||||
const commonConfig = {
|
||||
minify: true,
|
||||
};
|
||||
|
||||
async function buildDynamicFiles(platform) {
|
||||
const platformContent =
|
||||
platform === "node"
|
||||
? `export * from "./platform.node.js";`
|
||||
: `export * from "./platform.browser.js";`;
|
||||
|
||||
const platformPath = join(SRC_DIR, "platform.js");
|
||||
await writeFile(platformPath, platformContent);
|
||||
|
||||
const workerSource =
|
||||
platform === "node"
|
||||
? join(SRC_DIR, "worker.node.js")
|
||||
: join(SRC_DIR, "worker.browser.js");
|
||||
|
||||
const workerTarget = join(SRC_DIR, "worker.js");
|
||||
const workerContent = await readFile(workerSource, "utf8");
|
||||
await writeFile(workerTarget, workerContent);
|
||||
}
|
||||
|
||||
async function buildAndCopy(buildType) {
|
||||
const configs = {
|
||||
browser: {
|
||||
outdir: resolve(ROOT_DIR, "dist/browser"),
|
||||
splitting: false,
|
||||
format: "esm",
|
||||
target: "browser",
|
||||
platform: "browser",
|
||||
entrypoints: [resolve(SRC_DIR, "index.js")],
|
||||
},
|
||||
"node-esm": {
|
||||
outdir: resolve(ROOT_DIR, "dist/node-esm"),
|
||||
splitting: true,
|
||||
format: "esm",
|
||||
target: "node",
|
||||
platform: "node",
|
||||
entrypoints: [resolve(SRC_DIR, "index.js"), resolve(SRC_DIR, "worker.js")],
|
||||
},
|
||||
"node-cjs": {
|
||||
outdir: resolve(ROOT_DIR, "dist/node-cjs"),
|
||||
splitting: false,
|
||||
format: "cjs",
|
||||
target: "node",
|
||||
platform: "node",
|
||||
entrypoints: [resolve(SRC_DIR, "index.js"), resolve(SRC_DIR, "worker.js")],
|
||||
},
|
||||
};
|
||||
|
||||
const config = configs[buildType];
|
||||
await buildDynamicFiles(config.platform);
|
||||
|
||||
const result = await build({
|
||||
...commonConfig,
|
||||
...config,
|
||||
});
|
||||
|
||||
if (!result.outputs || result.outputs.length === 0) {
|
||||
throw new Error(
|
||||
`No outputs generated for ${buildType} build. Result: ${JSON.stringify(result)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (buildType !== "browser") {
|
||||
await copyFile(resolve(ROOT_DIR, "wasm/d2.wasm"), join(config.outdir, "d2.wasm"));
|
||||
await copyFile(
|
||||
resolve(ROOT_DIR, "wasm/wasm_exec.js"),
|
||||
join(config.outdir, "wasm_exec.js")
|
||||
);
|
||||
await copyFile(resolve(ROOT_DIR, "src/elk.js"), join(config.outdir, "elk.js"));
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await buildAndCopy("browser");
|
||||
await buildAndCopy("node-esm");
|
||||
await buildAndCopy("node-cjs");
|
||||
} catch (error) {
|
||||
console.error("Build failed:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
Binary file not shown.
|
|
@ -1,75 +0,0 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
. "$(dirname "$0")/../../../ci/sub/lib.sh"
|
||||
cd -- "$(dirname "$0")/.."
|
||||
|
||||
cd ../..
|
||||
sh_c "GOOS=js GOARCH=wasm go build -ldflags='-s -w' -trimpath -o main.wasm ./d2js"
|
||||
sh_c "mv main.wasm ./d2js/js/wasm/d2.wasm"
|
||||
|
||||
if [ ! -f ./d2js/js/wasm/d2.wasm ]; then
|
||||
echoerr "Error: d2.wasm is missing"
|
||||
exit 1
|
||||
else
|
||||
echo "d2.wasm exists. Size:"
|
||||
ls -lh ./d2js/js/wasm/d2.wasm | awk '{print $5}'
|
||||
fi
|
||||
|
||||
cd d2js/js
|
||||
sh_c bun build.js
|
||||
|
||||
if [ -n "${NPM_VERSION:-}" ]; then
|
||||
cp package.json package.json.bak
|
||||
trap 'rm -f .npmrc; mv package.json.bak package.json' EXIT
|
||||
|
||||
if [ "$NPM_VERSION" = "nightly" ]; then
|
||||
echo "Publishing nightly version to npm..."
|
||||
|
||||
DATE_TAG=$(date +'%Y%m%d')
|
||||
COMMIT_SHORT=$(git rev-parse --short HEAD)
|
||||
CURRENT_VERSION=$(node -p "require('./package.json').version")
|
||||
PUBLISH_VERSION="${CURRENT_VERSION}-nightly.${DATE_TAG}.${COMMIT_SHORT}"
|
||||
NPM_TAG="nightly"
|
||||
|
||||
echo "Updating package version to ${PUBLISH_VERSION}"
|
||||
else
|
||||
echo "Publishing official version ${NPM_VERSION} to npm..."
|
||||
PUBLISH_VERSION="$NPM_VERSION"
|
||||
NPM_TAG="latest"
|
||||
|
||||
echo "Setting package version to ${PUBLISH_VERSION}"
|
||||
fi
|
||||
|
||||
# Update package.json with the new version
|
||||
npm version "${PUBLISH_VERSION}" --no-git-tag-version
|
||||
|
||||
echo "Publishing to npm with tag '${NPM_TAG}'..."
|
||||
if [ -n "${NPM_TOKEN-}" ]; then
|
||||
# Create .npmrc file with auth token
|
||||
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
|
||||
|
||||
if npm publish --tag "$NPM_TAG"; then
|
||||
echo "Successfully published @terrastruct/d2@${PUBLISH_VERSION} to npm with tag '${NPM_TAG}'"
|
||||
|
||||
# For official releases, bump the patch version
|
||||
if [ "$NPM_VERSION" != "nightly" ]; then
|
||||
# Restore original package.json first
|
||||
mv package.json.bak package.json
|
||||
|
||||
echo "Bumping version to ${NPM_VERSION}"
|
||||
npm version "${NPM_VERSION}" --no-git-tag-version
|
||||
git add package.json
|
||||
git commit -m "Bump version to ${NPM_VERSION} [skip ci]"
|
||||
|
||||
# Cancel the trap since we manually restored and don't want it to execute on exit
|
||||
trap - EXIT
|
||||
fi
|
||||
else
|
||||
echoerr "Failed to publish package to npm"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echoerr "NPM_TOKEN environment variable is required for publishing to npm"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
BIN
d2js/js/d2.wasm
BIN
d2js/js/d2.wasm
Binary file not shown.
|
|
@ -1,72 +0,0 @@
|
|||
const fs = require("fs/promises");
|
||||
const path = require("path");
|
||||
|
||||
const MIME_TYPES = {
|
||||
".html": "text/html",
|
||||
".js": "text/javascript",
|
||||
".mjs": "text/javascript",
|
||||
".css": "text/css",
|
||||
".wasm": "application/wasm",
|
||||
".svg": "image/svg+xml",
|
||||
};
|
||||
|
||||
const server = Bun.serve({
|
||||
port: 3000,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
let filePath = url.pathname.slice(1); // Remove leading "/"
|
||||
|
||||
if (filePath === "") {
|
||||
filePath = "examples/";
|
||||
}
|
||||
|
||||
try {
|
||||
const fullPath = path.join(process.cwd(), filePath);
|
||||
const stats = await fs.stat(fullPath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
const entries = await fs.readdir(fullPath);
|
||||
const links = await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const entryPath = path.join(fullPath, entry);
|
||||
const isDir = (await fs.stat(entryPath)).isDirectory();
|
||||
const slash = isDir ? "/" : "";
|
||||
return `<li><a href="${filePath}${entry}${slash}">${entry}${slash}</a></li>`;
|
||||
})
|
||||
);
|
||||
|
||||
const html = `
|
||||
<html>
|
||||
<body>
|
||||
<h1>Examples</h1>
|
||||
<ul>
|
||||
${links.join("")}
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
return new Response(html, {
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
} else {
|
||||
const ext = path.extname(filePath);
|
||||
const mimeType = MIME_TYPES[ext] || "application/octet-stream";
|
||||
|
||||
const file = Bun.file(filePath);
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
"Content-Type": mimeType,
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp",
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Error serving ${filePath}:`, err);
|
||||
return new Response(`File not found: ${filePath}`, { status: 404 });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`Server running at http://localhost:3000`);
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
body {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
padding: 20px;
|
||||
height: 100vh;
|
||||
margin: 0;
|
||||
}
|
||||
textarea {
|
||||
width: 400px;
|
||||
height: 300px;
|
||||
}
|
||||
#output {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
#output svg {
|
||||
max-width: 100%;
|
||||
max-height: 90vh;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<textarea id="input">x -> y</textarea>
|
||||
<button onclick="compile()">Compile</button>
|
||||
</div>
|
||||
<div id="output"></div>
|
||||
<script type="module">
|
||||
import { D2 } from "../dist/browser/index.js";
|
||||
const d2 = new D2();
|
||||
window.compile = async () => {
|
||||
const input = document.getElementById("input").value;
|
||||
try {
|
||||
const result = await d2.compile(input);
|
||||
const svg = await d2.render(result.diagram, result.renderOptions);
|
||||
document.getElementById("output").innerHTML = svg;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
document.getElementById("output").textContent = err.message;
|
||||
}
|
||||
};
|
||||
compile();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,459 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
body {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
padding: 20px;
|
||||
height: 100vh;
|
||||
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;
|
||||
padding: 8px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.options-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.option:has(.option-toggle-box:not(:checked)) .option-select {
|
||||
opacity: 0.5;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.input-label,
|
||||
.checkbox-label,
|
||||
.select-label {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.checkbox-label,
|
||||
.select-label {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.text-input,
|
||||
.number-input {
|
||||
width: 3rem;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 8px 16px;
|
||||
background: #0066cc;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #0052a3;
|
||||
}
|
||||
|
||||
#output {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 4px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
#output svg {
|
||||
min-width: 100%;
|
||||
max-height: 90vh;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="controls">
|
||||
<textarea id="input">x -> y</textarea>
|
||||
<div class="options-group">
|
||||
<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="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="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="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="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>
|
||||
<option value="4">Cool classics</option>
|
||||
<option value="5">Mixed berry blue</option>
|
||||
<option value="6">Grape soda</option>
|
||||
<option value="7">Aubergine</option>
|
||||
<option value="8">Colorblind clear</option>
|
||||
<option value="100">Vanilla nitro cola</option>
|
||||
<option value="101">Orange creamsicle</option>
|
||||
<option value="102">Shirley temple</option>
|
||||
<option value="103">Earth tones</option>
|
||||
<option value="104">Everglade green</option>
|
||||
<option value="105">Buttered toast</option>
|
||||
<option value="200">Dark mauve</option>
|
||||
<option value="300">Terminal</option>
|
||||
<option value="301">Terminal grayscale</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<option value="5">Mixed berry blue</option>
|
||||
<option value="6">Grape soda</option>
|
||||
<option value="7">Aubergine</option>
|
||||
<option value="8">Colorblind clear</option>
|
||||
<option value="100">Vanilla nitro cola</option>
|
||||
<option value="101">Orange creamsicle</option>
|
||||
<option value="102">Shirley temple</option>
|
||||
<option value="103">Earth tones</option>
|
||||
<option value="104">Everglade green</option>
|
||||
<option value="105">Buttered toast</option>
|
||||
<option value="200">Dark mauve</option>
|
||||
<option value="300">Terminal</option>
|
||||
<option value="301">Terminal grayscale</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<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="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 class="option">
|
||||
<div class="option-toggle">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="target-toggle" class="option-toggle-box" />
|
||||
<span>Target</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<input type="text" id="target-input" class="text-input" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option">
|
||||
<div class="option-toggle">
|
||||
<label class="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="animate-interval-toggle"
|
||||
class="option-toggle-box"
|
||||
/>
|
||||
<span>Animate Interval</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<input
|
||||
type="number"
|
||||
id="animate-interval-input"
|
||||
value="0"
|
||||
step="100"
|
||||
min="0"
|
||||
class="number-input"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option">
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<span>Salt</span>
|
||||
<input type="text" id="salt-input" class="text-input" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option">
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<span>Regular Font</span>
|
||||
<input
|
||||
type="file"
|
||||
accept=".ttf"
|
||||
id="font-regular-input"
|
||||
class="file-input"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option">
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<span>Italic Font</span>
|
||||
<input
|
||||
type="file"
|
||||
accept=".ttf"
|
||||
id="font-italic-input"
|
||||
class="file-input"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option">
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<span>Bold Font</span>
|
||||
<input type="file" accept=".ttf" id="font-bold-input" class="file-input" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="option">
|
||||
<div class="option-select">
|
||||
<label class="input-label">
|
||||
<span>Semibold Font</span>
|
||||
<input
|
||||
type="file"
|
||||
accept=".ttf"
|
||||
id="font-semibold-input"
|
||||
class="file-input"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button onclick="compile()">Compile</button>
|
||||
</div>
|
||||
<div id="output"></div>
|
||||
<script type="module">
|
||||
import { D2 } from "../dist/browser/index.js";
|
||||
const d2 = new D2();
|
||||
const loadFont = async (file) => {
|
||||
if (file != undefined) {
|
||||
const font = await file.arrayBuffer();
|
||||
return Array.from(new Uint8Array(font));
|
||||
}
|
||||
};
|
||||
window.compile = async () => {
|
||||
const input = document.getElementById("input").value;
|
||||
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;
|
||||
const target = document.getElementById("target-toggle").checked
|
||||
? String(document.getElementById("target-input").value)
|
||||
: null;
|
||||
const animateInterval = document.getElementById("animate-interval-toggle").checked
|
||||
? Number(document.getElementById("animate-interval-input").value)
|
||||
: null;
|
||||
const salt = String(document.getElementById("salt-input").value);
|
||||
const fontRegular = await loadFont(
|
||||
document.getElementById("font-regular-input").files[0]
|
||||
);
|
||||
const fontItalic = await loadFont(
|
||||
document.getElementById("font-italic-input").files[0]
|
||||
);
|
||||
const fontBold = await loadFont(
|
||||
document.getElementById("font-bold-input").files[0]
|
||||
);
|
||||
const fontSemibold = await loadFont(
|
||||
document.getElementById("font-semibold-input").files[0]
|
||||
);
|
||||
try {
|
||||
const result = await d2.compile(input, {
|
||||
layout,
|
||||
sketch,
|
||||
themeId,
|
||||
darkThemeId,
|
||||
scale,
|
||||
pad,
|
||||
center,
|
||||
forceAppendix,
|
||||
target,
|
||||
animateInterval,
|
||||
salt,
|
||||
fontRegular,
|
||||
fontItalic,
|
||||
fontSemibold,
|
||||
fontBold,
|
||||
noXmlTag: true,
|
||||
});
|
||||
const svg = await d2.render(result.diagram, result.renderOptions);
|
||||
document.getElementById("output").innerHTML = svg;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
document.getElementById("output").textContent = err.message;
|
||||
}
|
||||
};
|
||||
compile();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
343
d2js/js/index.d.ts
vendored
343
d2js/js/index.d.ts
vendored
|
|
@ -1,343 +0,0 @@
|
|||
export class D2 {
|
||||
compile(input: string, options?: Omit<CompileRequest, "fs">): Promise<CompileResponse>;
|
||||
compile(input: CompileRequest): Promise<CompileResponse>;
|
||||
|
||||
render(diagram: Diagram, options?: RenderOptions): Promise<string>;
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
/** Enable sketch mode [default: false] */
|
||||
sketch?: boolean;
|
||||
/** Theme ID to use [default: 0] */
|
||||
themeID?: number;
|
||||
/** Theme ID to use when client is in dark mode */
|
||||
darkThemeID?: number;
|
||||
/** Center the SVG in the containing viewbox [default: false] */
|
||||
center?: boolean;
|
||||
/** Pixels padded around the rendered diagram [default: 100] */
|
||||
pad?: number;
|
||||
/** 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. */
|
||||
scale?: number;
|
||||
/** Adds an appendix for tooltips and links [default: false] */
|
||||
forceAppendix?: boolean;
|
||||
/** Target board/s to render. If target ends with '', it will be rendered with all of its scenarios, steps, and layers. Otherwise, only the target board will be rendered. E.g. target: 'layers.x.*' to render layer 'x' with all of its children. Pass '' to render all scenarios, steps, and layers. By default, only the root board is rendered. Multi-board outputs are currently only supported for animated SVGs and so animateInterval must be set to a value greater than 0 when targeting multiple boards. */
|
||||
target?: string;
|
||||
/** If given, multiple boards are packaged as 1 SVG which transitions through each board at the interval (in milliseconds). */
|
||||
animateInterval?: number;
|
||||
/** Add a salt value to ensure the output uses unique IDs. This is useful when generating multiple identical diagrams to be included in the same HTML doc, so that duplicate IDs do not cause invalid HTML. The salt value is a string that will be appended to IDs in the output. */
|
||||
salt?: string;
|
||||
/** Omit XML tag (<?xml ...?>) from output SVG files. Useful when generating SVGs for direct HTML embedding. */
|
||||
noXMLTag?: boolean;
|
||||
}
|
||||
|
||||
export interface CompileOptions extends RenderOptions {
|
||||
/** Layout engine to use [default: 'dagre'] */
|
||||
layout?: "dagre" | "elk";
|
||||
/** A byte array containing .ttf file to use for the regular font. If none provided, Source Sans Pro Regular is used. */
|
||||
fontRegular?: Uint8Array;
|
||||
/** A byte array containing .ttf file to use for the italic font. If none provided, Source Sans Pro Italic is used. */
|
||||
fontItalic?: Uint8Array;
|
||||
/** A byte array containing .ttf file to use for the bold font. If none provided, Source Sans Pro Bold is used. */
|
||||
fontBold?: Uint8Array;
|
||||
/** A byte array containing .ttf file to use for the semibold font. If none provided, Source Sans Pro Semibold is used. */
|
||||
fontSemibold?: Uint8Array;
|
||||
}
|
||||
|
||||
export interface CompileRequest {
|
||||
/** A mapping of D2 file paths to their content*/
|
||||
fs: Record<string, string>;
|
||||
/** The path of the entry D2 file [default: index]*/
|
||||
inputPath?: string;
|
||||
/** The CompileOptions to pass to the compiler*/
|
||||
options: CompileOptions;
|
||||
}
|
||||
|
||||
export interface CompileResponse {
|
||||
/** Compiled D2 diagram*/
|
||||
diagram: Diagram /* d2target.Diagram */;
|
||||
/** RenderOptions: Render options merged with configuration set in diagram*/
|
||||
renderOptions: RenderOptions;
|
||||
fs: Record<string, string>;
|
||||
graph: Graph;
|
||||
inputPath: string;
|
||||
}
|
||||
|
||||
export interface Diagram {
|
||||
config?: RenderOptions;
|
||||
name: string;
|
||||
/**
|
||||
* See docs on the same field in d2graph to understand what it means.
|
||||
*/
|
||||
isFolderOnly: boolean;
|
||||
description?: string;
|
||||
fontFamily?: any /* d2fonts.FontFamily */;
|
||||
shapes: Shape[];
|
||||
connections: Connection[];
|
||||
root: Shape;
|
||||
legend?: Legend;
|
||||
layers?: (Diagram | undefined)[];
|
||||
scenarios?: (Diagram | undefined)[];
|
||||
steps?: (Diagram | undefined)[];
|
||||
}
|
||||
|
||||
export interface Legend {
|
||||
shapes?: Shape[];
|
||||
connections?: Connection[];
|
||||
}
|
||||
|
||||
export type Shape = (Class | SQLTable | Text) & ShapeBase;
|
||||
|
||||
export interface ShapeBase {
|
||||
id: string;
|
||||
type: string;
|
||||
classes?: string[];
|
||||
pos: Point;
|
||||
width: number /* int */;
|
||||
height: number /* int */;
|
||||
opacity: number /* float64 */;
|
||||
strokeDash: number /* float64 */;
|
||||
strokeWidth: number /* int */;
|
||||
borderRadius: number /* int */;
|
||||
fill: string;
|
||||
fillPattern?: string;
|
||||
stroke: string;
|
||||
animated: boolean;
|
||||
shadow: boolean;
|
||||
"3d": boolean;
|
||||
multiple: boolean;
|
||||
"double-border": boolean;
|
||||
tooltip: string;
|
||||
link: string;
|
||||
prettyLink?: string;
|
||||
icon?: string /* url.URL */;
|
||||
iconPosition: string;
|
||||
/**
|
||||
* Whether the shape should allow shapes behind it to bleed through
|
||||
* Currently just used for sequence diagram groups
|
||||
*/
|
||||
blend: boolean;
|
||||
contentAspectRatio?: number /* float64 */;
|
||||
labelPosition?: string;
|
||||
zIndex: number /* int */;
|
||||
level: number /* int */;
|
||||
/**
|
||||
* These are used for special shapes, sql_table and class
|
||||
*/
|
||||
primaryAccentColor?: string;
|
||||
secondaryAccentColor?: string;
|
||||
neutralAccentColor?: string;
|
||||
}
|
||||
|
||||
export interface Point {
|
||||
x: number /* int */;
|
||||
y: number /* int */;
|
||||
}
|
||||
|
||||
export interface Class {
|
||||
fields: ClassField[];
|
||||
methods: ClassMethod[];
|
||||
}
|
||||
|
||||
export interface ClassField {
|
||||
name: string;
|
||||
type: string;
|
||||
visibility: string;
|
||||
}
|
||||
|
||||
export interface ClassMethod {
|
||||
name: string;
|
||||
return: string;
|
||||
visibility: string;
|
||||
}
|
||||
|
||||
export interface SQLTable {
|
||||
columns: SQLColumn[];
|
||||
}
|
||||
|
||||
export interface SQLColumn {
|
||||
name: Text;
|
||||
type: Text;
|
||||
constraint: string[];
|
||||
reference: string;
|
||||
}
|
||||
|
||||
export interface Text {
|
||||
label: string;
|
||||
fontSize: number /* int */;
|
||||
fontFamily: string;
|
||||
language: string;
|
||||
color: string;
|
||||
italic: boolean;
|
||||
bold: boolean;
|
||||
underline: boolean;
|
||||
labelWidth: number /* int */;
|
||||
labelHeight: number /* int */;
|
||||
labelFill?: string;
|
||||
}
|
||||
|
||||
export interface Connection extends Text {
|
||||
id: string;
|
||||
classes?: string[];
|
||||
src: string;
|
||||
srcArrow: Arrowhead;
|
||||
srcLabel?: Text;
|
||||
dst: string;
|
||||
dstArrow: Arrowhead;
|
||||
dstLabel?: Text;
|
||||
opacity: number /* float64 */;
|
||||
strokeDash: number /* float64 */;
|
||||
strokeWidth: number /* int */;
|
||||
stroke: string;
|
||||
fill?: string;
|
||||
borderRadius?: number /* float64 */;
|
||||
labelPosition: string;
|
||||
labelPercentage: number /* float64 */;
|
||||
link: string;
|
||||
prettyLink?: string;
|
||||
route: (any /* geo.Point */ | undefined)[];
|
||||
isCurve?: boolean;
|
||||
animated: boolean;
|
||||
tooltip: string;
|
||||
icon?: string /* url.URL */;
|
||||
iconPosition?: string;
|
||||
zIndex: number /* int */;
|
||||
}
|
||||
|
||||
export type Arrowhead =
|
||||
| "none"
|
||||
| "arrow"
|
||||
| "unfilled-triangle"
|
||||
| "triangle"
|
||||
| "diamond"
|
||||
| "filled-diamond"
|
||||
| "circle"
|
||||
| "filled-circle"
|
||||
| "box"
|
||||
| "filled-box"
|
||||
| "line"
|
||||
| "cf-one"
|
||||
| "cf-many"
|
||||
| "cf-one-required"
|
||||
| "cf-many-required";
|
||||
|
||||
export interface Graph {
|
||||
name: string;
|
||||
/**
|
||||
* IsFolderOnly indicates a board or scenario itself makes no modifications from its
|
||||
* base. Folder only boards do not have a render and are used purely for organizing
|
||||
* the board tree.
|
||||
*/
|
||||
isFolderOnly: boolean;
|
||||
ast?: any /* d2ast.Map */;
|
||||
root?: Object;
|
||||
legend?: Legend;
|
||||
edges: (Edge | undefined)[];
|
||||
objects: (Object | undefined)[];
|
||||
layers?: (Graph | undefined)[];
|
||||
scenarios?: (Graph | undefined)[];
|
||||
steps?: (Graph | undefined)[];
|
||||
theme?: any /* d2themes.Theme */;
|
||||
/**
|
||||
* Object.Level uses the location of a nested graph
|
||||
*/
|
||||
rootLevel?: number /* int */;
|
||||
/**
|
||||
* Currently this holds data embedded from source code configuration variables
|
||||
* Plugins only have access to exported graph, so this data structure allows
|
||||
* carrying arbitrary metadata that any plugin might handle
|
||||
*/
|
||||
data?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface Edge {
|
||||
index: number /* int */;
|
||||
srcTableColumnIndex?: number /* int */;
|
||||
dstTableColumnIndex?: number /* int */;
|
||||
labelPosition?: string;
|
||||
labelPercentage?: number /* float64 */;
|
||||
isCurve: boolean;
|
||||
route?: (any /* geo.Point */ | undefined)[];
|
||||
src_arrow: boolean;
|
||||
srcArrowhead?: Attributes;
|
||||
/**
|
||||
* TODO alixander (Mon Sep 12 2022): deprecate SrcArrow and DstArrow and just use SrcArrowhead and DstArrowhead
|
||||
*/
|
||||
dst_arrow: boolean;
|
||||
dstArrowhead?: Attributes;
|
||||
references?: EdgeReference[];
|
||||
attributes?: Attributes;
|
||||
zIndex: number /* int */;
|
||||
}
|
||||
|
||||
export interface Attributes {
|
||||
label: Scalar;
|
||||
labelDimensions: TextDimensions;
|
||||
style: Style;
|
||||
icon?: string /* url.URL */;
|
||||
tooltip?: Scalar;
|
||||
link?: Scalar;
|
||||
width?: Scalar;
|
||||
height?: Scalar;
|
||||
top?: Scalar;
|
||||
left?: Scalar;
|
||||
/**
|
||||
* TODO consider separate Attributes struct for shape-specific and edge-specific
|
||||
* Shapes only
|
||||
*/
|
||||
near_key?: any /* d2ast.KeyPath */;
|
||||
language?: string;
|
||||
/**
|
||||
* TODO: default to ShapeRectangle instead of empty string
|
||||
*/
|
||||
shape: Scalar;
|
||||
direction: Scalar;
|
||||
constraint: string[];
|
||||
gridRows?: Scalar;
|
||||
gridColumns?: Scalar;
|
||||
gridGap?: Scalar;
|
||||
verticalGap?: Scalar;
|
||||
horizontalGap?: Scalar;
|
||||
labelPosition?: Scalar;
|
||||
iconPosition?: Scalar;
|
||||
/**
|
||||
* These names are attached to the rendered elements in SVG
|
||||
* so that users can target them however they like outside of D2
|
||||
*/
|
||||
classes?: string[];
|
||||
}
|
||||
|
||||
export interface EdgeReference {
|
||||
map_key_edge_index: number /* int */;
|
||||
}
|
||||
|
||||
export interface Scalar {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface Style {
|
||||
opacity?: Scalar;
|
||||
stroke?: Scalar;
|
||||
fill?: Scalar;
|
||||
fillPattern?: Scalar;
|
||||
strokeWidth?: Scalar;
|
||||
strokeDash?: Scalar;
|
||||
borderRadius?: Scalar;
|
||||
shadow?: Scalar;
|
||||
"3d"?: Scalar;
|
||||
multiple?: Scalar;
|
||||
font?: Scalar;
|
||||
fontSize?: Scalar;
|
||||
fontColor?: Scalar;
|
||||
animated?: Scalar;
|
||||
bold?: Scalar;
|
||||
italic?: Scalar;
|
||||
underline?: Scalar;
|
||||
filled?: Scalar;
|
||||
doubleBorder?: Scalar;
|
||||
textTransform?: Scalar;
|
||||
}
|
||||
|
||||
export interface TextDimensions {
|
||||
width: number /* int */;
|
||||
height: number /* int */;
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
if [ ! -e "$(dirname "$0")/../../ci/sub/.git" ]; then
|
||||
set -x
|
||||
git submodule update --init
|
||||
set +x
|
||||
fi
|
||||
. "$(dirname "$0")/../../ci/sub/lib.sh"
|
||||
PATH="$(cd -- "$(dirname "$0")" && pwd)/../../ci/sub/bin:$PATH"
|
||||
cd -- "$(dirname "$0")"
|
||||
|
||||
if ! command -v bun >/dev/null 2>&1; then
|
||||
if [ -n "${CI-}" ]; then
|
||||
echo "Bun is not installed. Installing Bun..."
|
||||
curl -fsSL https://bun.sh/install | bash
|
||||
export PATH="$HOME/.bun/bin:$PATH"
|
||||
else
|
||||
echoerr "You need bun to build d2.js: curl -fsSL https://bun.sh/install | bash"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
_make "$@"
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
{
|
||||
"name": "@terrastruct/d2",
|
||||
"author": "Terrastruct, Inc.",
|
||||
"description": "D2.js is a wrapper around the WASM build of D2, the modern text-to-diagram language.",
|
||||
"version": "0.1.23",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/terrastruct/d2.git",
|
||||
"directory": "d2js/js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/terrastruct/d2/issues"
|
||||
},
|
||||
"homepage": "https://github.com/terrastruct/d2/tree/master/d2js/js#readme",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "./dist/cjs/index.js",
|
||||
"module": "./dist/esm/index.js",
|
||||
"exports": {
|
||||
".": {
|
||||
"browser": "./dist/browser/index.js",
|
||||
"import": {
|
||||
"browser": "./dist/browser/index.js",
|
||||
"default": "./dist/node-esm/index.js",
|
||||
"types": "./index.d.ts"
|
||||
},
|
||||
"require": {
|
||||
"default": "./dist/node-cjs/index.js",
|
||||
"types": "./index.d.ts"
|
||||
},
|
||||
"default": "./dist/node-esm/index.js"
|
||||
},
|
||||
"./worker": "./dist/browser/worker.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"index.d.ts"
|
||||
],
|
||||
"types": "./index.d.ts",
|
||||
"scripts": {
|
||||
"build": "./make.sh build",
|
||||
"test": "bun test test/unit",
|
||||
"test:integration": "bun test test/integration",
|
||||
"test:all": "bun run test && bun run test:integration",
|
||||
"dev": "bun --watch dev-server.js"
|
||||
},
|
||||
"keywords": [
|
||||
"d2",
|
||||
"d2lang",
|
||||
"diagram",
|
||||
"wasm",
|
||||
"text-to-diagram",
|
||||
"go"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"devDependencies": {
|
||||
"bun": "latest"
|
||||
}
|
||||
}
|
||||
105805
d2js/js/src/elk.js
105805
d2js/js/src/elk.js
File diff suppressed because it is too large
Load diff
|
|
@ -1,102 +0,0 @@
|
|||
import { createWorker, loadFile } from "./platform.js";
|
||||
|
||||
export class D2 {
|
||||
constructor() {
|
||||
this.ready = this.init();
|
||||
}
|
||||
|
||||
setupMessageHandler() {
|
||||
const isNode = typeof window === "undefined";
|
||||
return new Promise((resolve, reject) => {
|
||||
if (isNode) {
|
||||
this.worker.on("message", (data) => {
|
||||
if (data.type === "ready") resolve();
|
||||
if (data.type === "error") reject(new Error(data.error));
|
||||
if (data.type === "result" && this.currentResolve) {
|
||||
this.currentResolve(data.data);
|
||||
}
|
||||
if (data.type === "error" && this.currentReject) {
|
||||
this.currentReject(new Error(data.error));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.worker.onmessage = (e) => {
|
||||
if (e.data.type === "ready") resolve();
|
||||
if (e.data.type === "error") reject(new Error(e.data.error));
|
||||
if (e.data.type === "result" && this.currentResolve) {
|
||||
this.currentResolve(e.data.data);
|
||||
}
|
||||
if (e.data.type === "error" && this.currentReject) {
|
||||
this.currentReject(new Error(e.data.error));
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async init() {
|
||||
this.worker = await createWorker();
|
||||
|
||||
const elkContent = await loadFile("./elk.js");
|
||||
const wasmExecContent = await loadFile("./wasm_exec.js");
|
||||
const wasmBinary = await loadFile("./d2.wasm");
|
||||
|
||||
const isNode = typeof window === "undefined";
|
||||
const messageHandler = this.setupMessageHandler();
|
||||
|
||||
if (isNode) {
|
||||
this.worker.on("error", (error) => {
|
||||
console.error("Worker (node) encountered an error:", error.message || error);
|
||||
});
|
||||
} else {
|
||||
this.worker.onerror = (error) => {
|
||||
console.error("Worker encountered an error:", error.message || error);
|
||||
};
|
||||
}
|
||||
|
||||
this.worker.postMessage({
|
||||
type: "init",
|
||||
data: {
|
||||
wasm: wasmBinary,
|
||||
wasmExecContent: isNode ? wasmExecContent.toString() : null,
|
||||
elkContent: isNode ? elkContent.toString() : null,
|
||||
wasmExecUrl: isNode
|
||||
? null
|
||||
: URL.createObjectURL(
|
||||
new Blob([wasmExecContent], { type: "application/javascript" })
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
return messageHandler;
|
||||
}
|
||||
|
||||
async sendMessage(type, data) {
|
||||
await this.ready;
|
||||
return new Promise((resolve, reject) => {
|
||||
this.currentResolve = resolve;
|
||||
this.currentReject = reject;
|
||||
this.worker.postMessage({ type, data });
|
||||
});
|
||||
}
|
||||
|
||||
async compile(input, options = {}) {
|
||||
const request =
|
||||
typeof input === "string"
|
||||
? { fs: { index: input }, options }
|
||||
: { ...input, options: { ...options, ...input.options } };
|
||||
return this.sendMessage("compile", request);
|
||||
}
|
||||
|
||||
async render(diagram, options = {}) {
|
||||
return this.sendMessage("render", { diagram, options });
|
||||
}
|
||||
|
||||
async encode(script) {
|
||||
return this.sendMessage("encode", script);
|
||||
}
|
||||
|
||||
async decode(encoded) {
|
||||
return this.sendMessage("decode", encoded);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
import { wasmBinary, wasmExecJs } from "./wasm-loader.browser.js";
|
||||
import workerScript from "./worker.js" with { type: "text" };
|
||||
import elkScript from "./elk.js" with { type: "text" };
|
||||
|
||||
// For the browser version, we build the wasm files into a file (wasm-loader.browser.js)
|
||||
// and loading a file just reads the text, so there's no external dependency calls
|
||||
export async function loadFile(path) {
|
||||
if (path === "./d2.wasm") {
|
||||
return wasmBinary.buffer;
|
||||
}
|
||||
if (path === "./wasm_exec.js") {
|
||||
return new TextEncoder().encode(wasmExecJs).buffer;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function createWorker() {
|
||||
let blob = new Blob([wasmExecJs, elkScript, workerScript], {
|
||||
type: "text/javascript;charset=utf-8",
|
||||
});
|
||||
|
||||
const worker = new Worker(URL.createObjectURL(blob), {
|
||||
type: "module",
|
||||
});
|
||||
return worker;
|
||||
}
|
||||
|
|
@ -1 +0,0 @@
|
|||
export * from "./platform.node.js";
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
let nodeModules = null;
|
||||
|
||||
async function loadNodeModules() {
|
||||
if (!nodeModules) {
|
||||
nodeModules = {
|
||||
fs: await import("fs/promises"),
|
||||
path: await import("path"),
|
||||
url: await import("url"),
|
||||
worker: await import("worker_threads"),
|
||||
};
|
||||
}
|
||||
return nodeModules;
|
||||
}
|
||||
|
||||
export async function loadFile(path) {
|
||||
const modules = await loadNodeModules();
|
||||
const readFile = modules.fs.readFile;
|
||||
const { join, dirname } = modules.path;
|
||||
const { fileURLToPath } = modules.url;
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
try {
|
||||
return await readFile(join(__dirname, path));
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") {
|
||||
return await readFile(join(__dirname, "../../../wasm", path.replace("./", "")));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWorker() {
|
||||
const modules = await loadNodeModules();
|
||||
const { Worker } = modules.worker;
|
||||
const { join, dirname } = modules.path;
|
||||
const { fileURLToPath } = modules.url;
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const workerPath = join(__dirname, "worker.js");
|
||||
return new Worker(workerPath);
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
import { readFile } from "fs/promises";
|
||||
import { fileURLToPath } from "url";
|
||||
import { dirname, resolve } from "path";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export async function getWasmBinary() {
|
||||
return readFile(resolve(__dirname, "./d2.wasm"));
|
||||
}
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
let currentPort;
|
||||
let d2;
|
||||
let elk;
|
||||
|
||||
export function setupMessageHandler(isNode, port, initWasm) {
|
||||
currentPort = port;
|
||||
|
||||
const handleMessage = async (e) => {
|
||||
const { type, data } = e;
|
||||
|
||||
switch (type) {
|
||||
case "init":
|
||||
try {
|
||||
if (isNode) {
|
||||
eval(data.wasmExecContent);
|
||||
}
|
||||
d2 = await initWasm(data.wasm);
|
||||
elk = new ELK();
|
||||
currentPort.postMessage({ type: "ready" });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
|
||||
case "compile":
|
||||
try {
|
||||
// We use Go to get the intermediate ELK graph
|
||||
// Then natively run elk layout
|
||||
// This is due to elk.layout being an async function, which a
|
||||
// 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 the layout option has not been set, we generate the elk layout now
|
||||
// anyway to support `layout-engine: elk` in d2-config vars
|
||||
if (data.options.layout === "elk" || data.options.layout == null) {
|
||||
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
|
||||
const response = JSON.parse(elkGraph);
|
||||
if (response.error) throw new Error(response.error.message);
|
||||
const elkGraph2 = response.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);
|
||||
currentPort.postMessage({ type: "result", data: response.data });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
|
||||
case "render":
|
||||
try {
|
||||
const result = await d2.render(JSON.stringify(data));
|
||||
const response = JSON.parse(result);
|
||||
if (response.error) throw new Error(response.error.message);
|
||||
const decoded = new TextDecoder().decode(
|
||||
Uint8Array.from(atob(response.data), (c) => c.charCodeAt(0))
|
||||
);
|
||||
currentPort.postMessage({ type: "result", data: decoded });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if (isNode) {
|
||||
port.on("message", handleMessage);
|
||||
} else {
|
||||
port.onmessage = (e) => handleMessage(e.data);
|
||||
}
|
||||
}
|
||||
|
||||
async function initWasmBrowser(wasmBinary) {
|
||||
const go = new Go();
|
||||
const result = await WebAssembly.instantiate(wasmBinary, go.importObject);
|
||||
go.run(result.instance);
|
||||
return self.d2;
|
||||
}
|
||||
|
||||
setupMessageHandler(false, self, initWasmBrowser);
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import { parentPort } from "node:worker_threads";
|
||||
|
||||
let currentPort;
|
||||
let d2;
|
||||
let elk;
|
||||
|
||||
export function setupMessageHandler(isNode, port, initWasm) {
|
||||
currentPort = port;
|
||||
|
||||
const handleMessage = async (e) => {
|
||||
const { type, data } = e;
|
||||
|
||||
switch (type) {
|
||||
case "init":
|
||||
try {
|
||||
if (isNode) {
|
||||
eval(data.wasmExecContent);
|
||||
eval(data.elkContent);
|
||||
}
|
||||
d2 = await initWasm(data.wasm);
|
||||
elk = new ELK();
|
||||
currentPort.postMessage({ type: "ready" });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
|
||||
case "compile":
|
||||
try {
|
||||
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);
|
||||
currentPort.postMessage({ type: "result", data: response.data });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
|
||||
case "render":
|
||||
try {
|
||||
const result = await d2.render(JSON.stringify(data));
|
||||
const response = JSON.parse(result);
|
||||
if (response.error) throw new Error(response.error.message);
|
||||
currentPort.postMessage({ type: "result", data: atob(response.data) });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if (isNode) {
|
||||
port.on("message", handleMessage);
|
||||
} else {
|
||||
port.onmessage = (e) => handleMessage(e.data);
|
||||
}
|
||||
}
|
||||
|
||||
async function initWasmNode(wasmBinary) {
|
||||
const go = new Go();
|
||||
const result = await WebAssembly.instantiate(wasmBinary, go.importObject);
|
||||
go.run(result.instance);
|
||||
return global.d2;
|
||||
}
|
||||
|
||||
setupMessageHandler(true, parentPort, initWasmNode);
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
import { parentPort } from "node:worker_threads";
|
||||
|
||||
let currentPort;
|
||||
let d2;
|
||||
let elk;
|
||||
|
||||
export function setupMessageHandler(isNode, port, initWasm) {
|
||||
currentPort = port;
|
||||
|
||||
const handleMessage = async (e) => {
|
||||
const { type, data } = e;
|
||||
|
||||
switch (type) {
|
||||
case "init":
|
||||
try {
|
||||
if (isNode) {
|
||||
eval(data.wasmExecContent);
|
||||
eval(data.elkContent);
|
||||
}
|
||||
d2 = await initWasm(data.wasm);
|
||||
elk = new ELK();
|
||||
currentPort.postMessage({ type: "ready" });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
|
||||
case "compile":
|
||||
try {
|
||||
if (data.options.layout === "elk" || data.options.layout == null) {
|
||||
const elkGraph = await d2.getELKGraph(JSON.stringify(data));
|
||||
const response = JSON.parse(elkGraph);
|
||||
if (response.error) throw new Error(response.error.message);
|
||||
const elkGraph2 = response.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);
|
||||
currentPort.postMessage({ type: "result", data: response.data });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
|
||||
case "render":
|
||||
try {
|
||||
const result = await d2.render(JSON.stringify(data));
|
||||
const response = JSON.parse(result);
|
||||
if (response.error) throw new Error(response.error.message);
|
||||
const decoded = new TextDecoder().decode(
|
||||
Uint8Array.from(atob(response.data), (c) => c.charCodeAt(0))
|
||||
);
|
||||
currentPort.postMessage({ type: "result", data: decoded });
|
||||
} catch (err) {
|
||||
currentPort.postMessage({ type: "error", error: err.message });
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if (isNode) {
|
||||
port.on("message", handleMessage);
|
||||
} else {
|
||||
port.onmessage = (e) => handleMessage(e.data);
|
||||
}
|
||||
}
|
||||
|
||||
async function initWasmNode(wasmBinary) {
|
||||
const go = new Go();
|
||||
const result = await WebAssembly.instantiate(wasmBinary, go.importObject);
|
||||
go.run(result.instance);
|
||||
return global.d2;
|
||||
}
|
||||
|
||||
setupMessageHandler(true, parentPort, initWasmNode);
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
import { expect, test, describe } from "bun:test";
|
||||
|
||||
describe("D2 CJS Integration", () => {
|
||||
test("can require and use CJS build", async () => {
|
||||
const { D2 } = require("../../dist/node-cjs/index.js");
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y");
|
||||
expect(result.diagram).toBeDefined();
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
});
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
import { expect, test, describe } from "bun:test";
|
||||
import { D2 } from "../../dist/node-esm/index.js";
|
||||
|
||||
describe("D2 ESM Integration", () => {
|
||||
test("can import and use ESM build", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y");
|
||||
expect(result.diagram).toBeDefined();
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
});
|
||||
|
|
@ -1,234 +0,0 @@
|
|||
import { expect, test, describe } from "bun:test";
|
||||
import { D2 } from "../../dist/node-esm/index.js";
|
||||
|
||||
describe("D2 Unit Tests", () => {
|
||||
test("basic compilation works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y");
|
||||
expect(result.diagram).toBeDefined();
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("elk layout works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y", { layout: "elk" });
|
||||
expect(result.diagram).toBeDefined();
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("import works", async () => {
|
||||
const d2 = new D2();
|
||||
const fs = {
|
||||
index: "a: @import",
|
||||
"import.d2": "x: {shape: circle}",
|
||||
};
|
||||
const result = await d2.compile({ fs });
|
||||
expect(result.diagram).toBeDefined();
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("relative import works", async () => {
|
||||
const d2 = new D2();
|
||||
const fs = {
|
||||
"folder/index.d2": "a: @../import",
|
||||
"import.d2": "x: {shape: circle}",
|
||||
};
|
||||
const inputPath = "folder/index.d2";
|
||||
const result = await d2.compile({ fs, inputPath });
|
||||
expect(result.diagram).toBeDefined();
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("render works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y");
|
||||
const svg = await d2.render(result.diagram);
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("d2-config read correctly", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile(
|
||||
`
|
||||
vars: {
|
||||
d2-config: {
|
||||
theme-id: 4
|
||||
dark-theme-id: 200
|
||||
pad: 10
|
||||
center: true
|
||||
sketch: true
|
||||
layout-engine: elk
|
||||
}
|
||||
}
|
||||
x -> y
|
||||
`
|
||||
);
|
||||
expect(result.renderOptions.sketch).toBe(true);
|
||||
expect(result.renderOptions.themeID).toBe(4);
|
||||
expect(result.renderOptions.darkThemeID).toBe(200);
|
||||
expect(result.renderOptions.center).toBe(true);
|
||||
expect(result.renderOptions.pad).toBe(10);
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("render options take priority", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile(
|
||||
`
|
||||
vars: {
|
||||
d2-config: {
|
||||
theme-id: 4
|
||||
dark-theme-id: 200
|
||||
pad: 10
|
||||
center: true
|
||||
sketch: true
|
||||
layout-engine: elk
|
||||
}
|
||||
}
|
||||
x -> y
|
||||
`,
|
||||
{
|
||||
sketch: false,
|
||||
themeID: 100,
|
||||
darkThemeID: 300,
|
||||
center: false,
|
||||
pad: 0,
|
||||
layout: "dagre",
|
||||
}
|
||||
);
|
||||
expect(result.renderOptions.sketch).toBe(false);
|
||||
expect(result.renderOptions.themeID).toBe(100);
|
||||
expect(result.renderOptions.darkThemeID).toBe(300);
|
||||
expect(result.renderOptions.center).toBe(false);
|
||||
expect(result.renderOptions.pad).toBe(0);
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("sketch render works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y", { sketch: true });
|
||||
const svg = await d2.render(result.diagram, { sketch: true });
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
expect(svg).toContain("sketch-overlay");
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("center render works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y", { center: true });
|
||||
const svg = await d2.render(result.diagram, { center: true });
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
expect(svg).toContain("xMidYMid meet");
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("no XML tag works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x -> y");
|
||||
const svg = await d2.render(result.diagram, { noXMLTag: true });
|
||||
expect(svg).not.toContain('<?xml version="1.0"');
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("force appendix works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x: {tooltip: x appendix}", { forceAppendix: true });
|
||||
const svg = await d2.render(result.diagram, { forceAppendix: true });
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
expect(svg).toContain('class="appendix"');
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("animated multi-board works", async () => {
|
||||
const d2 = new D2();
|
||||
const source = `
|
||||
x -> y
|
||||
layers: {
|
||||
numbers: {
|
||||
1 -> 2
|
||||
}
|
||||
}
|
||||
`;
|
||||
const options = { target: "*", animateInterval: 1000 };
|
||||
const result = await d2.compile(source, options);
|
||||
const svg = await d2.render(result.diagram, result.renderOptions);
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("latex works", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("x: |latex \\frac{f(x+h)-f(x)}{h} |");
|
||||
const svg = await d2.render(result.diagram);
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("unicode characters work", async () => {
|
||||
const d2 = new D2();
|
||||
const result = await d2.compile("こんにちは -> ♒️");
|
||||
const svg = await d2.render(result.diagram);
|
||||
expect(svg).toContain("<svg");
|
||||
expect(svg).toContain("</svg>");
|
||||
expect(svg).toContain("こんにちは");
|
||||
expect(svg).toContain("♒️");
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("handles syntax errors correctly", async () => {
|
||||
const d2 = new D2();
|
||||
try {
|
||||
await d2.compile("invalid -> -> syntax");
|
||||
throw new Error("Should have thrown syntax error");
|
||||
} catch (err) {
|
||||
expect(err).toBeDefined();
|
||||
expect(err.message).not.toContain("Should have thrown syntax error");
|
||||
}
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("handles unanimated multi-board error correctly", async () => {
|
||||
const d2 = new D2();
|
||||
const source = `
|
||||
x -> y
|
||||
layers: {
|
||||
numbers: {
|
||||
1 -> 2
|
||||
}
|
||||
}
|
||||
`;
|
||||
const result = await d2.compile(source);
|
||||
try {
|
||||
await d2.render(result.diagram, { target: "*" });
|
||||
throw new Error("Should have thrown compile error");
|
||||
} catch (err) {
|
||||
expect(err).toBeDefined();
|
||||
expect(err.message).not.toContain("Should have thrown compile error");
|
||||
}
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
|
||||
test("handles invalid imports correctly", async () => {
|
||||
const d2 = new D2();
|
||||
const fs = {
|
||||
"folder/index.d2": "a: @../invalid",
|
||||
"import.d2": "x: {shape: circle}",
|
||||
};
|
||||
const inputPath = "folder/index.d2";
|
||||
try {
|
||||
await d2.compile({ fs, inputPath });
|
||||
throw new Error("Should have thrown compile error");
|
||||
} catch (err) {
|
||||
expect(err).toBeDefined();
|
||||
expect(err.message).not.toContain("Should have thrown compile error");
|
||||
}
|
||||
await d2.worker.terminate();
|
||||
}, 20000);
|
||||
});
|
||||
|
|
@ -1,477 +0,0 @@
|
|||
"use strict";
|
||||
(() => {
|
||||
const o = () => {
|
||||
const h = new Error("not implemented");
|
||||
return (h.code = "ENOSYS"), h;
|
||||
};
|
||||
if (!globalThis.fs) {
|
||||
let h = "";
|
||||
globalThis.fs = {
|
||||
constants: {
|
||||
O_WRONLY: -1,
|
||||
O_RDWR: -1,
|
||||
O_CREAT: -1,
|
||||
O_TRUNC: -1,
|
||||
O_APPEND: -1,
|
||||
O_EXCL: -1,
|
||||
},
|
||||
writeSync(n, s) {
|
||||
h += y.decode(s);
|
||||
const i = h.lastIndexOf(`
|
||||
`);
|
||||
return (
|
||||
i != -1 && (console.log(h.substring(0, i)), (h = h.substring(i + 1))), s.length
|
||||
);
|
||||
},
|
||||
write(n, s, i, r, f, u) {
|
||||
if (i !== 0 || r !== s.length || f !== null) {
|
||||
u(o());
|
||||
return;
|
||||
}
|
||||
const d = this.writeSync(n, s);
|
||||
u(null, d);
|
||||
},
|
||||
chmod(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
chown(n, s, i, r) {
|
||||
r(o());
|
||||
},
|
||||
close(n, s) {
|
||||
s(o());
|
||||
},
|
||||
fchmod(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
fchown(n, s, i, r) {
|
||||
r(o());
|
||||
},
|
||||
fstat(n, s) {
|
||||
s(o());
|
||||
},
|
||||
fsync(n, s) {
|
||||
s(null);
|
||||
},
|
||||
ftruncate(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
lchown(n, s, i, r) {
|
||||
r(o());
|
||||
},
|
||||
link(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
lstat(n, s) {
|
||||
s(o());
|
||||
},
|
||||
mkdir(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
open(n, s, i, r) {
|
||||
r(o());
|
||||
},
|
||||
read(n, s, i, r, f, u) {
|
||||
u(o());
|
||||
},
|
||||
readdir(n, s) {
|
||||
s(o());
|
||||
},
|
||||
readlink(n, s) {
|
||||
s(o());
|
||||
},
|
||||
rename(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
rmdir(n, s) {
|
||||
s(o());
|
||||
},
|
||||
stat(n, s) {
|
||||
s(o());
|
||||
},
|
||||
symlink(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
truncate(n, s, i) {
|
||||
i(o());
|
||||
},
|
||||
unlink(n, s) {
|
||||
s(o());
|
||||
},
|
||||
utimes(n, s, i, r) {
|
||||
r(o());
|
||||
},
|
||||
};
|
||||
}
|
||||
if (
|
||||
(globalThis.process ||
|
||||
(globalThis.process = {
|
||||
getuid() {
|
||||
return -1;
|
||||
},
|
||||
getgid() {
|
||||
return -1;
|
||||
},
|
||||
geteuid() {
|
||||
return -1;
|
||||
},
|
||||
getegid() {
|
||||
return -1;
|
||||
},
|
||||
getgroups() {
|
||||
throw o();
|
||||
},
|
||||
pid: -1,
|
||||
ppid: -1,
|
||||
umask() {
|
||||
throw o();
|
||||
},
|
||||
cwd() {
|
||||
throw o();
|
||||
},
|
||||
chdir() {
|
||||
throw o();
|
||||
},
|
||||
}),
|
||||
!globalThis.crypto)
|
||||
)
|
||||
throw new Error(
|
||||
"globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"
|
||||
);
|
||||
if (!globalThis.performance)
|
||||
throw new Error(
|
||||
"globalThis.performance is not available, polyfill required (performance.now only)"
|
||||
);
|
||||
if (!globalThis.TextEncoder)
|
||||
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
||||
if (!globalThis.TextDecoder)
|
||||
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
||||
const g = new TextEncoder("utf-8"),
|
||||
y = new TextDecoder("utf-8");
|
||||
globalThis.Go = class {
|
||||
constructor() {
|
||||
(this.argv = ["js"]),
|
||||
(this.env = {}),
|
||||
(this.exit = (t) => {
|
||||
t !== 0 && console.warn("exit code:", t);
|
||||
}),
|
||||
(this._exitPromise = new Promise((t) => {
|
||||
this._resolveExitPromise = t;
|
||||
})),
|
||||
(this._pendingEvent = null),
|
||||
(this._scheduledTimeouts = new Map()),
|
||||
(this._nextCallbackTimeoutID = 1);
|
||||
const h = (t, e) => {
|
||||
this.mem.setUint32(t + 0, e, !0),
|
||||
this.mem.setUint32(t + 4, Math.floor(e / 4294967296), !0);
|
||||
},
|
||||
n = (t, e) => {
|
||||
this.mem.setUint32(t + 0, e, !0);
|
||||
},
|
||||
s = (t) => {
|
||||
const e = this.mem.getUint32(t + 0, !0),
|
||||
l = this.mem.getInt32(t + 4, !0);
|
||||
return e + l * 4294967296;
|
||||
},
|
||||
i = (t) => {
|
||||
const e = this.mem.getFloat64(t, !0);
|
||||
if (e === 0) return;
|
||||
if (!isNaN(e)) return e;
|
||||
const l = this.mem.getUint32(t, !0);
|
||||
return this._values[l];
|
||||
},
|
||||
r = (t, e) => {
|
||||
if (typeof e == "number" && e !== 0) {
|
||||
if (isNaN(e)) {
|
||||
this.mem.setUint32(t + 4, 2146959360, !0), this.mem.setUint32(t, 0, !0);
|
||||
return;
|
||||
}
|
||||
this.mem.setFloat64(t, e, !0);
|
||||
return;
|
||||
}
|
||||
if (e === void 0) {
|
||||
this.mem.setFloat64(t, 0, !0);
|
||||
return;
|
||||
}
|
||||
let a = this._ids.get(e);
|
||||
a === void 0 &&
|
||||
((a = this._idPool.pop()),
|
||||
a === void 0 && (a = this._values.length),
|
||||
(this._values[a] = e),
|
||||
(this._goRefCounts[a] = 0),
|
||||
this._ids.set(e, a)),
|
||||
this._goRefCounts[a]++;
|
||||
let c = 0;
|
||||
switch (typeof e) {
|
||||
case "object":
|
||||
e !== null && (c = 1);
|
||||
break;
|
||||
case "string":
|
||||
c = 2;
|
||||
break;
|
||||
case "symbol":
|
||||
c = 3;
|
||||
break;
|
||||
case "function":
|
||||
c = 4;
|
||||
break;
|
||||
}
|
||||
this.mem.setUint32(t + 4, 2146959360 | c, !0), this.mem.setUint32(t, a, !0);
|
||||
},
|
||||
f = (t) => {
|
||||
const e = s(t + 0),
|
||||
l = s(t + 8);
|
||||
return new Uint8Array(this._inst.exports.mem.buffer, e, l);
|
||||
},
|
||||
u = (t) => {
|
||||
const e = s(t + 0),
|
||||
l = s(t + 8),
|
||||
a = new Array(l);
|
||||
for (let c = 0; c < l; c++) a[c] = i(e + c * 8);
|
||||
return a;
|
||||
},
|
||||
d = (t) => {
|
||||
const e = s(t + 0),
|
||||
l = s(t + 8);
|
||||
return y.decode(new DataView(this._inst.exports.mem.buffer, e, l));
|
||||
},
|
||||
m = Date.now() - performance.now();
|
||||
this.importObject = {
|
||||
_gotest: { add: (t, e) => t + e },
|
||||
gojs: {
|
||||
"runtime.wasmExit": (t) => {
|
||||
t >>>= 0;
|
||||
const e = this.mem.getInt32(t + 8, !0);
|
||||
(this.exited = !0),
|
||||
delete this._inst,
|
||||
delete this._values,
|
||||
delete this._goRefCounts,
|
||||
delete this._ids,
|
||||
delete this._idPool,
|
||||
this.exit(e);
|
||||
},
|
||||
"runtime.wasmWrite": (t) => {
|
||||
t >>>= 0;
|
||||
const e = s(t + 8),
|
||||
l = s(t + 16),
|
||||
a = this.mem.getInt32(t + 24, !0);
|
||||
fs.writeSync(e, new Uint8Array(this._inst.exports.mem.buffer, l, a));
|
||||
},
|
||||
"runtime.resetMemoryDataView": (t) => {
|
||||
(t >>>= 0), (this.mem = new DataView(this._inst.exports.mem.buffer));
|
||||
},
|
||||
"runtime.nanotime1": (t) => {
|
||||
(t >>>= 0), h(t + 8, (m + performance.now()) * 1e6);
|
||||
},
|
||||
"runtime.walltime": (t) => {
|
||||
t >>>= 0;
|
||||
const e = new Date().getTime();
|
||||
h(t + 8, e / 1e3), this.mem.setInt32(t + 16, (e % 1e3) * 1e6, !0);
|
||||
},
|
||||
"runtime.scheduleTimeoutEvent": (t) => {
|
||||
t >>>= 0;
|
||||
const e = this._nextCallbackTimeoutID;
|
||||
this._nextCallbackTimeoutID++,
|
||||
this._scheduledTimeouts.set(
|
||||
e,
|
||||
setTimeout(() => {
|
||||
for (this._resume(); this._scheduledTimeouts.has(e); )
|
||||
console.warn("scheduleTimeoutEvent: missed timeout event"),
|
||||
this._resume();
|
||||
}, s(t + 8))
|
||||
),
|
||||
this.mem.setInt32(t + 16, e, !0);
|
||||
},
|
||||
"runtime.clearTimeoutEvent": (t) => {
|
||||
t >>>= 0;
|
||||
const e = this.mem.getInt32(t + 8, !0);
|
||||
clearTimeout(this._scheduledTimeouts.get(e)),
|
||||
this._scheduledTimeouts.delete(e);
|
||||
},
|
||||
"runtime.getRandomData": (t) => {
|
||||
(t >>>= 0), crypto.getRandomValues(f(t + 8));
|
||||
},
|
||||
"syscall/js.finalizeRef": (t) => {
|
||||
t >>>= 0;
|
||||
const e = this.mem.getUint32(t + 8, !0);
|
||||
if ((this._goRefCounts[e]--, this._goRefCounts[e] === 0)) {
|
||||
const l = this._values[e];
|
||||
(this._values[e] = null), this._ids.delete(l), this._idPool.push(e);
|
||||
}
|
||||
},
|
||||
"syscall/js.stringVal": (t) => {
|
||||
(t >>>= 0), r(t + 24, d(t + 8));
|
||||
},
|
||||
"syscall/js.valueGet": (t) => {
|
||||
t >>>= 0;
|
||||
const e = Reflect.get(i(t + 8), d(t + 16));
|
||||
(t = this._inst.exports.getsp() >>> 0), r(t + 32, e);
|
||||
},
|
||||
"syscall/js.valueSet": (t) => {
|
||||
(t >>>= 0), Reflect.set(i(t + 8), d(t + 16), i(t + 32));
|
||||
},
|
||||
"syscall/js.valueDelete": (t) => {
|
||||
(t >>>= 0), Reflect.deleteProperty(i(t + 8), d(t + 16));
|
||||
},
|
||||
"syscall/js.valueIndex": (t) => {
|
||||
(t >>>= 0), r(t + 24, Reflect.get(i(t + 8), s(t + 16)));
|
||||
},
|
||||
"syscall/js.valueSetIndex": (t) => {
|
||||
(t >>>= 0), Reflect.set(i(t + 8), s(t + 16), i(t + 24));
|
||||
},
|
||||
"syscall/js.valueCall": (t) => {
|
||||
t >>>= 0;
|
||||
try {
|
||||
const e = i(t + 8),
|
||||
l = Reflect.get(e, d(t + 16)),
|
||||
a = u(t + 32),
|
||||
c = Reflect.apply(l, e, a);
|
||||
(t = this._inst.exports.getsp() >>> 0),
|
||||
r(t + 56, c),
|
||||
this.mem.setUint8(t + 64, 1);
|
||||
} catch (e) {
|
||||
(t = this._inst.exports.getsp() >>> 0),
|
||||
r(t + 56, e),
|
||||
this.mem.setUint8(t + 64, 0);
|
||||
}
|
||||
},
|
||||
"syscall/js.valueInvoke": (t) => {
|
||||
t >>>= 0;
|
||||
try {
|
||||
const e = i(t + 8),
|
||||
l = u(t + 16),
|
||||
a = Reflect.apply(e, void 0, l);
|
||||
(t = this._inst.exports.getsp() >>> 0),
|
||||
r(t + 40, a),
|
||||
this.mem.setUint8(t + 48, 1);
|
||||
} catch (e) {
|
||||
(t = this._inst.exports.getsp() >>> 0),
|
||||
r(t + 40, e),
|
||||
this.mem.setUint8(t + 48, 0);
|
||||
}
|
||||
},
|
||||
"syscall/js.valueNew": (t) => {
|
||||
t >>>= 0;
|
||||
try {
|
||||
const e = i(t + 8),
|
||||
l = u(t + 16),
|
||||
a = Reflect.construct(e, l);
|
||||
(t = this._inst.exports.getsp() >>> 0),
|
||||
r(t + 40, a),
|
||||
this.mem.setUint8(t + 48, 1);
|
||||
} catch (e) {
|
||||
(t = this._inst.exports.getsp() >>> 0),
|
||||
r(t + 40, e),
|
||||
this.mem.setUint8(t + 48, 0);
|
||||
}
|
||||
},
|
||||
"syscall/js.valueLength": (t) => {
|
||||
(t >>>= 0), h(t + 16, parseInt(i(t + 8).length));
|
||||
},
|
||||
"syscall/js.valuePrepareString": (t) => {
|
||||
t >>>= 0;
|
||||
const e = g.encode(String(i(t + 8)));
|
||||
r(t + 16, e), h(t + 24, e.length);
|
||||
},
|
||||
"syscall/js.valueLoadString": (t) => {
|
||||
t >>>= 0;
|
||||
const e = i(t + 8);
|
||||
f(t + 16).set(e);
|
||||
},
|
||||
"syscall/js.valueInstanceOf": (t) => {
|
||||
(t >>>= 0), this.mem.setUint8(t + 24, i(t + 8) instanceof i(t + 16) ? 1 : 0);
|
||||
},
|
||||
"syscall/js.copyBytesToGo": (t) => {
|
||||
t >>>= 0;
|
||||
const e = f(t + 8),
|
||||
l = i(t + 32);
|
||||
if (!(l instanceof Uint8Array || l instanceof Uint8ClampedArray)) {
|
||||
this.mem.setUint8(t + 48, 0);
|
||||
return;
|
||||
}
|
||||
const a = l.subarray(0, e.length);
|
||||
e.set(a), h(t + 40, a.length), this.mem.setUint8(t + 48, 1);
|
||||
},
|
||||
"syscall/js.copyBytesToJS": (t) => {
|
||||
t >>>= 0;
|
||||
const e = i(t + 8),
|
||||
l = f(t + 16);
|
||||
if (!(e instanceof Uint8Array || e instanceof Uint8ClampedArray)) {
|
||||
this.mem.setUint8(t + 48, 0);
|
||||
return;
|
||||
}
|
||||
const a = l.subarray(0, e.length);
|
||||
e.set(a), h(t + 40, a.length), this.mem.setUint8(t + 48, 1);
|
||||
},
|
||||
debug: (t) => {
|
||||
console.log(t);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
async run(h) {
|
||||
if (!(h instanceof WebAssembly.Instance))
|
||||
throw new Error("Go.run: WebAssembly.Instance expected");
|
||||
(this._inst = h),
|
||||
(this.mem = new DataView(this._inst.exports.mem.buffer)),
|
||||
(this._values = [NaN, 0, null, !0, !1, globalThis, this]),
|
||||
(this._goRefCounts = new Array(this._values.length).fill(1 / 0)),
|
||||
(this._ids = new Map([
|
||||
[0, 1],
|
||||
[null, 2],
|
||||
[!0, 3],
|
||||
[!1, 4],
|
||||
[globalThis, 5],
|
||||
[this, 6],
|
||||
])),
|
||||
(this._idPool = []),
|
||||
(this.exited = !1);
|
||||
let n = 4096;
|
||||
const s = (m) => {
|
||||
const t = n,
|
||||
e = g.encode(m + "\0");
|
||||
return (
|
||||
new Uint8Array(this.mem.buffer, n, e.length).set(e),
|
||||
(n += e.length),
|
||||
n % 8 !== 0 && (n += 8 - (n % 8)),
|
||||
t
|
||||
);
|
||||
},
|
||||
i = this.argv.length,
|
||||
r = [];
|
||||
this.argv.forEach((m) => {
|
||||
r.push(s(m));
|
||||
}),
|
||||
r.push(0),
|
||||
Object.keys(this.env)
|
||||
.sort()
|
||||
.forEach((m) => {
|
||||
r.push(s(`${m}=${this.env[m]}`));
|
||||
}),
|
||||
r.push(0);
|
||||
const u = n;
|
||||
if (
|
||||
(r.forEach((m) => {
|
||||
this.mem.setUint32(n, m, !0), this.mem.setUint32(n + 4, 0, !0), (n += 8);
|
||||
}),
|
||||
n >= 12288)
|
||||
)
|
||||
throw new Error(
|
||||
"total length of command line and environment variables exceeds limit"
|
||||
);
|
||||
this._inst.exports.run(i, u),
|
||||
this.exited && this._resolveExitPromise(),
|
||||
await this._exitPromise;
|
||||
}
|
||||
_resume() {
|
||||
if (this.exited) throw new Error("Go program has already exited");
|
||||
this._inst.exports.resume(), this.exited && this._resolveExitPromise();
|
||||
}
|
||||
_makeFuncWrapper(h) {
|
||||
const n = this;
|
||||
return function () {
|
||||
const s = { id: h, this: this, args: arguments };
|
||||
return (n._pendingEvent = s), n._resume(), s.result;
|
||||
};
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
|
@ -9,7 +9,8 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"log/slog"
|
||||
"cdr.dev/slog"
|
||||
"github.com/dop251/goja"
|
||||
|
||||
"oss.terrastruct.com/util-go/xdefer"
|
||||
|
||||
|
|
@ -18,7 +19,6 @@ import (
|
|||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
"oss.terrastruct.com/d2/lib/geo"
|
||||
"oss.terrastruct.com/d2/lib/jsrunner"
|
||||
"oss.terrastruct.com/d2/lib/label"
|
||||
"oss.terrastruct.com/d2/lib/log"
|
||||
"oss.terrastruct.com/d2/lib/shape"
|
||||
|
|
@ -79,11 +79,11 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
defer xdefer.Errorf(&err, "failed to dagre layout")
|
||||
|
||||
debugJS := false
|
||||
runner := jsrunner.NewJSRunner()
|
||||
if _, err := runner.RunString(dagreJS); err != nil {
|
||||
vm := goja.New()
|
||||
if _, err := vm.RunString(dagreJS); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := runner.RunString(setupJS); err != nil {
|
||||
if _, err := vm.RunString(setupJS); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -135,7 +135,7 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
}
|
||||
|
||||
configJS := setGraphAttrs(rootAttrs)
|
||||
if _, err := runner.RunString(configJS); err != nil {
|
||||
if _, err := vm.RunString(configJS); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -179,22 +179,22 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
}
|
||||
|
||||
if debugJS {
|
||||
log.Debug(ctx, "script", slog.Any("all", setupJS+configJS+loadScript))
|
||||
log.Debug(ctx, "script", slog.F("all", setupJS+configJS+loadScript))
|
||||
}
|
||||
|
||||
if _, err := runner.RunString(loadScript); err != nil {
|
||||
if _, err := vm.RunString(loadScript); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := runner.RunString(`dagre.layout(g)`); err != nil {
|
||||
if _, err := vm.RunString(`dagre.layout(g)`); err != nil {
|
||||
if debugJS {
|
||||
log.Warn(ctx, "layout error", slog.Any("err", err))
|
||||
log.Warn(ctx, "layout error", slog.F("err", err))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
for i := range g.Objects {
|
||||
val, err := runner.RunString(fmt.Sprintf("JSON.stringify(g.node(g.nodes()[%d]))", i))
|
||||
val, err := vm.RunString(fmt.Sprintf("JSON.stringify(g.node(g.nodes()[%d]))", i))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -203,7 +203,7 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
return err
|
||||
}
|
||||
if debugJS {
|
||||
log.Debug(ctx, "graph", slog.Any("json", dn))
|
||||
log.Debug(ctx, "graph", slog.F("json", dn))
|
||||
}
|
||||
|
||||
obj := mapper.ToObj(dn.ID)
|
||||
|
|
@ -215,7 +215,7 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
}
|
||||
|
||||
for i, edge := range g.Edges {
|
||||
val, err := runner.RunString(fmt.Sprintf("JSON.stringify(g.edge(g.edges()[%d]))", i))
|
||||
val, err := vm.RunString(fmt.Sprintf("JSON.stringify(g.edge(g.edges()[%d]))", i))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -224,7 +224,7 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
return err
|
||||
}
|
||||
if debugJS {
|
||||
log.Debug(ctx, "graph", slog.Any("json", de))
|
||||
log.Debug(ctx, "graph", slog.F("json", de))
|
||||
}
|
||||
|
||||
points := make([]*geo.Point, len(de.Points))
|
||||
|
|
@ -570,12 +570,13 @@ func positionLabelsIcons(obj *d2graph.Object) {
|
|||
} else {
|
||||
obj.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
|
||||
}
|
||||
if float64(obj.LabelDimensions.Width) > obj.Width || float64(obj.LabelDimensions.Height) > obj.Height {
|
||||
if len(obj.ChildrenArray) > 0 {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
|
||||
} else {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
|
||||
}
|
||||
}
|
||||
|
||||
if float64(obj.LabelDimensions.Width) > obj.Width || float64(obj.LabelDimensions.Height) > obj.Height {
|
||||
if len(obj.ChildrenArray) > 0 {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
|
||||
} else {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
//go:build !js && !wasm
|
||||
|
||||
package d2elklayout
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
//go:embed elk.js
|
||||
var elkJS string
|
||||
33
d2layouts/d2elklayout/elk.js
vendored
33
d2layouts/d2elklayout/elk.js
vendored
|
|
@ -5,7 +5,15 @@
|
|||
define([], f);
|
||||
} else {
|
||||
var g;
|
||||
g = this;
|
||||
if (typeof window !== "undefined") {
|
||||
g = window;
|
||||
} else if (typeof global !== "undefined") {
|
||||
g = global;
|
||||
} else if (typeof self !== "undefined") {
|
||||
g = self;
|
||||
} else {
|
||||
g = this;
|
||||
}
|
||||
g.ELK = f();
|
||||
}
|
||||
})(function () {
|
||||
|
|
@ -329,6 +337,9 @@
|
|||
|
||||
// -------------- FAKE ELEMENTS GWT ASSUMES EXIST --------------
|
||||
var $wnd = { Error: {} };
|
||||
if (typeof window !== "undefined") $wnd = window;
|
||||
else if (typeof global !== "undefined") $wnd = global; // nodejs
|
||||
else if (typeof self !== "undefined") $wnd = self; // web worker
|
||||
|
||||
var $moduleName, $moduleBase;
|
||||
|
||||
|
|
@ -59784,8 +59795,13 @@
|
|||
}, 0);
|
||||
};
|
||||
}
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
module.exports = { default: j, Worker: j };
|
||||
if (typeof document === uke && typeof self !== uke) {
|
||||
var i = new h(self);
|
||||
self.onmessage = i.saveDispatch;
|
||||
} else if (typeof module !== uke && module.exports) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
module.exports = { default: j, Worker: j };
|
||||
}
|
||||
}
|
||||
function aae(a) {
|
||||
if (a.N) return;
|
||||
|
|
@ -105666,7 +105682,16 @@
|
|||
// -------------- RUN GWT INITIALIZATION CODE --------------
|
||||
gwtOnLoad(null, "elk", null);
|
||||
}.call(this));
|
||||
}.call(this, {}));
|
||||
}.call(
|
||||
this,
|
||||
typeof global !== "undefined"
|
||||
? global
|
||||
: typeof self !== "undefined"
|
||||
? self
|
||||
: typeof window !== "undefined"
|
||||
? window
|
||||
: {}
|
||||
));
|
||||
},
|
||||
{},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package d2elklayout
|
||||
|
||||
// No embed, since this is already bundled in the js worker
|
||||
var elkJS string
|
||||
|
|
@ -8,12 +8,15 @@ import (
|
|||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/dop251/goja"
|
||||
|
||||
"oss.terrastruct.com/util-go/xdefer"
|
||||
|
||||
"oss.terrastruct.com/util-go/go2"
|
||||
|
|
@ -21,11 +24,13 @@ import (
|
|||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
"oss.terrastruct.com/d2/lib/geo"
|
||||
"oss.terrastruct.com/d2/lib/jsrunner"
|
||||
"oss.terrastruct.com/d2/lib/label"
|
||||
"oss.terrastruct.com/d2/lib/shape"
|
||||
)
|
||||
|
||||
//go:embed elk.js
|
||||
var elkJS string
|
||||
|
||||
//go:embed setup.js
|
||||
var setupJS string
|
||||
|
||||
|
|
@ -157,20 +162,18 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
}
|
||||
defer xdefer.Errorf(&err, "failed to ELK layout")
|
||||
|
||||
runner := jsrunner.NewJSRunner()
|
||||
vm := goja.New()
|
||||
|
||||
if runner.Engine() == jsrunner.Goja {
|
||||
console := runner.NewObject()
|
||||
if err := runner.Set("console", console); err != nil {
|
||||
return err
|
||||
}
|
||||
console := vm.NewObject()
|
||||
if err := vm.Set("console", console); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := runner.RunString(elkJS); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := runner.RunString(setupJS); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := vm.RunString(elkJS); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := vm.RunString(setupJS); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
elkGraph := &ELKGraph{
|
||||
|
|
@ -440,30 +443,41 @@ func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err
|
|||
return err
|
||||
}
|
||||
|
||||
var val jsrunner.JSValue
|
||||
if runner.Engine() == jsrunner.Goja {
|
||||
loadScript := fmt.Sprintf(`var graph = %s`, raw)
|
||||
loadScript := fmt.Sprintf(`var graph = %s`, raw)
|
||||
|
||||
if _, err := runner.RunString(loadScript); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := vm.RunString(loadScript); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
val, err = runner.RunString(`elk.layout(graph)
|
||||
val, err := vm.RunString(`elk.layout(graph)
|
||||
.then(s => s)
|
||||
.catch(err => err.message)
|
||||
`)
|
||||
} else {
|
||||
val, err = runner.MustGet("elkResult")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result, err := runner.WaitPromise(ctx, val)
|
||||
p := val.Export()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ELK layout error: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
promise := p.(*goja.Promise)
|
||||
|
||||
for promise.State() == goja.PromiseStatePending {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if promise.State() == goja.PromiseStateRejected {
|
||||
return errors.New("ELK: something went wrong")
|
||||
}
|
||||
|
||||
result := promise.Result().Export()
|
||||
|
||||
var jsonOut map[string]interface{}
|
||||
switch out := result.(type) {
|
||||
case string:
|
||||
|
|
@ -1134,12 +1148,13 @@ func positionLabelsIcons(obj *d2graph.Object) {
|
|||
} else {
|
||||
obj.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
|
||||
}
|
||||
if float64(obj.LabelDimensions.Width) > obj.Width || float64(obj.LabelDimensions.Height) > obj.Height {
|
||||
if len(obj.ChildrenArray) > 0 {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
|
||||
} else {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
|
||||
}
|
||||
}
|
||||
|
||||
if float64(obj.LabelDimensions.Width) > obj.Width || float64(obj.LabelDimensions.Height) > obj.Height {
|
||||
if len(obj.ChildrenArray) > 0 {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
|
||||
} else {
|
||||
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,286 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package d2elklayout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/lib/geo"
|
||||
"oss.terrastruct.com/d2/lib/label"
|
||||
"oss.terrastruct.com/util-go/go2"
|
||||
"oss.terrastruct.com/util-go/xdefer"
|
||||
)
|
||||
|
||||
// This is mostly copy paste from Layout until elk.layout step
|
||||
func ConvertGraph(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (_ *ELKGraph, err error) {
|
||||
if opts == nil {
|
||||
opts = &DefaultOpts
|
||||
}
|
||||
defer xdefer.Errorf(&err, "failed to ELK layout")
|
||||
|
||||
elkGraph := &ELKGraph{
|
||||
ID: "",
|
||||
LayoutOptions: &elkOpts{
|
||||
Thoroughness: 8,
|
||||
EdgeEdgeBetweenLayersSpacing: 50,
|
||||
EdgeNode: edge_node_spacing,
|
||||
HierarchyHandling: "INCLUDE_CHILDREN",
|
||||
FixedAlignment: "BALANCED",
|
||||
ConsiderModelOrder: "NODES_AND_EDGES",
|
||||
CycleBreakingStrategy: "GREEDY_MODEL_ORDER",
|
||||
NodeSizeConstraints: "MINIMUM_SIZE",
|
||||
ContentAlignment: "H_CENTER V_CENTER",
|
||||
ConfigurableOpts: ConfigurableOpts{
|
||||
Algorithm: opts.Algorithm,
|
||||
NodeSpacing: opts.NodeSpacing,
|
||||
EdgeNodeSpacing: opts.EdgeNodeSpacing,
|
||||
SelfLoopSpacing: opts.SelfLoopSpacing,
|
||||
},
|
||||
},
|
||||
}
|
||||
if elkGraph.LayoutOptions.ConfigurableOpts.SelfLoopSpacing == DefaultOpts.SelfLoopSpacing {
|
||||
// +5 for a tiny bit of padding
|
||||
elkGraph.LayoutOptions.ConfigurableOpts.SelfLoopSpacing = go2.Max(elkGraph.LayoutOptions.ConfigurableOpts.SelfLoopSpacing, childrenMaxSelfLoop(g.Root, g.Root.Direction.Value == "down" || g.Root.Direction.Value == "" || g.Root.Direction.Value == "up")/2+5)
|
||||
}
|
||||
switch g.Root.Direction.Value {
|
||||
case "down":
|
||||
elkGraph.LayoutOptions.Direction = Down
|
||||
case "up":
|
||||
elkGraph.LayoutOptions.Direction = Up
|
||||
case "right":
|
||||
elkGraph.LayoutOptions.Direction = Right
|
||||
case "left":
|
||||
elkGraph.LayoutOptions.Direction = Left
|
||||
default:
|
||||
elkGraph.LayoutOptions.Direction = Down
|
||||
}
|
||||
|
||||
// set label and icon positions for ELK
|
||||
for _, obj := range g.Objects {
|
||||
positionLabelsIcons(obj)
|
||||
}
|
||||
|
||||
adjustments := make(map[*d2graph.Object]geo.Spacing)
|
||||
elkNodes := make(map[*d2graph.Object]*ELKNode)
|
||||
elkEdges := make(map[*d2graph.Edge]*ELKEdge)
|
||||
|
||||
// BFS
|
||||
var walk func(*d2graph.Object, *d2graph.Object, func(*d2graph.Object, *d2graph.Object))
|
||||
walk = func(obj, parent *d2graph.Object, fn func(*d2graph.Object, *d2graph.Object)) {
|
||||
if obj.Parent != nil {
|
||||
fn(obj, parent)
|
||||
}
|
||||
for _, ch := range obj.ChildrenArray {
|
||||
walk(ch, obj, fn)
|
||||
}
|
||||
}
|
||||
|
||||
walk(g.Root, nil, func(obj, parent *d2graph.Object) {
|
||||
incoming := 0.
|
||||
outgoing := 0.
|
||||
for _, e := range g.Edges {
|
||||
if e.Src == obj {
|
||||
outgoing++
|
||||
}
|
||||
if e.Dst == obj {
|
||||
incoming++
|
||||
}
|
||||
}
|
||||
if incoming >= 2 || outgoing >= 2 {
|
||||
switch g.Root.Direction.Value {
|
||||
case "right", "left":
|
||||
if obj.Attributes.HeightAttr == nil {
|
||||
obj.Height = math.Max(obj.Height, math.Max(incoming, outgoing)*port_spacing)
|
||||
}
|
||||
default:
|
||||
if obj.Attributes.WidthAttr == nil {
|
||||
obj.Width = math.Max(obj.Width, math.Max(incoming, outgoing)*port_spacing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if obj.HasLabel() && obj.HasIcon() {
|
||||
// this gives shapes extra height for their label if they also have an icon
|
||||
obj.Height += float64(obj.LabelDimensions.Height + label.PADDING)
|
||||
}
|
||||
|
||||
margin, _ := obj.SpacingOpt(label.PADDING, label.PADDING, false)
|
||||
width := margin.Left + obj.Width + margin.Right
|
||||
height := margin.Top + obj.Height + margin.Bottom
|
||||
adjustments[obj] = margin
|
||||
|
||||
n := &ELKNode{
|
||||
ID: obj.AbsID(),
|
||||
Width: width,
|
||||
Height: height,
|
||||
}
|
||||
|
||||
if len(obj.ChildrenArray) > 0 {
|
||||
n.LayoutOptions = &elkOpts{
|
||||
ForceNodeModelOrder: true,
|
||||
Thoroughness: 8,
|
||||
EdgeEdgeBetweenLayersSpacing: 50,
|
||||
HierarchyHandling: "INCLUDE_CHILDREN",
|
||||
FixedAlignment: "BALANCED",
|
||||
EdgeNode: edge_node_spacing,
|
||||
ConsiderModelOrder: "NODES_AND_EDGES",
|
||||
CycleBreakingStrategy: "GREEDY_MODEL_ORDER",
|
||||
NodeSizeConstraints: "MINIMUM_SIZE",
|
||||
ContentAlignment: "H_CENTER V_CENTER",
|
||||
ConfigurableOpts: ConfigurableOpts{
|
||||
NodeSpacing: opts.NodeSpacing,
|
||||
EdgeNodeSpacing: opts.EdgeNodeSpacing,
|
||||
SelfLoopSpacing: opts.SelfLoopSpacing,
|
||||
Padding: opts.Padding,
|
||||
},
|
||||
}
|
||||
if n.LayoutOptions.ConfigurableOpts.SelfLoopSpacing == DefaultOpts.SelfLoopSpacing {
|
||||
n.LayoutOptions.ConfigurableOpts.SelfLoopSpacing = go2.Max(n.LayoutOptions.ConfigurableOpts.SelfLoopSpacing, childrenMaxSelfLoop(obj, g.Root.Direction.Value == "down" || g.Root.Direction.Value == "" || g.Root.Direction.Value == "up")/2+5)
|
||||
}
|
||||
|
||||
switch elkGraph.LayoutOptions.Direction {
|
||||
case Down, Up:
|
||||
n.LayoutOptions.NodeSizeMinimum = fmt.Sprintf("(%d, %d)", int(math.Ceil(height)), int(math.Ceil(width)))
|
||||
case Right, Left:
|
||||
n.LayoutOptions.NodeSizeMinimum = fmt.Sprintf("(%d, %d)", int(math.Ceil(width)), int(math.Ceil(height)))
|
||||
}
|
||||
} else {
|
||||
n.LayoutOptions = &elkOpts{
|
||||
SelfLoopDistribution: "EQUALLY",
|
||||
}
|
||||
}
|
||||
|
||||
if obj.IsContainer() {
|
||||
padding := parsePadding(opts.Padding)
|
||||
padding = adjustPadding(obj, width, height, padding)
|
||||
n.LayoutOptions.Padding = padding.String()
|
||||
}
|
||||
|
||||
if obj.HasLabel() {
|
||||
n.Labels = append(n.Labels, &ELKLabel{
|
||||
Text: obj.Label.Value,
|
||||
Width: float64(obj.LabelDimensions.Width),
|
||||
Height: float64(obj.LabelDimensions.Height),
|
||||
})
|
||||
}
|
||||
|
||||
if parent == g.Root {
|
||||
elkGraph.Children = append(elkGraph.Children, n)
|
||||
} else {
|
||||
elkNodes[parent].Children = append(elkNodes[parent].Children, n)
|
||||
}
|
||||
|
||||
if obj.SQLTable != nil {
|
||||
n.LayoutOptions.PortConstraints = "FIXED_POS"
|
||||
columns := obj.SQLTable.Columns
|
||||
colHeight := n.Height / float64(len(columns)+1)
|
||||
n.Ports = make([]*ELKPort, 0, len(columns)*2)
|
||||
var srcSide, dstSide PortSide
|
||||
switch elkGraph.LayoutOptions.Direction {
|
||||
case Left:
|
||||
srcSide, dstSide = West, East
|
||||
default:
|
||||
srcSide, dstSide = East, West
|
||||
}
|
||||
for i, col := range columns {
|
||||
n.Ports = append(n.Ports, &ELKPort{
|
||||
ID: srcPortID(obj, col.Name.Label),
|
||||
Y: float64(i+1)*colHeight + colHeight/2,
|
||||
LayoutOptions: &elkOpts{PortSide: srcSide},
|
||||
})
|
||||
n.Ports = append(n.Ports, &ELKPort{
|
||||
ID: dstPortID(obj, col.Name.Label),
|
||||
Y: float64(i+1)*colHeight + colHeight/2,
|
||||
LayoutOptions: &elkOpts{PortSide: dstSide},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
elkNodes[obj] = n
|
||||
})
|
||||
|
||||
var srcSide, dstSide PortSide
|
||||
switch elkGraph.LayoutOptions.Direction {
|
||||
case Up:
|
||||
srcSide, dstSide = North, South
|
||||
default:
|
||||
srcSide, dstSide = South, North
|
||||
}
|
||||
|
||||
ports := map[struct {
|
||||
obj *d2graph.Object
|
||||
side PortSide
|
||||
}][]*ELKPort{}
|
||||
|
||||
for ei, edge := range g.Edges {
|
||||
var src, dst string
|
||||
|
||||
switch {
|
||||
case edge.SrcTableColumnIndex != nil:
|
||||
src = srcPortID(edge.Src, edge.Src.SQLTable.Columns[*edge.SrcTableColumnIndex].Name.Label)
|
||||
case edge.Src.SQLTable != nil:
|
||||
p := &ELKPort{
|
||||
ID: fmt.Sprintf("%s.%d", srcPortID(edge.Src, "__root__"), ei),
|
||||
LayoutOptions: &elkOpts{PortSide: srcSide},
|
||||
}
|
||||
src = p.ID
|
||||
elkNodes[edge.Src].Ports = append(elkNodes[edge.Src].Ports, p)
|
||||
k := struct {
|
||||
obj *d2graph.Object
|
||||
side PortSide
|
||||
}{edge.Src, srcSide}
|
||||
ports[k] = append(ports[k], p)
|
||||
default:
|
||||
src = edge.Src.AbsID()
|
||||
}
|
||||
|
||||
switch {
|
||||
case edge.DstTableColumnIndex != nil:
|
||||
dst = dstPortID(edge.Dst, edge.Dst.SQLTable.Columns[*edge.DstTableColumnIndex].Name.Label)
|
||||
case edge.Dst.SQLTable != nil:
|
||||
p := &ELKPort{
|
||||
ID: fmt.Sprintf("%s.%d", dstPortID(edge.Dst, "__root__"), ei),
|
||||
LayoutOptions: &elkOpts{PortSide: dstSide},
|
||||
}
|
||||
dst = p.ID
|
||||
elkNodes[edge.Dst].Ports = append(elkNodes[edge.Dst].Ports, p)
|
||||
k := struct {
|
||||
obj *d2graph.Object
|
||||
side PortSide
|
||||
}{edge.Dst, dstSide}
|
||||
ports[k] = append(ports[k], p)
|
||||
default:
|
||||
dst = edge.Dst.AbsID()
|
||||
}
|
||||
|
||||
e := &ELKEdge{
|
||||
ID: edge.AbsID(),
|
||||
Sources: []string{src},
|
||||
Targets: []string{dst},
|
||||
}
|
||||
if edge.Label.Value != "" {
|
||||
e.Labels = append(e.Labels, &ELKLabel{
|
||||
Text: edge.Label.Value,
|
||||
Width: float64(edge.LabelDimensions.Width),
|
||||
Height: float64(edge.LabelDimensions.Height),
|
||||
LayoutOptions: &elkOpts{
|
||||
InlineEdgeLabels: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
elkGraph.Edges = append(elkGraph.Edges, e)
|
||||
elkEdges[edge] = e
|
||||
}
|
||||
|
||||
for k, ports := range ports {
|
||||
width := elkNodes[k.obj].Width
|
||||
spacing := width / float64(len(ports)+1)
|
||||
for i, p := range ports {
|
||||
p.X = float64(i+1) * spacing
|
||||
}
|
||||
}
|
||||
return elkGraph, nil
|
||||
}
|
||||
|
|
@ -3,11 +3,12 @@ package d2layouts
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"cdr.dev/slog"
|
||||
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2layouts/d2grid"
|
||||
"oss.terrastruct.com/d2/d2layouts/d2near"
|
||||
|
|
@ -202,7 +203,7 @@ func LayoutNested(ctx context.Context, g *d2graph.Graph, graphInfo GraphInfo, co
|
|||
extractedEdges = append(extractedEdges, externalEdges...)
|
||||
extractedEdgeIDs = append(extractedEdgeIDs, externalEdgeIDs...)
|
||||
|
||||
log.Debug(ctx, "layout nested", slog.Any("level", curr.Level()), slog.Any("child", curr.AbsID()), slog.Any("gi", gi))
|
||||
log.Info(ctx, "layout nested", slog.F("level", curr.Level()), slog.F("child", curr.AbsID()), slog.F("gi", gi))
|
||||
nestedInfo := gi
|
||||
nearKey := curr.NearKey
|
||||
if gi.IsConstantNear {
|
||||
|
|
@ -249,19 +250,19 @@ func LayoutNested(ctx context.Context, g *d2graph.Graph, graphInfo GraphInfo, co
|
|||
if len(g.Objects) > 0 {
|
||||
switch graphInfo.DiagramType {
|
||||
case GridDiagram:
|
||||
log.Debug(ctx, "layout grid", slog.Any("rootlevel", g.RootLevel), slog.Any("shapes", g.PrintString()))
|
||||
log.Debug(ctx, "layout grid", slog.F("rootlevel", g.RootLevel), slog.F("shapes", g.PrintString()))
|
||||
if err = d2grid.Layout(ctx, g); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case SequenceDiagram:
|
||||
log.Debug(ctx, "layout sequence", slog.Any("rootlevel", g.RootLevel), slog.Any("shapes", g.PrintString()))
|
||||
log.Debug(ctx, "layout sequence", slog.F("rootlevel", g.RootLevel), slog.F("shapes", g.PrintString()))
|
||||
err = d2sequence.Layout(ctx, g, coreLayout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
log.Debug(ctx, "default layout", slog.Any("rootlevel", g.RootLevel), slog.Any("shapes", g.PrintString()))
|
||||
log.Debug(ctx, "default layout", slog.F("rootlevel", g.RootLevel), slog.F("shapes", g.PrintString()))
|
||||
err := coreLayout(ctx, g)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -336,7 +337,7 @@ func LayoutNested(ctx context.Context, g *d2graph.Graph, graphInfo GraphInfo, co
|
|||
}
|
||||
}
|
||||
|
||||
log.Debug(ctx, "done", slog.Any("rootlevel", g.RootLevel), slog.Any("shapes", g.PrintString()))
|
||||
log.Debug(ctx, "done", slog.F("rootlevel", g.RootLevel), slog.F("shapes", g.PrintString()))
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -190,20 +190,6 @@ func boundingBox(g *d2graph.Graph) (tl, br *geo.Point) {
|
|||
}
|
||||
}
|
||||
|
||||
for _, edge := range g.Edges {
|
||||
if edge.Src.OuterNearContainer() != nil || edge.Dst.OuterNearContainer() != nil {
|
||||
continue
|
||||
}
|
||||
if edge.Route != nil {
|
||||
for _, point := range edge.Route {
|
||||
x1 = math.Min(x1, point.X)
|
||||
y1 = math.Min(y1, point.Y)
|
||||
x2 = math.Max(x2, point.X)
|
||||
y2 = math.Max(y2, point.Y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if math.IsInf(x1, 1) && math.IsInf(x2, -1) {
|
||||
x1 = 0
|
||||
x2 = 0
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ package d2sequence
|
|||
|
||||
// units of space on the left/right when computing the space required between actors
|
||||
const HORIZONTAL_PAD = 40.
|
||||
const LABEL_HORIZONTAL_PAD = 60.
|
||||
|
||||
// units of space on the top/bottom when computing the space required between messages
|
||||
// TODO lower
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2compiler"
|
||||
"oss.terrastruct.com/d2/d2graph"
|
||||
"oss.terrastruct.com/d2/d2layouts/d2sequence"
|
||||
|
|
@ -51,7 +50,7 @@ n2 -> n1
|
|||
|
||||
nEdges := len(g.Edges)
|
||||
|
||||
ctx := log.WithTB(context.Background(), t)
|
||||
ctx := log.WithTB(context.Background(), t, nil)
|
||||
d2sequence.Layout(ctx, g, func(ctx context.Context, g *d2graph.Graph) error {
|
||||
// just set some position as if it had been properly placed
|
||||
for _, obj := range g.Objects {
|
||||
|
|
@ -177,7 +176,7 @@ b.t1 -> a.t1
|
|||
a.t2 -> b
|
||||
b -> a.t2`
|
||||
|
||||
ctx := log.WithTB(context.Background(), t)
|
||||
ctx := log.WithTB(context.Background(), t, nil)
|
||||
g, _, err := d2compiler.Compile("", strings.NewReader(input), nil)
|
||||
assert.Nil(t, err)
|
||||
|
||||
|
|
@ -298,7 +297,7 @@ func TestNestedSequenceDiagrams(t *testing.T) {
|
|||
c
|
||||
container -> c: edge 1
|
||||
`
|
||||
ctx := log.WithTB(context.Background(), t)
|
||||
ctx := log.WithTB(context.Background(), t, nil)
|
||||
g, _, err := d2compiler.Compile("", strings.NewReader(input), nil)
|
||||
assert.Nil(t, err)
|
||||
|
||||
|
|
@ -322,7 +321,7 @@ container -> c: edge 1
|
|||
assert.True(t, has)
|
||||
b_t1.Box = geo.NewBox(nil, 100, 100)
|
||||
|
||||
c := g.Root.EnsureChild([]d2ast.String{d2ast.FlatUnquotedString("c")})
|
||||
c := g.Root.EnsureChild([]string{"c"})
|
||||
c.Box = geo.NewBox(nil, 100, 100)
|
||||
c.Shape = d2graph.Scalar{Value: d2target.ShapeSquare}
|
||||
|
||||
|
|
@ -380,7 +379,7 @@ container -> c: edge 1
|
|||
func TestSelfEdges(t *testing.T) {
|
||||
g := d2graph.NewGraph()
|
||||
g.Root.Shape = d2graph.Scalar{Value: d2target.ShapeSequenceDiagram}
|
||||
n1 := g.Root.EnsureChild([]d2ast.String{d2ast.FlatUnquotedString("n1")})
|
||||
n1 := g.Root.EnsureChild([]string{"n1"})
|
||||
n1.Box = geo.NewBox(nil, 100, 100)
|
||||
|
||||
g.Edges = []*d2graph.Edge{
|
||||
|
|
@ -394,7 +393,7 @@ func TestSelfEdges(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
ctx := log.WithTB(context.Background(), t)
|
||||
ctx := log.WithTB(context.Background(), t, nil)
|
||||
d2sequence.Layout(ctx, g, func(ctx context.Context, g *d2graph.Graph) error {
|
||||
return nil
|
||||
})
|
||||
|
|
@ -416,12 +415,12 @@ func TestSelfEdges(t *testing.T) {
|
|||
func TestSequenceToDescendant(t *testing.T) {
|
||||
g := d2graph.NewGraph()
|
||||
g.Root.Shape = d2graph.Scalar{Value: d2target.ShapeSequenceDiagram}
|
||||
a := g.Root.EnsureChild([]d2ast.String{d2ast.FlatUnquotedString("a")})
|
||||
a := g.Root.EnsureChild([]string{"a"})
|
||||
a.Box = geo.NewBox(nil, 100, 100)
|
||||
a.Attributes = d2graph.Attributes{
|
||||
Shape: d2graph.Scalar{Value: shape.PERSON_TYPE},
|
||||
}
|
||||
a_t1 := a.EnsureChild([]d2ast.String{d2ast.FlatUnquotedString("t1")})
|
||||
a_t1 := a.EnsureChild([]string{"t1"})
|
||||
a_t1.Box = geo.NewBox(nil, 16, 80)
|
||||
|
||||
g.Edges = []*d2graph.Edge{
|
||||
|
|
@ -436,7 +435,7 @@ func TestSequenceToDescendant(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
ctx := log.WithTB(context.Background(), t)
|
||||
ctx := log.WithTB(context.Background(), t, nil)
|
||||
d2sequence.Layout(ctx, g, func(ctx context.Context, g *d2graph.Graph) error {
|
||||
return nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
package d2sequence
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
|
@ -52,9 +50,6 @@ func getObjEarliestLineNum(o *d2graph.Object) int {
|
|||
if ref.MapKey == nil {
|
||||
continue
|
||||
}
|
||||
if ref.Key.HasGlob() {
|
||||
continue
|
||||
}
|
||||
min = go2.IntMin(min, ref.MapKey.Range.Start.Line)
|
||||
}
|
||||
return min
|
||||
|
|
@ -66,9 +61,6 @@ func getEdgeEarliestLineNum(e *d2graph.Edge) int {
|
|||
if ref.MapKey == nil {
|
||||
continue
|
||||
}
|
||||
if ref.Edge.Src.HasGlob() || ref.Edge.Dst.HasGlob() {
|
||||
continue
|
||||
}
|
||||
min = go2.IntMin(min, ref.MapKey.Range.Start.Line)
|
||||
}
|
||||
return min
|
||||
|
|
@ -78,13 +70,6 @@ func newSequenceDiagram(objects []*d2graph.Object, messages []*d2graph.Edge) (*s
|
|||
var actors []*d2graph.Object
|
||||
var groups []*d2graph.Object
|
||||
|
||||
slices.SortFunc(objects, func(a, b *d2graph.Object) int {
|
||||
return cmp.Compare(getObjEarliestLineNum(a), getObjEarliestLineNum(b))
|
||||
})
|
||||
slices.SortFunc(messages, func(a, b *d2graph.Edge) int {
|
||||
return cmp.Compare(getEdgeEarliestLineNum(a), getEdgeEarliestLineNum(b))
|
||||
})
|
||||
|
||||
for _, obj := range objects {
|
||||
if obj.IsSequenceDiagramGroup() {
|
||||
queue := []*d2graph.Object{obj}
|
||||
|
|
@ -177,21 +162,17 @@ func newSequenceDiagram(objects []*d2graph.Object, messages []*d2graph.Edge) (*s
|
|||
|
||||
for _, message := range sd.messages {
|
||||
sd.verticalIndices[message.AbsID()] = getEdgeEarliestLineNum(message)
|
||||
// TODO this should not be global yStep, only affect the neighbors
|
||||
sd.yStep = math.Max(sd.yStep, float64(message.LabelDimensions.Height))
|
||||
|
||||
// ensures that long labels, spanning over multiple actors, don't make for large gaps between actors
|
||||
// by distributing the label length across the actors rank difference
|
||||
rankDiff := math.Abs(float64(sd.objectRank[message.Src]) - float64(sd.objectRank[message.Dst]))
|
||||
if rankDiff != 0 {
|
||||
// rankDiff = 0 for self edges
|
||||
distributedLabelWidth := float64(message.LabelDimensions.Width) / rankDiff
|
||||
for rank := go2.IntMin(sd.objectRank[message.Src], sd.objectRank[message.Dst]); rank <= go2.IntMax(sd.objectRank[message.Src], sd.objectRank[message.Dst])-1; rank++ {
|
||||
sd.actorXStep[rank] = math.Max(sd.actorXStep[rank], distributedLabelWidth+LABEL_HORIZONTAL_PAD)
|
||||
}
|
||||
} else {
|
||||
// self edge
|
||||
nextRank := sd.objectRank[message.Src]
|
||||
if nextRank < len(sd.actorXStep) {
|
||||
labelAdjust := float64(message.LabelDimensions.Width) + label.PADDING*4
|
||||
sd.actorXStep[nextRank] = math.Max(sd.actorXStep[nextRank], labelAdjust)
|
||||
sd.actorXStep[rank] = math.Max(sd.actorXStep[rank], distributedLabelWidth+HORIZONTAL_PAD)
|
||||
}
|
||||
}
|
||||
sd.lastMessage[message.Src] = message
|
||||
|
|
@ -248,12 +229,10 @@ func (sd *sequenceDiagram) placeGroup(group *d2graph.Object) {
|
|||
for _, m := range sd.messages {
|
||||
if m.ContainedBy(group) {
|
||||
for _, p := range m.Route {
|
||||
labelHeight := float64(m.LabelDimensions.Height) / 2.
|
||||
edgePad := math.Max(labelHeight+GROUP_CONTAINER_PADDING, MIN_MESSAGE_DISTANCE/2.)
|
||||
minX = math.Min(minX, p.X-HORIZONTAL_PAD)
|
||||
minY = math.Min(minY, p.Y-edgePad)
|
||||
minY = math.Min(minY, p.Y-MIN_MESSAGE_DISTANCE/2.)
|
||||
maxX = math.Max(maxX, p.X+HORIZONTAL_PAD)
|
||||
maxY = math.Max(maxY, p.Y+edgePad)
|
||||
maxY = math.Max(maxY, p.Y+MIN_MESSAGE_DISTANCE/2.)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -261,9 +240,6 @@ func (sd *sequenceDiagram) placeGroup(group *d2graph.Object) {
|
|||
for _, n := range sd.notes {
|
||||
inGroup := false
|
||||
for _, ref := range n.References {
|
||||
if ref.Key.HasGlob() {
|
||||
continue
|
||||
}
|
||||
curr := ref.ScopeObj
|
||||
for curr != nil {
|
||||
if curr == group {
|
||||
|
|
@ -311,8 +287,8 @@ func (sd *sequenceDiagram) adjustGroupLabel(group *d2graph.Object) {
|
|||
return
|
||||
}
|
||||
|
||||
heightAdd := (group.LabelDimensions.Height + EDGE_GROUP_LABEL_PADDING/2.)
|
||||
if heightAdd < GROUP_CONTAINER_PADDING {
|
||||
heightAdd := (group.LabelDimensions.Height + EDGE_GROUP_LABEL_PADDING) - GROUP_CONTAINER_PADDING
|
||||
if heightAdd < 0 {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -353,6 +329,7 @@ func (sd *sequenceDiagram) adjustGroupLabel(group *d2graph.Object) {
|
|||
n.TopLeft.Y += float64(heightAdd)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// placeActors places actors bottom aligned, side by side with centers spaced by sd.actorXStep
|
||||
|
|
@ -466,12 +443,7 @@ func (sd *sequenceDiagram) placeNotes() {
|
|||
|
||||
for _, msg := range sd.messages {
|
||||
if sd.verticalIndices[msg.AbsID()] < verticalIndex {
|
||||
if msg.Src == msg.Dst {
|
||||
// For self-messages, account for the full vertical space they occupy
|
||||
y += sd.yStep + math.Max(float64(msg.LabelDimensions.Height), MIN_MESSAGE_DISTANCE)*1.5
|
||||
} else {
|
||||
y += sd.yStep + float64(msg.LabelDimensions.Height)
|
||||
}
|
||||
y += sd.yStep
|
||||
}
|
||||
}
|
||||
for _, otherNote := range sd.notes {
|
||||
|
|
@ -564,6 +536,8 @@ func (sd *sequenceDiagram) placeSpans() {
|
|||
// routeMessages routes horizontal edges (messages) from Src to Dst lifeline (actor/span center)
|
||||
// in another step, routes are adjusted to spans borders when necessary
|
||||
func (sd *sequenceDiagram) routeMessages() error {
|
||||
var prevIsLoop bool
|
||||
var prevGroup *d2graph.Object
|
||||
messageOffset := sd.maxActorHeight + sd.yStep
|
||||
for _, message := range sd.messages {
|
||||
message.ZIndex = MESSAGE_Z_INDEX
|
||||
|
|
@ -574,6 +548,15 @@ func (sd *sequenceDiagram) routeMessages() error {
|
|||
}
|
||||
}
|
||||
|
||||
// we need extra space if the previous message is a loop in a different group
|
||||
group := message.GetGroup()
|
||||
if prevIsLoop && prevGroup != group {
|
||||
messageOffset += MIN_MESSAGE_DISTANCE
|
||||
}
|
||||
prevGroup = group
|
||||
|
||||
startY := messageOffset + noteOffset
|
||||
|
||||
var startX, endX float64
|
||||
if startCenter := getCenter(message.Src); startCenter != nil {
|
||||
startX = startCenter.X
|
||||
|
|
@ -600,24 +583,23 @@ func (sd *sequenceDiagram) routeMessages() error {
|
|||
isToSibling := currSrc == currDst
|
||||
|
||||
if isSelfMessage || isToDescendant || isFromDescendant || isToSibling {
|
||||
midX := startX + math.Max(SELF_MESSAGE_HORIZONTAL_TRAVEL, float64(message.LabelDimensions.Width)/2.+label.PADDING*2)
|
||||
startY := messageOffset + noteOffset
|
||||
endY := startY + math.Max(float64(message.LabelDimensions.Height), MIN_MESSAGE_DISTANCE)*1.5
|
||||
midX := startX + SELF_MESSAGE_HORIZONTAL_TRAVEL
|
||||
endY := startY + MIN_MESSAGE_DISTANCE*1.5
|
||||
message.Route = []*geo.Point{
|
||||
geo.NewPoint(startX, startY),
|
||||
geo.NewPoint(midX, startY),
|
||||
geo.NewPoint(midX, endY),
|
||||
geo.NewPoint(endX, endY),
|
||||
}
|
||||
messageOffset = endY + sd.yStep - noteOffset
|
||||
prevIsLoop = true
|
||||
} else {
|
||||
startY := messageOffset + noteOffset + float64(message.LabelDimensions.Height/2.)
|
||||
message.Route = []*geo.Point{
|
||||
geo.NewPoint(startX, startY),
|
||||
geo.NewPoint(endX, startY),
|
||||
}
|
||||
messageOffset = startY + float64(message.LabelDimensions.Height/2.) + sd.yStep - noteOffset
|
||||
prevIsLoop = false
|
||||
}
|
||||
messageOffset += sd.yStep
|
||||
|
||||
if message.Label.Value != "" {
|
||||
message.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
|
||||
|
|
@ -665,19 +647,7 @@ func (sd *sequenceDiagram) isActor(obj *d2graph.Object) bool {
|
|||
func (sd *sequenceDiagram) getWidth() float64 {
|
||||
// the layout is always placed starting at 0, so the width is just the last actor
|
||||
lastActor := sd.actors[len(sd.actors)-1]
|
||||
rightmost := lastActor.TopLeft.X + lastActor.Width
|
||||
|
||||
for _, m := range sd.messages {
|
||||
for _, p := range m.Route {
|
||||
rightmost = math.Max(rightmost, p.X)
|
||||
}
|
||||
// Self referential messages may have labels that extend further
|
||||
if m.Src == m.Dst {
|
||||
rightmost = math.Max(rightmost, m.Route[1].X+float64(m.LabelDimensions.Width)/2.)
|
||||
}
|
||||
}
|
||||
|
||||
return rightmost
|
||||
return lastActor.TopLeft.X + lastActor.Width
|
||||
}
|
||||
|
||||
func (sd *sequenceDiagram) getHeight() float64 {
|
||||
|
|
|
|||
12
d2lib/d2.go
12
d2lib/d2.go
|
|
@ -71,21 +71,9 @@ func Compile(ctx context.Context, input string, compileOpts *CompileOptions, ren
|
|||
|
||||
applyConfigs(config, compileOpts, renderOpts)
|
||||
applyDefaults(compileOpts, renderOpts)
|
||||
if config != nil {
|
||||
g.Data = config.Data
|
||||
}
|
||||
|
||||
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
|
||||
|
|
|
|||
|
|
@ -1,506 +0,0 @@
|
|||
// Completion implements lsp autocomplete features
|
||||
// Currently handles:
|
||||
// - Complete dot and inside maps for reserved keyword holders (style, labels, etc)
|
||||
// - Complete discrete values for keywords like shape
|
||||
// - Complete suggestions for formats for keywords like opacity
|
||||
package d2lsp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"oss.terrastruct.com/d2/d2ast"
|
||||
"oss.terrastruct.com/d2/d2parser"
|
||||
"oss.terrastruct.com/d2/d2target"
|
||||
)
|
||||
|
||||
type CompletionKind int
|
||||
|
||||
const (
|
||||
KeywordCompletion CompletionKind = iota
|
||||
StyleCompletion
|
||||
ShapeCompletion
|
||||
)
|
||||
|
||||
type CompletionItem struct {
|
||||
Label string
|
||||
Kind CompletionKind
|
||||
Detail string
|
||||
InsertText string
|
||||
}
|
||||
|
||||
func GetCompletionItems(text string, line, column int) ([]CompletionItem, error) {
|
||||
ast, err := d2parser.Parse("", strings.NewReader(text), nil)
|
||||
if err != nil {
|
||||
ast, _ = d2parser.Parse("", strings.NewReader(getTextUntilPosition(text, line, column)), nil)
|
||||
}
|
||||
|
||||
keyword := getKeywordContext(text, ast, line, column)
|
||||
switch keyword {
|
||||
case "style", "style.":
|
||||
return getStyleCompletions(), nil
|
||||
case "shape", "shape:":
|
||||
return getShapeCompletions(), nil
|
||||
case "shadow", "3d", "multiple", "animated", "bold", "italic", "underline", "filled", "double-border",
|
||||
"shadow:", "3d:", "multiple:", "animated:", "bold:", "italic:", "underline:", "filled:", "double-border:",
|
||||
"style.shadow:", "style.3d:", "style.multiple:", "style.animated:", "style.bold:", "style.italic:", "style.underline:", "style.filled:", "style.double-border:":
|
||||
return getBooleanCompletions(), nil
|
||||
case "fill-pattern", "fill-pattern:", "style.fill-pattern:":
|
||||
return getFillPatternCompletions(), nil
|
||||
case "text-transform", "text-transform:", "style.text-transform:":
|
||||
return getTextTransformCompletions(), nil
|
||||
case "opacity", "stroke-width", "stroke-dash", "border-radius", "font-size",
|
||||
"stroke", "fill", "font-color":
|
||||
return getValueCompletions(keyword), nil
|
||||
case "opacity:", "stroke-width:", "stroke-dash:", "border-radius:", "font-size:",
|
||||
"stroke:", "fill:", "font-color:",
|
||||
"style.opacity:", "style.stroke-width:", "style.stroke-dash:", "style.border-radius:", "style.font-size:",
|
||||
"style.stroke:", "style.fill:", "style.font-color:":
|
||||
return getValueCompletions(strings.TrimSuffix(strings.TrimPrefix(keyword, "style."), ":")), nil
|
||||
case "width", "height", "top", "left":
|
||||
return getValueCompletions(keyword), nil
|
||||
case "width:", "height:", "top:", "left:":
|
||||
return getValueCompletions(keyword[:len(keyword)-1]), nil
|
||||
case "source-arrowhead", "target-arrowhead":
|
||||
return getArrowheadCompletions(), nil
|
||||
case "source-arrowhead.shape:", "target-arrowhead.shape:":
|
||||
return getArrowheadShapeCompletions(), nil
|
||||
case "label", "label.":
|
||||
return getLabelCompletions(), nil
|
||||
case "icon", "icon:":
|
||||
return getIconCompletions(), nil
|
||||
case "icon.":
|
||||
return getLabelCompletions(), nil
|
||||
case "near", "near:":
|
||||
return getNearCompletions(), nil
|
||||
case "tooltip:", "tooltip":
|
||||
return getTooltipCompletions(), nil
|
||||
case "direction:", "direction":
|
||||
return getDirectionCompletions(), nil
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func getTextUntilPosition(text string, line, column int) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
if line >= len(lines) {
|
||||
return text
|
||||
}
|
||||
|
||||
result := strings.Join(lines[:line], "\n")
|
||||
if len(result) > 0 {
|
||||
result += "\n"
|
||||
}
|
||||
if column > len(lines[line]) {
|
||||
result += lines[line]
|
||||
} else {
|
||||
result += lines[line][:column]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func getKeywordContext(text string, m *d2ast.Map, line, column int) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(text, "\n")
|
||||
|
||||
for _, n := range m.Nodes {
|
||||
if n.MapKey == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
var firstPart, lastPart string
|
||||
var key *d2ast.KeyPath
|
||||
if len(n.MapKey.Edges) > 0 {
|
||||
key = n.MapKey.EdgeKey
|
||||
} else {
|
||||
key = n.MapKey.Key
|
||||
}
|
||||
if key != nil && len(key.Path) > 0 {
|
||||
firstKey := key.Path[0].Unbox()
|
||||
if !firstKey.IsUnquoted() {
|
||||
continue
|
||||
}
|
||||
firstPart = firstKey.ScalarString()
|
||||
|
||||
pathLen := len(key.Path)
|
||||
if pathLen > 1 {
|
||||
lastKey := key.Path[pathLen-1].Unbox()
|
||||
if lastKey.IsUnquoted() {
|
||||
lastPart = lastKey.ScalarString()
|
||||
_, isHolderLast := d2ast.ReservedKeywordHolders[lastPart]
|
||||
if !isHolderLast {
|
||||
_, isHolderLast = d2ast.CompositeReservedKeywords[lastPart]
|
||||
}
|
||||
keyRange := n.MapKey.Range
|
||||
lineText := lines[keyRange.End.Line]
|
||||
if isHolderLast && isAfterDot(lineText, column) {
|
||||
return lastPart + "."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, isBoard := d2ast.BoardKeywords[firstPart]; isBoard {
|
||||
firstPart = ""
|
||||
}
|
||||
if firstPart == "classes" {
|
||||
firstPart = ""
|
||||
}
|
||||
|
||||
_, isHolder := d2ast.ReservedKeywordHolders[firstPart]
|
||||
if !isHolder {
|
||||
_, isHolder = d2ast.CompositeReservedKeywords[firstPart]
|
||||
}
|
||||
|
||||
// Check nested map
|
||||
if n.MapKey.Value.Map != nil && isPositionInMap(line, column, n.MapKey.Value.Map) {
|
||||
if nested := getKeywordContext(text, n.MapKey.Value.Map, line, column); nested != "" {
|
||||
if isHolder {
|
||||
// If we got a direct key completion from inside a holder's map,
|
||||
// prefix it with the holder's name
|
||||
if strings.HasSuffix(nested, ":") && !strings.Contains(nested, ".") {
|
||||
return firstPart + "." + strings.TrimSuffix(nested, ":") + ":"
|
||||
}
|
||||
}
|
||||
return nested
|
||||
}
|
||||
return firstPart
|
||||
}
|
||||
|
||||
keyRange := n.MapKey.Range
|
||||
if line != keyRange.End.Line {
|
||||
continue
|
||||
}
|
||||
|
||||
// 1) Skip if cursor is well above/below this key
|
||||
if line < keyRange.Start.Line || line > keyRange.End.Line {
|
||||
continue
|
||||
}
|
||||
|
||||
// 2) If on the start line, skip if before the key
|
||||
if line == keyRange.Start.Line && column < keyRange.Start.Column {
|
||||
continue
|
||||
}
|
||||
|
||||
// 3) If on the end line, allow up to keyRange.End.Column + 1
|
||||
if line == keyRange.End.Line && column > keyRange.End.Column+1 {
|
||||
continue
|
||||
}
|
||||
|
||||
lineText := lines[keyRange.End.Line]
|
||||
|
||||
if isAfterColon(lineText, column) {
|
||||
if key != nil && len(key.Path) > 1 {
|
||||
if isHolder && (firstPart == "source-arrowhead" || firstPart == "target-arrowhead") {
|
||||
return firstPart + "." + lastPart + ":"
|
||||
}
|
||||
|
||||
_, isHolder := d2ast.ReservedKeywordHolders[lastPart]
|
||||
if !isHolder {
|
||||
return lastPart
|
||||
}
|
||||
}
|
||||
return firstPart + ":"
|
||||
}
|
||||
|
||||
if isAfterDot(lineText, column) && isHolder {
|
||||
return firstPart
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func isAfterDot(text string, pos int) bool {
|
||||
return pos > 0 && pos <= len(text) && text[pos-1] == '.'
|
||||
}
|
||||
|
||||
func isAfterColon(text string, pos int) bool {
|
||||
if pos < 1 || pos > len(text) {
|
||||
return false
|
||||
}
|
||||
i := pos - 1
|
||||
for i >= 0 && unicode.IsSpace(rune(text[i])) {
|
||||
i--
|
||||
}
|
||||
return i >= 0 && text[i] == ':'
|
||||
}
|
||||
|
||||
func isPositionInMap(line, column int, m *d2ast.Map) bool {
|
||||
if m == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
mapRange := m.Range
|
||||
if line < mapRange.Start.Line || line > mapRange.End.Line {
|
||||
return false
|
||||
}
|
||||
|
||||
if line == mapRange.Start.Line && column < mapRange.Start.Column {
|
||||
return false
|
||||
}
|
||||
if line == mapRange.End.Line && column > mapRange.End.Column {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getShapeCompletions() []CompletionItem {
|
||||
items := make([]CompletionItem, 0, len(d2target.Shapes))
|
||||
for _, shape := range d2target.Shapes {
|
||||
item := CompletionItem{
|
||||
Label: shape,
|
||||
Kind: ShapeCompletion,
|
||||
Detail: "shape",
|
||||
InsertText: shape,
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func getValueCompletions(property string) []CompletionItem {
|
||||
switch property {
|
||||
case "opacity":
|
||||
return []CompletionItem{{
|
||||
Label: "(number between 0.0 and 1.0)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. 0.4",
|
||||
InsertText: "",
|
||||
}}
|
||||
case "stroke-width":
|
||||
return []CompletionItem{{
|
||||
Label: "(number between 0 and 15)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. 2",
|
||||
InsertText: "",
|
||||
}}
|
||||
case "font-size":
|
||||
return []CompletionItem{{
|
||||
Label: "(number between 8 and 100)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. 14",
|
||||
InsertText: "",
|
||||
}}
|
||||
case "stroke-dash":
|
||||
return []CompletionItem{{
|
||||
Label: "(number between 0 and 10)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. 5",
|
||||
InsertText: "",
|
||||
}}
|
||||
case "border-radius":
|
||||
return []CompletionItem{{
|
||||
Label: "(number greater than or equal to 0)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. 4",
|
||||
InsertText: "",
|
||||
}}
|
||||
case "font-color", "stroke", "fill":
|
||||
return []CompletionItem{{
|
||||
Label: "(color name or hex code)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. blue, #ff0000",
|
||||
InsertText: "",
|
||||
}}
|
||||
case "width", "height", "top", "left":
|
||||
return []CompletionItem{{
|
||||
Label: "(pixels)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. 400",
|
||||
InsertText: "",
|
||||
}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getStyleCompletions() []CompletionItem {
|
||||
items := make([]CompletionItem, 0, len(d2ast.StyleKeywords))
|
||||
for keyword := range d2ast.StyleKeywords {
|
||||
item := CompletionItem{
|
||||
Label: keyword,
|
||||
Kind: StyleCompletion,
|
||||
Detail: "style property",
|
||||
InsertText: keyword + ": ",
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func getBooleanCompletions() []CompletionItem {
|
||||
return []CompletionItem{
|
||||
{
|
||||
Label: "true",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "boolean",
|
||||
InsertText: "true",
|
||||
},
|
||||
{
|
||||
Label: "false",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "boolean",
|
||||
InsertText: "false",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getFillPatternCompletions() []CompletionItem {
|
||||
items := make([]CompletionItem, 0, len(d2ast.FillPatterns))
|
||||
for _, pattern := range d2ast.FillPatterns {
|
||||
item := CompletionItem{
|
||||
Label: pattern,
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "fill pattern",
|
||||
InsertText: pattern,
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func getTextTransformCompletions() []CompletionItem {
|
||||
items := make([]CompletionItem, 0, len(d2ast.TextTransforms))
|
||||
for _, transform := range d2ast.TextTransforms {
|
||||
item := CompletionItem{
|
||||
Label: transform,
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "text transform",
|
||||
InsertText: transform,
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func isOnEmptyLine(text string, line int) bool {
|
||||
lines := strings.Split(text, "\n")
|
||||
if line >= len(lines) {
|
||||
return true
|
||||
}
|
||||
|
||||
return strings.TrimSpace(lines[line]) == ""
|
||||
}
|
||||
|
||||
func getLabelCompletions() []CompletionItem {
|
||||
return []CompletionItem{{
|
||||
Label: "near",
|
||||
Kind: StyleCompletion,
|
||||
Detail: "label position",
|
||||
InsertText: "near: ",
|
||||
}}
|
||||
}
|
||||
|
||||
func getNearCompletions() []CompletionItem {
|
||||
items := make([]CompletionItem, 0, len(d2ast.LabelPositionsArray)+1)
|
||||
|
||||
items = append(items, CompletionItem{
|
||||
Label: "(object ID)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "e.g. container.inner_shape",
|
||||
InsertText: "",
|
||||
})
|
||||
|
||||
for _, pos := range d2ast.LabelPositionsArray {
|
||||
item := CompletionItem{
|
||||
Label: pos,
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "label position",
|
||||
InsertText: pos,
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func getTooltipCompletions() []CompletionItem {
|
||||
return []CompletionItem{
|
||||
{
|
||||
Label: "(markdown)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "markdown formatted text",
|
||||
InsertText: "|md\n # Tooltip\n Hello world\n|",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getIconCompletions() []CompletionItem {
|
||||
return []CompletionItem{
|
||||
{
|
||||
Label: "(URL, e.g. https://icons.terrastruct.com/xyz.svg)",
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "icon URL",
|
||||
InsertText: "https://icons.terrastruct.com/essentials%2F073-add.svg",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getDirectionCompletions() []CompletionItem {
|
||||
directions := []string{"up", "down", "right", "left"}
|
||||
items := make([]CompletionItem, len(directions))
|
||||
for i, dir := range directions {
|
||||
items[i] = CompletionItem{
|
||||
Label: dir,
|
||||
Kind: KeywordCompletion,
|
||||
Detail: "direction",
|
||||
InsertText: dir,
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func getArrowheadShapeCompletions() []CompletionItem {
|
||||
arrowheads := []string{
|
||||
"triangle",
|
||||
"arrow",
|
||||
"diamond",
|
||||
"circle",
|
||||
"cf-one", "cf-one-required",
|
||||
"cf-many", "cf-many-required",
|
||||
}
|
||||
|
||||
items := make([]CompletionItem, len(arrowheads))
|
||||
details := map[string]string{
|
||||
"triangle": "default",
|
||||
"arrow": "like triangle but pointier",
|
||||
"cf-one": "crows foot one",
|
||||
"cf-one-required": "crows foot one (required)",
|
||||
"cf-many": "crows foot many",
|
||||
"cf-many-required": "crows foot many (required)",
|
||||
}
|
||||
|
||||
for i, shape := range arrowheads {
|
||||
detail := details[shape]
|
||||
if detail == "" {
|
||||
detail = "arrowhead shape"
|
||||
}
|
||||
items[i] = CompletionItem{
|
||||
Label: shape,
|
||||
Kind: ShapeCompletion,
|
||||
Detail: detail,
|
||||
InsertText: shape,
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func getArrowheadCompletions() []CompletionItem {
|
||||
completions := []string{
|
||||
"shape",
|
||||
"label",
|
||||
"style.filled",
|
||||
}
|
||||
|
||||
items := make([]CompletionItem, len(completions))
|
||||
|
||||
for i, shape := range completions {
|
||||
items[i] = CompletionItem{
|
||||
Label: shape,
|
||||
Kind: ShapeCompletion,
|
||||
InsertText: shape,
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue