inkless 0.0.0-stage → 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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/bin/inkless.js +10 -0
  4. package/console-dist/assets/BlueprintTool-CLWuM21a.js +4226 -0
  5. package/console-dist/assets/index-CIqLZU6s.js +33 -0
  6. package/console-dist/assets/index-Dv7Gg9qm.css +1 -0
  7. package/console-dist/favicon.svg +11 -0
  8. package/console-dist/index.html +18 -0
  9. package/native/linux/rfcomm.py +84 -0
  10. package/native/macos/build/InklessBluetooth.app/Contents/Info.plist +26 -0
  11. package/native/macos/build/InklessBluetooth.app/Contents/MacOS/InklessBluetooth +0 -0
  12. package/native/macos/build/InklessBluetooth.app/Contents/_CodeSignature/CodeResources +115 -0
  13. package/package.json +60 -4
  14. package/skills/inkless/SKILL.md +213 -0
  15. package/src/core/bits.js +143 -0
  16. package/src/core/blueprint/demos.js +119 -0
  17. package/src/core/blueprint/geometry.js +232 -0
  18. package/src/core/blueprint/index.js +100 -0
  19. package/src/core/blueprint/layout.js +210 -0
  20. package/src/core/blueprint/mesh.js +101 -0
  21. package/src/core/blueprint/methods.js +95 -0
  22. package/src/core/blueprint/remesh.js +250 -0
  23. package/src/core/blueprint/slice.js +134 -0
  24. package/src/core/blueprint/unfold.js +185 -0
  25. package/src/core/design/codes.js +39 -0
  26. package/src/core/design/filters.js +109 -0
  27. package/src/core/design/render.js +317 -0
  28. package/src/core/design/schema.js +132 -0
  29. package/src/core/formats/fit.js +46 -0
  30. package/src/core/formats/index.js +210 -0
  31. package/src/core/formats/library.js +341 -0
  32. package/src/core/formats/share.js +65 -0
  33. package/src/core/index.js +15 -0
  34. package/src/core/printers/hp6.js +160 -0
  35. package/src/core/printers/index.js +14 -0
  36. package/src/core/printers/pm290.js +115 -0
  37. package/src/core/session.js +56 -0
  38. package/src/node/artwork.js +33 -0
  39. package/src/node/cli.js +430 -0
  40. package/src/node/console/actions.js +30 -0
  41. package/src/node/console/client.js +68 -0
  42. package/src/node/console/paths.js +8 -0
  43. package/src/node/console/server.js +286 -0
  44. package/src/node/design.js +99 -0
  45. package/src/node/formats.js +39 -0
  46. package/src/node/frames.js +93 -0
  47. package/src/node/index.js +6 -0
  48. package/src/node/kit.js +12 -0
  49. package/src/node/skill.js +44 -0
  50. package/src/node/transports/index.js +21 -0
  51. package/src/node/transports/linux.js +52 -0
  52. package/src/node/transports/macos.js +81 -0
