Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "7000000ugnot"
render.gno
package toolbox
import (
"net/url"
"strings"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
tb "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox/v0"
)
// Render routes gnoweb paths:
//
// / the directory
// /?tag=identity the directory, filtered to one tag
// /<slug> one tool
func Render(path string) string {
req := realmpath.Parse(path)
parts := req.PathParts()
if len(parts) == 0 || parts[0] == "" {
return renderIndex(req.Query.Get("tag"))
}
if len(parts) > 1 {
return renderUnknown(parts[0] + "/" + parts[1])
}
t, ok := catalog.Get(parts[0])
if !ok {
return renderUnknown(parts[0])
}
return renderTool(t)
}
func renderIndex(tag string) string {
var b strings.Builder
b.WriteString(md.H1("Toolbox"))
b.WriteString("\nSmall utilities on gno.land. Each one is its own realm, composing contracts that are already on chain and showing the answer as a page instead of as a query you have to compose.\n")
list := catalog.List()
if tag != "" {
list = catalog.ByTag(tag)
b.WriteString("\nFiltered to " + md.InlineCode(tag) + ". " +
md.Link("Show all", hubURL) + "\n")
}
b.WriteString("\n" + tb.Index(list))
if tag == "" {
if links := tagLinks(catalog, hubURL); links != "" {
b.WriteString("\nTags: " + links + "\n")
}
}
b.WriteString("\n" + md.H2("What a tool is"))
b.WriteString("\n" + md.BulletList([]string{
"A realm at " + md.InlineCode("gno.land/r/moul/toolbox/<slug>") + ", reachable on its own.",
"Read-only unless it says otherwise: a page you open, not a transaction you sign.",
"Composed from contracts already on chain, so the toolbox adds the view and not the data.",
}))
return b.String()
}
// tagLinks renders the tag filter row, or "" when nothing is tagged.
//
// QueryEscape, not plain concatenation: a tag is an arbitrary string on Tool,
// and "a&b" would otherwise become a second query parameter while "a#b" would
// become a fragment, in both cases linking to a filter nobody asked for.
func tagLinks(c *tb.Catalog, base string) string {
tags := c.Tags()
if len(tags) == 0 {
return ""
}
links := make([]string, 0, len(tags))
for _, name := range tags {
links = append(links, md.Link(name, base+"?tag="+url.QueryEscape(name)))
}
return strings.Join(links, " · ")
}
func renderTool(t tb.Tool) string {
var b strings.Builder
b.WriteString(tb.Nav(hubURL, "Toolbox"))
b.WriteString("\n" + tb.Card(t))
return b.String()
}
func renderUnknown(slug string) string {
var b strings.Builder
b.WriteString(md.H1("Not found"))
b.WriteString("\nNo tool called " + md.InlineCode(slug) + ".\n")
b.WriteString("\n" + md.Link("Back to the toolbox", hubURL) + "\n")
return b.String()
}
render_example_test.gno
package toolbox
// ExampleRender pins the directory page. The catalog is compiled in, so this
// output changes only when a tool is added or re-described, which is exactly
// when a reviewer should see the diff.
func ExampleRender() {
print(Render(""))
// Output:
// # Toolbox
//
// Small utilities on gno.land. Each one is its own realm, composing contracts that are already on chain and showing the answer as a page instead of as a query you have to compose.
//
// | Tool | What it does | Tags |
// | --- | --- | --- |
// | [Usernames](/r/moul/toolbox/usernames) | Resolve a gno\.land username to an address, or an address to a username\. | identity, read |
//
// Tags: [identity](/r/moul/toolbox?tag=identity) · [read](/r/moul/toolbox?tag=read)
//
// ## What a tool is
//
// - A realm at `gno.land/r/moul/toolbox/<slug>`, reachable on its own.
// - Read-only unless it says otherwise: a page you open, not a transaction you sign.
// - Composed from contracts already on chain, so the toolbox adds the view and not the data.
}
toolbox.gno
// Package toolbox is the directory of moul's small gno.land utilities: one
// page listing every tool, each tool a realm of its own at
// `r/moul/toolbox/<slug>`.
//
// It holds no logic. A tool composes other contracts (resolve a username,
// read a DAO, decode a denom) and renders the answer; this realm only says
// which tools exist and where they are. The model, the rendering and the
// query-form builder are
// [p/moul/toolbox](/p/moul/toolbox/v0).
//
// # Why the catalog is compiled in and not registered
//
// The obvious design is the opposite one: each tool calls `Register` on this
// realm from its own init, and the directory assembles itself. That design is
// unavailable here, and the reason is worth stating because it is not a
// preference.
//
// `private = true` buys redeploy-in-place at the same path and costs the
// ability to be imported: the type checker refuses any realm importing a
// private one (`ImportPrivateError`, `gnovm/pkg/gnolang/gotypecheck.go`). So a
// private hub cannot be imported by its tools, and a hub that accepts
// registration has to be public. A public realm can never be redeployed, which
// would freeze this path at v0 and move the directory's URL on the first bug
// in it.
//
// A stable URL is the whole point of a directory, so the trade goes the other
// way: everything here is private and redeployable, and adding a tool is one
// entry in [tools] plus a redeploy. The catalog is rebuilt from source every
// time, so the redeploy wipe costs nothing: there is no state to lose.
//
// [p/moul/toolbox.Catalog] stays mutable for whoever wants the other trade.
package toolbox
import "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox/v0"
// hubPath is this realm's own path. A realm can ask the chain for it, but a
// constant is what [p/moul/toolbox.SlugOf] is checked against in tests, where
// there is no chain frame to ask.
const hubPath = "gno.land/r/moul/toolbox"
// hubURL is the gnoweb path of this realm, which every tool page links back
// to. A tool cannot import this realm to read it, so each one repeats it; this
// is the copy that is authoritative.
const hubURL = "/r/moul/toolbox"
// tools is the directory. Adding one here and redeploying is how the toolbox
// grows; see the package doc for why it is not a registration call.
//
// Every entry must be a realm under this one: [buildCatalog] refuses an entry
// whose slug does not match its path, so a copy-paste that keeps the wrong
// path fails the deploy rather than publishing a dead link.
var tools = []toolbox.Tool{
{
Slug: "usernames",
Path: "gno.land/r/moul/toolbox/usernames",
Title: "Usernames",
Desc: "Resolve a gno.land username to an address, or an address to a username.",
Tags: []string{"identity", "read"},
},
}
// catalog is the directory, sorted and checked once at deploy.
var catalog = buildCatalog()
func buildCatalog() *toolbox.Catalog {
c := &toolbox.Catalog{}
for _, t := range tools {
if err := c.Set(t); err != nil {
panic(err)
}
if got := toolbox.SlugOf(hubPath, t.Path); got != t.Slug {
panic("toolbox: " + t.Slug + " is declared at " + t.Path +
", which is not gno.land/r/moul/toolbox/" + t.Slug)
}
}
return c
}
// Count is how many tools the directory holds.
func Count() int { return catalog.Len() }
// Slugs lists every tool's slug, in directory order.
//
// gnokey query vm/qeval -data 'gno.land/r/moul/toolbox.Slugs()'
func Slugs() []string {
out := make([]string, 0, catalog.Len())
for _, t := range catalog.List() {
out = append(out, t.Slug)
}
return out
}
// PathOf returns the package path of one tool, or "" when there is no such
// tool. Flat strings rather than the struct: a nested value inside a persisted
// object prints as an opaque `ref(...)` over `vm/qeval`, so a read API that is
// meant to be queried returns scalars.
//
// gnokey query vm/qeval -data 'gno.land/r/moul/toolbox.PathOf("usernames")'
func PathOf(slug string) string {
t, ok := catalog.Get(slug)
if !ok {
return ""
}
return t.Path
}
// TitleOf returns the human name of one tool, or "".
func TitleOf(slug string) string {
t, ok := catalog.Get(slug)
if !ok {
return ""
}
return t.Title
}
// DescOf returns the one-line description of one tool, or "".
func DescOf(slug string) string {
t, ok := catalog.Get(slug)
if !ok {
return ""
}
return t.Desc
}
// Has reports whether a tool with that slug is listed.
func Has(slug string) bool { return catalog.Has(slug) }
// Tags lists every tag any tool carries, each once.
func Tags() []string { return catalog.Tags() }
toolbox_test.gno
package toolbox
import (
"strings"
"testing"
tb "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox/v0"
"gno.land/p/nt/uassert/v0"
)
// TestEveryToolIsNested is the check that makes the compiled-in catalog safe:
// a copy-pasted entry that kept the wrong path would publish a dead link, and
// buildCatalog panics on it at deploy rather than at read.
func TestEveryToolIsNested(t *testing.T) {
uassert.True(t, len(tools) > 0)
for _, tool := range tools {
uassert.NoError(t, tool.Validate())
uassert.Equal(t, tool.Slug, tb.SlugOf(hubPath, tool.Path))
}
}
func TestReadAPI(t *testing.T) {
uassert.Equal(t, len(tools), Count())
uassert.True(t, Has("usernames"))
uassert.False(t, Has("nope"))
uassert.Equal(t, "gno.land/r/moul/toolbox/usernames", PathOf("usernames"))
uassert.Equal(t, "Usernames", TitleOf("usernames"))
uassert.True(t, strings.Contains(DescOf("usernames"), "address"))
uassert.Equal(t, "", PathOf("nope"))
uassert.Equal(t, "", TitleOf("nope"))
uassert.Equal(t, "", DescOf("nope"))
}
func TestSlugsAreSorted(t *testing.T) {
got := Slugs()
uassert.Equal(t, Count(), len(got))
for i := 1; i < len(got); i++ {
uassert.True(t, got[i-1] < got[i])
}
}
func TestTags(t *testing.T) {
got := Tags()
uassert.True(t, len(got) > 0)
found := false
for _, tag := range got {
if tag == "identity" {
found = true
}
}
uassert.True(t, found)
}
func TestRenderIndex(t *testing.T) {
got := Render("")
uassert.True(t, strings.Contains(got, "# Toolbox"))
uassert.True(t, strings.Contains(got, "[Usernames](/r/moul/toolbox/usernames)"))
uassert.True(t, strings.Contains(got, "Tags:"))
}
func TestRenderTagFilter(t *testing.T) {
kept := Render("?tag=identity")
uassert.True(t, strings.Contains(kept, "[Usernames](/r/moul/toolbox/usernames)"))
uassert.True(t, strings.Contains(kept, "Show all"))
empty := Render("?tag=nope")
uassert.True(t, strings.Contains(empty, "No tools yet."))
uassert.False(t, strings.Contains(empty, "[Usernames]"))
}
// TestTagLinkIsURLEscaped: a tag is an arbitrary string on Tool, and
// concatenating one into a query string unescaped turns "a&b" into two
// parameters and "a#b" into a fragment, so the link filters by something
// nobody asked for. Values copied from what QueryEscape actually emits.
func TestTagLinkIsURLEscaped(t *testing.T) {
var c tb.Catalog
uassert.NoError(t, c.Set(tb.Tool{
Slug: "weird",
Path: "gno.land/r/moul/toolbox/weird",
Title: "Weird",
Tags: []string{"a&b c"},
}))
got := tagLinks(&c, hubURL)
uassert.True(t, strings.Contains(got, "?tag=a%26b+c"))
uassert.False(t, strings.Contains(got, "?tag=a&b c"))
}
func TestTagLinksEmpty(t *testing.T) {
var c tb.Catalog
uassert.Equal(t, "", tagLinks(&c, hubURL))
}
func TestRenderTool(t *testing.T) {
got := Render("usernames")
uassert.True(t, strings.Contains(got, "[toolbox](/r/moul/toolbox)"))
uassert.True(t, strings.Contains(got, "## Usernames"))
uassert.True(t, strings.Contains(got, "`gno.land/r/moul/toolbox/usernames`"))
}
func TestRenderUnknown(t *testing.T) {
for _, path := range []string{"nope", "a/b", "usernames/extra"} {
got := Render(path)
uassert.True(t, strings.Contains(got, "# Not found"))
uassert.True(t, strings.Contains(got, "Back to the toolbox"))
}
}
// TestRenderNeverEmitsTwoBlankLines: gno collapses them in an Output block, so
// a Render that produces one can never be pinned by an example. Checked here
// rather than discovered later.
func TestRenderNeverEmitsTwoBlankLines(t *testing.T) {
for _, path := range []string{"", "?tag=identity", "usernames", "nope"} {
uassert.False(t, strings.Contains(Render(path), "\n\n\n"))
}
}