Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

doc.gno

/*
Package svg is a minimalist and extensible SVG generation library for Gno.

It is the B+ tree successor to [gno.land/p/nym-moultest123/svg/v0] (whose canvas styles are
backed by an AVL tree): a bump to v2 because the backing data structure used for
the canvas style map — and thus the on-chain storage layout — changed from
[gno.land/p/nt/avl/v0] to [gno.land/p/nt/bptree/v0]. The exported API is
otherwise identical to v1.

A B+ tree packs many entries per persisted node, so a stored style entry costs
less storage than the AVL backing (and inserts spend materially less gas).
Prefer v2 when the canvas is part of persisted realm state.

Two behavioral caveats inherited from the in-place-mutating B+ tree backing:

  - do NOT call AddStyle from inside a Canvas.String/Render iteration — the AVL
    backing tolerated mutation during iteration, the B+ tree one does not;
  - do NOT copy a non-zero Canvas by value once styles have been added — the
    copies would share live B+ tree nodes (v1's AVL copies were independent).

It provides a structured way to create and compose SVG elements such as rectangles, circles, text, paths, and more. The package is designed to be modular and developer-friendly, enabling optional attributes and method chaining for ease of use.

Each SVG element embeds a BaseAttrs struct, which supports common SVG attributes like `id`, `class`, `style`, `fill`, `stroke`, and `transform`.

Canvas objects represent the root SVG container and support global dimensions, viewBox configuration, embedded styles, and element composition.

Example:

	import "gno.land/p/nym-moultest123/svg/v0"

	func Foo() string {
		canvas := svg.NewCanvas(200, 200).WithViewBox(0, 0, 200, 200)
		canvas.AddStyle(".my-rect", "stroke:black;stroke-width:2")
		canvas.Append(
			svg.NewRectangle(60, 40, 100, 50, "red").WithClass("my-rect"),
			svg.NewCircle(50, 80, 40, "blue"),
			&svg.Path{D: `M 10,30
			A 20,20 0,0,1 50,30
				A 20,20 0,0,1  90,30
				Q 90,60 50,90
				Q 10,60 10,30 z`, Fill: "magenta"},
			svg.NewText(20, 50, "Hello SVG", "black"),
		)
		mysvg := canvas.Base64()
	}
*/
package svg // import "gno.land/p/nym-moultest123/svg/v0"

gnomod.toml

module = "gno.land/p/nym-moultest123/svg/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186404
  max_deposit = "7000000ugnot"

svg.gno

package svg

import (
	"encoding/base64"
	"strings"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/ufmt/v0"
)

type Canvas struct {
	Width, Height int
	ViewBox       string
	Elems         []Elem
	Style         *bptree.BPTree
}

type Elem interface{ String() string }

func NewCanvas(width, height int) *Canvas {
	return &Canvas{
		Width:  width,
		Height: height,
		Style:  nil,
	}
}

func (c *Canvas) AddStyle(key, value string) *Canvas {
	if c.Style == nil {
		c.Style = bptree.NewBPTree32()
	}
	c.Style.Set(key, value)
	return c
}

func (c *Canvas) WithViewBox(x, y, width, height int) *Canvas {
	c.ViewBox = ufmt.Sprintf("%d %d %d %d", x, y, width, height)
	return c
}

// Render renders your canvas
func (c Canvas) Render(alt string) string {
	base64SVG := base64.StdEncoding.EncodeToString([]byte(c.String()))
	return ufmt.Sprintf("![%s](data:image/svg+xml;base64,%s)", alt, base64SVG)
}

