diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3705f..a7c6aeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- Label designer: a "Match printer size" button on the printer size note rescales the whole design to the paired printer's label (positions, boxes and text size), and a rejected Width or Length change now says fields extend past the new size and what to do. - Test labels: the cooldown is now 15 seconds and a refused re-print in the designer reads "Printer is busy, try again in Ns" instead of an error; the designer rechecks an offline printer every 15 seconds (plus a "Check again" button), re-saves once if the design changed mid-save, says when the saved design could not be used, and notes that Feie printers print the standard label. The test-print online check honours the virtual printer's longer window. - Label design: a "Print test label" button in the designer that saves a changed design, then sends a sample order to the booth's printer (off with a reason when the booth has no printer or it is offline). A booth picker replaces the 404 for vendors with several booths. New fields and logos land in a free spot instead of on top of existing ones. The rendered preview stays visible until the design changes and no longer waits forever on a stalled request. diff --git a/README.md b/README.md index 9a1fca6..12c80bb 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,12 @@ and as a table from the `md` (768px) breakpoint up. An "All labels / Needs a boo control (a client component, `src/app/dashboard/history/history-filter.tsx`) filters the list (`?unrouted=1` still deep-links to it), test prints have no Reprint, and the copy says "labels" rather than "jobs". +In the sticker designer (`src/app/dashboard/printers/designer/`), when the +label size does not match the selected printer's media, the printer-fit notice +offers a "Match printer size" button that resizes the template to the printer +(`fitTemplateToSize` in `src/lib/sticker-fit.ts`). If fields extend past the new +edge the resize is refused with a specific message instead of a generic error. + `/reset-password` shows its form only to the session a fresh reset link created, within 15 minutes, through a signed recovery-window cookie set by `/auth/callback`. Any other signed-in session gets the expired card. See diff --git a/src/app/dashboard/printers/designer/README.md b/src/app/dashboard/printers/designer/README.md index 09f686b..3c7c1b6 100644 --- a/src/app/dashboard/printers/designer/README.md +++ b/src/app/dashboard/printers/designer/README.md @@ -22,3 +22,5 @@ The designer page carries the tab title "Label design", matching its heading. A failed save shows its message through the shared `@merqo/ui` `FormError`. `loading.tsx` is the route's skeleton, built from the shared `Skeleton`, using the page's `max-w-6xl` cap so the layout does not jump when data arrives; the shared skeleton pulses only when motion is allowed. + +The printer size note offers "Match printer size" (not for Feie), which calls `fitTemplateToSize` from `src/lib/sticker-fit.ts` through the designer's `update()` so undo and saved status keep working. A Width or Length change that would push fields past the margins is refused with a message that names the cause and suggests Match printer size when a printer is paired. diff --git a/src/app/dashboard/printers/designer/printer-fit-notice.tsx b/src/app/dashboard/printers/designer/printer-fit-notice.tsx index 0ac7f97..27bcf77 100644 --- a/src/app/dashboard/printers/designer/printer-fit-notice.tsx +++ b/src/app/dashboard/printers/designer/printer-fit-notice.tsx @@ -1,4 +1,5 @@ import type { StickerTemplate } from "@/lib/sticker-template"; +import { Button } from "@merqo/ui/primitives"; export type DesignerPrinter = { model: string; @@ -18,9 +19,11 @@ const close = (a: number, b: number) => Math.abs(a - b) < 0.05; export function PrinterFitNotice({ printer, template, + onMatch, }: { printer?: DesignerPrinter; template: StickerTemplate; + onMatch?: () => void; }) { if (!printer) return null; if (printer.connector === "vendor_cloud") @@ -36,11 +39,18 @@ export function PrinterFitNotice({ ) return null; return ( -

+

Your {printer.model} label is {printer.labelWidthMm} by{" "} {printer.labelHeightMm} mm, but this sticker is {template.widthMm} by{" "} {template.heightMm} mm. It will be scaled to fit the label and centered. Set the sticker size to match for the sharpest print. -

