Files
uberbringer/internal/pkg/receipt/blocklayout.go
T
57_WolveandClaude Opus 5.5 4562f0cebb
Security / Vulnerability check (push) Successful in 50s
Test / Lint and test (push) Successful in 1m59s
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>
2026-11-30 00:49:45 -06:00

406 lines
11 KiB
Go

package receipt
import (
"strings"
"uberbringer/internal/pkg/escpos"
)
// Room a box needs around its title and footer, and a rule or divider
// around its label: corners, fills of at least one (title, footer) or two
// (labels) characters, and a space on each side of the text.
const (
inlineTitleRoom = 6 // ┌─ Title ─┐
cappedTitleRoom = 8 // ╔═╡ Title ╞═╗
footerRoom = 7 // └─ footer ──┘
labelRoom = 6 // ── Label ──
minBoxWidth = 3
// kvMinWidth fits a one-character key, a space, a two-character
// leader, a space and a one-character value.
kvMinWidth = 6
)
// layout lays out blocks in one code page. It normalizes their text as it
// goes and counts the characters that print as '?'.
type layout struct {
cp escpos.CodePage
unknown int
}
func (lo *layout) text(s string) string {
s, n := normalize(s, lo.cp)
lo.unknown += n
return expandTabs(s, 0)
}
func (lo *layout) line(s string) string {
s, n := normalizeLine(s, lo.cp)
lo.unknown += n
return s
}
// centre places lines of width cells in the middle of cols cells.
func centre(lines []blockLine, width, cols int) []blockLine {
margin := (cols - width) / 2
if margin <= 0 {
return lines
}
for i, l := range lines {
lines[i] = append(blockLine{plain(spaces(margin))}, l...)
}
return lines
}
// blockWidth is the width of a block with the given columns field on a
// line of cols cells.
func blockWidth(columns, cols int) int {
if columns > 0 {
return min(columns, cols)
}
return cols
}
// Kinds of item in a box body.
const (
itemText = iota
itemFeed
itemDivider
itemKV
)
// boxItem is one part of a box body, with its text already normalized.
type boxItem struct {
kind int
// itemText.
text string
style textStyle
align escpos.Justification
wrap bool
// itemFeed.
lines int
// itemDivider: label, style and alignment, and the weight of the line.
double bool
// itemKV.
pairs []kvRow
leader string
}
// kvRow is a Pair with its text normalized.
type kvRow struct {
key, value string
bold bool
}
// box lays out a box on a line of cols cells. Every line it returns, apart
// from the centring margin, is exactly the box width.
func (lo *layout) box(el Element, spec boxSpec, cols int) []blockLine {
set := bordersFor(spec.style, lo.cp)
items := lo.boxItems(el, spec)
title, footer := lo.line(el.Title), lo.line(el.Footer)
titleRoom := inlineTitleRoom
if spec.capped {
titleRoom = cappedTitleRoom
}
width := blockWidth(spec.columns, cols)
padding := spec.padding
if spec.fit {
need := minBoxWidth + 2*padding
if title != "" {
need = max(need, runeLen(title)+titleRoom)
}
if footer != "" {
need = max(need, runeLen(footer)+footerRoom)
}
for _, it := range items {
if it.kind == itemDivider {
if it.text != "" {
// The label needs its room inside the two junctions.
need = max(need, runeLen(it.text)+labelRoom+2)
}
continue
}
need = max(need, it.naturalWidth(width-2-2*padding)+2+2*padding)
}
width = min(width, need)
}
// Narrow boxes give up padding before they give up content.
width = max(width, minBoxWidth)
padding = min(padding, (width-minBoxWidth)/2)
content := width - 2 - 2*padding
lines := []blockLine{set.top(title, spec.capped, width)}
for _, it := range items {
if it.kind == itemDivider {
lines = append(lines, lo.divider(set, it, width))
continue
}
for _, row := range it.contentLines(content) {
line := blockLine{plain(string(set.vertical) + spaces(padding))}
line = append(line, row...)
line = append(line, plain(spaces(padding)+string(set.vertical)))
lines = append(lines, line)
}
}
lines = append(lines, set.bottom(footer, width))
return centre(lines, width, cols)
}
// boxItems turns the body of a box, its text or its children, into items.
// The job has been validated, so the children's specs parse; their errors
// are not checked again here.
func (lo *layout) boxItems(el Element, spec boxSpec) []boxItem {
if len(el.Children) == 0 {
return []boxItem{{kind: itemText, text: lo.text(el.Text), style: spec.text, align: spec.align, wrap: true}}
}
var items []boxItem
for _, child := range el.Children {
switch child.Type {
case TypeText:
ts, _ := child.textSpec()
align := ts.align
if child.Align == "" {
align = spec.align
}
items = append(items, boxItem{
kind: itemText,
text: lo.text(child.Text),
style: textStyle{bold: ts.bold, underline: ts.underline, invert: ts.invert},
align: align,
wrap: ts.wrap,
})
case TypeFeed:
n, _ := child.feedLines()
items = append(items, boxItem{kind: itemFeed, lines: int(n)})
case TypeRule:
rs, _ := child.ruleSpec(true)
items = append(items, boxItem{
kind: itemDivider,
text: lo.line(child.Text),
style: textStyle{bold: rs.bold},
align: rs.align,
double: rs.style == ruleDouble,
})
case TypeKV:
ks, _ := child.kvSpec()
items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)})
}
}
return items
}
// naturalWidth is the content width a text or kv item needs, given at most
// limit cells; fit boxes shrink to the widest item.
func (it boxItem) naturalWidth(limit int) int {
limit = max(limit, 1)
switch it.kind {
case itemText:
widest := 0
for _, row := range it.rows(limit) {
widest = max(widest, runeLen(row))
}
return widest
case itemKV:
widest := 0
for _, p := range it.pairs {
widest = max(widest, runeLen(p.key)+4+runeLen(p.value))
}
return min(widest, limit)
}
return 0
}
// rows splits a text item into lines of at most width runes.
func (it boxItem) rows(width int) []string {
if it.wrap {
return wrap(it.text, width, width)
}
var rows []string
for _, para := range strings.Split(it.text, "\n") {
r := []rune(para)
for len(r) > width {
rows = append(rows, string(r[:width]))
r = r[width:]
}
rows = append(rows, string(r))
}
return rows
}
// contentLines lays out a text, feed or kv item at exactly width cells.
func (it boxItem) contentLines(width int) []blockLine {
switch it.kind {
case itemFeed:
lines := make([]blockLine, it.lines)
for i := range lines {
lines[i] = blockLine{plain(spaces(width))}
}
return lines
case itemKV:
return kvLines(it.pairs, it.leader, width)
}
var lines []blockLine
for _, row := range it.rows(width) {
n := runeLen(row)
left := 0
switch it.align {
case escpos.JustifyCenter:
left = (width - n) / 2
case escpos.JustifyRight:
left = width - n
}
lines = append(lines, blockLine{
plain(spaces(left)),
{text: row, style: it.style},
plain(spaces(width - n - left)),
})
}
return lines
}
// top draws the top border, with the title set into it.
func (b borders) top(title string, capped bool, width int) blockLine {
h := string(b.horizontal)
inner := width - 2
room := inlineTitleRoom
if capped {
room = cappedTitleRoom
}
title = truncate(title, width-room)
if title == "" {
return blockLine{plain(string(b.topLeft) + fill(h, inner) + string(b.topRight))}
}
head := string(b.topLeft) + h + " "
tail := " "
if capped {
head = string(b.topLeft) + h + string(b.capLeft) + " "
tail = " " + string(b.capRight)
}
rest := width - runeLen(head) - runeLen(title) - runeLen(tail) - 1
return blockLine{
plain(head),
plain(title),
plain(tail + fill(h, rest) + string(b.topRight)),
}
}
// bottom draws the bottom border, with the footer set into it on the right.
func (b borders) bottom(footer string, width int) blockLine {
h := string(b.horizontal)
footer = truncate(footer, width-footerRoom)
if footer == "" {
return blockLine{plain(string(b.bottomLeft) + fill(h, width-2) + string(b.bottomRight))}
}
rest := width - runeLen(footer) - 6
return blockLine{
plain(string(b.bottomLeft) + fill(h, rest) + " "),
plain(footer),
plain(" " + fill(h, 2) + string(b.bottomRight)),
}
}
// divider draws a rule inside a box, joined to its borders.
func (lo *layout) divider(b borders, it boxItem, width int) blockLine {
left, h, right := b.divider(it.double, lo.cp)
line := blockLine{plain(string(left))}
line = append(line, labelled(string(h), it.text, it.style, it.align, width-2)...)
return append(line, plain(string(right)))
}
// labelled draws a line of pattern, width cells long, with label set into
// it at align.
func labelled(pattern, label string, style textStyle, align escpos.Justification, width int) blockLine {
label = truncate(label, width-labelRoom)
if label == "" {
return blockLine{plain(fill(pattern, width))}
}
rest := width - runeLen(label) - 2
var left int
switch align {
case escpos.JustifyLeft:
left = 2
case escpos.JustifyRight:
left = rest - 2
default:
left = rest / 2
}
return blockLine{
plain(fillTowards(pattern, left, true) + " "),
{text: label, style: style},
plain(" " + fillTowards(pattern, rest-left, false)),
}
}
// rule lays out a rule on a line of cols cells.
func (lo *layout) rule(el Element, spec ruleSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
line := labelled(rulePattern(spec.style, lo.cp), lo.line(el.Text), textStyle{bold: spec.bold}, spec.align, width)
return centre([]blockLine{line}, width, cols)
}
// kv lays out a kv block on a line of cols cells.
func (lo *layout) kv(el Element, spec kvSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
lines := kvLines(lo.kvRows(el.Pairs), leaderFor(spec.leader, lo.cp), width)
return centre(lines, width, cols)
}
func (lo *layout) kvRows(pairs []Pair) []kvRow {
rows := make([]kvRow, len(pairs))
for i, p := range pairs {
rows[i] = kvRow{key: lo.line(p.Key), value: lo.text(p.Value), bold: p.Bold}
}
return rows
}
// kvLines lays out rows at exactly width cells: the key, a space, a leader
// of at least two, a space and the value. A value too long for the line
// wraps to the room after the key, and its further lines are right-aligned.
func kvLines(rows []kvRow, leader string, width int) []blockLine {
if width < kvMinWidth {
return narrowKVLines(rows, width)
}
var lines []blockLine
for _, row := range rows {
style := textStyle{bold: row.bold}
key := truncate(row.key, max(width-8, 1))
room := max(width-runeLen(key)-4, 1)
values := wrap(row.value, room, room)
first := values[0]
dots := width - runeLen(key) - 2 - runeLen(first)
tail := blockLine{plain(" "), {text: first, style: style}}
if first == "" {
dots++
tail = nil
}
line := blockLine{{text: key, style: style}, plain(" " + fill(leader, dots))}
lines = append(lines, append(line, tail...))
for _, v := range values[1:] {
lines = append(lines, blockLine{plain(spaces(width - runeLen(v))), {text: v, style: style}})
}
}
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.
func narrowKVLines(rows []kvRow, width int) []blockLine {
width = max(width, 1)
var lines []blockLine
for _, row := range rows {
style := textStyle{bold: row.bold}
key := truncate(row.key, width)
lines = append(lines, blockLine{{text: key, style: style}, plain(spaces(width - runeLen(key)))})
for _, v := range wrap(row.value, width, width) {
lines = append(lines, blockLine{plain(spaces(width - runeLen(v))), {text: v, style: style}})
}
}
return lines
}