Add box, rule and kv blocks, text folding and receipt preview
Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.
- receipt: box, rule and kv elements, laid out when the job renders from
the printer profile, size and font (never fixed widths). Boxes take a
title (inline or capped), a footer, padding, fit and columns, and a
body of text or children (text, feed, kv, and rules as dividers joined
to the borders). Glyphs a code page lacks fall back per set: double-h
and double-v to double, then single, then ascii; a missing junction
switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
checks fields per block type, allows one level of children and counts
them toward the 500-element limit. Block fields on the older types are
problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
trademark), as the owner approved on 2026-11-29. An emoji sequence
prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
command stream back as the printer would print it. It takes the
profile so that it can follow the printer's own wrapping and
alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
too_many_lines on preview; printer.box_line_spacing (default 0).
Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9fdea32b4f
commit
4562f0cebb
109 files changed
+6383
-487
No files matched your search
+124
-20
@@ -3,16 +3,25 @@
|
||||
package receipt
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// Element types.
|
||||
// ErrTrailingData is returned by DecodeJob for input with more after the
|
||||
// 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.
|
||||
const (
|
||||
TypeText = "text"
|
||||
TypeFeed = "feed"
|
||||
@@ -21,12 +30,16 @@ const (
|
||||
TypeImage = "image"
|
||||
TypeRaw = "raw"
|
||||
TypeCut = "cut"
|
||||
TypeBox = "box"
|
||||
TypeRule = "rule"
|
||||
TypeKV = "kv"
|
||||
)
|
||||
|
||||
// Job limits.
|
||||
// Job limits. MaxElements counts the children of boxes too.
|
||||
const (
|
||||
MaxElements = 500
|
||||
MaxCopies = 5
|
||||
MaxPairs = 100
|
||||
)
|
||||
|
||||
// Element defaults.
|
||||
@@ -45,10 +58,13 @@ type Job struct {
|
||||
Copies int `json:"copies,omitempty"`
|
||||
}
|
||||
|
||||
// Element is one item on a receipt. Type selects which fields apply; fields
|
||||
// that do not apply to the type are ignored. Width and Height mean character
|
||||
// multipliers for text, module width and bar height for barcodes, and target
|
||||
// width in dots for images.
|
||||
// Element is one item on a receipt. 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.
|
||||
type Element struct {
|
||||
Type string `json:"type"`
|
||||
|
||||
@@ -83,6 +99,42 @@ type Element struct {
|
||||
|
||||
// Cut.
|
||||
Mode string `json:"mode,omitempty"`
|
||||
|
||||
// Blocks. Style is the border or line style of a box or rule. Children
|
||||
// are the body of a box, one level deep.
|
||||
Children []Element `json:"children,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
TitleStyle string `json:"title_style,omitempty"`
|
||||
Footer string `json:"footer,omitempty"`
|
||||
Style string `json:"style,omitempty"`
|
||||
Padding *int `json:"padding,omitempty"`
|
||||
Fit bool `json:"fit,omitempty"`
|
||||
Columns int `json:"columns,omitempty"`
|
||||
Pairs []Pair `json:"pairs,omitempty"`
|
||||
Leader string `json:"leader,omitempty"`
|
||||
}
|
||||
|
||||
// Pair is one row of a kv block: a key, a leader and a value.
|
||||
type Pair struct {
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
Bold bool `json:"bold,omitempty"`
|
||||
}
|
||||
|
||||
// DecodeJob strictly decodes one JSON job. An unknown field is an error, so
|
||||
// that a typo fails loudly instead of being ignored, and so is anything
|
||||
// after the job. It does not validate the job.
|
||||
func DecodeJob(data []byte) (Job, error) {
|
||||
var job Job
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&job); err != nil {
|
||||
return Job{}, err
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return Job{}, ErrTrailingData
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
// ValidationError lists every problem found in a job.
|
||||
@@ -99,19 +151,23 @@ func (e *ValidationError) Error() string {
|
||||
// to the printer unless the entire receipt can be printed.
|
||||
func (j Job) Validate() error {
|
||||
var problems []string
|
||||
switch {
|
||||
children := 0
|
||||
for _, el := range j.Elements {
|
||||
children += len(el.Children)
|
||||
}
|
||||
switch total := len(j.Elements) + children; {
|
||||
case len(j.Elements) == 0:
|
||||
problems = append(problems, "elements: at least one element is required")
|
||||
case len(j.Elements) > MaxElements:
|
||||
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", len(j.Elements), MaxElements))
|
||||
case total > MaxElements && children > 0:
|
||||
problems = append(problems, fmt.Sprintf("elements: %d elements including %d box children, limit is %d", total, children, MaxElements))
|
||||
case total > MaxElements:
|
||||
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", total, MaxElements))
|
||||
}
|
||||
if j.Copies < 0 || j.Copies > MaxCopies {
|
||||
problems = append(problems, fmt.Sprintf("copies must be 1-%d", MaxCopies))
|
||||
}
|
||||
for i, el := range j.Elements {
|
||||
if err := el.validate(); err != nil {
|
||||
problems = append(problems, fmt.Sprintf("elements[%d] (%s): %v", i, el.Type, err))
|
||||
}
|
||||
problems = append(problems, el.problems(fmt.Sprintf("elements[%d]", i), false)...)
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return &ValidationError{Problems: problems}
|
||||
@@ -123,11 +179,44 @@ func (j Job) copies() int {
|
||||
return max(j.Copies, 1)
|
||||
}
|
||||
|
||||
func (el Element) validate() error {
|
||||
// problems returns every problem with el, and with its children when it is
|
||||
// a box, each prefixed with its path, e.g. "elements[0].children[3] (qr): ".
|
||||
func (el Element) problems(path string, inBox bool) []string {
|
||||
prefix := fmt.Sprintf("%s (%s): ", path, el.Type)
|
||||
var messages []string
|
||||
for _, msg := range el.validate(inBox) {
|
||||
messages = append(messages, prefix+msg)
|
||||
}
|
||||
if el.Type == TypeBox && !inBox {
|
||||
for i, child := range el.Children {
|
||||
messages = append(messages, child.problems(fmt.Sprintf("%s.children[%d]", path, i), true)...)
|
||||
}
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// validate checks el's own fields. inBox is set for the children of a box,
|
||||
// which allow fewer types and fields.
|
||||
func (el Element) validate(inBox bool) []string {
|
||||
if inBox {
|
||||
switch el.Type {
|
||||
case TypeText, TypeFeed, TypeRule, TypeKV:
|
||||
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)}
|
||||
}
|
||||
}
|
||||
problems := el.checkFields(inBox)
|
||||
var err error
|
||||
switch el.Type {
|
||||
case TypeText:
|
||||
_, err = el.textSpec()
|
||||
if err == nil && inBox && el.Newline != nil && !*el.Newline {
|
||||
err = fmt.Errorf("newline:false is not allowed inside a box")
|
||||
}
|
||||
case TypeFeed:
|
||||
_, err = el.feedLines()
|
||||
case TypeQR:
|
||||
@@ -140,12 +229,22 @@ func (el Element) validate() error {
|
||||
_, err = el.rawBytes()
|
||||
case TypeCut:
|
||||
_, err = el.cutMode()
|
||||
case TypeBox:
|
||||
_, err = el.boxSpec()
|
||||
case TypeRule:
|
||||
_, err = el.ruleSpec(inBox)
|
||||
case TypeKV:
|
||||
_, err = el.kvSpec()
|
||||
problems = append(problems, el.pairProblems()...)
|
||||
case "":
|
||||
err = fmt.Errorf("type is required")
|
||||
default:
|
||||
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw or cut)", el.Type)
|
||||
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule or kv)", el.Type)
|
||||
}
|
||||
return err
|
||||
if err != nil {
|
||||
problems = append(problems, err.Error())
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
type textSpec struct {
|
||||
@@ -187,15 +286,20 @@ func (el Element) textSpec() (textSpec, error) {
|
||||
if s.align, err = parseAlign(el.Align); err != nil {
|
||||
return s, err
|
||||
}
|
||||
switch el.Underline {
|
||||
case 0, 1, 2:
|
||||
s.underline = escpos.Underline(el.Underline)
|
||||
default:
|
||||
return s, fmt.Errorf("underline must be 0, 1 or 2")
|
||||
if s.underline, err = parseUnderline(el.Underline); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func parseUnderline(n int) (escpos.Underline, error) {
|
||||
switch n {
|
||||
case 0, 1, 2:
|
||||
return escpos.Underline(n), nil
|
||||
}
|
||||
return 0, fmt.Errorf("underline must be 0, 1 or 2")
|
||||
}
|
||||
|
||||
func (el Element) feedLines() (uint8, error) {
|
||||
switch {
|
||||
case el.Lines == 0:
|
||||
|
||||
Reference in new issue
Block a user