+ {onMatch && ( +
+ +
+ )} +
); } diff --git a/src/app/dashboard/printers/designer/sticker-designer.dom.test.tsx b/src/app/dashboard/printers/designer/sticker-designer.dom.test.tsx index 21872c5..933470e 100644 --- a/src/app/dashboard/printers/designer/sticker-designer.dom.test.tsx +++ b/src/app/dashboard/printers/designer/sticker-designer.dom.test.tsx @@ -52,6 +52,66 @@ describe("sticker designer prototype", () => { ); expect(screen.queryByRole("note")).not.toBeInTheDocument(); }); + it("suggests Match printer size when a resize is rejected and a printer is paired", () => { + render( + , + ); + fireEvent.change(screen.getByLabelText("Width (mm)"), { + target: { value: "20" }, + }); + fireEvent.blur(screen.getByLabelText("Width (mm)")); + expect(screen.getByRole("alert")).toHaveTextContent( + /Press "Match printer size"/, + ); + }); + it("fits the design to the printer label with Match printer size and saves it", async () => { + save.mockResolvedValueOnce({ ok: true }); + render( + , + ); + fireEvent.click(screen.getByRole("button", { name: "Match printer size" })); + expect(screen.queryByRole("note")).not.toBeInTheDocument(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(screen.getByLabelText("Width (mm)")).toHaveValue(50); + expect(screen.getByLabelText("Length (mm)")).toHaveValue(30); + fireEvent.click(screen.getByRole("button", { name: "Save design" })); + await waitFor(() => + expect(save).toHaveBeenCalledWith( + "booth", + expect.objectContaining({ widthMm: 50, heightMm: 30 }), + ), + ); + }); + it("offers no Match printer size button for a Feie printer", () => { + render( + , + ); + expect( + screen.queryByRole("button", { name: "Match printer size" }), + ).not.toBeInTheDocument(); + }); it("says a Feie printer prints the standard label", () => { render( { }); fireEvent.blur(screen.getByLabelText("Width (mm)")); expect(screen.getByRole("alert")).toHaveTextContent( - /outside the printable margins/i, + /fields extend past the new size.*move or shrink those fields first/i, ); expect(screen.getByLabelText("Width (mm)")).toHaveValue(40); fireEvent.click(screen.getByRole("button", { name: "Reset preview" })); diff --git a/src/app/dashboard/printers/designer/sticker-designer.tsx b/src/app/dashboard/printers/designer/sticker-designer.tsx index a3aeeb6..00ba458 100644 --- a/src/app/dashboard/printers/designer/sticker-designer.tsx +++ b/src/app/dashboard/printers/designer/sticker-designer.tsx @@ -15,6 +15,7 @@ import { StickerSize } from "./sticker-size"; import { PrinterFitNotice, type DesignerPrinter } from "./printer-fit-notice"; import { AddFieldButtons } from "./add-field-buttons"; import { arrowDelta, clampPosition, type DragState } from "./sticker-move"; +import { fitTemplateToSize } from "@/lib/sticker-fit"; import { names } from "./sticker-content"; import { discardLogo, @@ -78,9 +79,24 @@ export function StickerDesigner({ function update(next: StickerTemplate) { const result = stickerTemplateSchema.safeParse(next); if (!result.success) { - setError( - "The label or a field extends outside the printable margins. Adjust the field or use a larger label.", + const resized = + next.widthMm !== template.widthMm || + next.heightMm !== template.heightMm; + const pastEdge = result.error.issues.some( + (issue) => + issue.message === "Element extends outside printable margins", ); + let message = + "The label or a field extends outside the printable margins. Adjust the field or use a larger label."; + if (resized && pastEdge) { + const canMatch = printer && printer.connector !== "vendor_cloud"; + message = `Some fields extend past the new size. ${ + canMatch + ? 'Press "Match printer size" to fit them, or move the fields first.' + : "Move or shrink those fields first." + }`; + } + setError(message); return; } invalidate(); @@ -369,7 +385,20 @@ export function StickerDesigner({
- + + printer && + update( + fitTemplateToSize( + template, + printer.labelWidthMm, + printer.labelHeightMm, + ), + ) + } + />

Fields

diff --git a/src/lib/README.md b/src/lib/README.md index 776e3ce..a96c19c 100644 --- a/src/lib/README.md +++ b/src/lib/README.md @@ -277,3 +277,5 @@ The B1 calibration sample uses the shared label renderer at 40 mm across by 60 m Limits and windows that nothing outside their module reads (`KIT_LIMIT`, `STUCK_AFTER_MS`, `HEALTH_ONLINE_MS`, `SEEN_WRITE_THROTTLE_MS`, `MAX_BATCH_LABELS`, `MAX_LOGOS`, `AUTH_NEXT_MAX_AGE`) are not exported, so `knip` flags any that gain an unused export again. `job-expiry.ts` is the one source for `JOB_EXPIRY_MS` and `CONFIRM_TIMEOUT_MS`; `job-dispatch.ts` imports them rather than re-exporting. `render-job.test.ts` covers the saved-design path, the default-layout fallback and the booth-name lookup. - `sticker-design-status.ts` — `hasStickerDesign(supabase, vendorId)`: whether the vendor has an active label design; drives the Overview "Design your label" card and treats a read error as designed. + +- `sticker-fit.ts` — `fitTemplateToSize`: rescales a sticker template to a new width and length (positions and boxes by the printable-area ratios, text by the smaller ratio, logos keep their aspect), rounded to 0.1 mm so the result still passes `stickerTemplateSchema`. diff --git a/src/lib/sticker-fit.test.ts b/src/lib/sticker-fit.test.ts new file mode 100644 index 0000000..1cd414f --- /dev/null +++ b/src/lib/sticker-fit.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; +import { fitTemplateToSize } from "./sticker-fit"; +import { + defaultStickerTemplate, + stickerTemplateSchema, + type StickerTemplate, +} from "./sticker-template"; + +const logoPath = + "10000000-0000-4000-8000-000000000001/20000000-0000-4000-8000-000000000002/30000000-0000-4000-8000-000000000003.png"; + +const valid = (template: StickerTemplate) => + stickerTemplateSchema.safeParse(template).success; + +describe("fitTemplateToSize", () => { + it("turns the 40x60 default into a valid 50x30 template", () => { + const fitted = fitTemplateToSize(defaultStickerTemplate, 50, 30); + expect(fitted.widthMm).toBe(50); + expect(fitted.heightMm).toBe(30); + expect(valid(fitted)).toBe(true); + }); + + it("scales positions by the ratio of the printable areas", () => { + const fitted = fitTemplateToSize(defaultStickerTemplate, 80, 120); + const first = fitted.elements[0]; + expect(first.xMm).toBeCloseTo(2 + (3 - 2) * (76 / 36), 1); + expect(first.widthMm).toBeCloseTo(24 * (76 / 36), 1); + expect(first.yMm).toBeCloseTo(2 + (3 - 2) * (116 / 56), 1); + expect(valid(fitted)).toBe(true); + }); + + it("scales text by the smaller ratio so it stays inside its box", () => { + const fitted = fitTemplateToSize(defaultStickerTemplate, 50, 30); + const scaled = fitted.elements[0]; + expect(scaled.kind === "field" && scaled.fontSizeMm).toBeCloseTo( + 6 * Math.min(46 / 36, 26 / 56), + 1, + ); + }); + + it("clamps font size to the schema minimum and maximum", () => { + const small = fitTemplateToSize(defaultStickerTemplate, 20, 20); + for (const element of small.elements) + if (element.kind === "field") + expect(element.fontSizeMm).toBeGreaterThanOrEqual(1.5); + const big = fitTemplateToSize( + { + ...defaultStickerTemplate, + elements: [ + { ...defaultStickerTemplate.elements[0], fontSizeMm: 25 }, + ] as StickerTemplate["elements"], + }, + 200, + 500, + ); + const only = big.elements[0]; + expect(only.kind === "field" && only.fontSizeMm).toBe(30); + expect(valid(big)).toBe(true); + }); + + it("keeps a logo's aspect ratio inside its scaled box", () => { + const template: StickerTemplate = { + ...defaultStickerTemplate, + elements: [ + { + id: "40000000-0000-4000-8000-000000000004", + kind: "logo", + path: logoPath, + xMm: 4, + yMm: 4, + widthMm: 20, + heightMm: 10, + }, + ], + }; + const fitted = fitTemplateToSize(template, 100, 60); + const logo = fitted.elements[0]; + expect(logo.widthMm / logo.heightMm).toBeCloseTo(2, 1); + expect(logo.widthMm).toBeLessThanOrEqual(20 * (96 / 36) + 0.01); + expect(logo.heightMm).toBeLessThanOrEqual(10.01); + expect(valid(fitted)).toBe(true); + }); + + it("never lets rounding push an element past the margin", () => { + for (const [w, h] of [ + [43, 37], + [57.3, 31.7], + [20, 20], + [200, 500], + [33.3, 77.7], + ]) + expect(valid(fitTemplateToSize(defaultStickerTemplate, w, h))).toBe(true); + }); + + it("keeps ids and the margin", () => { + const fitted = fitTemplateToSize(defaultStickerTemplate, 50, 30); + expect(fitted.marginMm).toBe(2); + expect(fitted.elements.map((e) => e.id)).toEqual( + defaultStickerTemplate.elements.map((e) => e.id), + ); + }); +}); diff --git a/src/lib/sticker-fit.ts b/src/lib/sticker-fit.ts new file mode 100644 index 0000000..6011eb2 --- /dev/null +++ b/src/lib/sticker-fit.ts @@ -0,0 +1,81 @@ +import type { StickerTemplate } from "@/lib/sticker-template"; + +type Element = StickerTemplate["elements"][number]; + +const MIN_BOX_MM = 2; +const MIN_FONT_MM = 1.5; +const MAX_FONT_MM = 30; +// Absorbs float error so a box that exactly touches the margin is not read as past it. +const EPSILON = 1e-9; + +const round1 = (value: number) => Math.round(value * 10) / 10; +const floor1 = (value: number) => Math.floor(value * 10 + EPSILON) / 10; + +/** + * Places a box of `size` starting near `start` inside [min, max]. Rounding and + * the schema's minimum box size can push a box past the margin, so the box is + * shrunk by 0.1 mm, then moved back, until the end edge fits. + */ +function fitAxis( + start: number, + size: number, + min: number, + max: number, +): [number, number] { + let length = Math.max(MIN_BOX_MM, Math.min(round1(size), floor1(max - min))); + let position = Math.max(min, Math.min(round1(start), max - length)); + while (position + length > max + EPSILON && length > MIN_BOX_MM) + length = round1(length - 0.1); + while (position + length > max + EPSILON && position > min) + position = Math.max(min, round1(position - 0.1)); + return [position, length]; +} + +/** + * Rescales a design to a new sticker size so every element keeps its place + * relative to the printable area. Text grows or shrinks with the smaller of + * the two ratios so it never overflows its box, and logos keep their shape. + */ +export function fitTemplateToSize( + template: StickerTemplate, + widthMm: number, + heightMm: number, +): StickerTemplate { + const m = template.marginMm; + const rx = (widthMm - 2 * m) / (template.widthMm - 2 * m); + const ry = (heightMm - 2 * m) / (template.heightMm - 2 * m); + const uniform = Math.min(rx, ry); + const maxX = widthMm - m; + const maxY = heightMm - m; + + const elements = template.elements.map((element): Element => { + const boxX = m + (element.xMm - m) * rx; + const boxY = m + (element.yMm - m) * ry; + const boxW = element.widthMm * rx; + const boxH = element.heightMm * ry; + + if (element.kind === "logo") { + const w = element.widthMm * uniform; + const h = element.heightMm * uniform; + const [xMm, widthOut] = fitAxis(boxX + (boxW - w) / 2, w, m, maxX); + const [yMm, heightOut] = fitAxis(boxY + (boxH - h) / 2, h, m, maxY); + return { ...element, xMm, yMm, widthMm: widthOut, heightMm: heightOut }; + } + + const [xMm, widthOut] = fitAxis(boxX, boxW, m, maxX); + const [yMm, heightOut] = fitAxis(boxY, boxH, m, maxY); + return { + ...element, + xMm, + yMm, + widthMm: widthOut, + heightMm: heightOut, + fontSizeMm: Math.min( + MAX_FONT_MM, + Math.max(MIN_FONT_MM, round1(element.fontSizeMm * uniform)), + ), + }; + }); + + return { ...template, widthMm, heightMm, elements }; +}