d2svgimport

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2026 License: MPL-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package d2svgimport imports the bounded, network-free SVG subset used by D2 assets and MathJax into d2scene.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParsePath

func ParsePath(ctx context.Context, source, data string, limits PathLimits) ([]d2scene.PathCommand, error)

ParsePath converts the complete common SVG path grammar to absolute typed d2scene commands. source must already be safe to include in an error (asset resolvers should pass their redacted display name, never a credentialed URL).

Types

type ImportOptions

type ImportOptions struct {
	CurrentColor *color.NRGBA
}

ImportOptions selects caller-owned presentation context that is outside the imported SVG subtree. A nil CurrentColor preserves SVG's opaque-black initial color. ImportNodeWithOptions copies the pointed-to value before parsing and never retains the pointer.

type Limits

type Limits struct {
	MaxBytes              int
	MaxDepth              int
	MaxElements           int
	MaxAttributes         int
	MaxAttributeBytes     int
	MaxPathCommands       int
	MaxTransformFunctions int
	MaxUseDepth           int
	MaxResources          int
}

Limits are required caller-selected hard limits for one SVG import. Every field must be positive. MaxElements and MaxPathCommands independently cap both parsed source and emitted scene totals. MaxResources caps declared IDs plus distinct embedded raster assets, and independently caps expanded local-use instances. MaxBytes also caps the retained encoded and decoded raster-asset totals so callers gain a finite image budget without a new required limit.

type Metrics

type Metrics struct {
	SourceBytes          int
	ParsedElements       int
	ParsedAttributes     int
	ParsedAttributeBytes int
	ParsedPathCommands   int
	ParsedTransformFuncs int
	DeclaredResources    int
	ExpandedUseInstances int
	EmittedElements      int
	EmittedPathCommands  int
	EmbeddedRasterAssets int
	EmbeddedRasterBytes  int
	DecodedRasterBytes   int64
}

Metrics reports bounded source and emitted-scene work for one successful import. Callers retaining multiple imported subscenes use these counters to enforce a shared document budget in addition to Limits' per-import ceilings.

type PathLimits

type PathLimits struct {
	MaxBytes    int
	MaxCommands int
}

PathLimits are caller-selected hard limits for one SVG path data string. MaxCommands counts parsed source command groups, including groups such as an identical-endpoint arc that SVG defines to emit no segment. Both values must be positive.

type Result

type Result struct {
	Root              *d2scene.Node
	ViewBox           d2scene.Box
	Width             float64
	Height            float64
	Aspect            d2scene.AspectRatio
	ViewportTransform d2scene.Matrix
	// Assets owns every immutable raster resource referenced by Image
	// primitives below Root. Keys are stable content IDs; callers embedding the
	// subtree must merge these assets into their document without mutation.
	Assets  map[d2scene.AssetID]d2scene.Asset
	Metrics Metrics
}

Result is an owned, network-free SVG subtree plus its viewport metadata. Root remains in SVG user coordinates. ViewportTransform maps ViewBox into the intrinsic Width x Height viewport using Aspect. A caller embedding the subtree must clip final painting to [0,Width] x [0,Height]; in particular, AspectSlice intentionally maps content outside that viewport.

func ImportNode

func ImportNode(ctx context.Context, source string, data []byte, limits Limits) (*Result, error)

ImportNode imports a strict SVG subset. It never reads files, resolves a URL, or performs network I/O. On every error it returns a nil result. Nested svg viewports are limited to finite absolute placement and dimensions with an explicit viewBox. Paint servers other than bounded local user-space linear gradients, clipping outside the bounded local user-space subset, masking, general painted text, nested SVG images, and external references are intentionally rejected rather than silently approximated. Embedded images are restricted to canonical base64 data URIs containing one static PNG, JPEG, GIF, or WebP resource. The sole painted text exception is the exact U+00B5 fallback emitted by D2's frozen MathJax renderer; it is converted to a pinned deterministic outline. Root ex lengths are accepted only with MathJax's exact inert vertical-align form, where one ex is deterministically eight CSS pixels. Non-painting title and corpus-bounded editor metadata are ignored after strict validation. Stylesheets are limited to a bounded simple class-selector subset; see stylesheet.go.

Example (LocalClipPath)
result, err := ImportNode(context.Background(), "clip.svg", []byte(`<svg width="2" height="1"><clipPath id="c"><rect width="1" height="1"/></clipPath><rect width="2" height="1" clip-path="url(#c)"/></svg>`), generousImportLimits())
fmt.Println(err, result.Root.Children[0].Clip != nil)
Output:
<nil> true

func ImportNodeWithOptions

func ImportNodeWithOptions(ctx context.Context, source string, data []byte, limits Limits, options ImportOptions) (*Result, error)

ImportNodeWithOptions imports the same strict subset as ImportNode with an explicit initial currentColor. An SVG color declaration still takes normal cascade precedence over this caller-supplied value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL