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

gnomod.toml

module = "gno.land/r/nym-alexiscolin000/gnosplit/v1"
gno = "0.9"

[addpkg]
  creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq"
  height = 275540
  max_deposit = "50000000ugnot"

gnosplit.gno

// Package gnosplit shares a group's expenses, like Tricount: who paid what,
// who owes whom, and the fewest transfers that settle everything.
//
// A group has members, each a name with or without a wallet. Members with a
// wallet linked are the group's editors: they record expenses, incomes and
// transfers, and get a gnotif notification when one concerns them. Members
// without one are just names: a friend with no wallet still has a balance.
//
// Amounts are cents of the group's currency, a label such as "€" or "CHF":
// no coin moves here, a transfer records a payment made elsewhere. Every
// balance is kept up to date on each write, so reading a group never adds
// up its history.
package gnosplit

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

	"gno.land/p/nym-alexiscolin000/gnosplit/ledger/v0"
	"gno.land/p/nt/avl/v0"
)

// Limits keep every page and every write small.
const (
	maxMembers  = 30
	maxEntries  = 5000 // per group
	maxName     = 24   // a member's name, in bytes
	maxGroup    = 40   // a group's name
	maxTitle    = 60   // an entry's title
	maxCurrency = 8
	remindEvery = 12 * 60 * 60 // seconds between two reminders to one member
)

// Kind is what an entry records.
type Kind uint8

const (
	KindExpense  Kind = iota // Payer paid Total for Who
	KindIncome               // Payer received Total that belongs to Who
	KindTransfer             // Payer paid Total to Who[0]
)

// Member is one person in a group. Bal is what they paid minus what they owe,
// in cents: > 0 the group owes them, < 0 they owe the group.
type Member struct {
	Name   string
	Addr   address // "" while no wallet is linked
	Bal    int64
	Paid   int64 // total of the expenses they paid, net of incomes received
	Share  int64 // total of their shares of expenses, net of incomes
	Nudged int64 // when they were last reminded, unix seconds
}

// Entry is one expense, income or transfer. Owe[i] is the part of Who[i]; the
// parts sum to Total. An income stores Total and Owe as negative amounts, so
// one rule applies every kind: Payer gains Total, each of Who loses its part.
type Entry struct {
	ID    int
	Kind  Kind
	Title string
	Cat   int
	Payer int
	Total int64
	Note  string // the foreign amount, "" if none
	Who   []int
	Owe   []int64
	At    int64
	By    address
}

// Group is one shared account.
type Group struct {
	ID       int
	Name     string
	Currency string
	Members  []Member
	Entries  avl.Tree // key(ID) → *Entry
	Next     int      // the next entry's ID
	Spent    int64    // expenses minus incomes, for the header
	ByCat    []int64  // expenses per category, incomes left out
	Created  int64
	Moved    bool // taken over by the successor realm: read-only here
}

var (
	groups avl.Tree // key(ID) → *Group
	byAddr avl.Tree // addr + "/" + key(ID) → true, the groups a wallet belongs to
	nextID = 1
)

// self is this realm's pkgpath and hub its gnoweb path, read at init while
// this realm is current: every link follows from them.
var (
	self = unsafe.CurrentRealm().PkgPath()
	hub  = strings.TrimPrefix(self, "gno.land")
)

func init(cur realm) {
	setUp(unsafe.OriginCaller(), runtime.ChainID())
	declareTriggers(cur)
}

// CreateGroup opens a group named name, counting in currency, with the
// caller as member you (wallet linked) and others, comma-separated names,
// without wallets. It returns the group's ID.
func CreateGroup(cur realm, name, currency, you, others string) int {
	caller := cur.Previous().Address()
	name, currency = strings.TrimSpace(name), strings.TrimSpace(currency)
	if !validText(name, maxGroup) {
		panic("gnosplit: a group name is 1 to 40 bytes on one line")
	}
	if !validText(currency, maxCurrency) || strings.ContainsAny(currency, " ,<>[]()|*_`\\&\"'") {
		panic("gnosplit: a currency is 1 to 8 bytes with no space, like € or CHF")
	}
	g := &Group{ID: nextID, Name: name, Currency: currency, Created: time.Now().Unix(), ByCat: make([]int64, len(categories))}
	g.addMember(you, caller)
	for _, n := range splitList(others) {
		g.addMember(n, "")
	}
	nextID++
	groups.Set(key(g.ID), g)
	chain.Emit(EventGroupCreated, "group", itoa(g.ID), "by", caller.String())
	return g.ID
}

// AddMember adds name to the group, with a wallet if addr is set: that member
// becomes an editor and is told by gnotif.
func AddMember(cur realm, group, name, addr string) {
	g, by := editable(cur, group)
	a := parseAddr(addr)
	i := g.addMember(name, a)
	chain.Emit(EventMemberAdded, "group", itoa(g.ID), "member", g.Members[i].Name)
	if a != "" {
		notifyJoined(g, a, g.Members[by].Name)
	}
}

// LinkMember links a wallet to a member who has none yet, making them an
// editor. A linked wallet is never replaced, so no editor can take over
// another's place.
func LinkMember(cur realm, group, name, addr string) {
	g, by := editable(cur, group)
	i := g.member(name)
	if g.Members[i].Addr != "" {
		panic("gnosplit: " + g.Members[i].Name + " already has a wallet")
	}
	a := parseAddr(addr)
	if a == "" {
		panic("gnosplit: an address is required")
	}
	g.link(i, a)
	chain.Emit(EventMemberLinked, "group", itoa(g.ID), "member", g.Members[i].Name, "addr", a.String())
	notifyJoined(g, a, g.Members[by].Name)
}

// AddExpense records that paidBy paid amount for forWhom (comma-separated
// names, "" for everyone), split equally. amount is "42.50", or a foreign
// amount with its rate, "50 USD x0.92". It returns the entry's ID.
func AddExpense(cur realm, group, title, amount, paidBy, forWhom, category string) int {
	g, by := editable(cur, group)
	total, note := mustAmount(amount)
	who := g.members(forWhom)
	return g.record(by, KindExpense, title, category, g.member(paidBy), total, note, who, ledger.Equal(total, len(who)))
}

// AddByShares records an expense split by shares: shares is "Alice:2, Bob:1",
// so Alice owes two thirds.
func AddByShares(cur realm, group, title, amount, paidBy, shares, category string) int {
	g, by := editable(cur, group)
	total, note := mustAmount(amount)
	who, w := g.pairs(shares, func(s string) (int64, bool) {
		n, err := strconv.Atoi(s)
		return int64(n), err == nil && n > 0 && n <= 1000
	}, "a share is a whole number from 1 to 1000")
	return g.record(by, KindExpense, title, category, g.member(paidBy), total, note, who, ledger.Weighted(total, w))
}

// AddByAmounts records an expense split by exact amounts: amounts is
// "Alice:12.50, Bob:7.50", and the expense is their sum.
func AddByAmounts(cur realm, group, title, paidBy, amounts, category string) int {
	g, by := editable(cur, group)
	who, owe := g.pairs(amounts, ledger.ParseCents, "an amount is like 12.50")
	var total int64
	for _, o := range owe {
		total += o
	}
	if total > ledger.MaxCents {
		panic("gnosplit: the amounts add up to too much")
	}
	return g.record(by, KindExpense, title, category, g.member(paidBy), total, "", who, owe)
}

// AddIncome records money receivedBy got on behalf of forWhom (a refund, a
// deposit returned), split equally: it lowers what each of them paid.
func AddIncome(cur realm, group, title, amount, receivedBy, forWhom string) int {
	g, by := editable(cur, group)
	total, note := mustAmount(amount)
	who := g.members(forWhom)
	return g.record(by, KindIncome, title, "", g.member(receivedBy), -total, note, who, ledger.Equal(-total, len(who)))
}

// AddTransfer records that from paid amount to to, outside the chain.
func AddTransfer(cur realm, group, from, to, amount string) int {
	g, by := editable(cur, group)
	total, note := mustAmount(amount)
	f, t := g.member(from), g.member(to)
	if f == t {
		panic("gnosplit: a transfer goes to someone else")
	}
	title := g.Members[f].Name + " → " + g.Members[t].Name
	return g.record(by, KindTransfer, title, "", f, total, note, []int{t}, []int64{total})
}

// Delete removes an entry and undoes its effect on every balance.
func Delete(cur realm, group, entry string) {
	g, _ := editable(cur, group)
	id, err := strconv.Atoi(strings.TrimSpace(entry))
	if err != nil {
		panic("gnosplit: no entry " + entry)
	}
	v, ok := g.Entries.Remove(key(id))
	if !ok {
		panic("gnosplit: no entry " + entry)
	}
	g.apply(v.(*Entry), -1)
	chain.Emit(EventEntryDeleted, "group", itoa(g.ID), "entry", itoa(id), "by", cur.Previous().Address().String())
}

// Remind sends member, who owes the group, a gnotif reminder: at most one
// every 12 hours, and only to a member with a wallet.
func Remind(cur realm, group, member string) {
	g, by := editable(cur, group)
	i := g.member(member)
	m := &g.Members[i]
	now := time.Now().Unix()
	switch {
	case m.Bal >= 0:
		panic("gnosplit: " + m.Name + " owes nothing")
	case m.Addr == "":
		panic("gnosplit: " + m.Name + " has no wallet to remind")
	case i == by:
		panic("gnosplit: you cannot remind yourself")
	case now-m.Nudged < remindEvery:
		panic("gnosplit: " + m.Name + " was reminded less than 12 hours ago")
	}
	m.Nudged = now
	notifyReminder(g, m, g.Members[by].Name)
}

// record validates and stores an entry, then applies it to the balances.
func (g *Group) record(by int, kind Kind, title, category string, payer int, total int64, note string, who []int, owe []int64) int {
	title = strings.TrimSpace(title)
	if !validText(title, maxTitle) {
		panic("gnosplit: a title is 1 to 60 bytes on one line")
	}
	if g.Entries.Size() >= maxEntries {
		panic("gnosplit: this group is full (5000 entries)")
	}
	e := &Entry{
		ID: g.Next, Kind: kind, Title: title, Cat: categoryOf(category), Payer: payer,
		Total: total, Note: note, Who: who, Owe: owe,
		At: time.Now().Unix(), By: g.Members[by].Addr,
	}
	g.Next++
	g.Entries.Set(key(e.ID), e)
	g.apply(e, 1)
	chain.Emit(EventEntryAdded, "group", itoa(g.ID), "entry", itoa(e.ID), "by", e.By.String())
	notifyEntry(g, e, by)
	return e.ID
}

// apply adds an entry to the balances (sign 1) or takes it back out (-1).
func (g *Group) apply(e *Entry, sign int64) {
	g.Members[e.Payer].Bal += sign * e.Total
	for i, m := range e.Who {
		g.Members[m].Bal -= sign * e.Owe[i]
	}
	if e.Kind == KindTransfer {
		return
	}
	g.Spent += sign * e.Total
	if e.Kind == KindExpense {
		g.ByCat[e.Cat] += sign * e.Total
	}
	g.Members[e.Payer].Paid += sign * e.Total
	for i, m := range e.Who {
		g.Members[m].Share += sign * e.Owe[i]
	}
}

// addMember appends a member and returns its index.
func (g *Group) addMember(name string, a address) int {
	name = strings.TrimSpace(name)
	if !validName(name) {
		panic("gnosplit: a name is 1 to 24 bytes, without , : ; or =")
	}
	if g.find(name) >= 0 {
		panic("gnosplit: there is already a " + name)
	}
	if len(g.Members) >= maxMembers {
		panic("gnosplit: a group has at most 30 members")
	}
	g.Members = append(g.Members, Member{Name: name})
	i := len(g.Members) - 1
	if a != "" {
		g.link(i, a)
	}
	return i
}

func (g *Group) link(i int, a address) {
	if g.editor(a) >= 0 {
		panic("gnosplit: this wallet is already in the group")
	}
	g.Members[i].Addr = a
	byAddr.Set(a.String()+"/"+key(g.ID), true)
}

// find is the index of the member called name, any case, or -1.
func (g *Group) find(name string) int {
	name = strings.ToLower(strings.TrimSpace(name))
	for i, m := range g.Members {
		if strings.ToLower(m.Name) == name {
			return i
		}
	}
	return -1
}

func (g *Group) member(name string) int {
	i := g.find(name)
	if i < 0 {
		panic("gnosplit: no member called " + strings.TrimSpace(name))
	}
	return i
}

// members reads a comma-separated list of names, "" for everyone.
func (g *Group) members(list string) []int {
	names := splitList(list)
	if len(names) == 0 {
		all := make([]int, len(g.Members))
		for i := range all {
			all[i] = i
		}
		return all
	}
	var out []int
	seen := make([]bool, len(g.Members))
	for _, n := range names {
		i := g.member(n)
		if seen[i] {
			panic("gnosplit: " + g.Members[i].Name + " is listed twice")
		}
		seen[i] = true
		out = append(out, i)
	}
	return out
}

// pairs reads "Name:value, Name:value" with parse checking each value.
func (g *Group) pairs(list string, parse func(string) (int64, bool), hint string) ([]int, []int64) {
	var who []int
	var vals []int64
	seen := make([]bool, len(g.Members))
	for _, p := range splitList(list) {
		name, val, ok := strings.Cut(p, ":")
		if !ok {
			panic("gnosplit: write each one as Name:value, like Alice:2")
		}
		i := g.member(name)
		v, ok := parse(strings.TrimSpace(val))
		if !ok {
			panic("gnosplit: " + hint)
		}
		if seen[i] {
			panic("gnosplit: " + g.Members[i].Name + " is listed twice")
		}
		seen[i] = true
		who, vals = append(who, i), append(vals, v)
	}
	if len(who) == 0 {
		panic("gnosplit: name at least one member")
	}
	return who, vals
}

// editor is the index of the member whose wallet is a, or -1.
func (g *Group) editor(a address) int {
	for i, m := range g.Members {
		if m.Addr == a {
			return i
		}
	}
	return -1
}

// editable is the one write check: the group exists, is still kept here, and
// the immediate caller is one of its members with a wallet.
func editable(cur realm, group string) (*Group, int) {
	g := mustGroup(group)
	if g.Moved {
		panic("gnosplit: this group moved to " + successor)
	}
	by := g.editor(cur.Previous().Address())
	if by < 0 {
		panic("gnosplit: only a member with a linked wallet can change this group")
	}
	return g, by
}

func getGroup(group string) *Group {
	id, err := strconv.Atoi(strings.TrimSpace(group))
	if err != nil {
		return nil
	}
	v := groups.Get(key(id))
	if v == nil {
		return nil
	}
	return v.(*Group)
}

func mustGroup(group string) *Group {
	g := getGroup(group)
	if g == nil {
		panic("gnosplit: no group " + group)
	}
	return g
}

func mustAmount(s string) (int64, string) {
	total, note, ok := ledger.ParseAmount(s)
	if !ok {
		panic("gnosplit: an amount is like 42.50, or 50 USD x0.92 for a foreign one")
	}
	return total, note
}

func parseAddr(s string) address {
	s = strings.TrimSpace(s)
	if s == "" {
		return ""
	}
	a := address(s)
	if !a.IsValid() {
		panic("gnosplit: not an address: " + s)
	}
	return a
}

// splitList cuts a comma-separated list, dropping blanks.
func splitList(s string) []string {
	var out []string
	for _, p := range strings.Split(s, ",") {
		if p = strings.TrimSpace(p); p != "" {
			out = append(out, p)
		}
	}
	return out
}

// validText is 1 to max bytes with no control character.
func validText(s string, max int) bool {
	if len(s) == 0 || len(s) > max {
		return false
	}
	for i := 0; i < len(s); i++ {
		if s[i] < 0x20 || s[i] == 0x7f {
			return false
		}
	}
	return true
}

// validName also refuses the separators the forms use.
func validName(s string) bool {
	return validText(s, maxName) && !strings.ContainsAny(s, ",:;=")
}

// key pads an ID so the trees keep numeric order.
func key(id int) string {
	s := strconv.Itoa(id)
	return strings.Repeat("0", 10-len(s)) + s
}

func itoa(n int) string { return strconv.Itoa(n) }

notify.gno

package gnosplit

import (
	"chain"

	"gno.land/p/nym-alexiscolin000/gnosplit/ledger/v0"
	gnotif "gno.land/r/nym-gfanton001/gnotif/v0"
)

// Events. The first ones say what changed, for indexers and apps. The notify
// ones each carry "to", a wallet: gnotif turns them into a browser
// notification for whoever opted in with that address. A notify event goes
// only to members with a wallet, never to the member who acted.
const (
	EventGroupCreated = "GroupCreated"
	EventMemberAdded  = "MemberAdded"
	EventMemberLinked = "MemberLinked"
	EventEntryAdded   = "EntryAdded"
	EventEntryDeleted = "EntryDeleted"
	EventGroupMoved   = "GroupMoved"
	EventOwnerOffered = "OwnerOffered"
	EventOwnerChanged = "OwnerChanged"
	EventSuccessorSet = "SuccessorSet"

	NotifyExpense  = "Expense"  // to, group, gname, by, title, share
	NotifyIncome   = "Income"   // to, group, gname, by, title, share
	NotifyTransfer = "Transfer" // to, group, gname, from, peer, amount
	NotifyReminder = "Reminder" // to, group, gname, by, amount
	NotifyJoined   = "Joined"   // to, group, gname, by
)

// declareTriggers registers the notify events with gnotif at deploy. The
// registry marks them verified, since this realm declares its own.
// ponytail: gnotif is a v0 on onyx; a new registry version means a new
// release of this realm, which is why every gnotif call lives in this file.
func declareTriggers(cur realm) {
	triggers := [][2]string{
		{NotifyExpense, "{by} added {title}. Your share: {share}"},
		{NotifyIncome, "{by} recorded {title}. You get back {share}"},
		{NotifyTransfer, "{from} paid {peer} {amount}"},
		{NotifyReminder, "{by} reminds you that you owe {amount}"},
		{NotifyJoined, "{by} added you to the group"},
	}
	for _, t := range triggers {
		gnotif.Declare(cross(cur), self, t[0], "", "to", "{gname}", t[1], hub+":{group}")
	}
}

func notifyEntry(g *Group, e *Entry, by int) {
	if e.Kind == KindTransfer {
		for _, i := range []int{e.Payer, e.Who[0]} {
			if to := g.Members[i].Addr; to != "" && i != by {
				chain.Emit(NotifyTransfer, "to", to.String(), "group", itoa(g.ID), "gname", g.Name,
					"from", g.Members[e.Payer].Name, "peer", g.Members[e.Who[0]].Name, "amount", g.money(e.Total))
			}
		}
		return
	}
	event := NotifyExpense
	if e.Kind == KindIncome {
		event = NotifyIncome
	}
	for k, i := range e.Who {
		if to := g.Members[i].Addr; to != "" && i != by {
			share := e.Owe[k]
			if share < 0 {
				share = -share
			}
			chain.Emit(event, "to", to.String(), "group", itoa(g.ID), "gname", g.Name,
				"by", g.Members[by].Name, "title", e.Title, "share", g.money(share))
		}
	}
}

func notifyReminder(g *Group, m *Member, by string) {
	chain.Emit(NotifyReminder, "to", m.Addr.String(), "group", itoa(g.ID), "gname", g.Name,
		"by", by, "amount", g.money(-m.Bal))
}

func notifyJoined(g *Group, a address, by string) {
	chain.Emit(NotifyJoined, "to", a.String(), "group", itoa(g.ID), "gname", g.Name, "by", by)
}

// money writes cents with the group's currency: "42.50 €".
func (g *Group) money(c int64) string { return ledger.Format(c) + " " + g.Currency }

owner.gno

package gnosplit

import (
	"chain"
	"strings"
)

// The realm's owner, the deployer, holds one power: naming the release that
// takes over (SetSuccessor), once. It cannot touch a group. The role passes
// by Transfer then Accept; Renounce drops it for good.
var (
	owner     address // "" once renounced
	pending   address // the address a Transfer offered the role to
	successor string  // the pkgpath of the next release, "" until named
)

// setUp is init's owner half. Only `gno test` (chain "dev") runs with no
// signer, and an owner "" holds no power.
func setUp(deployer address, chainID string) {
	if deployer == "" && chainID != "dev" {
		panic("gnosplit: no owner: deploy gnosplit from an account")
	}
	owner = deployer
}

// Owner is the realm's owner, "" once renounced.
func Owner() address { return owner }

// Successor is the pkgpath of the release that takes groups over, "" if none.
func Successor() string { return successor }

func isOwner(a address) bool { return owner != "" && a == owner }

// Transfer offers the role to another address, which takes it with Accept.
func Transfer(cur realm, to address) {
	if !isOwner(cur.Previous().Address()) {
		panic("gnosplit: only the owner can transfer the role")
	}
	if !to.IsValid() {
		panic("gnosplit: not an address: " + to.String())
	}
	pending = to
	chain.Emit(EventOwnerOffered, "to", to.String())
}

// Accept takes the role a Transfer offered the caller.
func Accept(cur realm) {
	caller := cur.Previous().Address()
	if owner == "" || pending == "" || caller != pending {
		panic("gnosplit: no transfer of the role is offered to you")
	}
	owner, pending = caller, ""
	chain.Emit(EventOwnerChanged, "owner", owner.String())
}

// Renounce gives the role up for good.
func Renounce(cur realm) {
	if !isOwner(cur.Previous().Address()) {
		panic("gnosplit: only the owner can renounce the role")
	}
	owner, pending = "", ""
	chain.Emit(EventOwnerChanged, "owner", "")
}

// SetSuccessor names the release that takes groups over, once: a realm under
// this one's namespace, like gno.land/r/<ns>/gnosplit/v2. From then on that
// realm can move a group with MoveOut; nothing moves by itself.
func SetSuccessor(cur realm, pkgpath string) {
	if !isOwner(cur.Previous().Address()) {
		panic("gnosplit: only the owner can name a successor")
	}
	if successor != "" {
		panic("gnosplit: the successor is already " + successor)
	}
	ns := self[:strings.LastIndex(self, "/")+1] // "gno.land/r/<ns>/gnosplit/"
	if !strings.HasPrefix(pkgpath, ns) || pkgpath == self || len(pkgpath) > 100 || strings.ContainsAny(pkgpath, " :?#") {
		panic("gnosplit: a successor is a sibling release under " + ns)
	}
	successor = pkgpath
	chain.Emit(EventSuccessorSet, "pkgpath", pkgpath)
}

// MoveOut marks a group as taken over and returns it, as Export writes it.
// Only the successor realm can call it, which decides when a group moves
// (when one of its editors asks). The group stays readable here, frozen.
func MoveOut(cur realm, group string) string {
	prev := cur.Previous()
	if successor == "" || !prev.IsCode() || prev.PkgPath() != successor {
		panic("gnosplit: only the successor can move a group")
	}
	g := mustGroup(group)
	if g.Moved {
		panic("gnosplit: group " + group + " already moved")
	}
	g.Moved = true
	chain.Emit(EventGroupMoved, "group", itoa(g.ID), "to", successor)
	return Export(group)
}

render.gno

package gnosplit

import (
	"encoding/base64"
	"html"
	"strconv"
	"strings"
	"time"

	"gno.land/p/nym-alexiscolin000/gnosplit/ledger/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
)

// categories are an expense's kinds, in the order ByCat counts them. The last
// one is the default. A form sends the name.
var categories = []struct{ Name, Icon, Color string }{
	{"Food", "🍽", "#4e79a7"},
	{"Groceries", "🛒", "#f28e2b"},
	{"Transport", "🚗", "#59a14f"},
	{"Lodging", "🏠", "#e15759"},
	{"Activities", "🎟", "#76b7b2"},
	{"Shopping", "🛍", "#edc948"},
	{"Bills", "🧾", "#b07aa1"},
	{"Other", "📦", "#9c755f"},
}

func categoryOf(name string) int {
	name = strings.ToLower(strings.TrimSpace(name))
	if name == "" {
		return len(categories) - 1
	}
	for i, c := range categories {
		if strings.ToLower(c.Name) == name {
			return i
		}
	}
	panic("gnosplit: no category " + name)
}

const (
	pageSize = 25 // entries per history page
	latest   = 8  // entries on a group's page
)