func (c Canvas) String() string {
	out := ""
	out += ufmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="%s">`, c.Width, c.Height, c.ViewBox)
	if c.Style != nil {
		out += "<style>"
		c.Style.Iterate("", "", func(k string, val interface{}) bool {
			v := val.(string)
			out += ufmt.Sprintf("%s{%s}", k, v)
			return false
		})
		out += "</style>"
	}
	for _, elem := range c.Elems {
		out += elem.String()
	}
	out += "</svg>"
	return out
}

func (c Canvas) Base64() string {
	out := c.String()
	return base64.StdEncoding.EncodeToString([]byte(out))
}

func (c *Canvas) Append(elem ...Elem) {
	c.Elems = append(c.Elems, elem...)
}

type BaseAttrs struct {
	ID          string
	Class       string
	Style       string
	Stroke      string
	StrokeWidth string
	Opacity     string
	Transform   string
	Visibility  string
}

func (b BaseAttrs) String() string {
	var elems []string

	if b.ID != "" {
		elems = append(elems, `id="`+b.ID+`"`)
	}
	if b.Class != "" {
		elems = append(elems, `class="`+b.Class+`"`)
	}
	if b.Style != "" {
		elems = append(elems, `style="`+b.Style+`"`)
	}
	if b.Stroke != "" {
		elems = append(elems, `stroke="`+b.Stroke+`"`)
	}
	if b.StrokeWidth != "" {
		elems = append(elems, `stroke-width="`+b.StrokeWidth+`"`)
	}
	if b.Opacity != "" {
		elems = append(elems, `opacity="`+b.Opacity+`"`)
	}
	if b.Transform != "" {
		elems = append(elems, `transform="`+b.Transform+`"`)
	}
	if b.Visibility != "" {
		elems = append(elems, `visibility="`+b.Visibility+`"`)
	}
	if len(elems) == 0 {
		return ""
	}
	return strings.Join(elems, " ")
}

type Circle struct {
	CX   int // center X
	CY   int // center Y
	R    int // radius
	Fill string
	Attr BaseAttrs
}

func (c Circle) String() string {
	return ufmt.Sprintf(`<circle cx="%d" cy="%d" r="%d" fill="%s" %s/>`, c.CX, c.CY, c.R, c.Fill, c.Attr.String())
}

func NewCircle(cx, cy, r int, fill string) *Circle {
	return &Circle{
		CX:   cx,
		CY:   cy,
		R:    r,
		Fill: fill,
	}
}

func (c *Circle) WithClass(class string) *Circle {
	c.Attr.Class = class
	return c
}

type Ellipse struct {
	CX   int // center X
	CY   int // center Y
	RX   int // radius X
	RY   int // radius Y
	Fill string
	Attr BaseAttrs
}

func (e Ellipse) String() string {
	return ufmt.Sprintf(`<ellipse cx="%d" cy="%d" rx="%d" ry="%d" fill="%s" %s/>`, e.CX, e.CY, e.RX, e.RY, e.Fill, e.Attr.String())
}

func NewEllipse(cx, cy int, fill string) *Ellipse {
	return &Ellipse{
		CX:   cx,
		CY:   cy,
		Fill: fill,
	}
}

func (e *Ellipse) WithClass(class string) *Ellipse {
	e.Attr.Class = class
	return e
}

type Rectangle struct {
	X, Y, Width, Height int
	RX, RY              int // corner radiuses
	Fill                string
	Attr                BaseAttrs
}

func (r Rectangle) String() string {
	return ufmt.Sprintf(`<rect x="%d" y="%d" width="%d" height="%d" rx="%d" ry="%d" fill="%s" %s/>`, r.X, r.Y, r.Width, r.Height, r.RX, r.RY, r.Fill, r.Attr.String())
}

func NewRectangle(x, y, width, height int, fill string) *Rectangle {
	return &Rectangle{
		X:      x,
		Y:      y,
		Width:  width,
		Height: height,
		Fill:   fill,
	}
}

func (r *Rectangle) WithClass(class string) *Rectangle {
	r.Attr.Class = class
	return r
}

type Path struct {
	D    string
	Fill string
	Attr BaseAttrs
}

func (p Path) String() string {
	return ufmt.Sprintf(`<path d="%s" fill="%s" %s/>`, p.D, p.Fill, p.Attr.String())
}

func NewPath(d, fill string) *Path {
	return &Path{
		D:    d,
		Fill: fill,
	}
}

func (p *Path) WithClass(class string) *Path {
	p.Attr.Class = class
	return p
}

type Polygon struct { // closed shape
	Points string
	Fill   string
	Attr   BaseAttrs
}

func (p Polygon) String() string {
	return ufmt.Sprintf(`<polygon points="%s" fill="%s" %s/>`, p.Points, p.Fill, p.Attr.String())
}

func NewPolygon(points, fill string) *Polygon {
	return &Polygon{
		Points: points,
		Fill:   fill,
	}
}

func (p *Polygon) WithClass(class string) *Polygon {
	p.Attr.Class = class
	return p
}

type Polyline struct { // polygon but not necessarily closed
	Points string
	Fill   string
	Attr   BaseAttrs
}

func (p Polyline) String() string {
	return ufmt.Sprintf(`<polyline points="%s" fill="%s" %s/>`, p.Points, p.Fill, p.Attr.String())
}

func NewPolyline(points, fill string) *Polyline {
	return &Polyline{
		Points: points,
		Fill:   fill,
	}
}

func (p *Polyline) WithClass(class string) *Polyline {
	p.Attr.Class = class
	return p
}

type Text struct {
	X, Y       int
	DX, DY     int // shift text pos horizontally/ vertically
	Rotate     string
	Text, Fill string
	Attr       BaseAttrs
}

func (c Text) String() string {
	return ufmt.Sprintf(`<text x="%d" y="%d" dx="%d" dy="%d" rotate="%s" fill="%s" %s>%s</text>`, c.X, c.Y, c.DX, c.DY, c.Rotate, c.Fill, c.Attr.String(), c.Text)
}

func NewText(x, y int, text, fill string) *Text {
	return &Text{
		X:    x,
		Y:    y,
		Text: text,
		Fill: fill,
	}
}

func (c *Text) WithClass(class string) *Text {
	c.Attr.Class = class
	return c
}

type Group struct {
	Elems []Elem
	Fill  string
	Attr  BaseAttrs
}

func (g Group) String() string {
	out := ""
	for _, e := range g.Elems {
		out += e.String()
	}
	return ufmt.Sprintf(`<g fill="%s" %s>%s</g>`, g.Fill, g.Attr.String(), out)
}

func NewGroup(fill string) *Group {
	return &Group{
		Fill: fill,
	}
}

func (g *Group) Append(elem ...Elem) {
	g.Elems = append(g.Elems, elem...)
}

func (g *Group) WithClass(class string) *Group {
	g.Attr.Class = class
	return g
}

svg_test.gno

package svg

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestBaseAttrsEmpty(t *testing.T) {
	uassert.Equal(t, "", BaseAttrs{}.String())
}

func TestBaseAttrsAllFields(t *testing.T) {
	b := BaseAttrs{
		ID:          "i",
		Class:       "c",
		Style:       "fill:red",
		Stroke:      "black",
		StrokeWidth: "2",
		Opacity:     "0.5",
		Transform:   "rotate(90)",
		Visibility:  "hidden",
	}
	uassert.Equal(t,
		`id="i" class="c" style="fill:red" stroke="black" stroke-width="2" opacity="0.5" transform="rotate(90)" visibility="hidden"`,
		b.String())
}

func TestBaseAttrsSkipsEmptyFields(t *testing.T) {
	uassert.Equal(t, `id="i" opacity="0.5"`, BaseAttrs{ID: "i", Opacity: "0.5"}.String())
}

func TestCircle(t *testing.T) {
	c := NewCircle(1, 2, 3, "red")
	uassert.Equal(t, `<circle cx="1" cy="2" r="3" fill="red" />`, c.String())

	uassert.True(t, c.WithClass("dot") == c, "WithClass should be chainable: same pointer back")
	uassert.Equal(t, `<circle cx="1" cy="2" r="3" fill="red" class="dot"/>`, c.String())
}

func TestEllipse(t *testing.T) {
	e := NewEllipse(4, 5, "blue")
	// NewEllipse takes no radii, so RX/RY stay zero until set directly.
	uassert.Equal(t, `<ellipse cx="4" cy="5" rx="0" ry="0" fill="blue" />`, e.String())

	e.RX, e.RY = 10, 20
	e.WithClass("blob")
	uassert.Equal(t, `<ellipse cx="4" cy="5" rx="10" ry="20" fill="blue" class="blob"/>`, e.String())
}

func TestRectangle(t *testing.T) {
	r := NewRectangle(1, 2, 30, 40, "green")
	uassert.Equal(t, `<rect x="1" y="2" width="30" height="40" rx="0" ry="0" fill="green" />`, r.String())

	r.RX, r.RY = 5, 6
	r.WithClass("box")
	uassert.Equal(t, `<rect x="1" y="2" width="30" height="40" rx="5" ry="6" fill="green" class="box"/>`, r.String())
}

func TestPath(t *testing.T) {
	p := NewPath("M0 0 L10 10", "none")
	uassert.Equal(t, `<path d="M0 0 L10 10" fill="none" />`, p.String())

	p.WithClass("stroke")
	uassert.Equal(t, `<path d="M0 0 L10 10" fill="none" class="stroke"/>`, p.String())
}

func TestPolygon(t *testing.T) {
	p := NewPolygon("0,0 10,0 5,8", "yellow")
	uassert.Equal(t, `<polygon points="0,0 10,0 5,8" fill="yellow" />`, p.String())

	p.WithClass("tri")
	uassert.Equal(t, `<polygon points="0,0 10,0 5,8" fill="yellow" class="tri"/>`, p.String())
}

func TestPolyline(t *testing.T) {
	p := NewPolyline("0,0 10,10", "none")
	uassert.Equal(t, `<polyline points="0,0 10,10" fill="none" />`, p.String())

	p.WithClass("line")
	uassert.Equal(t, `<polyline points="0,0 10,10" fill="none" class="line"/>`, p.String())
}

func TestText(t *testing.T) {
	tx := NewText(7, 8, "hello", "black")
	uassert.Equal(t, `<text x="7" y="8" dx="0" dy="0" rotate="" fill="black" >hello</text>`, tx.String())

	tx.DX, tx.DY, tx.Rotate = 1, 2, "45"
	tx.WithClass("label")
	uassert.Equal(t, `<text x="7" y="8" dx="1" dy="2" rotate="45" fill="black" class="label">hello</text>`, tx.String())
}

func TestGroup(t *testing.T) {
	g := NewGroup("purple")
	uassert.Equal(t, `<g fill="purple" ></g>`, g.String())

	g.Append(NewCircle(0, 0, 1, "red"), NewPath("M0 0", "none"))
	g.WithClass("layer")
	uassert.Equal(t,
		`<g fill="purple" class="layer"><circle cx="0" cy="0" r="1" fill="red" /><path d="M0 0" fill="none" /></g>`,
		g.String())
}

func TestGroupNesting(t *testing.T) {
	inner := NewGroup("a")
	inner.Append(NewCircle(1, 1, 1, "red"))
	outer := NewGroup("b")
	outer.Append(inner)

	uassert.Equal(t,
		`<g fill="b" ><g fill="a" ><circle cx="1" cy="1" r="1" fill="red" /></g></g>`,
		outer.String())
}

func TestCanvasEmpty(t *testing.T) {
	c := NewCanvas(100, 50)
	uassert.Equal(t,
		`<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50" viewBox=""></svg>`,
		c.String())
}

