Add the list block and the module layer with the note module
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:
1 parent
6b2e402f1a
commit
3e9779f71a
69 files changed
+3092
-262
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -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())
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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
@@ -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
@@ -0,0 +1,13 @@
|
||||
1b401b74001b61001b4d001d21001b45001b2d001d4200dac42053686f707069
|
||||
6e6720c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
|
||||
bf0ab3204d696c6b2c206567677320616e642074686520676f6f642062726561
|
||||
642066726f6d2074686520b30ab32062616b657279206f6e20456c6d2053742e
|
||||
20202020202020202020202020202020202020202020b30ab320202020202020
|
||||
2020202020202020202020202020202020202020202020202020202020202020
|
||||
20b30ab3205b205d204d696c6b20202020202020202020202020202020202020
|
||||
202020202020202020202020b30ab3205b205d20456767732020202020202020
|
||||
2020202020202020202020202020202020202020202020b30ab3205bfb5d2042
|
||||
7265616420202020202020202020202020202020202020202020202020202020
|
||||
2020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4203330
|
||||
204e6f762030383a353620c4c4d90a1b45001b2d001d42001d21001b4d001d56
|
||||
4200
|
||||
@@ -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]}
|
||||
]}
|
||||
]}
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user