// Render serves "" (home), "u/<address>" (a wallet's groups) and a group's
// pages: "<id>", then "/add", "/settle", "/settle/<from>/<to>/<cents>",
// "/members", "/stats", "/history[/<page>]", "/e/<entry>" and "/csv".
func Render(path string) string {
	if path == "" {
		return renderHome()
	}
	if strings.HasPrefix(path, "u/") {
		return renderWallet(address(strings.TrimPrefix(path, "u/")))
	}
	parts := strings.Split(path, "/")
	g := getGroup(parts[0])
	if g == nil {
		return "# Not found\n\nNo group " + sanitize.InlineText(parts[0]) + ". [Back home](" + hub + ")\n"
	}
	page := ""
	if len(parts) > 1 {
		page = parts[1]
	}
	switch {
	case page == "" && len(parts) == 1:
		return renderGroup(g)
	case page == "add" && len(parts) == 2:
		return renderAdd(g)
	case page == "settle" && len(parts) == 2:
		return renderSettle(g, -1, -1, 0)
	case page == "settle" && len(parts) == 5:
		f, t, c := atoi(parts[2]), atoi(parts[3]), atoi(parts[4])
		if f >= 0 && t >= 0 && f < len(g.Members) && t < len(g.Members) && c > 0 {
			return renderSettle(g, f, t, int64(c))
		}
	case page == "members" && len(parts) == 2:
		return renderMembers(g)
	case page == "stats" && len(parts) == 2:
		return renderStats(g)
	case page == "history" && len(parts) <= 3:
		n := 1
		if len(parts) == 3 {
			n = atoi(parts[2])
		}
		if n >= 1 {
			return renderHistory(g, n)
		}
	case page == "e" && len(parts) == 3:
		if v := g.Entries.Get(key(atoi(parts[2]))); v != nil {
			return renderEntry(g, v.(*Entry))
		}
	case page == "csv" && len(parts) == 2:
		return header(g, "Export") + "Every member and entry, as CSV.\n\n" + sanitize.CodeBlock(Export(parts[0]))
	}
	return "# Not found\n\n[Back to the group](" + link(g, "") + ")\n"
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# gnosplit\n\n")
	b.WriteString("**Share expenses with friends, then settle up in as few transfers as possible.** ")
	b.WriteString("Trips, flatshares, dinners: like Tricount, on gno.land, with no account and no ads.\n\n")
	b.WriteString("<gno-columns>\n### 1. Create a group\nName it, pick a currency, list your friends. They don't need a wallet.\n")
	b.WriteString("<gno-columns-sep />\n### 2. Add expenses\nWho paid, for whom: split equally, by shares or by exact amounts. Foreign currencies too.\n")
	b.WriteString("<gno-columns-sep />\n### 3. Settle up\ngnosplit works out who pays whom, in the fewest transfers. Friends with a wallet get notified.\n")
	b.WriteString("</gno-columns>\n\n")
	b.WriteString("## Create a group\n\n")
	b.WriteString("<gno-form exec=\"CreateGroup\">\n")
	b.WriteString(input("name", "Group name, like Ski trip", "", true))
	b.WriteString(input("currency", "Currency, like € or CHF", "€", true))
	b.WriteString(input("you", "Your name in the group", "", true))
	b.WriteString(input("others", "Your friends, comma-separated: Alice, Bob", "", false))
	b.WriteString("</gno-form>\n\n")
	b.WriteString("> [!NOTE] Everything is public\n> A group lives on gno.land: anyone with its link can read it. ")
	b.WriteString("Use first names, and keep private details out of titles.\n\n")
	b.WriteString("## Your groups\n\nOpen `" + hub + ":u/<your address>` to list the groups your wallet is in. ")
	b.WriteString(plural(groups.Size(), "group") + " so far.\n")
	return b.String()
}

func renderWallet(a address) string {
	if !a.IsValid() {
		return "# Not found\n\nNot an address. [Back home](" + hub + ")\n"
	}
	var b strings.Builder
	b.WriteString("# Your groups\n\n" + a.String() + "\n\n")
	n := 0
	byAddr.Iterate(a.String()+"/", a.String()+"0", func(k string, _ any) bool {
		g := groups.Get(k[strings.LastIndex(k, "/")+1:]).(*Group)
		m := g.Members[g.editor(a)]
		if n == 0 {
			b.WriteString("| Group | You | Your balance |\n|---|---|---:|\n")
		}
		b.WriteString("| [" + cellText(g.Name) + "](" + link(g, "") + ") | " + sanitize.TableCell(m.Name) +
			" | " + ledger.Signed(m.Bal) + " " + g.Currency + " |\n")
		n++
		return false
	})
	if n == 0 {
		b.WriteString("This wallet is in no group yet. [Create one](" + hub + ")\n")
	}
	return b.String()
}

func renderGroup(g *Group) string {
	var b strings.Builder
	b.WriteString(header(g, ""))
	b.WriteString("<gno-columns>\n## Balances\n\n| Member | | Balance |\n|---|---|---:|\n")
	var max int64
	for _, m := range g.Members {
		if abs(m.Bal) > max {
			max = abs(m.Bal)
		}
	}
	for _, m := range g.Members {
		b.WriteString("| " + sanitize.TableCell(m.Name) + " | " + balanceBar(m.Bal, max) + " | **" + g.money(m.Bal) + "** |\n")
	}
	b.WriteString("\n<gno-columns-sep />\n## Settle up\n\n")
	b.WriteString(transfers(g, true))
	b.WriteString("</gno-columns>\n\n## Latest\n\n")
	if g.Entries.Size() == 0 {
		b.WriteString("No expense yet. [Add the first one](" + link(g, "/add") + ")\n")
		return b.String()
	}
	b.WriteString(entryTable(g, 0, latest))
	if g.Entries.Size() > latest {
		b.WriteString("\n[All " + plural(g.Entries.Size(), "entry") + " →](" + link(g, "/history") + ")\n")
	}
	return b.String()
}

// transfers lists the payments that settle the group, each with a link that
// fills in the form to record it.
func transfers(g *Group, short bool) string {
	bal := make([]int64, len(g.Members))
	for i, m := range g.Members {
		bal[i] = m.Bal
	}
	ts := ledger.Settle(bal)
	if len(ts) == 0 {
		return "> [!SUCCESS] All settled up\n> Nobody owes anything.\n\n"
	}
	var b strings.Builder
	b.WriteString("| Who | Pays | Amount | |\n|---|---|---:|---|\n")
	for _, t := range ts {
		b.WriteString("| " + sanitize.TableCell(g.Members[t.From].Name) + " | " + sanitize.TableCell(g.Members[t.To].Name) +
			" | " + g.money(t.Amount) + " | [Record](" + link(g, "/settle/"+itoa(t.From)+"/"+itoa(t.To)+"/"+strconv.FormatInt(t.Amount, 10)) + ") |\n")
	}
	if short {
		b.WriteString("\n" + plural(len(ts), "transfer") + " settle everything. [Settle up →](" + link(g, "/settle") + ")\n")
	}
	return b.String()
}

