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 forms is a Google-Forms-shaped questionnaire realm: publish a form,
// collect responses on chain, read them back rendered — with gnoweb as the
// only UI.
//
// # How it works
//
// The realm renders each form with p/jeronimoalbi/mdform. gnoweb turns that
// markdown into a real HTML form whose submit builds a /vm.m_call to Submit,
// mapping every input to the Submit parameter of the same name. A respondent
// fills the form in a browser, signs with their wallet, and the answers land
// in realm state. No frontend, no backend, no indexer.
//
// # Slugs
//
// A form's ID is a slug chosen at creation — lowercase letters, digits and
// single hyphens, 3 to 48 characters, unique per realm. It is the URL
// segment: /r/<ns>/forms:valoper-questionnaire. Response IDs are sequential.
//
// # Field encoding
//
// Create takes four parallel, pipe-separated strings so it stays usable from
// gnokey and gnoweb without structured arguments:
//
//	labels:   "Name|Why gno.land?|Server type"
//	kinds:    "text|textarea|select"
//	required: "1|1|0"
//	options:  "||cloud,on-prem,data-center"
//
// Kinds are text, textarea, number and select. Options are comma-separated
// and only read for select fields. A form has at most MaxFields (8) fields;
// Submit accordingly takes eight answer slots, of which the form's field
// count are read and the rest must be empty. gnoweb passes "" for any
// parameter the form does not render an input for.
//
// # Who pays
//
// Respondents pay the storage deposit for their own answers, which is the
// spam resistance. Withdraw deletes a response and the chain refunds the
// deposit to the caller — which is why only the author may withdraw: a
// deletion by the owner would refund the owner with the respondent's coins.
//
// # What is public
//
// Everything. Answers, who gave them, and when are all readable by anyone
// from realm state and from the transactions themselves. This realm is for
// information that can be public. Sealed responses would need encryption
// on the respondent's side before the transaction exists, which gnoweb
// cannot do on a realm's behalf; that is a deliberate non-goal of v1.
//
// # Routes
//
//	/r/<ns>/forms                     index
//	/r/<ns>/forms:<id>                a form, fillable
//	/r/<ns>/forms:<id>/responses      responses, paginated
//	/r/<ns>/forms:<id>/responses.csv  responses as CSV in a code block
package forms

errors.gno

package forms

import "errors"

var (
	ErrFormNotFound     = errors.New("form not found")
	ErrBadSlug          = errors.New("slug must be 3-48 lowercase letters, digits and single hyphens, e.g. valoper-questionnaire")
	ErrSlugTaken        = errors.New("a form with this slug already exists")
	ErrFormClosed       = errors.New("form is closed")
	ErrFormOpen         = errors.New("form is already open")
	ErrNotOwner         = errors.New("caller is not the form owner")
	ErrNoFields         = errors.New("a form needs at least one field")
	ErrTooManyFields    = errors.New("a form can have at most 8 fields")
	ErrFieldSpecMismatch = errors.New("labels, kinds and required must describe the same number of fields")
	ErrBadFieldKind     = errors.New("field kind must be one of text, textarea, number, select")
	ErrSelectNoOptions  = errors.New("a select field needs at least one option")
	ErrEmptyLabel       = errors.New("field label cannot be empty")
	ErrPipeInField      = errors.New("field labels and options cannot contain |")
	ErrEmptyTitle       = errors.New("form title cannot be empty")
	ErrTitleTooLong     = errors.New("form title is too long")
	ErrDescriptionTooLong = errors.New("form description is too long")
	ErrBadDeadline      = errors.New("deadline must be a future chain height or 0")
	ErrDeadlinePassed   = errors.New("form deadline has passed")
	ErrAlreadyResponded = errors.New("this address has already responded to this form")
	ErrNoResponse       = errors.New("no response from this address to withdraw")
	ErrRequired         = errors.New("required field is empty")
	ErrNotANumber       = errors.New("field expects a number")
	ErrNotAnOption      = errors.New("value is not one of the select options")
	ErrAnswerTooLong    = errors.New("answer exceeds the field's maximum length")
	ErrTooManyAnswers   = errors.New("more answers than the form has fields")
	ErrNotUserCall      = errors.New("this function must be called by a user account")
)

