@angadie/chittie-preview 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Asyncdot Engineering
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ Portions of this software are vendored from MIT-licensed projects and retain
16
+ their original copyright notices; see VENDOR.md.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # @angadie/chittie-preview
2
+
3
+ Render a receipt to an **image** by parsing the ESC/POS bytes chittie emits — a
4
+ software preview of *what the printer will actually print*. Platform-neutral: you
5
+ inject a canvas factory, so it works in the browser (`HTMLCanvasElement`) and in
6
+ Node (`@napi-rs/canvas`) with **no hard dependency** — the same pattern as
7
+ [`@angadie/chittie-text`](../chittie-text)'s injected rasterizer.
8
+
9
+ Handles chittie's real output: text + bold + double-size, rules, paper cut, and
10
+ **both image modes** (column `ESC *` — the default — and raster `GS v 0`). Barcodes
11
+ and QR codes are drawn as labelled placeholder boxes (their bytes are parsed and
12
+ skipped cleanly, so nothing desyncs).
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pnpm add @angadie/chittie-preview
18
+ ```
19
+
20
+ ## Browser
21
+
22
+ ```ts
23
+ import { renderReceipt } from '@angadie/chittie-preview';
24
+
25
+ const canvas = renderReceipt(bytes, {
26
+ createCanvas: (w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }),
27
+ });
28
+ document.body.appendChild(canvas); // or canvas.toDataURL()
29
+ ```
30
+
31
+ ## Node
32
+
33
+ ```ts
34
+ import { renderReceipt } from '@angadie/chittie-preview';
35
+ import { createCanvas } from '@napi-rs/canvas';
36
+ import { writeFileSync } from 'node:fs';
37
+
38
+ const canvas = renderReceipt(bytes, { createCanvas });
39
+ writeFileSync('receipt.png', canvas.toBuffer('image/png'));
40
+ ```
41
+
42
+ `bytes` is the `Uint8Array` from chittie's `render()` or `encode()`.
43
+
44
+ ## Options
45
+
46
+ | Option | Default | Meaning |
47
+ |---|---|---|
48
+ | `createCanvas(w, h)` | — | **required** canvas factory |
49
+ | `columns` | `32` | characters per line (match your `<Printer width>`) |
50
+ | `cellWidth` | `12` | px per character cell |
51
+ | `lineHeight` | `26` | px per text line |
52
+ | `fontFamily` | `'monospace'` | text font |
53
+ | `padding` | `16` | outer padding px |
54
+
55
+ ## Prior art
56
+
57
+ [`node-thermal-printer`](https://github.com/Klemen1337/node-thermal-printer) prints
58
+ to thermal printers from Node (file/network/OS-printer), but it's Node-only
59
+ (`fs`/`net`/`pngjs`) and has no preview. chittie-preview is platform-neutral (browser
60
+ + node via the injected canvas) and renders the byte stream itself.
61
+
62
+ ## License
63
+
64
+ MIT.
@@ -0,0 +1,39 @@
1
+ //#region src/index.d.ts
2
+ /** The 2D context methods/properties chittie-preview draws with. */
3
+ interface PreviewContext2D {
4
+ fillStyle: string;
5
+ strokeStyle: string;
6
+ font: string;
7
+ textBaseline: string;
8
+ fillRect(x: number, y: number, w: number, h: number): void;
9
+ strokeRect(x: number, y: number, w: number, h: number): void;
10
+ fillText(text: string, x: number, y: number): void;
11
+ setLineDash(segments: number[]): void;
12
+ beginPath(): void;
13
+ moveTo(x: number, y: number): void;
14
+ lineTo(x: number, y: number): void;
15
+ stroke(): void;
16
+ }
17
+ interface PreviewCanvas {
18
+ width: number;
19
+ height: number;
20
+ getContext(type: '2d'): PreviewContext2D | null;
21
+ }
22
+ interface PreviewOptions {
23
+ /** Canvas factory. Web: `(w,h)=>Object.assign(document.createElement('canvas'),{width:w,height:h})`. Node: `@napi-rs/canvas` `createCanvas`. */
24
+ createCanvas: (width: number, height: number) => PreviewCanvas;
25
+ /** Characters per line (default 32). */
26
+ columns?: number;
27
+ /** Pixels per character cell (default 12). */
28
+ cellWidth?: number;
29
+ /** Pixels per text line (default 26). */
30
+ lineHeight?: number;
31
+ /** Font family for text (default 'monospace'). */
32
+ fontFamily?: string;
33
+ /** Outer padding in px (default 16). */
34
+ padding?: number;
35
+ }
36
+ /** Render ESC/POS bytes (from chittie `render()` / `encode()`) to a canvas. */
37
+ declare function renderReceipt(bytes: Uint8Array, options: PreviewOptions): PreviewCanvas;
38
+ //#endregion
39
+ export { PreviewCanvas, PreviewContext2D, PreviewOptions, renderReceipt };
package/dist/index.mjs ADDED
@@ -0,0 +1,205 @@
1
+ //#region src/index.ts
2
+ const CP437_HIGH = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
3
+ const decode = (b) => b < 128 ? String.fromCharCode(b) : CP437_HIGH[b - 128] ?? "";
4
+ function parse(bytes, cfg) {
5
+ const dots = cfg.columns * cfg.cellWidth;
6
+ const u16 = (lo, hi) => lo + hi * 256;
7
+ const ops = [];
8
+ let x = 0;
9
+ let y = cfg.padding;
10
+ let bold = false;
11
+ let wScale = 1;
12
+ let hScale = 1;
13
+ let lineMaxScale = 1;
14
+ let align = "left";
15
+ let suppressNextLF = false;
16
+ let i = 0;
17
+ const n = bytes.length;
18
+ const imgX = (w) => align === "center" ? Math.max(0, Math.round((dots - w) / 2)) : align === "right" ? Math.max(0, dots - w) : 0;
19
+ while (i < n) {
20
+ const b = bytes[i];
21
+ if (b === 27) {
22
+ const c = bytes[i + 1];
23
+ if (c === 64) i += 2;
24
+ else if (c === 69) {
25
+ bold = !!bytes[i + 2];
26
+ i += 3;
27
+ } else if (c === 33) {
28
+ const m = bytes[i + 2];
29
+ bold = !!(m & 8);
30
+ wScale = m & 32 ? 2 : 1;
31
+ hScale = m & 16 ? 2 : 1;
32
+ i += 3;
33
+ } else if (c === 97) {
34
+ const m = bytes[i + 2];
35
+ align = m === 1 ? "center" : m === 2 ? "right" : "left";
36
+ i += 3;
37
+ } else if (c === 74) {
38
+ y += bytes[i + 2] ?? 0;
39
+ i += 3;
40
+ } else if (c === 100) {
41
+ y += (bytes[i + 2] ?? 0) * cfg.lineHeight;
42
+ i += 3;
43
+ } else if (c === 112) i += 5;
44
+ else if (c === 50) i += 2;
45
+ else if (c === 42) {
46
+ const m = bytes[i + 2];
47
+ const cols = u16(bytes[i + 3], bytes[i + 4]);
48
+ const bpc = m === 0 || m === 1 ? 1 : 3;
49
+ const start = i + 5;
50
+ const data = bytes.subarray(start, start + bpc * cols);
51
+ const ix = imgX(cols);
52
+ const blacks = [];
53
+ for (let col = 0; col < cols; col++) for (let byte = 0; byte < bpc; byte++) {
54
+ const v = data[col * bpc + byte] ?? 0;
55
+ for (let bit = 0; bit < 8; bit++) if (v & 128 >> bit) blacks.push([ix + col, y + byte * 8 + bit]);
56
+ }
57
+ ops.push({
58
+ k: "img",
59
+ blacks
60
+ });
61
+ y += bpc * 8;
62
+ suppressNextLF = true;
63
+ i = start + bpc * cols;
64
+ } else if (c === 51) i += 3;
65
+ else if (c === 116 || c === 77 || c === 82 || c === 32 || c === 45 || c === 123 || c === 71) i += 3;
66
+ else i += 2;
67
+ } else if (b === 29) {
68
+ const c = bytes[i + 1];
69
+ if (c === 33) {
70
+ const m = bytes[i + 2];
71
+ wScale = (m >> 4 & 7) + 1;
72
+ hScale = (m & 7) + 1;
73
+ i += 3;
74
+ } else if (c === 86) {
75
+ ops.push({
76
+ k: "cut",
77
+ y
78
+ });
79
+ y += 14;
80
+ i += (bytes[i + 2] ?? 0) >= 65 ? 4 : 3;
81
+ } else if (c === 118 && bytes[i + 2] === 48) {
82
+ const wbytes = u16(bytes[i + 4], bytes[i + 5]);
83
+ const h = u16(bytes[i + 6], bytes[i + 7]);
84
+ const start = i + 8;
85
+ const w = wbytes * 8;
86
+ const data = bytes.subarray(start, start + wbytes * h);
87
+ const ix = imgX(w);
88
+ const blacks = [];
89
+ for (let row = 0; row < h; row++) for (let col = 0; col < w; col++) if (data[row * wbytes + (col >> 3)] & 128 >> (col & 7)) blacks.push([ix + col, y + row]);
90
+ ops.push({
91
+ k: "img",
92
+ blacks
93
+ });
94
+ y += h + 4;
95
+ i = start + wbytes * h;
96
+ } else if (c === 107) {
97
+ const m = bytes[i + 2];
98
+ let j;
99
+ if (m >= 65) j = i + 4 + (bytes[i + 3] ?? 0);
100
+ else {
101
+ j = i + 3;
102
+ while (j < n && bytes[j] !== 0) j++;
103
+ j++;
104
+ }
105
+ const w = Math.min(dots, 220);
106
+ ops.push({
107
+ k: "box",
108
+ x: imgX(w),
109
+ y,
110
+ w,
111
+ h: 54,
112
+ label: "barcode"
113
+ });
114
+ y += 60;
115
+ i = j;
116
+ } else if (c === 40 && bytes[i + 2] === 107) {
117
+ const dlen = u16(bytes[i + 3], bytes[i + 4]);
118
+ if (bytes[i + 5] === 49 && bytes[i + 6] === 80) {
119
+ ops.push({
120
+ k: "box",
121
+ x: imgX(96),
122
+ y,
123
+ w: 96,
124
+ h: 96,
125
+ label: "QR"
126
+ });
127
+ y += 102;
128
+ }
129
+ i = i + 5 + dlen;
130
+ } else if (c === 104 || c === 119 || c === 72 || c === 102 || c === 66 || c === 69) i += 3;
131
+ else i += 3;
132
+ } else if (b === 28) i += bytes[i + 1] === 46 || bytes[i + 1] === 38 ? 2 : 3;
133
+ else if (b === 10) {
134
+ if (suppressNextLF) suppressNextLF = false;
135
+ else {
136
+ y += cfg.lineHeight * lineMaxScale;
137
+ lineMaxScale = 1;
138
+ }
139
+ x = 0;
140
+ i += 1;
141
+ } else if (b === 13) i += 1;
142
+ else {
143
+ const ch = decode(b);
144
+ if (ch && ch !== " ") ops.push({
145
+ k: "ch",
146
+ x,
147
+ y,
148
+ c: ch,
149
+ bold,
150
+ scale: hScale
151
+ });
152
+ if (hScale > lineMaxScale) lineMaxScale = hScale;
153
+ x += cfg.cellWidth * wScale;
154
+ i += 1;
155
+ }
156
+ }
157
+ return {
158
+ ops,
159
+ height: y + cfg.padding
160
+ };
161
+ }
162
+ /** Render ESC/POS bytes (from chittie `render()` / `encode()`) to a canvas. */
163
+ function renderReceipt(bytes, options) {
164
+ const cfg = {
165
+ columns: options.columns ?? 32,
166
+ cellWidth: options.cellWidth ?? 12,
167
+ lineHeight: options.lineHeight ?? 26,
168
+ padding: options.padding ?? 16
169
+ };
170
+ const fontFamily = options.fontFamily ?? "monospace";
171
+ const dots = cfg.columns * cfg.cellWidth;
172
+ const { ops, height } = parse(bytes, cfg);
173
+ const canvas = options.createCanvas(dots + cfg.padding * 2, height);
174
+ const ctx = canvas.getContext("2d");
175
+ if (!ctx) throw new Error("chittie-preview: createCanvas returned no 2d context");
176
+ ctx.fillStyle = "#fff";
177
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
178
+ ctx.textBaseline = "top";
179
+ for (const op of ops) if (op.k === "ch") {
180
+ ctx.fillStyle = "#000";
181
+ ctx.font = `${op.bold ? "bold " : ""}${18 * op.scale}px ${fontFamily}`;
182
+ ctx.fillText(op.c, cfg.padding + op.x, op.y);
183
+ } else if (op.k === "img") {
184
+ ctx.fillStyle = "#000";
185
+ for (const [px, py] of op.blacks) ctx.fillRect(cfg.padding + px, py, 1, 1);
186
+ } else if (op.k === "cut") {
187
+ ctx.strokeStyle = "#999";
188
+ ctx.setLineDash([4, 4]);
189
+ ctx.beginPath();
190
+ ctx.moveTo(cfg.padding, op.y);
191
+ ctx.lineTo(cfg.padding + dots, op.y);
192
+ ctx.stroke();
193
+ ctx.setLineDash([]);
194
+ } else {
195
+ ctx.strokeStyle = "#000";
196
+ ctx.setLineDash([]);
197
+ ctx.strokeRect(cfg.padding + op.x, op.y, op.w, op.h);
198
+ ctx.fillStyle = "#666";
199
+ ctx.font = `12px ${fontFamily}`;
200
+ ctx.fillText(op.label, cfg.padding + op.x + 6, op.y + op.h / 2 - 6);
201
+ }
202
+ return canvas;
203
+ }
204
+ //#endregion
205
+ export { renderReceipt };
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@angadie/chittie-preview",
3
+ "version": "0.1.0",
4
+ "description": "Render a receipt to an image by parsing the ESC/POS bytes chittie emits — a software preview of what the printer will print. Platform-neutral via an injected canvas (browser or @napi-rs/canvas).",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "types": "./dist/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "devDependencies": {
18
+ "@canvas/image-data": "^1.1.0",
19
+ "@angadie/chittie": "0.1.0",
20
+ "@angadie/chittie-text": "0.1.0"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "scripts": {
26
+ "build": "tsdown",
27
+ "typecheck": "tsc --noEmit",
28
+ "test": "tsx spikes/preview.spike.ts"
29
+ }
30
+ }