Add the list block and the module layer with the note module
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m50s

The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.

internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.

Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.

The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 10:55:50 -06:00
1 parent 6b2e402f1a
commit 3e9779f71a
69 files changed
+3092 -262

No files matched your search

+27 -1
View File
@@ -118,6 +118,13 @@ type FormatConfig struct {
// MaxLines fails a job that would print more lines, all copies
// counted. It is a backstop against runaway text.
MaxLines int `mapstructure:"max_lines"`
// Timezone is the zone the times modules print are in: an IANA name
// such as "Europe/London", "UTC", or "Local" for the host's zone.
Timezone string `mapstructure:"timezone"`
// TimeLayout is the Go time layout those times are printed in.
TimeLayout string `mapstructure:"time_layout"`
}
// QueueConfig configures the print queue.
@@ -192,7 +199,9 @@ func Default() Config {
RetryDelay: time.Second,
},
Format: FormatConfig{
MaxLines: 2000,
MaxLines: 2000,
Timezone: "Local",
TimeLayout: "02 Jan 15:04",
},
Queue: QueueConfig{
Size: 100,
@@ -574,6 +583,13 @@ func (c *Config) Validate() error {
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
check(c.Format.MaxLines > 0, "format.max_lines must be positive")
if c.Format.Timezone == "" {
errs = append(errs, errors.New(`format.timezone is required: an IANA name such as "Europe/London", "UTC" or "Local"`))
} else if _, err := time.LoadLocation(c.Format.Timezone); err != nil {
errs = append(errs, fmt.Errorf(`format.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, c.Format.Timezone))
}
check(showsTime(c.Format.TimeLayout),
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative")
@@ -592,6 +608,16 @@ func (c *Config) Validate() error {
return errors.Join(errs...)
}
// showsTime reports whether layout prints something of the time it
// formats: two times that differ in every field format differently. A
// layout with none of Go's reference values, such as "HH:MM", prints
// itself.
func showsTime(layout string) bool {
a := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
b := time.Date(2012, 11, 22, 16, 47, 58, 0, time.FixedZone("X", 3600))
return a.Format(layout) != b.Format(layout)
}
func validPort(port int) bool {
return port >= 1 && port <= 65535
}
+41 -1
View File
@@ -7,6 +7,9 @@ import (
"testing"
"time"
// Embeds the zone database, so that IANA names load on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/config"
)
@@ -53,6 +56,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 {
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing)
}
if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" {
t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout)
}
}
func TestLoadOverridesAndDurations(t *testing.T) {
@@ -66,6 +72,8 @@ paper_width = 384
box_line_spacing = 24
[format]
max_lines = 500
timezone = "Europe/London"
time_layout = "2006-01-02 15:04"
[images]
allowed_hosts = ["images.lan"]
[sentry]
@@ -77,6 +85,9 @@ format = "json"
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Format.Timezone != "Europe/London" || cfg.Format.TimeLayout != "2006-01-02 15:04" {
t.Errorf("format = %+v", cfg.Format)
}
if cfg.Printer.DialTimeout != 750*time.Millisecond {
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
}
@@ -154,6 +165,31 @@ func TestLoadErrors(t *testing.T) {
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n",
wantErr: "printer.box_line_spacing must be 0-255",
},
{
name: "unknown time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"Europe/Londn\"\n",
wantErr: `format.timezone: "Europe/Londn" is not a known time zone`,
},
{
name: "time zone that is a path",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"../etc/passwd\"\n",
wantErr: "format.timezone",
},
{
name: "empty time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"\"\n",
wantErr: "format.timezone is required",
},
{
name: "time layout without a time",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntime_layout = \"HH:MM\"\n",
wantErr: `format.time_layout: "HH:MM" shows no date or time`,
},
{
name: "empty time layout",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntime_layout = \"\"\n",
wantErr: "format.time_layout",
},
{
name: "unknown format key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n",
@@ -289,7 +325,8 @@ func TestExampleConfigLoads(t *testing.T) {
}
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing {
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout {
t.Error("example config values drifted from the defaults it documents")
}
}
@@ -447,6 +484,7 @@ func TestLoadEnvironmentErrors(t *testing.T) {
{"only spaces", "UBERBRINGER_IMAGES_ALLOWED_HOSTS", " ", "UBERBRINGER_IMAGES_ALLOWED_HOSTS holds only spaces"},
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
{"unknown time zone", "UBERBRINGER_FORMAT_TIMEZONE", "Mars/Olympus", "format.timezone"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -480,6 +518,8 @@ func TestValue(t *testing.T) {
{key: "webserver.trusted_proxies", want: "127.0.0.1,::1"},
{key: "images.allowed_hosts", want: "a.lan,b.lan"},
{key: "images.allow_private_networks", want: "false"},
{key: "format.timezone", want: "Local"},
{key: "format.time_layout", want: "02 Jan 15:04"},
{key: "printer", wantErr: `"printer" is a section`},
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
+128
View File
@@ -0,0 +1,128 @@
package modules
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"reflect"
"slices"
"strconv"
"strings"
)
// maxNameInProblem caps how much of an unknown field's name a problem
// repeats.
const maxNameInProblem = 64
// DecodeStrict decodes body, which must be one JSON object, into the struct
// v points to. A name must match a field's json tag exactly, so a name in
// another case is unknown. Every problem is reported at once, in a
// *PayloadError: a body that is not one JSON object, each unknown field and
// each field of the wrong type. A field that is null counts as absent.
func DecodeStrict(body []byte, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Struct {
panic("modules.DecodeStrict: v must point to a struct")
}
var object map[string]json.RawMessage
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(&object); err != nil {
return &PayloadError{Problems: []string{bodyProblem(err)}}
}
if object == nil {
return &PayloadError{Problems: []string{"body: expected a JSON object, got null"}}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return &PayloadError{Problems: []string{"body: trailing data after the payload"}}
}
target := rv.Elem()
fields := jsonFields(target.Type())
var problems []string
for _, name := range slices.Sorted(maps.Keys(object)) {
index, ok := fields[name]
if !ok {
problems = append(problems, fieldName(name)+": unknown field")
continue
}
field := target.Field(index)
if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil {
problems = append(problems, fmt.Sprintf("%s: expected %s", name, describe(field.Type())))
}
}
if len(problems) > 0 {
return &PayloadError{Problems: problems}
}
return nil
}
// bodyProblem describes why a body is not a JSON object.
func bodyProblem(err error) string {
var typeErr *json.UnmarshalTypeError
switch {
case errors.Is(err, io.EOF):
return "body: empty; expected a JSON object"
case errors.As(err, &typeErr):
return "body: expected a JSON object, got " + typeErr.Value
}
return "body: not valid JSON: " + err.Error()
}
// jsonFields maps the json name of each exported field of the struct type t
// to its index.
func jsonFields(t reflect.Type) map[string]int {
fields := make(map[string]int, t.NumField())
for i := range t.NumField() {
f := t.Field(i)
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if !f.IsExported() || name == "-" {
continue
}
if name == "" {
name = f.Name
}
fields[name] = i
}
return fields
}
// fieldName shows a field name from a payload in a problem: as written when
// it is a plain name, quoted otherwise, and cut when it is long.
func fieldName(name string) string {
plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == ""
if r := []rune(name); len(r) > maxNameInProblem {
name = string(r[:maxNameInProblem]) + "..."
}
if plain {
return name
}
return strconv.Quote(name)
}
// describe names the JSON a field of type t takes.
func describe(t reflect.Type) string {
switch t.Kind() {
case reflect.Pointer:
return describe(t.Elem())
case reflect.String:
return "a string"
case reflect.Bool:
return "true or false"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "a whole number"
case reflect.Slice:
switch t.Elem().Kind() {
case reflect.String:
return "an array of strings"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "an array of whole numbers"
}
return "an array"
}
return t.String()
}
+88
View File
@@ -0,0 +1,88 @@
package modules_test
import (
"errors"
"strings"
"testing"
"uberbringer/internal/pkg/modules"
)
type decodeTarget struct {
Name string `json:"name"`
Count int `json:"count"`
On *bool `json:"on"`
Tags []string `json:"tags"`
Marks []int `json:"marks"`
Skip string `json:"-"`
}
func TestDecodeStrict(t *testing.T) {
var got decodeTarget
body := `{"name":"n","count":3,"on":false,"tags":["a","b"],"marks":[1,2],"count":4}`
if err := modules.DecodeStrict([]byte(body), &got); err != nil {
t.Fatal(err)
}
if got.Name != "n" || got.Count != 4 || got.On == nil || *got.On || strings.Join(got.Tags, ",") != "a,b" || len(got.Marks) != 2 {
t.Errorf("decoded %+v", got)
}
var empty decodeTarget
if err := modules.DecodeStrict([]byte(` {"name": null} `), &empty); err != nil || empty.Name != "" {
t.Errorf("a null field: %v, %+v; want it treated as absent", err, empty)
}
}
func TestDecodeStrictProblems(t *testing.T) {
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"empty body", "", []string{"body: empty; expected a JSON object"}},
{"blank body", " \n", []string{"body: empty; expected a JSON object"}},
{"array", `[1]`, []string{"body: expected a JSON object, got array"}},
{"string", `"x"`, []string{"body: expected a JSON object, got string"}},
{"null", `null`, []string{"body: expected a JSON object, got null"}},
{"syntax error", `{"name":`, []string{"body: not valid JSON: unexpected EOF"}},
{"trailing data", `{} {}`, []string{"body: trailing data after the payload"}},
{"every problem at once", `{"Name":"x","colour":1,"count":"3","on":"yes","tags":[1],"marks":[1.5],"hidden":"h","Skip":"s","-":1}`, []string{
"-: unknown field",
"Name: unknown field",
"Skip: unknown field",
"colour: unknown field",
"count: expected a whole number",
"hidden: unknown field",
"marks: expected an array of whole numbers",
"on: expected true or false",
"tags: expected an array of strings",
}},
{"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}},
{"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{
`"a b": unknown field`,
strings.Repeat("x", 64) + "...: unknown field",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var v decodeTarget
err := modules.DecodeStrict([]byte(tt.body), &v)
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestDecodeStrictNeedsAStruct(t *testing.T) {
defer func() {
if recover() == nil {
t.Error("DecodeStrict into a map did not panic")
}
}()
var m map[string]any
_ = modules.DecodeStrict([]byte(`{}`), &m)
}
+108
View File
@@ -0,0 +1,108 @@
package modules
import (
"context"
"fmt"
"strings"
"uberbringer/internal/pkg/receipt"
)
// noteStyles are the box styles a note may ask for.
var noteStyles = []string{"single", "double", "double-h", "double-v"}
// Note returns the note module: a box with an optional title, the text and
// an optional checklist, stamped with the time in its bottom border.
func Note() Module {
return note{}
}
type note struct{}
// notePayload is the body of a note.
type notePayload struct {
Title string `json:"title"`
Text string `json:"text"`
Items []string `json:"items"`
Done []int `json:"done"`
Style string `json:"style"`
Footer string `json:"footer"`
Stamp *bool `json:"stamp"`
}
func (note) Name() string { return "note" }
func (note) Description() string { return "Boxed note with an optional checklist" }
// Build lays the note out as a box: the text, then, when there are items,
// an empty line and a checklist. The footer is the payload's, or the build
// time unless stamp is false.
func (note) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notePayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
if problems := p.problems(); len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
children := []receipt.Element{{Type: receipt.TypeText, Text: p.Text}}
if len(p.Items) > 0 {
children = append(children,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeList, Bullet: "checkbox", Items: p.Items, Done: p.Done},
)
}
footer := p.Footer
if footer == "" && (p.Stamp == nil || *p.Stamp) {
footer = env.Stamp()
}
box := receipt.Element{
Type: receipt.TypeBox,
Title: p.Title,
Style: strings.ToLower(p.Style),
Footer: footer,
Children: children,
}
return receipt.Job{Elements: []receipt.Element{box}}, nil
}
// problems checks what the box and its list would refuse, in the payload's
// own terms.
func (p notePayload) problems() []string {
var problems []string
if strings.TrimSpace(p.Text) == "" {
problems = append(problems, "text: required")
}
if p.Style != "" && !containsFold(noteStyles, p.Style) {
problems = append(problems, "style: must be "+strings.Join(noteStyles[:len(noteStyles)-1], ", ")+" or "+noteStyles[len(noteStyles)-1])
}
if n := len(p.Items); n > receipt.MaxItems {
problems = append(problems, fmt.Sprintf("items: %d items, limit is %d", n, receipt.MaxItems))
}
for i, item := range p.Items {
if item == "" {
problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i))
}
}
seen := make(map[int]bool, len(p.Done))
for i, index := range p.Done {
switch {
case index < 0 || index >= len(p.Items):
problems = append(problems, fmt.Sprintf("done[%d]: index %d is out of range", i, index))
case seen[index]:
problems = append(problems, fmt.Sprintf("done[%d]: index %d is repeated", i, index))
}
seen[index] = true
}
return problems
}
func containsFold(list []string, s string) bool {
for _, item := range list {
if strings.EqualFold(item, s) {
return true
}
}
return false
}
+244
View File
@@ -0,0 +1,244 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
// Embeds the zone database, so that Europe/London loads on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/note/*.txt from the current output")
// fixedEnv is 29 Nov 2026 21:04:05 UTC in Europe/London, which is on GMT
// then.
func fixedEnv(t *testing.T) modules.Env {
t.Helper()
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
return modules.Env{
Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC),
Location: london,
TimeLayout: "02 Jan 15:04",
}
}
// previewText previews job on a TM-T88 in CP437: its lines, then its
// warnings.
func previewText(t *testing.T, job receipt.Job) string {
t.Helper()
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var b strings.Builder
for _, l := range p.Lines {
b.WriteString(l.Text)
b.WriteByte('\n')
}
if len(p.Warnings) > 0 {
b.WriteString("=== warnings\n")
for _, w := range p.Warnings {
b.WriteString(w)
b.WriteByte('\n')
}
}
return b.String()
}
type noFetch struct{}
func (noFetch) Fetch(context.Context, string) ([]byte, error) {
return nil, errors.New("previews do not fetch")
}
// TestNoteGoldens builds each testdata/note/*.json payload with a fixed
// clock and compares its preview with NAME.txt. Run with -update to rewrite
// the .txt files, then review the diff.
func TestNoteGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "note", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no payloads in testdata/note")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := modules.Note().Build(context.Background(), body, fixedEnv(t))
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("the note built an invalid job: %v", err)
}
got := previewText(t, job)
golden := filepath.Join("testdata", "note", name+".txt")
if *update {
if err := os.WriteFile(golden, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("%v (run go test -run TestNoteGoldens -update)", err)
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", golden, got, want)
}
})
}
}
// TestNoteMockup pins the note the formatters plan shows as mockup 5.
func TestNoteMockup(t *testing.T) {
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Fatal(err)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Milk, eggs and the good bread from the │\n" +
"│ bakery on Elm St. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [ ] Eggs │\n" +
"│ [√] Bread │\n" +
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
}
// TestNoteBuildsThePaperJob checks that the note still builds the job whose
// printed result was checked on the TM-T88IV, and whose bytes the receipt
// package pins: the shopping note, built at 08:56 on a host at UTC-6.
func TestNoteBuildsThePaperJob(t *testing.T) {
env := modules.Env{
Now: time.Date(2026, 11, 30, 14, 56, 39, 0, time.UTC),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "note.json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the note builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
}
func TestNotePayloadProblems(t *testing.T) {
items := make([]string, receipt.MaxItems+1)
for i := range items {
items[i] = fmt.Sprintf("%q", "item")
}
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"unknown field", `{"text":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"field in another case", `{"Text":"x"}`, []string{"Text: unknown field"}},
{"wrong type", `{"text":"x","items":"Milk","stamp":"no"}`, []string{"items: expected an array of strings", "stamp: expected true or false"}},
{"missing text", `{"title":"Shopping"}`, []string{"text: required"}},
{"blank text", `{"text":" \n "}`, []string{"text: required"}},
{"done index out of range", `{"text":"x","items":["Milk","Eggs"],"done":[5,-1]}`,
[]string{"done[0]: index 5 is out of range", "done[1]: index -1 is out of range"}},
{"done without items", `{"text":"x","done":[0]}`, []string{"done[0]: index 0 is out of range"}},
{"done repeated", `{"text":"x","items":["a","b"],"done":[1,1]}`, []string{"done[1]: index 1 is repeated"}},
{"more than 200 items", `{"text":"x","items":[` + strings.Join(items, ",") + `]}`, []string{"items: 201 items, limit is 200"}},
{"empty item", `{"text":"x","items":["a",""]}`, []string{"items[1]: must not be empty"}},
{"style", `{"text":"x","style":"ascii"}`, []string{"style: must be single, double, double-h or double-v"}},
{"every problem at once", `{"style":"bold","items":[""],"done":[3]}`, []string{
"text: required",
"style: must be single, double, double-h or double-v",
"items[0]: must not be empty",
"done[0]: index 3 is out of range",
}},
{"not an object", `["text"]`, []string{"body: expected a JSON object, got array"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Note().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
// TestNoteBuildsValidJobs checks that a payload the note accepts always
// builds a job that passes validation, at the limits too.
func TestNoteBuildsValidJobs(t *testing.T) {
items := make([]string, receipt.MaxItems)
for i := range items {
items[i] = fmt.Sprintf("%q", fmt.Sprint("item ", i))
}
bodies := []string{
`{"text":"x"}`,
`{"text":"x","items":[],"done":[]}`,
`{"text":"x","style":"DOUBLE-V","stamp":false}`,
`{"text":"x","items":[` + strings.Join(items, ",") + `],"done":[0,199]}`,
`{"title":"\u001b@","text":"\u0007","footer":"\t","items":["\u001bd"]}`,
}
for _, body := range bodies {
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", body, err)
continue
}
if err := job.Validate(); err != nil {
t.Errorf("%s: built an invalid job: %v", body, err)
}
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package modules turns plain payloads, such as a note's title, text and
// items, into receipt jobs built from the layout blocks. Each module owns
// its payload format; the HTTP routes and the command line look modules up
// by name in a Registry.
package modules
import (
"context"
"errors"
"fmt"
"maps"
"regexp"
"slices"
"strings"
"time"
"uberbringer/internal/pkg/receipt"
)
// ErrSkip is returned by Build when the payload asks for nothing to be
// printed.
var ErrSkip = errors.New("nothing to print")
// PayloadError lists every problem with a payload, each prefixed with the
// field it concerns, e.g. "done[0]: index 5 is out of range".
type PayloadError struct {
Problems []string
}
// Error implements error.
func (e *PayloadError) Error() string {
return "invalid payload: " + strings.Join(e.Problems, "; ")
}
// Env is what a module may know about the time a receipt is built at. A
// module never reads the clock itself, so that its output is reproducible.
type Env struct {
// Now is the time the receipt is built at.
Now time.Time
// Location is the time zone times are printed in. Nil means local time.
Location *time.Location
// TimeLayout is the Go time layout times are printed in, e.g.
// "02 Jan 15:04".
TimeLayout string
}
// Stamp returns Now in Location, formatted with TimeLayout.
func (e Env) Stamp() string {
loc := e.Location
if loc == nil {
loc = time.Local
}
return e.Now.In(loc).Format(e.TimeLayout)
}
// Module builds a receipt from its own payload format.
type Module interface {
// Name is the module's name in routes, e.g. "note" in
// /api/v1/print/note.
Name() string
// Description says in one line what the module prints.
Description() string
// Build turns body into a job. It returns a *PayloadError for a body
// that is not a valid payload, and ErrSkip for one that asks for
// nothing to be printed. The job it returns is expected to pass
// Job.Validate; one that does not is a bug in the module.
Build(ctx context.Context, body []byte, env Env) (receipt.Job, error)
}
// Info describes a module for listings.
type Info struct {
Name string
Description string
}
// validName is the form of a module name: it appears as a path segment.
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
// Registry holds the modules by name. It is safe for concurrent use once
// built.
type Registry struct {
modules map[string]Module
}
// NewRegistry returns a registry of mods. Each name must be unique and made
// of lowercase letters, digits and dashes, starting with a letter.
func NewRegistry(mods ...Module) (*Registry, error) {
r := &Registry{modules: make(map[string]Module, len(mods))}
for _, m := range mods {
name := m.Name()
if !validName.MatchString(name) {
return nil, fmt.Errorf("module name %q: want lowercase letters, digits and dashes, starting with a letter", name)
}
if _, ok := r.modules[name]; ok {
return nil, fmt.Errorf("module %q is registered twice", name)
}
r.modules[name] = m
}
return r, nil
}
// Get returns the module called name.
func (r *Registry) Get(name string) (Module, bool) {
m, ok := r.modules[name]
return m, ok
}
// List describes every module, sorted by name.
func (r *Registry) List() []Info {
infos := make([]Info, 0, len(r.modules))
for _, name := range slices.Sorted(maps.Keys(r.modules)) {
infos = append(infos, Info{Name: name, Description: r.modules[name].Description()})
}
return infos
}
+105
View File
@@ -0,0 +1,105 @@
package modules_test
import (
"context"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// stubModule is a module that prints one line of text.
type stubModule struct{ name, description string }
func (m stubModule) Name() string { return m.name }
func (m stubModule) Description() string { return m.description }
func (m stubModule) Build(context.Context, []byte, modules.Env) (receipt.Job, error) {
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: m.name}}}, nil
}
func TestRegistryLookup(t *testing.T) {
r, err := modules.NewRegistry(stubModule{"b", "B"}, modules.Note(), stubModule{"a-2", "A"})
if err != nil {
t.Fatal(err)
}
m, ok := r.Get("note")
if !ok || m.Name() != "note" {
t.Errorf("Get(note) = %v, %v", m, ok)
}
for _, name := range []string{"Note", "nope", ""} {
if _, ok := r.Get(name); ok {
t.Errorf("Get(%q) found a module", name)
}
}
got := r.List()
want := []modules.Info{{"a-2", "A"}, {"b", "B"}, {"note", "Boxed note with an optional checklist"}}
if len(got) != len(want) {
t.Fatalf("List() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("List()[%d] = %v, want %v", i, got[i], want[i])
}
}
}
func TestRegistryListIsNeverNil(t *testing.T) {
r, err := modules.NewRegistry()
if err != nil {
t.Fatal(err)
}
if got := r.List(); got == nil || len(got) != 0 {
t.Errorf("List() = %#v, want an empty list", got)
}
}
func TestRegistryRefusals(t *testing.T) {
tests := []struct {
name string
mods []modules.Module
wantErr string
}{
{"duplicate name", []modules.Module{stubModule{"note", ""}, modules.Note()}, `module "note" is registered twice`},
{"upper case", []modules.Module{stubModule{"Note", ""}}, `module name "Note"`},
{"empty", []modules.Module{stubModule{"", ""}}, `module name ""`},
{"slash", []modules.Module{stubModule{"a/b", ""}}, `module name "a/b"`},
{"leading digit", []modules.Module{stubModule{"1a", ""}}, `module name "1a"`},
{"too long", []modules.Module{stubModule{strings.Repeat("a", 33), ""}}, "module name"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.NewRegistry(tt.mods...)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("err = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
func TestEnvStamp(t *testing.T) {
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
summer := time.Date(2026, 7, 14, 20, 4, 5, 0, time.UTC)
tests := []struct {
env modules.Env
want string
}{
{modules.Env{Now: summer, Location: london, TimeLayout: "02 Jan 15:04"}, "14 Jul 21:04"},
{modules.Env{Now: summer, Location: time.UTC, TimeLayout: "02 Jan 15:04"}, "14 Jul 20:04"},
{modules.Env{Now: summer, Location: london, TimeLayout: "2006-01-02 15:04 MST"}, "2026-07-14 21:04 BST"},
}
for _, tt := range tests {
if got := tt.env.Stamp(); got != tt.want {
t.Errorf("Stamp() in %v with %q = %q, want %q", tt.env.Location, tt.env.TimeLayout, got, tt.want)
}
}
local := modules.Env{Now: summer, TimeLayout: time.RFC3339}
if got, want := local.Stamp(), summer.In(time.Local).Format(time.RFC3339); got != want {
t.Errorf("Stamp() without a location = %q, want local time %q", got, want)
}
}
+1
View File
@@ -0,0 +1 @@
{"title": "Packing", "text": "All done.", "items": ["Passport", "Charger", "Tickets"], "done": [0, 1, 2]}
+8
View File
@@ -0,0 +1,8 @@
┌─ Packing ──────────────────────────────┐
│ All done. │
│ │
│ [√] Passport │
│ [√] Charger │
│ [√] Tickets │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Footer", "text": "A footer replaces the time.", "footer": "from the kitchen"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Footer ───────────────────────────────┐
│ A footer replaces the time. │
└──────────────────── from the kitchen ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"text": "No title, but a checklist.", "items": ["One", "Two"]}
+7
View File
@@ -0,0 +1,7 @@
┌────────────────────────────────────────┐
│ No title, but a checklist. │
│ │
│ [ ] One │
│ [ ] Two │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "A title that is far too long to fit into the top border of the box", "text": "First paragraph.\nSecond paragraph, which is long enough to wrap inside the box.", "items": ["An item that is long enough to wrap onto a second line with a hanging indent", "“Curly quotes” — and an emoji 🎉"], "done": [1]}
+13
View File
@@ -0,0 +1,13 @@
┌─ A title that is far too long to f... ─┐
│ First paragraph. │
│ Second paragraph, which is long enough │
│ to wrap inside the box. │
│ │
│ [ ] An item that is long enough to │
│ wrap onto a second line with a │
│ hanging indent │
│ [√] "Curly quotes" -- and an emoji ? │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[0]: 1 character not in cp437 printed as ?
+1
View File
@@ -0,0 +1 @@
{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
+9
View File
@@ -0,0 +1,9 @@
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "No stamp", "text": "stamp false leaves the bottom border plain.", "stamp": false}
+5
View File
@@ -0,0 +1,5 @@
┌─ No stamp ─────────────────────────────┐
│ stamp false leaves the bottom border │
│ plain. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-h", "text": "style double-h", "style": "double-h", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╒═ Double-h ═════════════════════════════╕
│ style double-h │
│ │
│ [ ] a │
╘════════════════════════ 29 Nov 21:04 ══╛
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-v", "text": "style double-v", "style": "double-v", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╓─ Double-v ─────────────────────────────╖
║ style double-v ║
║ ║
║ [ ] a ║
╙──────────────────────── 29 Nov 21:04 ──╜
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Double", "text": "style double", "style": "double", "items": ["a"], "done": [0]}
+6
View File
@@ -0,0 +1,6 @@
╔═ Double ═══════════════════════════════╗
║ style double ║
║ ║
║ [√] a ║
╚════════════════════════ 29 Nov 21:04 ══╝
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Single", "text": "style single, written in capitals", "style": "SINGLE"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Single ───────────────────────────────┐
│ style single, written in capitals │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"text": "Back at 3."}
+4
View File
@@ -0,0 +1,4 @@
┌────────────────────────────────────────┐
│ Back at 3. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Reminder", "text": "Call the plumber about the kitchen tap before Friday."}
+5
View File
@@ -0,0 +1,5 @@
┌─ Reminder ─────────────────────────────┐
│ Call the plumber about the kitchen tap │
│ before Friday. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+79 -1
View File
@@ -80,16 +80,20 @@ var fields = []field{
{"columns", func(e Element) bool { return e.Columns != 0 }},
{"pairs", func(e Element) bool { return e.Pairs != nil }},
{"leader", func(e Element) bool { return e.Leader != "" }},
{"items", func(e Element) bool { return e.Items != nil }},
{"bullet", func(e Element) bool { return e.Bullet != "" }},
{"done", func(e Element) bool { return e.Done != nil }},
}
// blockOnly are the fields no other type takes.
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader")
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader items bullet done")
// blockFields are the fields each block takes at the top level.
var blockFields = map[string]map[string]bool{
TypeBox: fieldSet("text bold underline invert align size font children title title_style footer style padding fit columns"),
TypeRule: fieldSet("text bold align size font style columns"),
TypeKV: fieldSet("pairs leader size font columns"),
TypeList: fieldSet("items bullet done size font columns"),
}
// childFields are the fields each type takes inside a box.
@@ -98,6 +102,7 @@ var childFields = map[string]map[string]bool{
TypeFeed: fieldSet("lines"),
TypeRule: fieldSet("text bold align style"),
TypeKV: fieldSet("pairs leader"),
TypeList: fieldSet("items bullet done"),
}
// inherited are the fields a child takes from its box.
@@ -334,3 +339,76 @@ func (el Element) pairProblems() []string {
}
return problems
}
// listBullet selects what marks each item of a list.
type listBullet int
const (
bulletDot listBullet = iota
bulletDash
bulletNumber
bulletCheckbox
)
type listSpec struct {
bullet listBullet
columns int
size int
font escpos.Font
}
func (el Element) listSpec() (listSpec, error) {
s := listSpec{columns: el.Columns}
var err error
if s.size, s.font, err = el.blockScale(); err != nil {
return s, err
}
switch strings.ToLower(el.Bullet) {
case "", "dot":
s.bullet = bulletDot
case "dash":
s.bullet = bulletDash
case "number":
s.bullet = bulletNumber
case "checkbox":
s.bullet = bulletCheckbox
default:
return s, fmt.Errorf("bullet must be dot, dash, number or checkbox")
}
if err := checkColumns(el.Columns); err != nil {
return s, err
}
switch n := len(el.Items); {
case n == 0:
return s, fmt.Errorf("items: at least one item is required")
case n > MaxItems:
return s, fmt.Errorf("items: %d items, limit is %d", n, MaxItems)
}
return s, nil
}
// itemProblems reports every empty item and every problem with done: done
// on a list that is not a checklist, and an index that is out of range or
// repeated.
func (el Element) itemProblems() []string {
var problems []string
for i, item := range el.Items {
if item == "" {
problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i))
}
}
if len(el.Done) > 0 && !strings.EqualFold(el.Bullet, "checkbox") {
return append(problems, `done: only a list with bullet "checkbox" has done items`)
}
seen := make(map[int]bool, len(el.Done))
for i, index := range el.Done {
switch {
case index < 0 || index >= len(el.Items):
problems = append(problems, fmt.Sprintf("done[%d]: index %d is out of range", i, index))
case seen[index]:
problems = append(problems, fmt.Sprintf("done[%d]: index %d is repeated", i, index))
}
seen[index] = true
}
return problems
}
+86 -1
View File
@@ -1,6 +1,8 @@
package receipt
import (
"fmt"
"strconv"
"strings"
"uberbringer/internal/pkg/escpos"
@@ -67,6 +69,7 @@ const (
itemFeed
itemDivider
itemKV
itemList
)
// boxItem is one part of a box body, with its text already normalized.
@@ -88,6 +91,9 @@ type boxItem struct {
// itemKV.
pairs []kvRow
leader string
// itemList.
list []listRow
}
// kvRow is a Pair with its text normalized.
@@ -189,6 +195,9 @@ func (lo *layout) boxItems(el Element, spec boxSpec) []boxItem {
case TypeKV:
ks, _ := child.kvSpec()
items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)})
case TypeList:
ls, _ := child.listSpec()
items = append(items, boxItem{kind: itemList, list: lo.listRows(child, ls)})
}
}
return items
@@ -211,6 +220,16 @@ func (it boxItem) naturalWidth(limit int) int {
widest = max(widest, runeLen(p.key)+4+runeLen(p.value))
}
return min(widest, limit)
case itemList:
widest := 0
for _, row := range it.list {
bullet := runeLen(row.bullet)
room := max(limit-bullet, 1)
for _, text := range wrap(row.text, room, room) {
widest = max(widest, bullet+runeLen(text))
}
}
return min(widest, limit)
}
return 0
}
@@ -232,7 +251,8 @@ func (it boxItem) rows(width int) []string {
return rows
}
// contentLines lays out a text, feed or kv item at exactly width cells.
// contentLines lays out a text, feed, kv or list item at exactly width
// cells.
func (it boxItem) contentLines(width int) []blockLine {
switch it.kind {
case itemFeed:
@@ -243,6 +263,8 @@ func (it boxItem) contentLines(width int) []blockLine {
return lines
case itemKV:
return kvLines(it.pairs, it.leader, width)
case itemList:
return listLines(it.list, width)
}
var lines []blockLine
for _, row := range it.rows(width) {
@@ -387,6 +409,69 @@ func kvLines(rows []kvRow, leader string, width int) []blockLine {
return lines
}
// list lays out a list block on a line of cols cells.
func (lo *layout) list(el Element, spec listSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
return centre(listLines(lo.listRows(el, spec), width), width, cols)
}
// listRow is one list item: its bullet, with the space after it, and its
// text, normalized.
type listRow struct {
bullet, text string
}
// listRows gives each item of a list its bullet: "· ", "- ", a number
// right-aligned to the widest, or a checkbox, ticked for the done items.
func (lo *layout) listRows(el Element, spec listSpec) []listRow {
done := make(map[int]bool, len(el.Done))
for _, index := range el.Done {
done[index] = true
}
digits := len(strconv.Itoa(len(el.Items)))
rows := make([]listRow, len(el.Items))
for i, item := range el.Items {
var bullet string
switch spec.bullet {
case bulletDash:
bullet = "- "
case bulletNumber:
bullet = fmt.Sprintf("%*d. ", digits, i+1)
case bulletCheckbox:
bullet = "[ ] "
if done[i] {
bullet = "[" + checkMark(lo.cp) + "] "
}
default:
bullet = listDot(lo.cp) + " "
}
rows[i] = listRow{bullet: bullet, text: lo.text(item)}
}
return rows
}
// listLines lays out rows at exactly width cells: each bullet, then the
// item's text wrapped to the room after it, its further lines indented to
// line up with the first. On a line too narrow for the whole bullet, the
// bullet is cut so that one cell is left for the text.
func listLines(rows []listRow, width int) []blockLine {
width = max(width, 1)
var lines []blockLine
for _, row := range rows {
bullet := []rune(row.bullet)
indent := min(len(bullet), width-1)
room := width - indent
for i, text := range wrap(row.text, room, room) {
lead := spaces(indent)
if i == 0 {
lead = string(bullet[:indent])
}
lines = append(lines, blockLine{plain(lead + text + spaces(room-runeLen(text)))})
}
}
return lines
}
// narrowKVLines lays out rows on lines too narrow for a key, a leader and a
// value side by side: the key on a line of its own, then the value,
// right-aligned.
+1
View File
@@ -78,6 +78,7 @@ var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex
// TM-T88 in CP437 with the default options.
var paperReceipts = []struct{ job, hex string }{
{filepath.Join("..", "..", "..", "examples", "blocks.json"), filepath.Join("testdata", "paper", "blocks.hex")},
{filepath.Join("testdata", "paper", "note.json"), filepath.Join("testdata", "paper", "note.hex")},
}
// TestPaperReceipts fails when the bytes of a receipt checked on paper
+34 -8
View File
@@ -10,16 +10,19 @@ import (
"uberbringer/internal/pkg/receipt"
)
// FuzzBlocks lays out random boxes, rules and kv blocks on random printers
// and code pages, and checks that every line is exactly the block's width,
// no wider than the line, with the borders in the first and last columns,
// and that no control byte reaches the printer inside the text.
// FuzzBlocks lays out random boxes, rules, kv blocks and lists on random
// printers and code pages, and checks that every line is exactly the
// block's width, no wider than the line, with the borders in the first and
// last columns, and that no control byte reaches the printer inside the
// text.
func FuzzBlocks(f *testing.F) {
f.Add(uint8(0), uint8(0), uint8(0), uint8(1), uint8(0), uint8(1), false, uint8(0), "Title", "Footer", "Some text that wraps", "key", "value")
f.Add(uint8(0x3C), uint8(1), uint8(9), uint8(2), uint8(1), uint8(3), true, uint8(12), "“A long title” — with folds…", "", "line\nline\ttab 🎉👨\u200D👩\u200D👧", "k", "")
f.Add(uint8(1), uint8(2), uint8(6), uint8(0), uint8(0), uint8(0), false, uint8(200), "", "", "Label", "", "")
f.Add(uint8(2), uint8(3), uint8(4), uint8(1), uint8(1), uint8(2), false, uint8(7), "", "", "", "A key that is long", "a value that wraps over several lines")
f.Add(uint8(0xF8), uint8(4), uint8(3), uint8(2), uint8(0), uint8(0), true, uint8(3), "\x1b@\x00", "\x07", "\x1bd\x05 text \x1dV", "\x0a", "\x09")
f.Add(uint8(3), uint8(1), uint8(3), uint8(0), uint8(1), uint8(2), true, uint8(5), "A done item", "", "An item that wraps\nwith a hanging indent", "k", "v")
f.Add(uint8(0x80), uint8(0x83), uint8(2), uint8(0), uint8(0), uint8(1), true, uint8(0), "Title", "", "text", "", "")
f.Fuzz(func(t *testing.T, kind, printerSel, style, size, font, padding uint8, fit bool, columns uint8,
title, footer, text, key, value string) {
el := fuzzBlock(kind, style, size, font, padding, fit, columns, title, footer, text, key, value)
@@ -95,8 +98,9 @@ func fontOf(name string) escpos.Font {
return escpos.FontA
}
// fuzzBlock builds a box, rule or kv element from the fuzzer's values. The
// low bits of kind pick the type; for a box, the others pick its children.
// fuzzBlock builds a box, rule, kv or list element from the fuzzer's values.
// The low bits of kind pick the type; for a box, the others pick its
// children.
func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8, title, footer, text, key, value string) receipt.Element {
boxStyles := []string{"single", "double", "double-h", "double-v", "ascii"}
ruleStyles := []string{"single", "double", "light", "medium", "dark", "solid", "dashed", "dotted", "ascii"}
@@ -106,7 +110,7 @@ func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8,
if font%2 == 1 {
el.Font = "b"
}
switch kind % 3 {
switch kind % 4 {
case 0:
el.Type = "box"
el.Style = boxStyles[int(style)%len(boxStyles)]
@@ -136,15 +140,37 @@ func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8,
if children&8 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "feed", Lines: 1 + int(padding)%3})
}
if children&0x20 != 0 {
list := fuzzList(style, fit, title, text, value)
list.Size, list.Columns, list.Font = 0, 0, ""
el.Children = append(el.Children, list)
}
case 1:
el.Type = "rule"
el.Style = ruleStyles[int(style)%len(ruleStyles)]
el.Text = text
el.Align = aligns[int(padding)%3]
default:
case 2:
el.Type = "kv"
el.Leader = leaders[int(style)%len(leaders)]
el.Pairs = []receipt.Pair{{Key: key + "k", Value: value}, {Key: title + "t", Value: text, Bold: fit}}
default:
list := fuzzList(style, fit, title, text, value)
el.Type, el.Bullet, el.Items, el.Done = list.Type, list.Bullet, list.Items, list.Done
}
return el
}
// fuzzList builds a list whose items are the fuzzer's strings. style picks
// the bullet, and fit marks the first item done on a checklist.
func fuzzList(style uint8, fit bool, items ...string) receipt.Element {
bullets := []string{"dot", "dash", "number", "checkbox"}
el := receipt.Element{Type: "list", Bullet: bullets[int(style)%len(bullets)]}
for _, item := range items {
el.Items = append(el.Items, item+"i")
}
if fit && el.Bullet == "checkbox" {
el.Done = []int{0}
}
return el
}
+11
View File
@@ -113,6 +113,17 @@ var leaderFallbacks = map[string][]string{
"─": {"─", "-"},
}
// checkMark is the tick of a done checklist item: √, or x on code pages
// without it.
func checkMark(cp escpos.CodePage) string {
return firstPrintable([]string{"√"}, cp, "x")
}
// listDot is the bullet of a dotted list: ·, or . on code pages without it.
func listDot(cp escpos.CodePage) string {
return firstPrintable([]string{"·"}, cp, ".")
}
// rulePattern returns the fill of style that cp can print.
func rulePattern(style ruleStyle, cp escpos.CodePage) string {
return firstPrintable(rulePatterns[style], cp, "-")
+32 -17
View File
@@ -20,8 +20,8 @@ import (
// job.
var ErrTrailingData = errors.New("trailing data after the job")
// Element types. Box, rule and kv are blocks: they are laid out to the
// paper width when the job is rendered.
// Element types. Box, rule, kv and list are blocks: they are laid out to
// the paper width when the job is rendered.
const (
TypeText = "text"
TypeFeed = "feed"
@@ -33,6 +33,7 @@ const (
TypeBox = "box"
TypeRule = "rule"
TypeKV = "kv"
TypeList = "list"
)
// Job limits. MaxElements counts the children of boxes too.
@@ -40,6 +41,7 @@ const (
MaxElements = 500
MaxCopies = 5
MaxPairs = 100
MaxItems = 200
)
// Element defaults.
@@ -64,18 +66,19 @@ type Job struct {
}
// Element is one item on a receipt. Its type selects which fields apply. On
// the blocks (box, rule and kv) and inside a box, a field that does not
// apply is an error; on the other types it is ignored, except for the block
// fields. width and height mean character multipliers for text, module width
// and bar height for barcodes, and target width in dots for images. A
// block's width is set by columns, in characters of its own size and font,
// never by width; without columns a block spans the line. The enums list
// the canonical spellings: apart from type and leader, other letter case is
// accepted too, and so are a few aliases such as centre and ean-13.
// the blocks (box, rule, kv and list) and inside a box, a field that does
// not apply is an error; on the other types it is ignored, except for the
// block fields. width and height mean character multipliers for text,
// module width and bar height for barcodes, and target width in dots for
// images. A block's width is set by columns, in characters of its own size
// and font, never by width; without columns a block spans the line. The
// enums list the canonical spellings: apart from type and leader, other
// letter case is accepted too, and so are a few aliases such as centre and
// ean-13.
type Element struct {
// Type is the kind of element. box, rule and kv are blocks, laid out to
// the printer model's width when the job prints.
Type string `json:"type" jsonschema:"required,enum=text,enum=feed,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut,enum=box,enum=rule,enum=kv"`
// Type is the kind of element. box, rule, kv and list are blocks, laid
// out to the printer model's width when the job prints.
Type string `json:"type" jsonschema:"required,enum=text,enum=feed,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut,enum=box,enum=rule,enum=kv,enum=list"`
// Text is a text element's UTF-8 text, a box's body or a rule's label.
// \n starts a new line.
@@ -138,7 +141,7 @@ type Element struct {
Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"`
// Children are a box's body as elements, one level deep: text, feed,
// rule and kv. Set text or children, not both.
// rule, kv and list. Set text or children, not both.
Children []Element `json:"children,omitempty"`
// Title is text set into a box's top border.
Title string `json:"title,omitempty"`
@@ -165,6 +168,15 @@ type Element struct {
// Leader is the fill between a kv row's key and value: ".", the
// default, "·", " " (or "space"), "_", "-" or "─".
Leader string `json:"leader,omitempty" jsonschema:"enum=.,enum=·,enum= ,enum=space,enum=_,enum=-,enum=─"`
// Items are a list's items, 1-200, none empty; required for list. An
// item too long for its line wraps with a hanging indent.
Items []string `json:"items,omitempty" jsonschema:"minItems=1,maxItems=200,minLength=1"`
// Bullet marks each item of a list: dot, the default, dash, number
// (right-aligned to the widest number) or checkbox.
Bullet string `json:"bullet,omitempty" jsonschema:"enum=dot,enum=dash,enum=number,enum=checkbox"`
// Done are the indexes into items, from 0, of a checkbox list's ticked
// items, each once. They print as [√], or [x] on code pages without √.
Done []int `json:"done,omitempty" jsonschema:"uniqueItems=true,minimum=0,maximum=199"`
}
// Pair is one row of a kv block: a key, a leader and a value.
@@ -258,13 +270,13 @@ func (el Element) problems(path string, inBox bool) []string {
func (el Element) validate(inBox bool) []string {
if inBox {
switch el.Type {
case TypeText, TypeFeed, TypeRule, TypeKV:
case TypeText, TypeFeed, TypeRule, TypeKV, TypeList:
case TypeBox, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut:
return []string{"not allowed inside a box; place it after the box"}
case "":
return []string{"type is required"}
default:
return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule or kv)", el.Type)}
return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule, kv or list)", el.Type)}
}
}
problems := el.checkFields(inBox)
@@ -294,10 +306,13 @@ func (el Element) validate(inBox bool) []string {
case TypeKV:
_, err = el.kvSpec()
problems = append(problems, el.pairProblems()...)
case TypeList:
_, err = el.listSpec()
problems = append(problems, el.itemProblems()...)
case "":
err = fmt.Errorf("type is required")
default:
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule or kv)", el.Type)
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule, kv or list)", el.Type)
}
if err != nil {
problems = append(problems, err.Error())
+10 -3
View File
@@ -246,7 +246,7 @@ func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type {
case TypeText:
return p.text(el)
case TypeBox, TypeRule, TypeKV:
case TypeBox, TypeRule, TypeKV, TypeList:
return p.block(el)
case TypeFeed:
lines, err := el.feedLines()
@@ -361,8 +361,8 @@ func (p *printer) resetStyle() error {
return nil
}
// block lays out a box, rule or kv element and prints it line by line,
// each line left-justified and exactly as wide as the layout made it.
// block lays out a box, rule, kv or list element and prints it line by
// line, each line left-justified and exactly as wide as the layout made it.
func (p *printer) block(el Element) error {
lo := layout{cp: p.codePage}
var (
@@ -386,6 +386,13 @@ func (p *printer) block(el Element) error {
}
size, font = spec.size, spec.font
lines = lo.rule(el, spec, p.blockColumns(font, size))
case TypeList:
spec, err := el.listSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.list(el, spec, p.blockColumns(font, size))
default:
spec, err := el.kvSpec()
if err != nil {
+11
View File
@@ -111,6 +111,9 @@ func TestEnumTagsMatchValidation(t *testing.T) {
{"Leader", "leader", func(v string) []Element {
return []Element{{Type: TypeKV, Pairs: []Pair{{Key: "k", Value: "v"}}, Leader: v}}
}},
{"Bullet", "bullet", func(v string) []Element {
return []Element{{Type: TypeList, Items: []string{"i"}, Bullet: v}}
}},
}
for _, tt := range tests {
t.Run(tt.field, func(t *testing.T) {
@@ -193,6 +196,14 @@ func TestBoundTagsMatchValidation(t *testing.T) {
func(n int) Job { return one(kv(n, "k")) }},
{reflect.TypeFor[Pair](), "Key", "key", "minLength", "",
func(n int) Job { return one(kv(1, strings.Repeat("k", n))) }},
{reflect.TypeFor[Element](), "Items", "items", "minItems", "maxItems",
func(n int) Job { return one(Element{Type: TypeList, Items: slices.Repeat([]string{"i"}, n)}) }},
{reflect.TypeFor[Element](), "Items", "items", "minLength", "",
func(n int) Job { return one(Element{Type: TypeList, Items: []string{strings.Repeat("i", n)}}) }},
{reflect.TypeFor[Element](), "Done", "done", "minimum", "maximum",
func(n int) Job {
return one(Element{Type: TypeList, Bullet: "checkbox", Items: slices.Repeat([]string{"i"}, MaxItems), Done: []int{n}})
}},
}
for _, tt := range tests {
t.Run(tt.json, func(t *testing.T) {
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[x] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[x] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[xN
a
r
r
o
w
+- NAS REPORT ---------------------------+
| Host ........................... nas01 |
| Pool ................... tank (raidz2) |
| Used ............................. 94% |
+-- Services ----------------------------+
| · grafana up |
| · offsite-backup DOWN since 19:00 |
+------------------------ 29 Nov 21:04 --+
+- Shopping -----------------------------+
| Milk, eggs and the good bread from the |
| bakery on Elm St. |
| |
| [ ] Milk |
| [ ] Eggs |
| [x] Bread |
+------------------------ 29 Nov 21:04 --+
+------------------------+
| 1. A fit box |
| 2. shrinks to its list |
+------------------------+
- - - - - - - partial cut - - - - - - - -
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[√] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[√] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[√N
a
r
r
o
w
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
╔════════════════════════╗
║ 1. A fit box ║
║ 2. shrinks to its list ║
╚════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[x] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[x] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[xN
a
r
r
o
w
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [x] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
╔════════════════════════╗
║ 1. A fit box ║
║ 2. shrinks to its list ║
╚════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+27
View File
@@ -0,0 +1,27 @@
{"elements": [
{"type": "list", "items": ["Replace drive bay 3", "Order 2x 8 TB"]},
{"type": "list", "bullet": "dash", "items": ["Dashes", "for a plain list"]},
{"type": "list", "bullet": "number", "items": ["First item that is long enough to wrap with a hanging indent", "Second"]},
{"type": "list", "bullet": "checkbox", "items": ["Done item", "Open item"], "done": [0]},
{"type": "rule", "style": "dotted"},
{"type": "list", "bullet": "number", "items": ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve, which wraps to a hanging indent past the widest number"]},
{"type": "list", "items": ["A paragraph\nand a second one, both indented under the bullet", "\tA tab"]},
{"type": "list", "items": ["https://example.com/a/very/long/path/without/any/spaces/in/it"]},
{"type": "list", "bullet": "CHECKBOX", "columns": 24, "items": ["Centred in 24 columns", "Done"], "done": [1]},
{"type": "list", "size": 2, "bullet": "number", "items": ["Size 2", "Wraps at 21 columns of its own"]},
{"type": "list", "font": "b", "bullet": "dash", "items": ["Font B is fifty-six columns wide, so this line wraps later"]},
{"type": "list", "columns": 3, "bullet": "checkbox", "items": ["Narrow"], "done": [0]},
{"type": "box", "title": "NAS REPORT", "footer": "29 Nov 21:04", "children": [
{"type": "kv", "pairs": [{"key": "Host", "value": "nas01"}, {"key": "Pool", "value": "tank (raidz2)"}, {"key": "Used", "value": "94%", "bold": true}]},
{"type": "rule", "text": "Services", "align": "left"},
{"type": "list", "items": ["grafana up", "offsite-backup DOWN since 19:00"]}
]},
{"type": "box", "title": "Shopping", "footer": "29 Nov 21:04", "children": [
{"type": "text", "text": "Milk, eggs and the good bread from the bakery on Elm St."},
{"type": "feed"},
{"type": "list", "bullet": "checkbox", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
]},
{"type": "box", "fit": true, "style": "double", "children": [
{"type": "list", "bullet": "number", "items": ["A fit box", "shrinks to its list"]}
]}
]}
+13
View File
@@ -0,0 +1,13 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac42053686f707069
6e6720c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
bf0ab3204d696c6b2c206567677320616e642074686520676f6f642062726561
642066726f6d2074686520b30ab32062616b657279206f6e20456c6d2053742e
20202020202020202020202020202020202020202020b30ab320202020202020
2020202020202020202020202020202020202020202020202020202020202020
20b30ab3205b205d204d696c6b20202020202020202020202020202020202020
202020202020202020202020b30ab3205b205d20456767732020202020202020
2020202020202020202020202020202020202020202020b30ab3205bfb5d2042
7265616420202020202020202020202020202020202020202020202020202020
2020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4203330
204e6f762030383a353620c4c4d90a1b45001b2d001d42001d21001b4d001d56
4200
+7
View File
@@ -0,0 +1,7 @@
{"elements": [
{"type": "box", "title": "Shopping", "footer": "30 Nov 08:56", "children": [
{"type": "text", "text": "Milk, eggs and the good bread from the bakery on Elm St."},
{"type": "feed"},
{"type": "list", "bullet": "checkbox", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
]}
]}
+39 -2
View File
@@ -44,8 +44,10 @@ func TestValidateBlocks(t *testing.T) {
"elements[0].children[3] (cut): not allowed inside a box; place it after the box",
"elements[0].children[4] (barcode): not allowed inside a box; place it after the box",
}},
{"unknown child type", box(receipt.Element{Type: "list"}),
[]string{`elements[0].children[0] (list): unknown type "list" (inside a box, want text, feed, rule or kv)`}},
{"unknown child type", box(receipt.Element{Type: "table"}),
[]string{`elements[0].children[0] (table): unknown type "table" (inside a box, want text, feed, rule, kv or list)`}},
{"unknown type", receipt.Element{Type: "table"},
[]string{`elements[0] (table): unknown type "table" (want text, feed, qr, barcode, image, raw, cut, box, rule, kv or list)`}},
{"child without a type", box(receipt.Element{}),
[]string{"elements[0].children[0] (): type is required"}},
{"divider style", box(text, receipt.Element{Type: "rule", Style: "dark"}),
@@ -83,6 +85,31 @@ func TestValidateBlocks(t *testing.T) {
{"no pairs", receipt.Element{Type: "kv"}, []string{"elements[0] (kv): pairs: at least one pair is required"}},
{"too many pairs", receipt.Element{Type: "kv", Pairs: manyPairs(101)}, []string{"elements[0] (kv): pairs: 101 pairs, limit is 100"}},
{"kv size", receipt.Element{Type: "kv", Size: 9, Pairs: []receipt.Pair{{Key: "a"}}}, []string{"elements[0] (kv): size must be 1-3"}},
{"no items", receipt.Element{Type: "list"}, []string{"elements[0] (list): items: at least one item is required"}},
{"too many items", receipt.Element{Type: "list", Items: manyItems(201)}, []string{"elements[0] (list): items: 201 items, limit is 200"}},
{"empty item", receipt.Element{Type: "list", Items: []string{"a", ""}}, []string{"elements[0] (list): items[1]: must not be empty"}},
{"bullet", receipt.Element{Type: "list", Bullet: "star", Items: []string{"a"}},
[]string{"elements[0] (list): bullet must be dot, dash, number or checkbox"}},
{"done without checkboxes", receipt.Element{Type: "list", Bullet: "number", Items: []string{"a"}, Done: []int{0}},
[]string{`elements[0] (list): done: only a list with bullet "checkbox" has done items`}},
{"done out of range and repeated", receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a", "b"}, Done: []int{1, 2, -1, 1}},
[]string{
"elements[0] (list): done[1]: index 2 is out of range",
"elements[0] (list): done[2]: index -1 is out of range",
"elements[0] (list): done[3]: index 1 is repeated",
}},
{"list size and columns", receipt.Element{Type: "list", Size: 4, Columns: 300, Items: []string{"a"}},
[]string{"elements[0] (list): size must be 1-3"}},
{"list columns", receipt.Element{Type: "list", Columns: 300, Items: []string{"a"}},
[]string{"elements[0] (list): columns must be 1-255"}},
{"field that does not apply to a list", receipt.Element{Type: "list", Items: []string{"a"}, Bold: true, Leader: "."},
[]string{`elements[0] (list): field "bold" does not apply to list`, `elements[0] (list): field "leader" does not apply to list`}},
{"list fields on an old type", receipt.Element{Type: "text", Text: "x", Items: []string{"a"}, Done: []int{0}},
[]string{`elements[0] (text): field "items" does not apply to text`, `elements[0] (text): field "done" does not apply to text`}},
{"list fields inside a box", box(receipt.Element{Type: "list", Items: []string{"a"}, Columns: 10, Font: "b"}),
[]string{"elements[0].children[0] (list): font is inherited from the box", `elements[0].children[0] (list): field "columns" does not apply to list inside a box`}},
{"list problems inside a box", box(receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a"}, Done: []int{3}}),
[]string{"elements[0].children[0] (list): done[0]: index 3 is out of range"}},
{"old types stay lenient", receipt.Element{Type: "feed", Text: "ignored", Bold: true}, nil},
{"a full box", receipt.Element{
@@ -95,6 +122,8 @@ func TestValidateBlocks(t *testing.T) {
}}, nil},
{"a full rule", receipt.Element{Type: "rule", Style: "dashed", Text: "l", Align: "right", Bold: true, Columns: 255, Size: 3, Font: "a"}, nil},
{"a full kv", receipt.Element{Type: "kv", Leader: "space", Columns: 1, Size: 1, Font: "B", Pairs: manyPairs(100)}, nil},
{"a full list", receipt.Element{Type: "list", Bullet: "Checkbox", Columns: 1, Size: 3, Font: "b", Items: manyItems(200), Done: []int{0, 199}}, nil},
{"a list in a box", box(receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a", "b"}, Done: []int{1}}), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -106,6 +135,14 @@ func TestValidateBlocks(t *testing.T) {
}
}
func manyItems(n int) []string {
items := make([]string, n)
for i := range items {
items[i] = "item"
}
return items
}
func TestValidateCountsChildren(t *testing.T) {
children := make([]receipt.Element, receipt.MaxElements)
for i := range children {