forms.gno

package forms

import (
	"chain"
	"chain/runtime"
	"regexp"
	"strconv"
	"strings"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ownable/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/ufmt/v0"
)

var (
	forms      = avl.NewTree() // slug -> *Form
	nextRespID seqid.ID

	slugRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
)

// Create publishes a new form under slug, which becomes its ID and its URL
// segment (/r/<ns>/forms:<slug>). Slugs are unique per realm.
//
// Fields are described by four parallel, pipe-separated strings so the call
// stays usable from gnokey and gnoweb without structured arguments:
//
//	labels:   "Name|Why gno.land?|Server type"
//	kinds:    "text|textarea|select"
//	required: "1|1|0"
//	options:  "||cloud,on-prem,data-center"   (comma-separated; only select uses it)
//
// deadline is a chain height after which the form stops accepting responses,
// or 0 for none. onePerAddr limits each address to a single response.
func Create(cur realm, slug, title, description, labels, kinds, required, options string, onePerAddr bool, deadline int64) string {
	return create(cur, slug, title, description, labels, kinds, required, options, onePerAddr, deadline)
}

// CreateForm is Create for the browser: the index page renders it as a gnoweb
// form, one row per field, so nothing has to be typed into the wallet.
//
// Every parameter is a string because gnoweb submits "" for an empty or
// unchecked input, and "" is not a bool or an int64 as far as the VM is
// concerned. Checkboxes send "1" when ticked. Blank rows are skipped; a row
// with an empty kind is text. deadline "" means none.
func CreateForm(cur realm,
	slug, title, description string,
	l1, k1, r1, o1 string,
	l2, k2, r2, o2 string,
	l3, k3, r3, o3 string,
	l4, k4, r4, o4 string,
	l5, k5, r5, o5 string,
	l6, k6, r6, o6 string,
	l7, k7, r7, o7 string,
	l8, k8, r8, o8 string,
	onePerAddr, deadline string,
) string {
	rows := [][4]string{
		{l1, k1, r1, o1}, {l2, k2, r2, o2}, {l3, k3, r3, o3}, {l4, k4, r4, o4},
		{l5, k5, r5, o5}, {l6, k6, r6, o6}, {l7, k7, r7, o7}, {l8, k8, r8, o8},
	}

	var labels, kinds, required, options []string
	for _, row := range rows {
		label := strings.TrimSpace(row[0])
		if label == "" {
			continue
		}
		if strings.Contains(label, "|") || strings.Contains(row[3], "|") {
			panic(ErrPipeInField)
		}

		kind := strings.TrimSpace(row[1])
		if kind == "" {
			kind = string(KindText)
		}

		labels = append(labels, label)
		kinds = append(kinds, kind)
		required = append(required, boolFlag(row[2]))
		options = append(options, strings.TrimSpace(row[3]))
	}

	var dl int64
	if d := strings.TrimSpace(deadline); d != "" {
		n, err := strconv.Atoi(d)
		if err != nil {
			panic(ErrBadDeadline)
		}
		dl = int64(n)
	}

	return create(cur, slug, title, description,
		strings.Join(labels, "|"), strings.Join(kinds, "|"),
		strings.Join(required, "|"), strings.Join(options, "|"),
		boolFlag(onePerAddr) == "1", dl)
}

// boolFlag normalises a yes/no select value (or anything a human or gnokey
// might send) to the "1"/"0" the field-spec parser expects. Anything that is
// not affirmative is false, so an untouched control means "no".
func boolFlag(s string) string {
	switch strings.ToLower(strings.TrimSpace(s)) {
	case "1", "true", "on", "yes":
		return "1"
	}
	return "0"
}