func renderAdd(g *Group) string {
	var b strings.Builder
	b.WriteString(header(g, "Add"))
	if g.Moved {
		return b.String()
	}
	b.WriteString("Amounts are like `42.50`. Paid in another currency? Write `50 USD x0.92`: 50 dollars at 0.92 " +
		g.Currency + " each.\n\n")

	b.WriteString("## Split equally\n\n<gno-form exec=\"AddExpense\">\n")
	b.WriteString(groupField(g) + input("title", "What, like Groceries", "", true) + input("amount", "Amount", "", true))
	b.WriteString(memberSelect(g, "paidBy", "Paid by", -1))
	b.WriteString(memberChecks(g, "forWhom", "For whom"))
	b.WriteString(categorySelect())
	b.WriteString("</gno-form>\n\n")

	var shares, amounts []string
	for _, m := range g.Members {
		shares = append(shares, m.Name+":1")
		amounts = append(amounts, m.Name+":")
	}
	b.WriteString("## Split by shares\n\nGive each a number of shares: `Alice:2, Bob:1` makes Alice pay two thirds. Leave out who is not in.\n\n")
	b.WriteString("<gno-form exec=\"AddByShares\">\n")
	b.WriteString(groupField(g) + input("title", "What", "", true) + input("amount", "Amount", "", true))
	b.WriteString(memberSelect(g, "paidBy", "Paid by", -1))
	b.WriteString(input("shares", "Shares", strings.Join(shares, ", "), true))
	b.WriteString(categorySelect())
	b.WriteString("</gno-form>\n\n")

	b.WriteString("## Split by amounts\n\nWrite each one's exact part: `Alice:12.50, Bob:7.50`. The expense is their sum.\n\n")
	b.WriteString("<gno-form exec=\"AddByAmounts\">\n")
	b.WriteString(groupField(g) + input("title", "What", "", true))
	b.WriteString(memberSelect(g, "paidBy", "Paid by", -1))
	b.WriteString(input("amounts", "Amounts, like "+strings.Join(amounts, "12.50, ")+"12.50", "", true))
	b.WriteString(categorySelect())
	b.WriteString("</gno-form>\n\n")

	b.WriteString("## Money received\n\nA refund, a deposit returned: who received it, and for whom.\n\n")
	b.WriteString("<gno-form exec=\"AddIncome\">\n")
	b.WriteString(groupField(g) + input("title", "What, like Deposit back", "", true) + input("amount", "Amount", "", true))
	b.WriteString(memberSelect(g, "receivedBy", "Received by", -1))
	b.WriteString(memberChecks(g, "forWhom", "For whom"))
	b.WriteString("</gno-form>\n")
	return b.String()
}

func renderSettle(g *Group, from, to int, amount int64) string {
	var b strings.Builder
	b.WriteString(header(g, "Settle up"))
	if from < 0 {
		b.WriteString(transfers(g, false) + "\n")
	}
	if g.Moved {
		return b.String()
	}
	b.WriteString("## Record a payment\n\nA payment made outside gnosplit, by bank transfer or in cash.\n\n")
	b.WriteString("<gno-form exec=\"AddTransfer\">\n" + groupField(g))
	if to < 0 && len(g.Members) > 1 {
		to = 1 // a blank form starts on two different members
	}
	b.WriteString(memberSelect(g, "from", "From", from))
	b.WriteString(memberSelect(g, "to", "To", to))
	amt := ""
	if amount > 0 {
		amt = cents(amount)
	}
	b.WriteString(input("amount", "Amount", amt, true))
	b.WriteString("</gno-form>\n\n")
	if from >= 0 {
		return b.String()
	}
	var debtors []int
	for i, m := range g.Members {
		if m.Bal < 0 && m.Addr != "" {
			debtors = append(debtors, i)
		}
	}
	if len(debtors) > 0 {
		b.WriteString("## Send a reminder\n\nA notification to a member who owes, at most one every 12 hours.\n\n")
		b.WriteString("<gno-form exec=\"Remind\">\n" + groupField(g))
		for k, i := range debtors {
			b.WriteString(selectOpt("member", g.Members[i].Name, first(k, "Who"), k == 0))
		}
		b.WriteString("</gno-form>\n")
	}
	return b.String()
}

func renderMembers(g *Group) string {
	var b strings.Builder
	b.WriteString(header(g, "Members"))
	b.WriteString("| Member | Wallet | Paid | Share | Balance |\n|---|---|---:|---:|---:|\n")
	var free []int
	for i, m := range g.Members {
		w := "—"
		if m.Addr != "" {
			w = "[" + short(m.Addr) + "](" + hub + ":u/" + m.Addr.String() + ")"
		} else {
			free = append(free, i)
		}
		b.WriteString("| " + sanitize.TableCell(m.Name) + " | " + w + " | " + g.money(m.Paid) + " | " +
			g.money(m.Share) + " | **" + g.money(m.Bal) + "** |\n")
	}
	b.WriteString("\nMembers with a wallet can add and change entries, and get notified. ")
	b.WriteString("To turn notifications on, open [gnotif](https://gnotif.xyz) with your address.\n\n")
	if g.Moved {
		return b.String()
	}
	b.WriteString("## Add a member\n\n<gno-form exec=\"AddMember\">\n" + groupField(g))
	b.WriteString(input("name", "Name", "", true) + input("addr", "Their g1 address, if they have a wallet", "", false))
	b.WriteString("</gno-form>\n\n")
	if len(free) > 0 && len(g.Members) > 0 {
		b.WriteString("## Link a wallet\n\nA friend got a wallet: link it to their name. A linked wallet is never replaced.\n\n")
		b.WriteString("<gno-form exec=\"LinkMember\">\n" + groupField(g))
		for k, i := range free {
			b.WriteString(selectOpt("name", g.Members[i].Name, first(k, "Member"), k == 0))
		}
		b.WriteString(input("addr", "Their g1 address", "", true))
		b.WriteString("</gno-form>\n")
	}
	return b.String()
}

