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
+24
-351
@@ -1,6 +1,6 @@
|
||||
# Plan: CP437 blocks, modules and ntfy printing
|
||||
|
||||
Status: **phase 1 in progress.** Every design decision for phases 1-4 is made; the open questions left are an assumed default, config values, a calibration check and the second printer. Each phase runs in its own session, briefed from its section.
|
||||
Status: **phase 1 is done**: box, rule and kv, text folding and the preview are built and checked on paper (README § Blocks, design.md). Phases 2-5 are not started. Every design decision for phases 2-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section.
|
||||
|
||||
## Decisions (owner, 2026-11-29)
|
||||
|
||||
@@ -42,8 +42,8 @@ Ideas taken from the other designs:
|
||||
- From Design 2 (templates): fit boxes, a hand-written markdown subset with no new dependency, a plain fallback receipt, a since=<time> cursor, token scopes, and '?' warnings in preview.
|
||||
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
|
||||
|
||||
WHAT SHIPS WHEN (about 12-13 developer days to the end of phase 4)
|
||||
1. Boxes and preview, 3-4 days. One /print element gives the single or double CP437 boxes the owner liked. POST /api/v1/preview and `uberbringer preview` show the exact output without using paper.
|
||||
WHAT SHIPS WHEN (about 10 developer days to the end of phase 4)
|
||||
1. Boxes and preview: done.
|
||||
2. Notes and modules, 2 days. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
|
||||
3. Notifications, 3 days. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged. After this phase, ntfy printing needs only a client.yml entry and no jq.
|
||||
4. Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
|
||||
@@ -51,15 +51,13 @@ WHAT SHIPS WHEN (about 12-13 developer days to the end of phase 4)
|
||||
|
||||
BACKWARD COMPATIBILITY
|
||||
- Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
|
||||
- A byte-compatibility test, captured before any renderer change, pins today's output.
|
||||
- One deliberate change (approved): characters that print as '?' today print as close ASCII matches: smart quotes, dashes and the ellipsis. An emoji sequence prints as one '?' instead of several.
|
||||
- Emoji are removed only on the module and ntfy paths.
|
||||
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later phases keep them passing.
|
||||
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
|
||||
|
||||
WHERE THE JUDGES DISAGREED, AND WHAT THIS PLAN CHOSE
|
||||
- list: in (phase 2), because the note module needs checklists.
|
||||
- spans, table, group, banner, nested boxes and goldmark: deferred.
|
||||
- Geometry checks in the HTTP handler (Renderer.Check): rejected. Layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
|
||||
- Tight line spacing: off by default until a calibration print has been checked.
|
||||
- Scoped tokens: in phase 3, before any integration token is handed out.
|
||||
- Quiet hours: phase 4, as a morning digest (owner decision).
|
||||
|
||||
@@ -75,14 +73,9 @@ Before phase 4 (config, not design):
|
||||
2. Topics and auth: which topics and quiet-hours window to configure. A
|
||||
dedicated read-only ntfy user with an access token is assumed.
|
||||
|
||||
After phase 1's calibration print:
|
||||
|
||||
3. Are the small gaps in vertical borders acceptable, or should boxes use
|
||||
tighter line spacing (box_line_spacing)?
|
||||
|
||||
When the second printer arrives:
|
||||
|
||||
4. Which jobs and ntfy topics go to which printer, and should urgent messages
|
||||
3. Which jobs and ntfy topics go to which printer, and should urgent messages
|
||||
print on both?
|
||||
|
||||
## Mockups (42 columns, CP437)
|
||||
@@ -154,21 +147,6 @@ Prune finished
|
||||
│ [√] Bread │
|
||||
└──────────────────────── 29 Nov 21:04 ──┘
|
||||
|
||||
--- 6. Double box, capped title, centred
|
||||
╔═╡ ACHTUNG ╞════════════════════════════╗
|
||||
║ The coffee machine is being descaled. ║
|
||||
║ Do not use until 10:30. ║
|
||||
╚════════════════════════════════════════╝
|
||||
|
||||
--- 7. fit:true, one element each
|
||||
┌─────────────────────┐
|
||||
│ !!! ACHTUNG !!! │
|
||||
└─────────────────────┘
|
||||
|
||||
╔═══════════════════╗
|
||||
║ !!! ACHTUNG !!! ║
|
||||
╚═══════════════════╝
|
||||
|
||||
--- 8. Box with kv, labelled rule and list
|
||||
┌─ NAS REPORT ───────────────────────────┐
|
||||
│ Host ........................... nas01 │
|
||||
@@ -180,23 +158,6 @@ Prune finished
|
||||
└──────────────────────── 29 Nov 21:04 ──┘
|
||||
A pair can set "bold" (e.g. Used 94%).
|
||||
|
||||
--- 9a. rule: single double light medium
|
||||
──────────────────────────────────────────
|
||||
══════════════════════════════════════════
|
||||
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
||||
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
|
||||
|
||||
--- 9b. dark solid dashed dotted ascii
|
||||
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
|
||||
██████████████████████████████████████████
|
||||
- - - - - - - - - - - - - - - - - - - - -
|
||||
··········································
|
||||
------------------------------------------
|
||||
───────────────── TODAY ──────────────────
|
||||
═════════════════ TOTAL ══════════════════
|
||||
── Notes ─────────────────────────────────
|
||||
The last three are labelled rules.
|
||||
|
||||
--- 10. kv (long value wraps) and list
|
||||
Host ............................... nas01
|
||||
Note ... The scrub finished with 0 errors.
|
||||
@@ -210,22 +171,6 @@ Note ... The scrub finished with 0 errors.
|
||||
[√] Done item
|
||||
[ ] Open item
|
||||
|
||||
--- 11. Box styles and divider junctions
|
||||
┌──────┐ ╔══════╗ ╒══════╕ ╓──────╖
|
||||
│single│ ║double║ │dbl-h │ ║dbl-v ║
|
||||
└──────┘ ╚══════╝ ╘══════╛ ╙──────╜
|
||||
+------+
|
||||
|ascii |
|
||||
+------+
|
||||
|
||||
├──────┤ single box, single rule
|
||||
╞══════╡ single box, double rule
|
||||
╟──────╢ double box, single rule
|
||||
╠══════╣ double box, double rule
|
||||
cp850/858: double-h and double-v fall
|
||||
back to double. cp1252: every box is
|
||||
ascii (+-|). Preview shows the result.
|
||||
|
||||
--- 12. Rate-limit digest (phase 4)
|
||||
┌─ ntfy digest · 6 held ─────────────────┐
|
||||
│ 21:05 [!] Disk almost full │
|
||||
@@ -238,8 +183,8 @@ Note ... The scrub finished with 0 errors.
|
||||
One row per held message, in arrival
|
||||
order. Priority 5 never waits.
|
||||
|
||||
Glyphs never used: • (not in any code
|
||||
page), ► ◄ → ← and other 0x01-0x1F
|
||||
Glyphs never used: • (only cp1252 has
|
||||
it), ► ◄ → ← and other 0x01-0x1F
|
||||
glyphs (printer control codes), emoji.
|
||||
Use · ∙ ■ » √ ° instead.
|
||||
```
|
||||
@@ -249,43 +194,12 @@ Use · ∙ ■ » √ ° instead.
|
||||
All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"error","details"}. Successful print responses keep today's 202 body plus a Location header:
|
||||
{"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","created_at":"2026-11-29T21:04:05Z"}
|
||||
|
||||
==== PHASE 1: new elements in POST /api/v1/print ====
|
||||
==== Blocks in POST /api/v1/print ====
|
||||
|
||||
Fields shared by the blocks (box, rule, kv, list):
|
||||
- size: 1-3. Scales the borders and the text together.
|
||||
- font: a or b.
|
||||
- Borders are never bold.
|
||||
|
||||
box
|
||||
- style: single (default, ┌─┐│└┘), double (╔═╗║╚╝), double-h (╒═╕│╘═╛), double-v (╓─╖║╙─╜) or ascii (+-|).
|
||||
- title: text set into the top border.
|
||||
- title_style: inline (default, ┌─ Title ──┐) or capped (╔═╡ Title ╞═╗).
|
||||
- footer: text set into the bottom border, on the right.
|
||||
- text: shorthand for the body. It wraps, and "\n" starts a new paragraph. It takes bold, underline and invert.
|
||||
- children: alternative to text. Allowed child types are text, rule, kv, list (phase 2) and feed.
|
||||
- text and children cannot both be set.
|
||||
- align: alignment of the shorthand text, and the default for text children.
|
||||
- padding: 0-3, default 1.
|
||||
- fit: true shrinks the box to its content and centres it.
|
||||
- columns: a fixed outer width. It is clamped to the paper, and a narrower box is centred.
|
||||
|
||||
Children inside a box:
|
||||
- text: may set bold, underline, invert, align and wrap. size, width, height and font are inherited from the box, and newline:false is not allowed.
|
||||
- rule: only single or double, optionally with text as a label. It becomes a divider whose junctions join the side borders.
|
||||
- Not allowed: box, qr, barcode, image, raw and cut. Place them after the box.
|
||||
|
||||
rule
|
||||
- style: single (default) ─, double ═, light ░, medium ▒, dark ▓, solid █, dashed "- ", dotted · or ascii -.
|
||||
- text: an optional label.
|
||||
- align: where the label sits. center is the default.
|
||||
- bold: applies to the label only.
|
||||
- columns.
|
||||
|
||||
kv
|
||||
- pairs: [{key, value, bold}], 1-100 of them.
|
||||
- leader: one of . (default), ·, space, _, - or ─.
|
||||
box, rule and kv, the preview (POST /api/v1/preview, `uberbringer preview`) and format.max_lines are built; README § Blocks and § Preview a receipt describe them. Validation problems name nested elements, e.g. elements[0].children[3] (qr). Still to come:
|
||||
|
||||
list (phase 2)
|
||||
- A block like kv: size, font and columns, and allowed as a child of a box.
|
||||
- items: 1-200 strings.
|
||||
- bullet: dot (default), dash, number or checkbox.
|
||||
- done: indexes of finished items, checkbox only. They print as [√], or [x] on code pages without √.
|
||||
@@ -293,7 +207,7 @@ list (phase 2)
|
||||
image (phase 3)
|
||||
- New field optional: true. If the image can't be fetched or decoded, the receipt prints "[image unavailable]" instead of failing the whole job.
|
||||
|
||||
Example 1: a boxed note in one element (mockup 5, with list from phase 2)
|
||||
Example 1: a boxed note in one element (mockup 5)
|
||||
POST /api/v1/print
|
||||
{"elements":[
|
||||
{"type":"box","title":"Shopping","footer":"29 Nov 21:04","children":[
|
||||
@@ -303,60 +217,15 @@ POST /api/v1/print
|
||||
]}
|
||||
]}
|
||||
|
||||
Example 2: the owner's test-print look (mockups 6 and 7)
|
||||
{"elements":[
|
||||
{"type":"box","style":"double","title":"ACHTUNG","title_style":"capped","align":"center",
|
||||
"text":"The coffee machine is being descaled.\nDo not use until 10:30."},
|
||||
{"type":"box","fit":true,"padding":3,"text":"!!! ACHTUNG !!!"}
|
||||
]}
|
||||
|
||||
Example 3: status report with kv rows and a labelled divider (mockup 8)
|
||||
Example 2: status report with kv rows, a labelled divider and a list (mockup 8)
|
||||
{"elements":[
|
||||
{"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":"rule","style":"double","text":"TOTAL"},
|
||||
{"type":"text","text":"Total: ","newline":false},
|
||||
{"type":"text","text":"£12.50","bold":true}
|
||||
]}
|
||||
]}
|
||||
|
||||
Example 4: validation (400, same shape as today, now with nested paths)
|
||||
{"error":"invalid job","details":[
|
||||
"elements[0].children[3] (qr): not allowed inside a box; place it after the box",
|
||||
"elements[0].children[1] (rule): inside a box, style must be single or double",
|
||||
"elements[1] (box): set text or children, not both",
|
||||
"elements[2] (kv): pairs[2]: key is required",
|
||||
"elements[3] (rule): field \"pairs\" does not apply to rule"]}
|
||||
|
||||
Render-time limit:
|
||||
- If a job would print more lines than [format].max_lines (default 2000), the job fails with "receipt would print 2412 lines, limit is 2000". That is visible on GET /api/v1/jobs/{id}, and synchronously on /preview.
|
||||
|
||||
==== PHASE 1: POST /api/v1/preview ====
|
||||
|
||||
- Takes the same body as /print and validates it the same way (400 on problems).
|
||||
- Nothing is printed and no images are fetched.
|
||||
|
||||
Default response: 200 text/plain; charset=utf-8, the exact lines the bytes would print:
|
||||
┌─ Shopping ─────────────────────────────┐
|
||||
│ Milk, eggs and the good bread from the │
|
||||
...
|
||||
[qr: https://grafana.lan/d/disk]
|
||||
[image 384 dots: graph.png]
|
||||
- - - - - - - partial cut - - - - - - - -
|
||||
|
||||
With Accept: application/json:
|
||||
{"columns":42,"codepage":"cp437","line_count":9,
|
||||
"lines":[{"kind":"text","text":"╔═ HIGH ═══...═╗"},
|
||||
{"kind":"text","text":"║ [!] Disk almost full ...║","runs":[{"from":2,"to":40,"bold":true}]},
|
||||
{"kind":"qr","data":"https://grafana.lan/d/disk"},
|
||||
{"kind":"cut","data":"partial"}],
|
||||
"warnings":["elements[2]: 1 character not in cp437 printed as ?"]}
|
||||
|
||||
- 422 {"error":"receipt would print 2412 lines, limit is 2000"}
|
||||
- CLI: uberbringer preview [--config c.toml] [--module ntfy] [file.json|-]. It prints to the terminal, showing bold and invert with the existing liamg/tml dependency.
|
||||
|
||||
==== PHASE 2: modules ====
|
||||
|
||||
GET /api/v1/modules
|
||||
@@ -436,12 +305,9 @@ Job status:
|
||||
|
||||
==== PHASE 3-4: configuration (strict TOML, as today) ====
|
||||
|
||||
[format]
|
||||
max_lines = 2000 # phase 1
|
||||
[format] # max_lines is built
|
||||
timezone = "Local" # phase 2; IANA name, checked with time.LoadLocation
|
||||
time_layout = "02 Jan 15:04"
|
||||
[printer]
|
||||
box_line_spacing = 0 # phase 1; ESC 3 units around boxes; 0 = printer default (until calibrated)
|
||||
[ntfy.format] # phase 3
|
||||
style = "auto" # auto | box | compact
|
||||
max_lines = 40
|
||||
@@ -505,26 +371,12 @@ DATA FLOW
|
||||
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:<name>"}).
|
||||
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:<sub>", Ref: <ntfy id>}).
|
||||
|
||||
KEY TYPES (new or changed)
|
||||
|
||||
escpos
|
||||
func (cp CodePage) CanEncode(r rune) bool // r encodes to a byte >= 0x20, not 0x7F
|
||||
func (cp CodePage) Decode(b []byte) string
|
||||
type Span struct{ From, To int }
|
||||
type Run struct{ From, To int; Bold, Underline, Invert bool; Font Font; W, H int }
|
||||
type PreviewLine struct{ Kind string /* text|qr|barcode|image|raw|cut */; Text string; Runs []Run; Data string }
|
||||
func Interpret(stream []byte, cp CodePage, opaque []Span) ([]PreviewLine, error)
|
||||
KEY TYPES (new or changed; the escpos interpreter, the blocks and Renderer.Preview are built)
|
||||
|
||||
receipt
|
||||
TypeBox, TypeRule, TypeKV (phase 1); TypeList (phase 2)
|
||||
Element gains: Children []Element, Title, TitleStyle, Footer, Style, Padding *int, Fit bool,
|
||||
Columns int, Pairs []Pair, Leader (phase 1); Items []string, Done []int, Bullet (phase 2);
|
||||
Optional bool on image (phase 3)
|
||||
type Pair struct{ Key, Value string; Bold bool }
|
||||
type Preview struct{ Columns int; CodePage string; LineCount int; Lines []escpos.PreviewLine; Warnings []string }
|
||||
func (r *Renderer) Preview(ctx context.Context, job Job) (Preview, error)
|
||||
func StripEmoji(s string) string
|
||||
Options gain MaxLines and BoxLineSpacing
|
||||
TypeList (phase 2)
|
||||
Element gains Items []string, Done []int, Bullet (phase 2); Optional bool on image (phase 3)
|
||||
func StripEmoji(s string) string (phase 3)
|
||||
|
||||
modules (phase 2; Notice and Card in phase 3)
|
||||
type Env struct{ Now time.Time; Location *time.Location; TimeLayout string; Card CardOptions }
|
||||
@@ -544,90 +396,21 @@ ntfy
|
||||
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
|
||||
|
||||
server
|
||||
New(config Config, deps Deps, logger *slog.Logger)
|
||||
type Deps struct{ Jobs Jobs; Printer Printer; Previewer Previewer; Modules Modules }
|
||||
Deps gains Modules (phase 2): Deps{Jobs, Printer, Previewer, Modules}
|
||||
|
||||
printqueue
|
||||
Submit(job receipt.Job, meta Meta) (Status, error)
|
||||
type Meta struct{ Source, Ref string }
|
||||
Status gains Source
|
||||
|
||||
BLOCK LAYOUT RULES (receipt/blocklayout.go and receipt/glyphs.go)
|
||||
|
||||
Width
|
||||
- cols = Profile.Columns(font), or Options.Columns for Font A, divided by size (1-3). That gives 42 Font A or 56 Font B columns on all three Epson models.
|
||||
- `columns` clamps to cols.
|
||||
- `fit` sets the width to the smallest of: cols, and the larger of (widest content + 2 + 2*padding) and (title + 6).
|
||||
- A block narrower than the line is centred with leading spaces.
|
||||
|
||||
Box
|
||||
- Each body row is: border, padding, content, padding, border. The content width is width - 2 - 2*padding, which is 38 at the defaults.
|
||||
- Bold, underline and invert apply only to the content run. Borders are never styled.
|
||||
- Top border, inline title: ┌─ Title ───┐. The title is cut with "..." beyond width-6.
|
||||
- Top border, capped title: ╔═╡ Title ╞══╗, using ┤├ on boxes with single horizontal lines.
|
||||
- Bottom border: └──── footer ──┘. The footer is cut beyond width-7.
|
||||
|
||||
Dividers (a rule child inside a box) span the full width and join the side borders:
|
||||
- single box: ├─┤ for a single rule, ╞═╡ for a double rule
|
||||
- double box: ╟─╢ single, ╠═╣ double
|
||||
- double-h box: ├─┤ single, ╞═╡ double
|
||||
- double-v box: ╟─╢ single, ╠═╣ double
|
||||
- A labelled divider looks like ├── Label ───┤.
|
||||
|
||||
kv
|
||||
- Layout: key, a space, a leader fill of at least 2, a space, then the value.
|
||||
- When the line is too long, the value wraps to width - len(key) - 4 and the continuation lines are right-aligned.
|
||||
|
||||
list
|
||||
BLOCK LAYOUT (receipt/blocklayout.go and receipt/glyphs.go)
|
||||
box, rule and kv are built; docs/design.md records their rules. list (phase 2) follows them: its width comes from the line at its size and font and from columns, every line it returns is exactly that width, and a narrower list is centred.
|
||||
- Bullets: "· ", "- ", "N. " (numbers right-aligned to the widest), "[ ] " and "[√] ".
|
||||
- Wrapped lines get a hanging indent.
|
||||
|
||||
Glyph fallback, chosen per glyph set with CanEncode
|
||||
- double-h and double-v fall back to double, then single, then ascii (+ - | =).
|
||||
- A junction the code page lacks first switches to the other rule weight. On cp850, ╟╢ becomes ╠╣ and ╞╡ becomes ├┤.
|
||||
- Shades fall back to #, · to . and √ to x.
|
||||
- Checked with the Python codecs:
|
||||
- cp437 has every glyph used here.
|
||||
- cp850 and cp858 lack ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫, ▌▐, ∙ and √.
|
||||
- cp1252 has no box drawing or shade characters.
|
||||
- No supported code page has • (U+2022).
|
||||
- ► ◄ → ← map to 0x10-0x1F, which the printer reads as control codes.
|
||||
|
||||
Emitting lines
|
||||
- For each line: Justify(left), the left margin, then for each run Font, Size, Bold, Underline and Reverse, then Text(cp.Encode(run)), then LineFeed.
|
||||
- Styles are reset afterwards exactly as p.text does today.
|
||||
- When Options.BoxLineSpacing > 0, ESC 3 n is sent before a box and ESC 2 after it.
|
||||
|
||||
Images
|
||||
- Boxes cannot contain images, so loadImages keeps keying images by element index and no flatten step is needed.
|
||||
- √ falls back to x where the code page lacks it (cp850, cp858), chosen with CanEncode.
|
||||
|
||||
TEXT NORMALIZATION (receipt/normalize.go)
|
||||
It runs before wrap, so one rune is one column and one byte. Steps, in order:
|
||||
1. sanitize, as today.
|
||||
2. Unicode NFC, using golang.org/x/text/unicode/norm. golang.org/x/text is already a dependency.
|
||||
3. Fold only runes the code page cannot encode:
|
||||
- “ ” „ become "
|
||||
- ‘ ’ become '
|
||||
- – becomes -, and — becomes --
|
||||
- … becomes ...
|
||||
- • becomes ·
|
||||
- → becomes -> and ← becomes <-
|
||||
- ✓ and ✔ become √, or x where √ is missing
|
||||
- × becomes x
|
||||
- € becomes EUR (cp858 keeps €)
|
||||
- ™ becomes TM
|
||||
- a non-breaking space becomes a space
|
||||
4. Remove U+FE0E, U+FE0F, U+200B-U+200D, skin-tone modifiers and tag characters.
|
||||
5. Emoji:
|
||||
- On /print, each remaining emoji cluster becomes a single '?'.
|
||||
- Modules call StripEmoji after mapping a few typed emoji to markers: ⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1).
|
||||
The number of '?' left feeds the preview warnings.
|
||||
|
||||
PREVIEW (receipt/preview.go and escpos/interpret.go)
|
||||
- Renderer.Preview renders with a placeholder fetcher. It produces a blank raster at the requested or default width and never fetches anything.
|
||||
- It records the byte range of each raw element (Builder.Len before and after), then interprets the body with escpos.Interpret. Raw ranges become "[raw N bytes]", because arbitrary raw bytes cannot be parsed reliably.
|
||||
- Interpret understands every command the renderer emits: ESC @ t a M E - 3 2 d, GS ! B V, GS ( k, GS k and GS v 0.
|
||||
- The tests use the same interpreter in place of printedLines, so the preview always shows what the bytes actually say.
|
||||
Built: NFC, the fold table and one '?' per emoji sequence on /print. Phase 3 adds StripEmoji for modules: it maps a few typed emoji to markers (⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1)), then removes the remaining emoji instead of printing '?'.
|
||||
|
||||
NTFY AND NOTIFY CARD (modules/card.go)
|
||||
The same card is used for /print/notify, /print/ntfy and the subscriber.
|
||||
@@ -736,116 +519,6 @@ Images and logging
|
||||
|
||||
## Phases
|
||||
|
||||
### Phase 1: Boxes, rules, kv and preview (3-4 days)
|
||||
|
||||
**Goal.** One /print element gives the single and double CP437 boxes the owner liked. The output can be seen without using paper. Existing jobs print byte for byte as they do today.
|
||||
|
||||
**Work.**
|
||||
|
||||
Do this first: commit byte-compatibility fixtures. Put internal/pkg/receipt/testdata/compat/*.json and *.hex, rendered by the current code, in place before touching the renderer.
|
||||
|
||||
internal/pkg/escpos
|
||||
- codepage.go: CanEncode(r rune) bool and Decode([]byte) string.
|
||||
- interpret.go (new): Interpret(stream, cp, opaque []Span) ([]PreviewLine, error).
|
||||
- It parses ESC @ t a M E - 3 2 d, GS ! B V, GS ( k, GS k and GS v 0.
|
||||
- Output is text runs with their styles, plus placeholders for qr, barcode, image, raw and cut.
|
||||
|
||||
internal/pkg/receipt
|
||||
- job.go:
|
||||
- TypeBox, TypeRule and TypeKV.
|
||||
- New fields: Children, Title, TitleStyle, Footer, Style, Padding *int, Fit, Columns, Pairs, Leader; type Pair.
|
||||
- validate() recurses with path prefixes.
|
||||
- checkFields keeps a per-type allowed set. It applies to the new types; old types stay lenient.
|
||||
- Child rules allow only one level of nesting, and children count toward MaxElements.
|
||||
- The doc comment explains that columns, not width, sets a block's width.
|
||||
- block.go (new): boxSpec, ruleSpec and kvSpec. These checks are structural and independent of geometry.
|
||||
- glyphs.go (new): border sets, the junction table and the CanEncode fallback chain.
|
||||
- normalize.go (new):
|
||||
- NFC, using golang.org/x/text/unicode/norm.
|
||||
- The fold table, applied only to runes the code page can't encode.
|
||||
- Removal of variation selectors and ZWJ.
|
||||
- The emoji policy: replace on /print.
|
||||
- A count of '?' left over, for warnings.
|
||||
- It is called before wrap; wrap() itself is unchanged.
|
||||
- cells.go (new): style, run and line types.
|
||||
- blocklayout.go (new):
|
||||
- layoutBox, layoutRule and layoutKV. Every line they return is exactly the block width.
|
||||
- fit, columns clamping, title and footer truncation, and centring.
|
||||
- render.go:
|
||||
- Cases for box, rule and kv that lay out and then emit.
|
||||
- Line counting against Options.MaxLines.
|
||||
- ESC 3 n / ESC 2 around boxes when Options.BoxLineSpacing > 0.
|
||||
- Raw elements record their byte spans for preview.
|
||||
- preview.go (new): Renderer.Preview, using a placeholder fetcher and escpos.Interpret, and returning warnings.
|
||||
|
||||
internal/app/uberbringer/server
|
||||
- server.go: New(config, Deps{Jobs, Printer, Previewer}, logger) and the route POST /api/v1/preview.
|
||||
- handlers_preview.go (new): text/plain by default, JSON for Accept: application/json, 422 for max_lines.
|
||||
|
||||
internal/pkg/config
|
||||
- [format] max_lines and [printer] box_line_spacing, with defaults and validation.
|
||||
|
||||
internal/app/uberbringer
|
||||
- serve.go: passes MaxLines and BoxLineSpacing into receipt.Options, and the renderer as the Previewer.
|
||||
- cli.go: the `preview [--config] file|-` command, rendering bold and invert with liamg/tml.
|
||||
|
||||
Docs and examples
|
||||
- README.md: a Blocks section (field tables for box, rule and kv), a CP437 glyph cheat sheet (what prints and what doesn't), and a Preview section. Replace the hand-drawn ACHTUNG example with a box element.
|
||||
- configs/config.example.toml.
|
||||
- examples/blocks.json (new): a calibration gallery covering every style, padding, size 1-3, font b, dividers and fit.
|
||||
|
||||
**Tests.**
|
||||
|
||||
internal/pkg/escpos
|
||||
- CanEncode tables for each code page:
|
||||
- cp437 encodes every glyph used.
|
||||
- cp850 and cp858 lack ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫, ▌▐, ∙ and √.
|
||||
- cp1252 lacks all box and shade glyphs.
|
||||
- • and ► fail everywhere.
|
||||
- Decode round trip.
|
||||
- Interpret applied to Builder output for every command the renderer emits, including raw spans and unknown bytes.
|
||||
|
||||
internal/pkg/receipt
|
||||
- TestRenderCompat: the existing fixtures render identical bytes.
|
||||
- Golden tests: testdata/blocks/*.json rendered to *.txt through Preview, regenerated with -update. They cover:
|
||||
- box: 5 styles × inline and capped titles × padding 0-3 × size 1-3 × font a and b
|
||||
- fit, columns and footer
|
||||
- titles too long for the border
|
||||
- every divider junction, with and without labels
|
||||
- kv overflow
|
||||
- every rule style
|
||||
- the same set on cp850 and cp1252, to check fallbacks
|
||||
- FuzzBlocks, over random block trees and options:
|
||||
- every text line is exactly the block width and no wider than cols
|
||||
- corners and verticals sit in the first and last columns
|
||||
- no byte below 0x20 appears inside text runs
|
||||
- Validation table tests:
|
||||
- nested paths
|
||||
- checkFields
|
||||
- children that are not allowed (qr, image, raw, box)
|
||||
- text together with children
|
||||
- MaxElements counting children
|
||||
- normalize tables:
|
||||
- a decomposed é becomes one rune
|
||||
- fold runs before wrap (… takes 3 columns)
|
||||
- one emoji cluster becomes one '?'
|
||||
- ZWJ and VS16 are dropped
|
||||
- encodable text is untouched
|
||||
- receipt_test.go uses escpos.Interpret in place of printedLines. All existing tests stay green.
|
||||
|
||||
server
|
||||
- preview returns 200 text/plain and 200 JSON, 400 for an invalid job, 401 without a token, and 422 when max_lines is exceeded.
|
||||
|
||||
cli
|
||||
- A golden test of the preview command's output.
|
||||
|
||||
**Done when.**
|
||||
|
||||
- the full gate passes (CLAUDE.md lists it), including staticcheck and govulncheck, and the compat fixtures are byte-identical.
|
||||
- The README examples, mockups 6 and 7, print from one element each.
|
||||
- /api/v1/preview shows the same lines.
|
||||
- examples/blocks.json has been printed on the TM-T88IV and the owner has looked at the border gaps. box_line_spacing is then either set to a value checked on paper or left at 0.
|
||||
|
||||
### Phase 2: Notes and the module layer (2 days)
|
||||
|
||||
**Goal.** Basic inputs print advanced layouts. POST /api/v1/print/note with {title, text, items} prints a boxed checklist, and the module layer is ready for notifications.
|
||||
|
||||
Reference in new issue
Block a user