func create(cur realm, slug, title, description, labels, kinds, required, options string, onePerAddr bool, deadline int64) string {
	caller := mustUserCaller(cur)

	slug = strings.TrimSpace(slug)
	if len(slug) < MinSlugLen || len(slug) > MaxSlugLen || !slugRe.MatchString(slug) {
		panic(ErrBadSlug)
	}
	if forms.Has(slug) {
		panic(ErrSlugTaken)
	}

	title = strings.TrimSpace(title)
	description = strings.TrimSpace(description)

	if title == "" {
		panic(ErrEmptyTitle)
	}
	if len(title) > MaxTitleLen {
		panic(ErrTitleTooLong)
	}
	if len(description) > MaxDescriptionLen {
		panic(ErrDescriptionTooLong)
	}

	height := runtime.ChainHeight()
	if deadline < 0 || (deadline > 0 && deadline <= height) {
		panic(ErrBadDeadline)
	}

	fields := parseFields(labels, kinds, required, options)

	f := &Form{
		ID:          slug,
		Title:       title,
		Description: description,
		Fields:      fields,
		OnePerAddr:  onePerAddr,
		Deadline:    deadline,
		CreatedAt:   height,
		owner:       ownable.NewWithAddress(caller),
		responses:   avl.NewTree(),
		byAddr:      avl.NewTree(),
	}

	forms.Set(slug, f)

	chain.Emit("FormCreated", "id", slug, "owner", caller.String(), "title", title)

	return slug
}

// Close stops a form from accepting responses. Owner only.
func Close(cur realm, id string) {
	f := mustGetForm(id)
	f.owner.AssertOwnedBy(mustUserCaller(cur))

	if f.Closed {
		panic(ErrFormClosed)
	}

	f.Closed = true

	chain.Emit("FormClosed", "id", id)
}

// Reopen lets a closed form accept responses again. Owner only. A form
// whose deadline has passed stays closed regardless.
func Reopen(cur realm, id string) {
	f := mustGetForm(id)
	f.owner.AssertOwnedBy(mustUserCaller(cur))

	if !f.Closed {
		panic(ErrFormOpen)
	}
	if f.Deadline > 0 && runtime.ChainHeight() >= f.Deadline {
		panic(ErrDeadlinePassed)
	}

	f.Closed = false

	chain.Emit("FormReopened", "id", id)
}

// TransferOwnership hands a form to another address. Owner only.
func TransferOwnership(cur realm, id string, to address) {
	f := mustGetForm(id)
	f.owner.AssertOwnedBy(mustUserCaller(cur))

	if err := f.owner.TransferOwnership(0, cur, to); err != nil {
		panic(err)
	}

	chain.Emit("FormTransferred", "id", id, "to", to.String())
}

// GetForm returns a form by ID.
func GetForm(id string) (*Form, bool) {
	raw := forms.Get(id)
	if raw == nil {
		return nil, false
	}

	return raw.(*Form), true
}

// ResponseCount returns the number of responses a form has, or 0 if the
// form does not exist.
func ResponseCount(id string) int {
	f, ok := GetForm(id)
	if !ok {
		return 0
	}

	return f.ResponseCount()
}

// FormCount returns how many forms exist.
func FormCount() int {
	return forms.Size()
}

func mustGetForm(id string) *Form {
	f, ok := GetForm(id)
	if !ok {
		panic(ErrFormNotFound)
	}

	return f
}

// mustUserCaller returns the address of the user account that made the
// call. Only user accounts may create forms or respond: a realm submitting
// on someone's behalf would be attributed to the realm, which is never what
// a form wants.
func mustUserCaller(cur realm) address {
	if !cur.IsCurrent() {
		panic("realm value is not the caller's live cur")
	}

	prev := cur.Previous()
	if !prev.IsUser() {
		panic(ErrNotUserCall)
	}

	return prev.Address()
}