func renderStats(g *Group) string {
	var b strings.Builder
	b.WriteString(header(g, "Stats"))
	var total int64
	for _, c := range g.ByCat {
		total += c
	}
	if total <= 0 {
		b.WriteString("No expense yet.\n")
		return b.String()
	}
	b.WriteString("## By category\n\n" + categoryBar(g.ByCat, total) + "\n\n")
	b.WriteString("| | Category | Spent | Share |\n|---|---|---:|---:|\n")
	for i, c := range categories {
		if g.ByCat[i] == 0 {
			continue
		}
		b.WriteString("| " + swatch(c.Color) + " | " + c.Icon + " " + c.Name + " | " + g.money(g.ByCat[i]) +
			" | " + percent(g.ByCat[i], total) + " |\n")
	}
	b.WriteString("\n## By member\n\nWhat each one paid, and what their part of the expenses came to.\n\n")
	b.WriteString("| Member | Paid | Share | Of all paid |\n|---|---:|---:|---:|\n")
	for _, m := range g.Members {
		b.WriteString("| " + sanitize.TableCell(m.Name) + " | " + g.money(m.Paid) + " | " + g.money(m.Share) +
			" | " + percent(m.Paid, g.Spent) + " |\n")
	}
	return b.String()
}

func renderHistory(g *Group, page int) string {
	var b strings.Builder
	b.WriteString(header(g, "History"))
	n := g.Entries.Size()
	pages := (n + pageSize - 1) / pageSize
	if n == 0 || page > pages {
		b.WriteString("Nothing here.\n")
		return b.String()
	}
	b.WriteString(entryTable(g, (page-1)*pageSize, pageSize) + "\n")
	if page > 1 {
		b.WriteString("[← Newer](" + link(g, "/history/"+itoa(page-1)) + ") ")
	}
	if page < pages {
		b.WriteString("[Older →](" + link(g, "/history/"+itoa(page+1)) + ")")
	}
	b.WriteString("\n\nPage " + itoa(page) + " of " + itoa(pages) + " · [Export as CSV](" + link(g, "/csv") + ")\n")
	return b.String()
}

func renderEntry(g *Group, e *Entry) string {
	var b strings.Builder
	b.WriteString(header(g, "Entry"))
	b.WriteString("## " + entryIcon(e) + " " + sanitize.InlineText(e.Title) + "\n\n")
	total := abs(e.Total)
	b.WriteString("**" + g.money(total) + "**")
	if e.Note != "" {
		b.WriteString(" (" + e.Note + ")")
	}
	b.WriteString(" · " + verb(e) + " **" + sanitize.InlineText(g.Members[e.Payer].Name) + "** · " + date(e.At, "Mon Jan 2, 2006"))
	b.WriteString("\n\nRecorded by " + e.By.String() + "\n\n")
	if e.Kind != KindTransfer {
		b.WriteString("| Member | Part |\n|---|---:|\n")
		for i, m := range e.Who {
			b.WriteString("| " + sanitize.TableCell(g.Members[m].Name) + " | " + g.money(abs(e.Owe[i])) + " |\n")
		}
		b.WriteString("\n")
	}
	if g.Moved {
		return b.String()
	}
	b.WriteString("## Delete\n\nRemoves the entry and undoes it on every balance.\n\n")
	b.WriteString("<gno-form exec=\"Delete\">\n" + groupField(g) + readonly("entry", "Entry", itoa(e.ID)) + "</gno-form>\n")
	return b.String()
}

// entryTable writes count entries, newest first, from offset.
func entryTable(g *Group, offset, count int) string {
	var b strings.Builder
	b.WriteString("| Date | What | Paid by | For | Amount |\n|---|---|---|---|---:|\n")
	g.Entries.ReverseIterateByOffset(offset, count, func(_ string, v any) bool {
		e := v.(*Entry)
		title := "[" + cellText(e.Title) + "](" + link(g, "/e/"+itoa(e.ID)) + ")"
		amount := g.money(abs(e.Total))
		if e.Kind == KindIncome {
			amount = "−" + amount
		}
		b.WriteString("| " + date(e.At, "Jan 2") + " | " + entryIcon(e) + " " + title + " | " +
			sanitize.TableCell(g.Members[e.Payer].Name) + " | " + forWhom(g, e) + " | " + amount + " |\n")
		return false
	})
	return b.String()
}

func header(g *Group, page string) string {
	var b strings.Builder
	if page == "" {
		b.WriteString("# " + sanitize.InlineText(g.Name) + "\n\n")
	} else {
		b.WriteString("# [" + sanitize.InlineText(g.Name) + "](" + link(g, "") + ") · " + page + "\n\n")
	}
	b.WriteString(plural(len(g.Members), "member") + " · **" + g.money(g.Spent) + "** spent · ")
	b.WriteString("[Add](" + link(g, "/add") + ") · [Settle up](" + link(g, "/settle") + ") · [Members](" +
		link(g, "/members") + ") · [Stats](" + link(g, "/stats") + ") · [History](" + link(g, "/history") + ")\n\n")
	if g.Moved {
		b.WriteString("> [!WARNING] This group moved\n> It is kept read-only here. Its new home is [" + successor + "](" +
			strings.TrimPrefix(successor, "gno.land") + ":" + itoa(g.ID) + ").\n\n")
	}
	return b.String()
}

// Export writes a group as CSV: its members, then every entry, oldest first.
// MoveOut hands it to the successor, and the /csv page shows it.
func Export(group string) string {
	g := mustGroup(group)
	var b strings.Builder
	b.WriteString("member,address,balance,paid,share\n")
	for _, m := range g.Members {
		b.WriteString(csv(m.Name) + "," + m.Addr.String() + "," + cents(m.Bal) + "," + cents(m.Paid) + "," + cents(m.Share) + "\n")
	}
	b.WriteString("\nentry,kind,time,title,category,payer,total,note,split\n")
	g.Entries.Iterate("", "", func(_ string, v any) bool {
		e := v.(*Entry)
		split := make([]string, len(e.Who))
		for i, m := range e.Who {
			split[i] = g.Members[m].Name + ":" + cents(e.Owe[i])
		}
		b.WriteString(itoa(e.ID) + "," + [...]string{"expense", "income", "transfer"}[e.Kind] + "," +
			date(e.At, "2006-01-02T15:04:05Z") + "," + csv(e.Title) + "," + categories[e.Cat].Name + "," +
			csv(g.Members[e.Payer].Name) + "," + cents(e.Total) + "," + csv(e.Note) + "," + csv(strings.Join(split, ";")) + "\n")
		return false
	})
	return b.String()
}