func TestCanvasWithViewBox(t *testing.T) {
	c := NewCanvas(100, 50)
	uassert.True(t, c.WithViewBox(0, 0, 200, 100) == c, "WithViewBox should be chainable")
	uassert.True(t, strings.Contains(c.String(), `viewBox="0 0 200 100"`), "viewBox should be set")
}

func TestCanvasAppend(t *testing.T) {
	c := NewCanvas(10, 10)
	c.Append(NewCircle(1, 1, 1, "red"), NewCircle(2, 2, 2, "blue"))

	out := c.String()
	uassert.True(t, strings.Contains(out, `<circle cx="1" cy="1" r="1" fill="red" /><circle cx="2" cy="2" r="2" fill="blue" />`),
		"elements should render in insertion order")
}

// TestCanvasStyleIsKeyOrdered is the determinism check that matters on-chain:
// the style block must not depend on insertion order, or two nodes could
// disagree on the rendered output.
func TestCanvasStyleIsKeyOrdered(t *testing.T) {
	a := NewCanvas(10, 10)
	a.AddStyle("z-last", "fill:blue").AddStyle("a-first", "fill:red")

	b := NewCanvas(10, 10)
	b.AddStyle("a-first", "fill:red").AddStyle("z-last", "fill:blue")

	uassert.Equal(t, a.String(), b.String())
	uassert.True(t, strings.Contains(a.String(), `<style>a-first{fill:red}z-last{fill:blue}</style>`),
		"styles should be emitted in key order")
}

func TestCanvasNoStyleBlockWhenUnset(t *testing.T) {
	uassert.False(t, strings.Contains(NewCanvas(1, 1).String(), "<style>"),
		"a canvas with no styles should not emit an empty <style> block")
}

func TestCanvasAddStyleChainable(t *testing.T) {
	c := NewCanvas(1, 1)
	uassert.True(t, c.AddStyle("a", "b") == c, "AddStyle should be chainable")
}

func TestCanvasBase64RoundTrip(t *testing.T) {
	c := NewCanvas(10, 10)
	c.Append(NewCircle(1, 1, 1, "red"))

	// Base64 must encode exactly what String() produced.
	uassert.Equal(t, "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgdmlld0JveD0iIj48Y2lyY2xlIGN4PSIxIiBjeT0iMSIgcj0iMSIgZmlsbD0icmVkIiAvPjwvc3ZnPg==",
		c.Base64())
}

func TestCanvasRenderWrapsBase64(t *testing.T) {
	c := NewCanvas(10, 10)
	c.Append(NewCircle(1, 1, 1, "red"))

	uassert.Equal(t, "![a picture](data:image/svg+xml;base64,"+c.Base64()+")", c.Render("a picture"))
}