// parseFields decodes the four parallel field-spec strings.
func parseFields(labels, kinds, required, options string) []Field {
	labelList := splitFields(labels)
	kindList := splitFields(kinds)
	reqList := splitFields(required)
	optList := splitFields(options)

	n := len(labelList)
	if n == 0 || (n == 1 && labelList[0] == "") {
		panic(ErrNoFields)
	}
	if n > MaxFields {
		panic(ErrTooManyFields)
	}
	if len(kindList) != n || len(reqList) != n {
		panic(ErrFieldSpecMismatch)
	}
	// options may be omitted entirely when no field is a select.
	if len(optList) != n && !(len(optList) == 1 && optList[0] == "") {
		panic(ErrFieldSpecMismatch)
	}

	fields := make([]Field, 0, n)
	for i := 0; i < n; i++ {
		label := strings.TrimSpace(labelList[i])
		if label == "" {
			panic(ErrEmptyLabel)
		}
		if len(label) > MaxLabelLen {
			panic(ufmt.Errorf("field %d: label is too long", i+1))
		}

		kind := FieldKind(strings.TrimSpace(kindList[i]))
		switch kind {
		case KindText, KindTextarea, KindNumber, KindSelect:
		default:
			panic(ErrBadFieldKind)
		}

		field := Field{
			Label:    label,
			Kind:     kind,
			Required: strings.TrimSpace(reqList[i]) == "1",
		}

		if kind == KindSelect {
			raw := ""
			if len(optList) == n {
				raw = optList[i]
			}
			for _, o := range strings.Split(raw, ",") {
				o = strings.TrimSpace(o)
				if o == "" {
					continue
				}
				if len(o) > MaxOptionLen {
					panic(ufmt.Errorf("field %d: option is too long", i+1))
				}
				field.Options = append(field.Options, o)
			}
			if len(field.Options) == 0 {
				panic(ErrSelectNoOptions)
			}
		}

		fields = append(fields, field)
	}

	return fields
}

func splitFields(s string) []string {
	return strings.Split(s, "|")
}

gnomod.toml

module = "gno.land/r/g1eyr3hfdcup4rr5xlcd63vc5t64a03u9kecx2v0/forms"
gno = "0.9"

[addpkg]
  creator = "g1eyr3hfdcup4rr5xlcd63vc5t64a03u9kecx2v0"
  height = 108503
  max_deposit = "15000000ugnot"

render.gno

package forms

import (
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"

	"gno.land/p/jeronimoalbi/mdform/v0"
	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/mdtable/v0"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/avl/pager/v0"
	"gno.land/p/nt/mux/v0"
	"gno.land/p/nt/ufmt/v0"
)

const (
	formsPerPage     = 20
	responsesPerPage = 25
)

var router = mux.NewRouter()

func init() {
	router.HandleFunc("", renderIndex)
	router.HandleFunc("{id}", renderForm)
	router.HandleFunc("{id}/responses", renderResponses)
	router.HandleFunc("{id}/responses.csv", renderCSV)
}

// Render routes:
//
//	/r/<ns>/forms                     index of forms
//	/r/<ns>/forms:<id>                a form, fillable in gnoweb
//	/r/<ns>/forms:<id>/responses      its responses, paginated
//	/r/<ns>/forms:<id>/responses.csv  its responses as CSV
func Render(path string) string {
	return router.Render(path)
}