// Form fields. Every value is escaped for the attribute it lands in; a form's
// fields are in the order of its function's parameters, since gnoweb passes
// them by position.

func input(name, placeholder, value string, required bool) string {
	s := `<gno-input name="` + name + `" placeholder="` + attr(placeholder) + `"`
	if value != "" {
		s += ` value="` + attr(value) + `"`
	}
	if required {
		s += ` required="true"`
	}
	return s + " />\n"
}

func readonly(name, placeholder, value string) string {
	return `<gno-input name="` + name + `" placeholder="` + placeholder + `" value="` + attr(value) + `" readonly="true" />` + "\n"
}

func groupField(g *Group) string { return readonly("group", "Group", itoa(g.ID)) }

// selectOpt is one option of a select; gnoweb reads the description off
// the first one, so only that one carries it.
func selectOpt(name, value, description string, selected bool) string {
	s := `<gno-select name="` + name + `" value="` + attr(value) + `"`
	if description != "" {
		s += ` description="` + attr(description) + `"`
	}
	if selected {
		s += ` selected="true"`
	}
	return s + " />\n"
}

func memberSelect(g *Group, name, description string, selected int) string {
	var b strings.Builder
	if selected < 0 {
		selected = 0
	}
	for i, m := range g.Members {
		b.WriteString(selectOpt(name, m.Name, first(i, description), i == selected))
	}
	return b.String()
}

// first is s for the first item of a list, "" after.
func first(i int, s string) string {
	if i == 0 {
		return s
	}
	return ""
}

func memberChecks(g *Group, name, description string) string {
	var b strings.Builder
	for i, m := range g.Members {
		s := `<gno-input type="checkbox" name="` + name + `" value="` + attr(m.Name) + `" checked="true"`
		if i == 0 {
			s += ` description="` + description + `"`
		}
		b.WriteString(s + " />\n")
	}
	return b.String()
}

func categorySelect() string {
	var b strings.Builder
	for i, c := range categories {
		b.WriteString(selectOpt("category", c.Name, first(i, "Category"), i == len(categories)-1))
	}
	return b.String()
}

// Pictures: small SVGs as data URIs, the one image source gnoweb always shows.

// balanceBar draws a balance against the largest one: right and teal when the
// group owes the member, left and orange when they owe.
func balanceBar(v, max int64) string {
	w := 0
	if max > 0 {
		w = int(abs(v) * 56 / max)
		if w == 0 && v != 0 {
			w = 1
		}
	}
	x, color := 60, "#1a9e8f"
	if v < 0 {
		x, color = 60-w, "#e07b39"
	}
	return svg(120, 14, `<rect x="59.5" y="0" width="1" height="14" fill="#8b8f98"/><rect x="`+itoa(x)+
		`" y="2" width="`+itoa(w)+`" height="10" rx="2" fill="`+color+`"/>`)
}

// categoryBar is one bar split by category, in the table's order.
func categoryBar(byCat []int64, total int64) string {
	const w = 600
	var s strings.Builder
	x := 0
	for i, c := range byCat {
		if c <= 0 {
			continue
		}
		cw := int(c * w / total)
		if x+cw > w {
			cw = w - x
		}
		s.WriteString(`<rect x="` + itoa(x) + `" y="0" width="` + itoa(cw) + `" height="24" fill="` + categories[i].Color + `"/>`)
		x += cw
	}
	return svg(w, 24, s.String())
}

func swatch(color string) string {
	return svg(12, 12, `<rect width="12" height="12" rx="3" fill="`+color+`"/>`)
}

func svg(w, h int, body string) string {
	doc := `<svg xmlns="http://www.w3.org/2000/svg" width="` + itoa(w) + `" height="` + itoa(h) +
		`" viewBox="0 0 ` + itoa(w) + ` ` + itoa(h) + `">` + body + `</svg>`
	return "![](data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(doc)) + ")"
}

// Small helpers.

func link(g *Group, page string) string { return hub + ":" + itoa(g.ID) + page }

func entryIcon(e *Entry) string {
	switch e.Kind {
	case KindIncome:
		return "↩"
	case KindTransfer:
		return "⇄"
	}
	return categories[e.Cat].Icon
}

func verb(e *Entry) string {
	if e.Kind == KindIncome {
		return "received by"
	}
	return "paid by"
}

func forWhom(g *Group, e *Entry) string {
	if e.Kind == KindTransfer {
		return sanitize.TableCell(g.Members[e.Who[0]].Name)
	}
	if len(e.Who) == len(g.Members) {
		return "everyone"
	}
	var names []string
	for i, m := range e.Who {
		if i == 3 {
			return sanitize.TableCell(strings.Join(names, ", ")) + " +" + itoa(len(e.Who)-3)
		}
		names = append(names, g.Members[m].Name)
	}
	return sanitize.TableCell(strings.Join(names, ", "))
}

func date(unix int64, layout string) string { return time.Unix(unix, 0).UTC().Format(layout) }

func short(a address) string {
	s := a.String()
	if len(s) < 12 {
		return s
	}
	return s[:6] + "…" + s[len(s)-4:]
}

func percent(part, whole int64) string {
	if whole <= 0 {
		return "—"
	}
	return strconv.FormatInt((part*100+whole/2)/whole, 10) + "%"
}

func plural(n int, word string) string {
	if n == 1 {
		return "1 " + word
	}
	if strings.HasSuffix(word, "y") {
		return itoa(n) + " " + word[:len(word)-1] + "ies"
	}
	return itoa(n) + " " + word + "s"
}

// cents writes an amount for CSV: "42.50", no thousands separator.
func cents(c int64) string { return strings.ReplaceAll(ledger.Format(c), ",", "") }

func csv(s string) string {
	if !strings.ContainsAny(s, ",\"\n;") {
		return s
	}
	return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
}

func attr(s string) string { return html.EscapeString(s) }

// cellText is link text inside a table cell: InlineText leaves "|" alone,
// and a bare one would end the cell.
func cellText(s string) string { return strings.ReplaceAll(sanitize.InlineText(s), "|", `\|`) }

func abs(v int64) int64 {
	if v < 0 {
		return -v
	}
	return v
}

// atoi is a non-negative number, -1 for anything else.
func atoi(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil || n < 0 {
		return -1
	}
	return n
}