@@ -0,0 +1,317 @@
1
+ // @ts-check
2
+ // Design document -> 1-bit pages. Browser and Node share this: the caller
3
+ // injects canvas creation and image loading (DOM canvas or @napi-rs/canvas).
4
+ import { countInk, rgbaToGray } from "../bits.js";
5
+ import { applyFilter } from "./filters.js";
6
+ import { code128Bars, qrModules } from "./codes.js";
7
+ import { DOTS_PER_MM, PRINTER_SIZES, PT_TO_MM, normalizeDesign, pageDots } from "./schema.js";
8
+
9
+ /**
10
+ * `Path2D` is only needed for path elements; pass it when the canvas library
11
+ * does not expose it globally (@napi-rs/canvas does not).
12
+ * @typedef {{ createCanvas(width: number, height: number): any, loadImage(src: string): Promise<any>, Path2D?: any }} CanvasKit
13
+ * @typedef {{ bits: Uint8Array, width: number, height: number, ink: number }} RenderedPage bits: 1 = black
14
+ */
15
+
16
+ // Local element bitmaps hold INK (black), WHITE (opaque white, e.g. inverted
17
+ // text or an image's light dots) or NONE (the page shows through).
18
+ const NONE = 0;
19
+ const INK = 1;
20
+ const WHITE = 2;
21
+
22
+ const FONTS = {
23
+ sans: '"Helvetica Neue", Helvetica, Arial, "Liberation Sans", "DejaVu Sans", sans-serif',
24
+ serif: 'Georgia, "Times New Roman", "Liberation Serif", "DejaVu Serif", serif',
25
+ mono: 'Menlo, "SF Mono", Consolas, "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace',
26
+ display: 'Impact, "Arial Black", "Helvetica Neue", Arial, "DejaVu Sans", sans-serif',
27
+ };
28
+ const LINE_MM = 0.3;
29
+
30
+ /**
31
+ * A local bitmap: the element box plus `pad` dots on every side (strokes may
32
+ * overhang the box), row-major.
33
+ * @typedef {{ data: Uint8Array, lw: number, lh: number, pad: number }} Local
34
+ */
35
+ const blank = (w, h, pad) => {
36
+ const lw = Math.max(1, w + 2 * pad);
37
+ const lh = Math.max(1, h + 2 * pad);
38
+ return { data: new Uint8Array(lw * lh), lw, lh, pad };
39
+ };
40
+
41
+ /** Context of a fresh transparent canvas. */
42
+ function drawing(kit, w, h) {
43
+ const ctx = kit.createCanvas(Math.max(1, w), Math.max(1, h)).getContext("2d");
44
+ ctx.fillStyle = "#000";
45
+ ctx.strokeStyle = "#000";
46
+ return ctx;
47
+ }
48
+
49
+ /** Crisp ink from whatever was drawn: alpha at or above one half. */
50
+ function inkFromCanvas(ctx, local) {
51
+ const { data } = ctx.getImageData(0, 0, local.lw, local.lh);
52
+ for (let i = 0; i < local.data.length; i++) if (data[i * 4 + 3] >= 128) local.data[i] = INK;
53
+ return local;
54
+ }
55
+
56
+ function drawText(el, kit, w, h) {
57
+ const local = blank(w, h, 0);
58
+ const lines = String(el.text ?? "").split("\n");
59
+ const lineHeight = el.lineHeight ?? 1.2;
60
+ const font = FONTS[el.font] ?? FONTS.sans;
61
+ const ctx = drawing(kit, w, h);
62
+ const setFont = (px) => { ctx.font = `${el.weight ?? 400} ${px}px ${font}`; };
63
+ const fits = (px) => {
64
+ setFont(px);
65
+ return lines.length * lineHeight * px <= h && Math.max(...lines.map((l) => ctx.measureText(l).width)) <= w;
66
+ };
67
+ let px;
68
+ if (el.sizePt) px = el.sizePt * PT_TO_MM * DOTS_PER_MM;
69
+ else {
70
+ let lo = 1;
71
+ let hi = Math.max(2, h);
72
+ for (let i = 0; i < 24; i++) {
73
+ const mid = (lo + hi) / 2;
74
+ if (fits(mid)) lo = mid; else hi = mid;
75
+ }
76
+ px = lo;
77
+ }
78
+ setFont(px);
79
+ const align = el.align ?? "left";
80
+ ctx.textAlign = align;
81
+ ctx.textBaseline = "middle";
82
+ const x = align === "center" ? w / 2 : align === "right" ? w : 0;
83
+ lines.forEach((line, i) => ctx.fillText(line, x, (i + 0.5) * lineHeight * px));
84
+ return inkFromCanvas(ctx, local);
85
+ }
86
+
87
+ function roundedRect(ctx, x, y, w, h, r) {
88
+ const radius = Math.min(r, w / 2, h / 2);
89
+ ctx.beginPath();
90
+ ctx.moveTo(x + radius, y);
91
+ ctx.arcTo(x + w, y, x + w, y + h, radius);
92
+ ctx.arcTo(x + w, y + h, x, y + h, radius);
93
+ ctx.arcTo(x, y + h, x, y, radius);
94
+ ctx.arcTo(x, y, x + w, y, radius);
95
+ ctx.closePath();
96
+ }
97
+
98
+ function drawShape(el, kit, w, h) {
99
+ const stroke = (el.strokeMm ?? LINE_MM) * DOTS_PER_MM;
100
+ const line = el.shape === "line";
101
+ const local = blank(w, h, line ? Math.ceil(stroke / 2) + 1 : 0);
102
+ const ctx = drawing(kit, local.lw, local.lh);
103
+ ctx.lineWidth = stroke;
104
+ const { pad } = local;
105
+ if (line) {
106
+ ctx.beginPath();
107
+ ctx.moveTo(pad, pad);
108
+ ctx.lineTo(pad + w, pad + h);
109
+ ctx.stroke();
110
+ } else {
111
+ // Strokes sit inside the box, so a rect or ellipse never grows past it.
112
+ const inset = el.fill ? 0 : stroke / 2;
113
+ if (el.shape === "ellipse") {
114
+ ctx.beginPath();
115
+ ctx.ellipse(w / 2, h / 2, Math.max(0, w / 2 - inset), Math.max(0, h / 2 - inset), 0, 0, 2 * Math.PI);
116
+ } else {
117
+ roundedRect(ctx, inset, inset, w - 2 * inset, h - 2 * inset, (el.radiusMm ?? 0) * DOTS_PER_MM);
118
+ }
119
+ if (el.fill) ctx.fill(); else ctx.stroke();
120
+ }
121
+ return inkFromCanvas(ctx, local);
122
+ }
123
+
124
+ function drawPath(el, kit, w, h) {
125
+ const PathClass = kit.Path2D ?? globalThis.Path2D;
126
+ if (!PathClass) throw new Error("path elements need kit.Path2D (pass Path2D from your canvas library)");
127
+ const stroke = el.strokeMm ?? LINE_MM;
128
+ const local = blank(w, h, el.fill ? 0 : Math.ceil((stroke * DOTS_PER_MM) / 2) + 1);
129
+ const ctx = drawing(kit, local.lw, local.lh);
130
+ ctx.translate(local.pad, local.pad);
131
+ ctx.scale(DOTS_PER_MM, DOTS_PER_MM);
132
+ // Freehand drawings stretch with their box; the pen keeps its width.
133
+ const sx = el.viewW ? w / DOTS_PER_MM / el.viewW : 1;
134
+ const sy = el.viewH ? h / DOTS_PER_MM / el.viewH : 1;
135
+ ctx.scale(sx, sy);
136
+ ctx.lineWidth = stroke / Math.sqrt(sx * sy);
137
+ ctx.lineJoin = "round";
138
+ ctx.lineCap = "round";
139
+ const path = new PathClass(el.d);
140
+ if (el.fill) ctx.fill(path); else ctx.stroke(path);
141
+ return inkFromCanvas(ctx, local);
142
+ }
143
+
144
+ /** Whole-dot modules, centred in the box. */
145
+ function drawQr(el, w, h) {
146
+ const grid = qrModules(String(el.value ?? ""));
147
+ const module = Math.max(1, Math.floor(Math.min(w, h) / grid.length));
148
+ const local = blank(w, h, 0);
149
+ const ox = Math.floor((w - module * grid.length) / 2);
150
+ const oy = Math.floor((h - module * grid.length) / 2);
151
+ grid.forEach((row, r) => row.forEach((dark, c) => {
152
+ if (!dark) return;
153
+ for (let y = 0; y < module; y++) {
154
+ for (let x = 0; x < module; x++) {
155
+ const px = ox + c * module + x;
156
+ const py = oy + r * module + y;
157
+ if (px >= 0 && px < w && py >= 0 && py < h) local.data[py * w + px] = INK;
158
+ }
159
+ }
160
+ }));
161
+ return local;
162
+ }
163
+
164
+ function drawBarcode(el, w, h) {
165
+ const bars = code128Bars(String(el.value ?? ""));
166
+ const total = bars.reduce((a, b) => a + b, 0);
167
+ const module = Math.max(1, Math.floor(w / total));
168
+ const local = blank(w, h, 0);
169
+ let x = Math.floor((w - module * total) / 2);
170
+ bars.forEach((width, i) => {
171
+ for (let dx = 0; dx < width * module; dx++) {
172
+ if (i % 2 === 0 && x + dx >= 0 && x + dx < w) for (let y = 0; y < h; y++) local.data[y * w + x + dx] = INK;
173
+ }
174
+ x += width * module;
175
+ });
176
+ return local;
177
+ }
178
+
179
+ async function drawImage(el, kit, w, h, load) {
180
+ const img = await load(el.src);
181
+ const fit = el.fit ?? "contain";
182
+ const scale = fit === "stretch" ? null : (fit === "cover" ? Math.max : Math.min)(w / img.width, h / img.height);
183
+ const dw = Math.max(1, Math.round(scale ? img.width * scale : w));
184
+ const dh = Math.max(1, Math.round(scale ? img.height * scale : h));
185
+ // Contain draws only the fitted rectangle, so the empty margin stays untouched.
186
+ const cw = fit === "contain" ? Math.min(dw, w) : w;
187
+ const ch = fit === "contain" ? Math.min(dh, h) : h;
188
+ const ctx = kit.createCanvas(Math.max(1, cw), Math.max(1, ch)).getContext("2d");
189
+ ctx.imageSmoothingQuality = "high";
190
+ ctx.drawImage(img, Math.round((cw - dw) / 2), Math.round((ch - dh) / 2), dw, dh);
191
+ const { data } = ctx.getImageData(0, 0, cw, ch);
192
+ const bits = applyFilter(rgbaToGray(data, cw, ch), cw, ch, el.filter ?? { mode: "dither", style: "floyd" });
193
+ const local = blank(w, h, 0);
194
+ const ox = Math.floor((w - cw) / 2);
195
+ const oy = Math.floor((h - ch) / 2);
196
+ for (let y = 0; y < ch; y++) for (let x = 0; x < cw; x++) local.data[(oy + y) * w + ox + x] = bits[y * cw + x] ? INK : WHITE;
197
+ return local;
198
+ }
199
+
200
+ /** White on black inside the box: ink turns white, everything else black. */
201
+ function invertBox(local, w, h) {
202
+ for (let y = 0; y < h; y++) {
203
+ for (let x = 0; x < w; x++) {
204
+ const i = (y + local.pad) * local.lw + x + local.pad;
205
+ local.data[i] = local.data[i] === INK ? WHITE : INK;
206
+ }
207
+ }
208
+ }
209
+
210
+ /** Stamp a local bitmap on the page, turned `degrees` clockwise around its box centre. */
211
+ function composite(page, pageW, pageH, local, x0, y0, w, h, degrees) {
212
+ const angle = (degrees * Math.PI) / 180;
213
+ const cos = Math.cos(angle);
214
+ const sin = Math.sin(angle);
215
+ const cx = x0 + w / 2;
216
+ const cy = y0 + h / 2;
217
+ const hw = local.lw / 2;
218
+ const hh = local.lh / 2;
219
+ const reachX = Math.abs(hw * cos) + Math.abs(hh * sin);
220
+ const reachY = Math.abs(hw * sin) + Math.abs(hh * cos);
221
+ const yEnd = Math.min(pageH, Math.ceil(cy + reachY));
222
+ const xEnd = Math.min(pageW, Math.ceil(cx + reachX));
223
+ for (let py = Math.max(0, Math.floor(cy - reachY)); py < yEnd; py++) {
224
+ for (let px = Math.max(0, Math.floor(cx - reachX)); px < xEnd; px++) {
225
+ const dx = px + 0.5 - cx;
226
+ const dy = py + 0.5 - cy;
227
+ const lx = Math.floor(dx * cos + dy * sin + hw);
228
+ const ly = Math.floor(-dx * sin + dy * cos + hh);
229
+ if (lx < 0 || ly < 0 || lx >= local.lw || ly >= local.lh) continue;
230
+ const v = local.data[ly * local.lw + lx];
231
+ if (v !== NONE) page[py * pageW + px] = v === INK ? 1 : 0;
232
+ }
233
+ }
234
+ }
235
+
236
+ async function renderElement(el, kit, load) {
237
+ const w = Math.max(0, Math.round(el.w * DOTS_PER_MM));
238
+ const h = Math.max(0, Math.round(el.h * DOTS_PER_MM));
239
+ let local;
240
+ switch (el.type) {
241
+ case "text": local = drawText(el, kit, w, h); break;
242
+ case "image": local = await drawImage(el, kit, w, h, load); break;
243
+ case "shape": local = drawShape(el, kit, w, h); break;
244
+ case "path": local = drawPath(el, kit, w, h); break;
245
+ case "qr": local = drawQr(el, w, h); break;
246
+ case "barcode": local = drawBarcode(el, w, h); break;
247
+ default: throw new Error(`design: unknown element type "${el.type}"`);
248
+ }
249
+ if (el.invert) invertBox(local, w, h);
250
+ return { local, w, h };
251
+ }
252
+
253
+ async function renderOne(design, page, kit, load) {
254
+ const { width, height } = pageDots(design, page);
255
+ const bits = new Uint8Array(width * height);
256
+ for (const el of page.elements) {
257
+ const { local, w, h } = await renderElement(el, kit, load);
258
+ composite(bits, width, height, local, Math.round(el.x * DOTS_PER_MM), Math.round(el.y * DOTS_PER_MM), w, h, el.rotation ?? 0);
259
+ }
260
+ return { bits, width, height, ink: countInk(bits) };
261
+ }
262
+
263
+ /** Each image source loads once per render, however many elements use it. */
264
+ function imageLoader(kit) {
265
+ const cache = new Map();
266
+ return (src) => {
267
+ if (!cache.has(src)) cache.set(src, kit.loadImage(src));
268
+ return cache.get(src);
269
+ };
270
+ }
271
+
272
+ /**
273
+ * Render every page at 8 dots/mm, exactly what the printer burns.
274
+ * @param {import("./schema.js").Design} design
275
+ * @param {CanvasKit} kit
276
+ * @returns {Promise<RenderedPage[]>}
277
+ */
278
+ export async function renderDesign(design, kit) {
279
+ const doc = normalizeDesign(design);
280
+ const load = imageLoader(kit);
281
+ const pages = [];
282
+ for (const page of doc.pages) pages.push(await renderOne(doc, page, kit, load));
283
+ return pages;
284
+ }
285
+
286
+ /**
287
+ * Render one page: the 1-bit result, as the printer burns it (grayscale
288
+ * artwork before dithering is NOT shown).
289
+ * @returns {Promise<RenderedPage>}
290
+ */
291
+ export async function renderPage(design, pageIndex, kit) {
292
+ const doc = normalizeDesign(design);
293
+ const page = doc.pages[pageIndex];
294
+ if (!page) throw new Error(`design: no page ${pageIndex + 1}`);
295
+ return renderOne(doc, page, kit, imageLoader(kit));
296
+ }
297
+
298
+ /**
299
+ * Wrap plain artwork (an image source or text) as a one-element design that
300
+ * fills the printer's label: how `inkless print photo.jpg` and the image
301
+ * studio share one pipeline.
302
+ * @param {{ kind: "image", src: string } | { kind: "text", text: string }} art
303
+ * @param {{ printer?: "pm290" | "hp6", heightMm?: number, filter?: import("./schema.js").ImageFilter, aspect?: number }} [options]
304
+ * aspect: source width / height, used to size a PM290 label to the artwork.
305
+ */
306
+ export function designFromArtwork(art, options = {}) {
307
+ const printer = options.printer ?? "pm290";
308
+ const spec = PRINTER_SIZES[printer];
309
+ const { widthMm } = spec;
310
+ const wanted = options.heightMm ?? (options.aspect > 0 ? widthMm / options.aspect : spec.defaultHeightMm);
311
+ const heightMm = spec.heightMm ?? Math.min(spec.maxHeightMm, Math.max(spec.minHeightMm, Math.round(wanted * DOTS_PER_MM) / DOTS_PER_MM));
312
+ const box = { id: "art", x: 0, y: 0, w: widthMm, h: heightMm };
313
+ const element = art.kind === "image"
314
+ ? { ...box, type: "image", src: art.src, fit: "contain", ...(options.filter && { filter: options.filter }) }
315
+ : { ...box, type: "text", text: art.text, font: "sans", weight: 700, align: "center" };
316
+ return normalizeDesign({ version: 1, printer, size: { widthMm, heightMm }, pages: [{ id: "page-1", elements: [element] }] });
317
+ }
@@ -0,0 +1,132 @@
1
+ // @ts-check
2
+ // The inkless design document: what the console edits, what agents write with
3
+ // `inkless console show`, and what `inkless print design.json` renders.
4
+ // Units are millimetres, origin top-left of the label as it reads. 8 dots/mm.
5
+
6
+ /**
7
+ * @typedef {"pm290" | "hp6"} PrinterId
8
+ *
9
+ * @typedef {object} ImageFilter How an image becomes black and white.
10
+ * @property {"dither" | "threshold" | "edges" | "outline" | "halftone"} mode
11
+ * dither: error diffusion / ordered; threshold: one cut-off; edges: edge
12
+ * detection lines; outline: traced shapes drawn as strokes ("vectorize");
13
+ * halftone: round dots of varying size.
14
+ * @property {"floyd" | "atkinson" | "ordered"} [style] for mode "dither"
15
+ * @property {number} [level] 0..255 cut-off, default 128
16
+ * @property {number} [brightness] -255..255, default 0
17
+ * @property {number} [contrast] -255..255, default 0
18
+ * @property {number} [gamma] default 1
19
+ * @property {boolean} [invert]
20
+ * @property {number} [lineMm] stroke width for edges/outline, default 0.25
21
+ * @property {number} [cellMm] dot pitch for halftone, default 1
22
+ *
23
+ * @typedef {object} BaseElement
24
+ * @property {string} id
25
+ * @property {number} x mm
26
+ * @property {number} y mm
27
+ * @property {number} w mm
28
+ * @property {number} h mm
29
+ * @property {number} [rotation] degrees clockwise around the element centre
30
+ * @property {boolean} [invert] draw white on black inside the box
31
+ * @property {string} [template] text, qr and barcode filled from a format: the
32
+ * original text with {{key}} placeholders (see core/formats)
33
+ *
34
+ * @typedef {BaseElement & { type: "text", text: string, font?: "sans" | "serif" | "mono" | "display",
35
+ * sizePt?: number, weight?: 400 | 700, align?: "left" | "center" | "right", lineHeight?: number }} TextElement
36
+ * sizePt: 1 pt = 0.3528 mm. If omitted the text is fitted to the box.
37
+ * @typedef {BaseElement & { type: "image", src: string, fit?: "contain" | "cover" | "stretch", filter?: ImageFilter }} ImageElement
38
+ * src: a data: URL or http(s) URL (the CLI also accepts a file path).
39
+ * @typedef {BaseElement & { type: "shape", shape: "rect" | "ellipse" | "line", strokeMm?: number, fill?: boolean, radiusMm?: number }} ShapeElement
40
+ * @typedef {BaseElement & { type: "qr", value: string }} QrElement
41
+ * @typedef {BaseElement & { type: "barcode", value: string }} BarcodeElement Code 128
42
+ * @typedef {BaseElement & { type: "path", d: string, strokeMm?: number, fill?: boolean, viewW?: number, viewH?: number }} PathElement
43
+ * d: SVG path data in millimetres relative to the element's x/y. Blueprint parts use it.
44
+ * viewW/viewH: the size d was drawn at; when set, d stretches to the box (freehand drawings).
45
+ * @typedef {TextElement | ImageElement | ShapeElement | QrElement | BarcodeElement | PathElement} Element
46
+ *
47
+ * @typedef {object} Page One printed label.
48
+ * @property {string} id
49
+ * @property {string} [name]
50
+ * @property {number} [heightMm] overrides design.size.heightMm for this page (PM290 roll only)
51
+ * @property {Element[]} elements
52
+ *
53
+ * @typedef {object} Design
54
+ * @property {1} version
55
+ * @property {string} [title]
56
+ * @property {PrinterId} printer
57
+ * @property {{ widthMm: number, heightMm: number }} size HP6-C is always 36 x 12
58
+ * @property {Page[]} pages
59
+ * @property {object} [blueprint] settings that produced the pages, see core/blueprint
60
+ * @property {number} [density] printer density override
61
+ * @property {{ id: string, name: string, fields: { key: string, label: string, example: string }[], values: Record<string, string> }} [format]
62
+ * the label format this design was filled from, and the values used
63
+ * @property {{ gridMm?: number, showGrid?: boolean, snap?: boolean, marginMm?: number }} [guides]
64
+ * editor aids only (grid over the label, snapping, margin box); printing ignores them
65
+ */
66
+
67
+ export const DOTS_PER_MM = 8;
68
+ export const PT_TO_MM = 0.3528;
69
+
70
+ export const PRINTER_SIZES = {
71
+ pm290: { widthMm: 48, minHeightMm: 5, maxHeightMm: 500, defaultHeightMm: 30 },
72
+ hp6: { widthMm: 36, heightMm: 12 },
73
+ };
74
+
75
+ let counter = 0;
76
+ export const newId = (prefix = "el") => `${prefix}-${Date.now().toString(36)}-${(counter++).toString(36)}`;
77
+
78
+ /** Fill defaults and fix the size for the printer. Throws on anything unusable. */
79
+ export function normalizeDesign(input) {
80
+ if (!input || typeof input !== "object") throw new Error("design: not an object");
81
+ const printer = input.printer === "hp6" ? "hp6" : "pm290";
82
+ const size = printer === "hp6"
83
+ ? { widthMm: 36, heightMm: 12 }
84
+ : {
85
+ widthMm: Math.min(48, Math.max(5, Number(input.size?.widthMm) || 48)),
86
+ heightMm: Math.min(500, Math.max(5, Number(input.size?.heightMm) || PRINTER_SIZES.pm290.defaultHeightMm)),
87
+ };
88
+ const pages = Array.isArray(input.pages) && input.pages.length ? input.pages : [{ id: "page-1", elements: [] }];
89
+ return {
90
+ ...input,
91
+ version: 1,
92
+ printer,
93
+ size,
94
+ pages: pages.map((page, i) => ({
95
+ ...page,
96
+ id: page.id ?? `page-${i + 1}`,
97
+ elements: (page.elements ?? []).map((el) => {
98
+ if (!el || typeof el.type !== "string") throw new Error(`design: page ${i + 1} has an element without a type`);
99
+ return { ...el, id: el.id ?? newId(el.type) };
100
+ }),
101
+ })),
102
+ };
103
+ }
104
+
105
+ /** A blank label for a printer. */
106
+ export function emptyDesign(printer = "pm290") {
107
+ return normalizeDesign({ version: 1, printer, title: "Untitled label", pages: [{ id: "page-1", elements: [] }] });
108
+ }
109
+
110
+ /** Page size in dots. */
111
+ export function pageDots(design, page) {
112
+ const heightMm = design.printer === "pm290" ? page.heightMm ?? design.size.heightMm : design.size.heightMm;
113
+ return { width: Math.round(design.size.widthMm * DOTS_PER_MM), height: Math.round(heightMm * DOTS_PER_MM) };
114
+ }
115
+
116
+ /** An example used by docs, tests and the console's "new label". */
117
+ export const EXAMPLE_DESIGN = normalizeDesign({
118
+ version: 1,
119
+ title: "Parts bin",
120
+ printer: "pm290",
121
+ size: { widthMm: 48, heightMm: 30 },
122
+ pages: [{
123
+ id: "page-1",
124
+ elements: [
125
+ { id: "title", type: "text", x: 3, y: 3, w: 30, h: 9, text: "M3 SCREWS\n12 MM", font: "sans", weight: 700 },
126
+ { id: "sub", type: "text", x: 3, y: 13, w: 30, h: 3, text: "socket head · stainless", font: "mono", sizePt: 7 },
127
+ { id: "rule", type: "shape", shape: "line", x: 3, y: 17, w: 42, h: 0, strokeMm: 0.3 },
128
+ { id: "date", type: "text", x: 3, y: 19, w: 26, h: 7, text: "BIN 07\nSHELF B", font: "mono", weight: 700 },
129
+ { id: "qr", type: "qr", x: 37, y: 19, w: 8, h: 8, value: "https://github.com/apresmoi/inkless" },
130
+ ],
131
+ }],
132
+ });
@@ -0,0 +1,46 @@
1
+ // @ts-check
2
+ // Move a design to another printer: every page scaled to fit the new label and centred.
3
+ import { DOTS_PER_MM, PRINTER_SIZES, normalizeDesign } from "../design/schema.js";
4
+
5
+ const round = (value, step = 0.1) => Math.round(value / step) * step;
6
+ const toDots = (mm) => Math.round(mm * DOTS_PER_MM) / DOTS_PER_MM;
7
+ const { minHeightMm, maxHeightMm } = PRINTER_SIZES.pm290;
8
+
9
+ /** A PM290 label length, kept on the roll's limits and whole dots. */
10
+ export const clampLength = (mm) => toDots(Math.min(maxHeightMm, Math.max(minHeightMm, mm)));
11
+
12
+ /**
13
+ * The same design on another printer. Notes say what may not survive the shrink.
14
+ * @param {import("../design/schema.js").Design} design
15
+ * @param {import("../design/schema.js").PrinterId} printer
16
+ * @returns {{ design: import("../design/schema.js").Design, notes: string[] }}
17
+ */
18
+ export function retargetDesign(design, printer) {
19
+ if (printer === design.printer) return { design, notes: [] };
20
+ const notes = new Set();
21
+ const pages = design.pages.map((page) => {
22
+ const from = { w: design.size.widthMm, h: design.printer === "pm290" ? page.heightMm ?? design.size.heightMm : design.size.heightMm };
23
+ const to = printer === "hp6" ? { w: 36, h: 12 } : { w: 48, h: clampLength((from.h * 48) / from.w) };
24
+ const s = Math.min(to.w / from.w, to.h / from.h);
25
+ const ox = (to.w - from.w * s) / 2;
26
+ const oy = (to.h - from.h * s) / 2;
27
+ const elements = page.elements.map((el) => {
28
+ const next = { ...el, x: round(ox + el.x * s), y: round(oy + el.y * s), w: round(el.w * s), h: round(el.h * s) };
29
+ if (next.type === "text" && next.sizePt) next.sizePt = round(next.sizePt * s, 0.5);
30
+ if ((next.type === "shape" || next.type === "path") && next.strokeMm) next.strokeMm = Math.max(0.15, round(next.strokeMm * s, 0.05));
31
+ if (s < 1 && next.type === "qr" && next.w < 10) notes.add("QR gets small and may not scan");
32
+ if (s < 1 && next.type === "text" && (next.sizePt ? next.sizePt < 6 : next.h < 2.5)) notes.add("Small text gets hard to read");
33
+ if (s !== 1 && next.type === "path" && !next.viewW) notes.add("Pieces change size");
34
+ return next;
35
+ });
36
+ return { ...page, heightMm: printer === "pm290" ? to.h : undefined, elements };
37
+ });
38
+ const first = pages[0]?.heightMm ?? 12;
39
+ const next = normalizeDesign({
40
+ ...design,
41
+ printer,
42
+ size: printer === "hp6" ? { widthMm: 36, heightMm: 12 } : { widthMm: 48, heightMm: first },
43
+ pages: pages.map((page) => ({ ...page, heightMm: page.heightMm === first ? undefined : page.heightMm })),
44
+ });
45
+ return { design: next, notes: [...notes] };
46
+ }