func renderIndex(res *mux.ResponseWriter, req *mux.Request) {
	var b strings.Builder

	b.WriteString(md.H1("Forms"))
	b.WriteString("Publish a form, collect responses on chain, read them back here. ")
	b.WriteString("Respondents fill it in on this page and pay their own storage deposit; ")
	b.WriteString("withdrawing a response refunds it.\n\n")

	if forms.Size() == 0 {
		b.WriteString("_No forms yet._\n\n")
		b.WriteString(renderCreateHelp())
		res.Write(b.String())
		return
	}

	page := pager.NewPager(forms, formsPerPage, true).MustGetPageByPath(req.RawPath)
	height := runtime.ChainHeight()

	table := &mdtable.Table{Headers: []string{"Form", "Status", "Responses", "Fields", "Owner"}}
	for _, item := range page.Items {
		f := item.Value.(*Form)
		table.Append([]string{
			md.Link(f.Title, formURL(f.ID)),
			statusLabel(f, height),
			strconv.Itoa(f.ResponseCount()),
			strconv.Itoa(len(f.Fields)),
			shortAddr(f.Owner()),
		})
	}

	b.WriteString(table.String())
	b.WriteString("\n")
	b.WriteString(page.Picker(req.RawPath))
	b.WriteString("\n\n")
	b.WriteString(renderCreateHelp())

	res.Write(b.String())
}

func renderForm(res *mux.ResponseWriter, req *mux.Request) {
	f, ok := GetForm(req.GetVar("id"))
	if !ok {
		res.Write("Form not found.")
		return
	}

	height := runtime.ChainHeight()
	id := f.ID

	var b strings.Builder

	b.WriteString(md.H1(f.Title))
	if f.Description != "" {
		b.WriteString(f.Description + "\n\n")
	}

	b.WriteString(ufmt.Sprintf("**Status:** %s · **Responses:** %d · **Owner:** `%s`",
		statusLabel(f, height), f.ResponseCount(), f.Owner()))
	if f.Deadline > 0 {
		b.WriteString(ufmt.Sprintf(" · **Closes at height:** %d", f.Deadline))
	}
	if f.OnePerAddr {
		b.WriteString(" · one response per address")
	}
	b.WriteString("\n\n")

	b.WriteString(md.Link("View responses", responsesURL(id)) + " · " +
		md.Link("CSV", csvURL(id)) + "\n\n")

	if f.IsOpen(height) {
		b.WriteString(md.H2("Respond"))
		b.WriteString(renderMDForm(f))
	} else {
		b.WriteString("_This form is not accepting responses._\n\n")
	}

	b.WriteString(md.H3("Owner actions"))
	if f.Closed {
		b.WriteString(md.Link("Reopen", txlink.Call("Reopen", "id", id)))
	} else {
		b.WriteString(md.Link("Close", txlink.Call("Close", "id", id)))
	}
	b.WriteString(" · " + md.Link("Withdraw my response", txlink.Call("Withdraw", "id", id)) + "\n")

	res.Write(b.String())
}

// renderMDForm draws the fillable form. gnoweb turns it into an HTML form
// that calls Submit; each input is named after the Submit parameter it fills.
func renderMDForm(f *Form) string {
	form := mdform.New("exec", "Submit")

	form.Input("id",
		"value", f.ID,
		"readonly", "true",
		"description", "Form ID",
	)

	for i, field := range f.Fields {
		name := "a" + strconv.Itoa(i+1)
		label := field.Label
		if field.Required {
			label += " *"
		}

		switch field.Kind {
		case KindTextarea:
			attrs := []string{"placeholder", label, "rows", "4"}
			if field.Required {
				attrs = append(attrs, "required", "true")
			}
			form.Textarea(name, attrs...)

		case KindSelect:
			for j, opt := range field.Options {
				attrs := []string{"description", label}
				if j == 0 && field.Required {
					attrs = append(attrs, "required", "true")
				}
				form.Select(name, opt, attrs...)
			}

		case KindNumber:
			attrs := []string{"type", "number", "placeholder", label, "description", label}
			if field.Required {
				attrs = append(attrs, "required", "true")
			}
			form.Input(name, attrs...)

		default:
			attrs := []string{"placeholder", label, "description", label}
			if field.Required {
				attrs = append(attrs, "required", "true")
			}
			form.Input(name, attrs...)
		}
	}

	return form.String() + "\n"
}

func renderResponses(res *mux.ResponseWriter, req *mux.Request) {
	f, ok := GetForm(req.GetVar("id"))
	if !ok {
		res.Write("Form not found.")
		return
	}

	var b strings.Builder

	b.WriteString(md.H1(f.Title + " — responses"))
	b.WriteString(ufmt.Sprintf("%d response(s). ", f.ResponseCount()))
	b.WriteString(md.Link("Back to form", formURL(f.ID)) + " · " +
		md.Link("CSV", csvURL(f.ID)) + "\n\n")

	if f.ResponseCount() == 0 {
		b.WriteString("_No responses yet._\n")
		res.Write(b.String())
		return
	}

	headers := []string{"#", "From", "Height"}
	for _, field := range f.Fields {
		headers = append(headers, field.Label)
	}
	table := &mdtable.Table{Headers: headers}

	page := pager.NewPager(f.responses, responsesPerPage, false).MustGetPageByPath(req.RawPath)
	for _, item := range page.Items {
		r := item.Value.(*Response)
		row := []string{r.ID.String(), shortAddr(r.Author), strconv.Itoa(int(r.Height))}
		for _, a := range r.Answers {
			row = append(row, cell(a))
		}
		table.Append(row)
	}

	b.WriteString(table.String())
	b.WriteString("\n")
	b.WriteString(page.Picker(req.RawPath))
	b.WriteString("\n")

	res.Write(b.String())
}

// renderCSV emits every response as CSV inside a code block, so a reviewer
// can copy it straight into a spreadsheet.
func renderCSV(res *mux.ResponseWriter, req *mux.Request) {
	f, ok := GetForm(req.GetVar("id"))
	if !ok {
		res.Write("Form not found.")
		return
	}

	var b strings.Builder

	header := []string{"response_id", "author", "height"}
	for _, field := range f.Fields {
		header = append(header, field.Label)
	}
	b.WriteString(csvRow(header))

	f.responses.Iterate("", "", func(_ string, value any) bool {
		r := value.(*Response)
		row := []string{r.ID.String(), r.Author.String(), strconv.Itoa(int(r.Height))}
		row = append(row, r.Answers...)
		b.WriteString(csvRow(row))
		return false
	})

	res.Write(md.LanguageCodeBlock("csv", b.String()))
}

// renderCreateHelp draws the form that creates forms. gnoweb submits it as a
// CreateForm call with every input mapped to the parameter of the same name.
func renderCreateHelp() string {
	form := mdform.New("exec", "CreateForm")

	form.Input("slug",
		"placeholder", "valoper-questionnaire",
		"description", "URL name — lowercase letters, digits, hyphens",
		"required", "true",
	)
	form.Input("title",
		"placeholder", "Valoper questionnaire",
		"description", "Title",
		"required", "true",
	)
	form.Textarea("description",
		"placeholder", "What this form is for (optional)",
		"rows", "3",
	)

	for i := 1; i <= MaxFields; i++ {
		n := strconv.Itoa(i)
		form.Input("l"+n,
			"placeholder", "Field "+n+" label (leave blank to skip)",
			"description", "Field "+n,
		)
		form.Select("k"+n, string(KindText), "description", "Field "+n+" type", "selected", "true")
		form.Select("k"+n, string(KindTextarea))
		form.Select("k"+n, string(KindNumber))
		form.Select("k"+n, string(KindSelect))
		// A two-option select, not a checkbox: gnoweb sends an untouched
		// checkbox's value attribute as if it were ticked, so every field came
		// out required. Untouched selects correctly send their default.
		form.Select("r"+n, "no", "description", "Field "+n+" required?", "selected", "true")
		form.Select("r"+n, "yes")
		form.Input("o"+n,
			"placeholder", "Options, comma-separated (select fields only)",
			"description", "Field "+n+" options",
		)
	}

	form.Select("onePerAddr", "no", "description", "One response per address?", "selected", "true")
	form.Select("onePerAddr", "yes")
	form.Input("deadline",
		"type", "number",
		"placeholder", "0",
		"description", "Close at chain height (0 = never)",
	)

	return md.H2("Create a form") +
		"Up to " + strconv.Itoa(MaxFields) + " fields. Blank rows are skipped. " +
		"Submitting opens your wallet with the call already filled in.\n\n" +
		form.String() + "\n" +
		"From a terminal, " + md.InlineCode("Create") + " takes the same thing as pipe-separated field specs — see the realm source.\n"
}

// --- helpers ---

func statusLabel(f *Form, height int64) string {
	if f.Closed {
		return "closed"
	}
	if f.Deadline > 0 && height >= f.Deadline {
		return "expired"
	}

	return "open"
}

func formURL(id string) string      { return realmURL() + ":" + id }
func responsesURL(id string) string { return realmURL() + ":" + id + "/responses" }
func csvURL(id string) string       { return realmURL() + ":" + id + "/responses.csv" }

var realmPath = unsafe.CurrentRealm().PkgPath()

// realmURL is this realm's path as gnoweb addresses it, derived from where
// it is deployed rather than hardcoded.
func realmURL() string {
	return strings.TrimPrefix(realmPath, "gno.land")
}

func shortAddr(a address) string {
	s := a.String()
	if len(s) <= 14 {
		return s
	}

	return s[:8] + "…" + s[len(s)-4:]
}

// cell makes an answer safe inside a markdown table cell.
func cell(s string) string {
	s = strings.ReplaceAll(s, "|", "\\|")
	s = strings.ReplaceAll(s, "\n", " ")

	return s
}

// csvRow quotes every field, doubling embedded quotes, per RFC 4180.
func csvRow(fields []string) string {
	out := make([]string, len(fields))
	for i, f := range fields {
		out[i] = `"` + strings.ReplaceAll(f, `"`, `""`) + `"`
	}

	return strings.Join(out, ",") + "\n"
}

submit.gno

package forms

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"
)

// Submit records a response to a form. Answers a1..a8 align with the form's
// fields in order; slots beyond the form's field count must be empty.
//
// gnoweb builds this call from the rendered form: each input is named after
// the parameter it fills, and parameters with no input arrive as "".
//
// The respondent pays the storage deposit for their own answers, and gets it
// back on Withdraw.
func Submit(cur realm, id string, a1, a2, a3, a4, a5, a6, a7, a8 string) {
	author := mustUserCaller(cur)
	f := mustGetForm(id)
	height := runtime.ChainHeight()

	if !f.IsOpen(height) {
		if f.Deadline > 0 && height >= f.Deadline {
			panic(ErrDeadlinePassed)
		}
		panic(ErrFormClosed)
	}

	if f.OnePerAddr && f.byAddr.Has(author.String()) {
		panic(ErrAlreadyResponded)
	}

	answers := validateAnswers(f, []string{a1, a2, a3, a4, a5, a6, a7, a8})

	rid := nextRespID.Next()
	r := &Response{
		ID:      rid,
		Form:    f.ID,
		Author:  author,
		Height:  height,
		Answers: answers,
	}

	f.responses.Set(rid.String(), r)
	f.byAddr.Set(author.String(), rid.String())

	chain.Emit("ResponseSubmitted", "form", id, "response", rid.String(), "author", author.String())
}

// Withdraw deletes the caller's response to a form. The storage deposit the
// answers were holding is refunded to the caller by the chain.
//
// Only the author can withdraw. Owners cannot delete responses: the refund
// goes to whoever deletes, which would hand the owner the respondent's
// deposit.
func Withdraw(cur realm, id string) {
	author := mustUserCaller(cur)
	f := mustGetForm(id)

	raw := f.byAddr.Get(author.String())
	if raw == nil {
		panic(ErrNoResponse)
	}
	rid := raw.(string)

	f.responses.Remove(rid)
	f.byAddr.Remove(author.String())

	chain.Emit("ResponseWithdrawn", "form", id, "response", rid, "author", author.String())
}

// validateAnswers checks every answer against its field and returns the
// trimmed answers, exactly len(f.Fields) long. Nothing is written before it
// returns, so a rejected submission leaves no trace.
func validateAnswers(f *Form, raw []string) []string {
	n := len(f.Fields)

	for i := n; i < len(raw); i++ {
		if strings.TrimSpace(raw[i]) != "" {
			panic(ErrTooManyAnswers)
		}
	}

	answers := make([]string, n)
	for i, field := range f.Fields {
		a := strings.TrimSpace(raw[i])

		if a == "" {
			if field.Required {
				panic(fieldErr(i, ErrRequired))
			}
			answers[i] = ""
			continue
		}

		if len(a) > field.MaxLen() {
			panic(fieldErr(i, ErrAnswerTooLong))
		}

		switch field.Kind {
		case KindNumber:
			if _, err := strconv.ParseFloat(a, 64); err != nil {
				panic(fieldErr(i, ErrNotANumber))
			}
		case KindSelect:
			if !contains(field.Options, a) {
				panic(fieldErr(i, ErrNotAnOption))
			}
		}

		answers[i] = a
	}

	return answers
}

func fieldErr(i int, err error) string {
	return "field " + strconv.Itoa(i+1) + ": " + err.Error()
}

func contains(list []string, s string) bool {
	for _, v := range list {
		if v == s {
			return true
		}
	}

	return false
}

types.gno

package forms

import (
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ownable/v0"
	"gno.land/p/nt/seqid/v0"
)

// FieldKind is the input type a field renders as, and the validation it gets.
type FieldKind string

const (
	KindText     FieldKind = "text"
	KindTextarea FieldKind = "textarea"
	KindNumber   FieldKind = "number"
	KindSelect   FieldKind = "select"
)

// Limits. Answers are stored on chain and the respondent pays the storage
// deposit for them, so the caps exist to keep that cost predictable rather
// than to save the realm anything.
const (
	MaxFields         = 8
	MaxTitleLen       = 120
	MaxDescriptionLen = 2048
	MaxLabelLen       = 120
	MaxOptionLen      = 120
	MaxTextLen        = 256
	MaxTextareaLen    = 2048
	MaxNumberLen      = 64
)

// Field is one question on a form.
type Field struct {
	Label    string
	Kind     FieldKind
	Required bool
	Options  []string // select only
}

// MaxLen is the longest answer the field accepts.
func (f Field) MaxLen() int {
	switch f.Kind {
	case KindTextarea:
		return MaxTextareaLen
	case KindNumber:
		return MaxNumberLen
	case KindSelect:
		return MaxOptionLen
	default:
		return MaxTextLen
	}
}

// Slug rules. A slug is the form's ID and its URL segment, chosen at creation:
// lowercase letters and digits, single hyphens between words, 3–48 characters.
const (
	MinSlugLen = 3
	MaxSlugLen = 48
)

// Form is a published questionnaire and its responses.
type Form struct {
	ID          string // the slug
	Title       string
	Description string
	Fields      []Field
	OnePerAddr  bool
	Deadline    int64 // chain height; 0 means none
	Closed      bool
	CreatedAt   int64

	owner     *ownable.Ownable
	responses *avl.Tree // response id -> *Response
	byAddr    *avl.Tree // author address -> response id
}

// Owner returns the form owner's address.
func (f *Form) Owner() address {
	return f.owner.Owner()
}

// ResponseCount returns how many responses the form currently holds.
func (f *Form) ResponseCount() int {
	return f.responses.Size()
}

// IsOpen reports whether the form accepts submissions at the given height.
func (f *Form) IsOpen(height int64) bool {
	if f.Closed {
		return false
	}

	return f.Deadline == 0 || height < f.Deadline
}

// Response is one submission to a form. Answers align with Form.Fields.
type Response struct {
	ID      seqid.ID
	Form    string // the form slug
	Author  address
	Height  int64
	Answers []string
}