diff --git a/frontend/src/cameraManager.js b/frontend/src/cameraManager.js new file mode 100644 index 0000000..b2a3471 --- /dev/null +++ b/frontend/src/cameraManager.js @@ -0,0 +1,222 @@ +// Shared camera stream manager used by any component that needs webcam access +// (WebcamFileSource, Scan). Centralizing this means every consumer gets device +// enumeration, preferred-camera memory, stream reuse and disconnect/reconnect +// handling for free instead of re-implementing it per component. +class CameraManager { + constructor() { + this.availableCameras = []; + this.activeStream = null; + this.selectedCameraId = null; + this.isInitialized = false; + this.streamUsers = 0; + } + + async enumerateDevices() { + try { + const devices = await navigator.mediaDevices.enumerateDevices(); + const videoDevices = devices.filter((d) => d.kind === 'videoinput' && d.deviceId); + + if (videoDevices.length === 0) return this.availableCameras; + + const uniqueMap = new Map(); + videoDevices.forEach((device) => uniqueMap.set(device.deviceId, device)); + + this.availableCameras = Array.from(uniqueMap.values()); + return this.availableCameras; + } catch (err) { + console.error('Error enumerating devices:', err); + return []; + } + } + + loadPreferredCamera() { + const savedCameras = this.getRecentCameras(); + if (savedCameras.length === 0) return null; + + if (this.availableCameras.length === 0) { + this.selectedCameraId = savedCameras[0]; + return savedCameras[0]; + } + + for (const cameraId of savedCameras) { + if (this.availableCameras.some((cam) => cam.deviceId === cameraId)) { + this.selectedCameraId = cameraId; + return cameraId; + } + } + return null; + } + + getRecentCameras() { + try { + const saved = localStorage.getItem('recentCameraIds'); + return saved ? JSON.parse(saved) : []; + } catch (err) { + console.error('Error loading recent cameras:', err); + return []; + } + } + + savePreferredCamera(cameraId) { + if (!cameraId) return; + + const recentCameras = this.getRecentCameras(); + const updated = [cameraId, ...recentCameras.filter((id) => id !== cameraId)]; + + try { + localStorage.setItem('recentCameraIds', JSON.stringify(updated)); + this.selectedCameraId = cameraId; + } catch (err) { + console.error('Error saving recent cameras:', err); + } + } + + async openStream(cameraId = null) { + const targetCameraId = cameraId || this.selectedCameraId; + + if (this.activeStream) { + const currentSettings = this.activeStream.getVideoTracks()[0].getSettings(); + if (currentSettings.deviceId === targetCameraId) { + this.streamUsers++; + return this.activeStream; + } + this.closeStream(true); + } + + if (!this.isInitialized) { + await this.enumerateDevices(); + this.isInitialized = true; + } + + this.selectedCameraId = this._selectCamera(targetCameraId); + + const constraints = { + video: this.selectedCameraId + ? { deviceId: { ideal: this.selectedCameraId } } + : { facingMode: 'environment' }, + audio: false, + }; + + try { + this.activeStream = await navigator.mediaDevices.getUserMedia(constraints); + this.streamUsers = 1; + await this.enumerateDevices(); + + const actualDeviceId = this.activeStream.getVideoTracks()[0]?.getSettings().deviceId; + if (actualDeviceId) this.selectedCameraId = actualDeviceId; + + this.activeStream.getVideoTracks().forEach((track) => { + track.onended = () => this.handleTrackEnded(track); + }); + + return this.activeStream; + } catch (err) { + console.error('Error opening camera stream:', err); + if (err.name === 'OverconstrainedError' && this.selectedCameraId) { + this.selectedCameraId = null; + localStorage.removeItem('recentCameraIds'); + return await this.openStream(); + } + throw err; + } + } + + _selectCamera(targetCameraId) { + if (targetCameraId) return targetCameraId; + + const preferredCamera = this.loadPreferredCamera(); + if (preferredCamera) return preferredCamera; + + return this.availableCameras[0]?.deviceId || null; + } + + async switchCamera(cameraId) { + this.savePreferredCamera(cameraId); + const wasActive = this.streamUsers > 0; + this.closeStream(true); + return wasActive ? await this.openStream(cameraId) : null; + } + + async handleTrackEnded(track) { + console.warn('Camera track ended (may have been unplugged)'); + const disconnectedDeviceId = track.getSettings().deviceId; + + this.activeStream = null; + this.streamUsers = 0; + await this.enumerateDevices(); + + if (this.availableCameras.some((cam) => cam.deviceId === disconnectedDeviceId)) return; + + if (this.availableCameras.length === 0) { + console.error('No cameras available after disconnection'); + this._dispatchCameraEvent('camera-disconnected', { error: 'No cameras available' }); + return; + } + + const fallbackCameraId = this._selectFallbackCamera(); + const fallbackCamera = this.availableCameras.find((cam) => cam.deviceId === fallbackCameraId); + + try { + await this.openStream(fallbackCameraId); + this._dispatchCameraEvent('camera-reconnected', { + deviceId: fallbackCameraId, + label: fallbackCamera?.label || 'Unknown', + }); + } catch (err) { + console.error('Failed to open fallback camera:', err); + this._dispatchCameraEvent('camera-disconnected', { error: 'No cameras available' }); + } + } + + _selectFallbackCamera() { + const recentCameras = this.getRecentCameras(); + for (const cameraId of recentCameras) { + if (this.availableCameras.some((cam) => cam.deviceId === cameraId)) { + return cameraId; + } + } + + return this.availableCameras[0]?.deviceId; + } + + _cleanCameraLabel(label) { + if (!label) return 'Unknown'; + const parts = label.split(':').map((p) => p.trim()); + if (parts.length === 2 && parts[0] === parts[1]) { + return parts[0]; + } + return label; + } + + _dispatchCameraEvent(eventName, detail) { + if (detail.label) { + detail.label = this._cleanCameraLabel(detail.label); + } + window.dispatchEvent(new CustomEvent(eventName, { detail })); + } + + closeStream(force = false) { + if (!this.activeStream) return; + + this.streamUsers = force ? 0 : Math.max(0, this.streamUsers - 1); + + if (this.streamUsers === 0) { + this.activeStream.getTracks().forEach((track) => track.stop()); + this.activeStream = null; + } + } + + getAvailableCameras() { + return this.availableCameras; + } + + getActiveStream() { + return this.activeStream; + } + + getSelectedCameraId() { + return this.selectedCameraId; + } +} + +export default new CameraManager(); diff --git a/frontend/src/components/inputs/WebcamFileSource.vue b/frontend/src/components/inputs/WebcamFileSource.vue index 61be6c0..1c6bc99 100644 --- a/frontend/src/components/inputs/WebcamFileSource.vue +++ b/frontend/src/components/inputs/WebcamFileSource.vue @@ -54,12 +54,13 @@ Save - - Select Camera Source - - {{ camera.label }} + + + {{ cleanCameraLabel(camera.label) || `Camera ${availableCameras.indexOf(camera) + 1}` }} @@ -74,6 +75,8 @@ \ No newline at end of file + diff --git a/frontend/src/label-layouts.js b/frontend/src/label-layouts.js index ae413b9..f052d06 100644 --- a/frontend/src/label-layouts.js +++ b/frontend/src/label-layouts.js @@ -1,33 +1,118 @@ -// Each template's `layout` is a tree as described in label.js, with "qrcode"/"text" leaves' -// `content` a function from the resolved field values (see label.js's buildLabelFields) to what -// they render - `null`/`undefined` from that function means the field isn't available yet (see -// templateIsAvailable below). A template is only selectable once every leaf's `content` resolves -// to a value. +// Each template's `layout` is a tree as described in label.js, with leaves whose `type` is one of +// label.js's QR_LEAF_TYPES keys or "text", and whose `content` is a function from the resolved +// field values (see label.js's buildLabelFields) to what they render - `null`/`undefined` from +// that function means the field isn't available yet (see templateIsAvailable below). A template +// is only selectable once every leaf's `content` resolves to a value. const GAP = {type: "empty", "min-width": "1mm", "min-height": "1mm"}; +// The full "just the code" matrix: every {symbology, error-correction level, [rMQR] size +// strategy} label.js's QR_LEAF_TYPES supports, one template each - a plain `id` (no suffix) is +// always anyd's own defaults, ecc "M" and (rMQR only) size "balanced". Coverage isn't uniform +// (see QR_LEAF_TYPES): full QR gets all four ecc grades L/M/Q/H; Micro QR swaps "L" (QR's actual +// lowest) for the even-lower, M1-only, detection-only "Detection" and has no "H" at all; rMQR +// only ever supports ecc "M" or "H", each of those crossed with all three size strategies +// (balanced/min/max). Generated (rather than hand-writing every near-duplicate entry) so a +// symbology/level/size this matrix is missing is one new row here, not a new block to keep in +// sync with its neighbors. `id` doubles as the layout's leaf `type`, since that's exactly what +// QR_LEAF_TYPES is keyed by. +const QR_ONLY_TEMPLATES = [ + { + id: "qr-l", name: "QR code only (low error correction)", + description: "Just the code, at QR's lowest error-correction level - fits more data (or a " + + "smaller code) for the same text, but less tolerant of damage.", + }, + {id: "qr", name: "QR code only", description: "Just the code - smallest label, prints fastest."}, + { + id: "qr-q", name: "QR code only (quartile error correction)", + description: "Just the code, at QR's second-highest (quartile) error-correction level - a " + + "middle ground between code size and damage tolerance.", + }, + { + id: "qr-h", name: "QR code only (high error correction)", + description: "Just the code, at QR's highest error-correction level - still scans if scuffed " + + "or partly obscured, at the cost of a bigger code for the same text.", + }, + { + id: "mqr-d", name: "Micro QR code only (detection only)", + description: "Just the code, in the more compact Micro QR format at its lowest, M1-only level - " + + "the smallest QR-family code there is, but can only tell a scan is corrupted, not " + + "recover from it.", + }, + { + id: "mqr-l", name: "Micro QR code only (low error correction)", + description: "Just the code, in the more compact Micro QR format at its low error-correction level.", + }, + { + id: "mqr", name: "Micro QR code only", + description: "Just the code, in the more compact Micro QR format - smallest label, prints fastest.", + }, + { + id: "mqr-q", name: "Micro QR code only (quartile error correction)", + description: "Just the code, in the more compact Micro QR format at its highest (quartile) " + + "error-correction level.", + }, + { + id: "rmqr", name: "rMQR code only", + description: "Just the code, in the rectangular rMQR format, sized for the smallest total area " + + "that fits the text - smallest label, prints fastest.", + }, + { + id: "rmqr-min", name: "rMQR code only (shortest, widest)", + description: "Just the code, in the rectangular rMQR format, preferring the flattest/widest " + + "symbol that fits the text - shortest across the tape, longest along it.", + }, + { + id: "rmqr-max", name: "rMQR code only (tallest, narrowest)", + description: "Just the code, in the rectangular rMQR format, preferring the tallest/narrowest " + + "symbol that fits the text - tallest across the tape, shortest along it.", + }, + { + id: "rmqr-h", name: "rMQR code only (high error correction)", + description: "Just the code, in the rectangular rMQR format at its high error-correction level, " + + "sized for the smallest total area that fits the text - still scans if scuffed or partly " + + "obscured, at the cost of a bigger code for the same text.", + }, + { + id: "rmqr-h-min", name: "rMQR code only (high error correction, shortest/widest)", + description: "Just the code, in the rectangular rMQR format at its high error-correction level, " + + "preferring the flattest/widest symbol that fits the text.", + }, + { + id: "rmqr-h-max", name: "rMQR code only (high error correction, tallest/narrowest)", + description: "Just the code, in the rectangular rMQR format at its high error-correction level, " + + "preferring the tallest/narrowest symbol that fits the text.", + }, +].map(t => ({...t, required_vars: ["text"], layout: [{type: t.id, content: c => c.text}]})); + export const LABEL_TEMPLATES = [ { - id: "qr", name: "QR code only", description: "Just the code - smallest label, prints fastest.", - required_vars: ["text"], - layout: [{type: "qrcode", content: c => c.text}] + id: "mqr-token", name: "MQR Token", description: "The code with the encoded text printed next to it.", + required_vars: ["shortId"], + layout: [{type: "mqr", content: c => c.shortId}] }, + { + id: "qr-url", name: "MQR Token", description: "The code with the encoded text printed next to it.", + required_vars: ["shortUrl"], + layout: [{type: "qr-h", content: c => c.shortUrl}] + },...QR_ONLY_TEMPLATES, + { id: "qr-text", name: "QR code + text", description: "The code with the encoded text printed next to it.", required_vars: ["text"], - layout: [{type: "qrcode", content: c => c.text}, GAP, {type: "text", content: c => c.text?.split("\n")}] + layout: [{type: "qr", content: c => c.text}, GAP, {type: "text", content: c => c.text?.split("\n")}] }, { id: "qr-text-below", name: "QR code + text below", description: "The code with the encoded text printed below it.", required_vars: ["text"], - layout: [[{type: "qrcode", content: c => c.text}, GAP, {type: "text", content: c => c.text?.split("\n")}]] + layout: [[{type: "qr", content: c => c.text}, GAP, {type: "text", content: c => c.text?.split("\n")}]] }, { id: "id-qr-text-vertical", name: "ID + QR code + text below", description: "The code with the encoded text printed below it.", required_vars: ["itemId", "text", "userHandle"], layout: [[{type: "text", content: c => "Item: "+c.itemId}, GAP, { - type: "qrcode", + type: "qr", content: c => c.text }, GAP, {type: "text", content: c => c.userHandle}]] }, @@ -68,31 +153,38 @@ export const LABEL_TEMPLATES = [ id: "item-url-qr-handle", name: "Item URL + handle", description: "Scannable item URL, with the item's compact handle printed alongside.", required_vars: ["itemUrl", "itemHandle"], - layout: [{type: "qrcode", content: c => c.itemUrl}, GAP, {type: "text", content: c => c.itemHandle}] + layout: [{type: "qr", content: c => c.itemUrl}, GAP, {type: "text", content: c => c.itemHandle}] }, { id: "item-url-qr-owner", name: "Item URL + owner", description: "Scannable item URL, with the owner's handle printed alongside.", required_vars: ["itemUrl", "userHandle"], - layout: [{type: "qrcode", content: c => c.itemUrl}, GAP, {type: "text", content: c => c.userHandle}] + layout: [{type: "qr", content: c => c.itemUrl}, GAP, {type: "text", content: c => c.userHandle}] }, { id: "item-url-qr-id", name: "Item URL + item ID", description: "Scannable item URL, with the bare item id printed alongside.", required_vars: ["itemUrl", "itemId"], - layout: [{type: "qrcode", content: c => c.itemUrl}, GAP, {type: "text", content: c => c.itemId}] + layout: [{type: "qr", content: c => c.itemUrl}, GAP, {type: "text", content: c => c.itemId}] }, { id: "item-url-qr-owner-id", name: "Item URL + owner + ID", description: "Scannable item URL, with the owner's handle and the item id on two lines alongside.", required_vars: ["itemUrl", "userHandle", "itemId"], - layout: [{type: "qrcode", content: c => c.itemUrl}, GAP, {type: "text", content: c => [c.userHandle, c.itemId]}] + layout: [{type: "qr", content: c => c.itemUrl}, GAP, {type: "text", content: c => [c.userHandle, c.itemId]}] + }, + { + id: "short-url-qr", name: "Short link (QR code)", + description: "Scannable short link for this item or storage location - more compact than " + + "the full URL. Available for any element with a resolvable short link, not just items.", + required_vars: ["shortUrl"], + layout: [{type: "qr", content: c => c.shortUrl}] }, { id: "item-url-qr-owner-id2", name: "Item URL + owner + ID", description: "Scannable item URL, with the owner's handle and the item id on two lines alongside.", required_vars: ["itemUrl", "userHandle", "itemId"], - layout: [{type: "qrcode", content: c => c.itemUrl}, GAP, [{ + layout: [{type: "qr", content: c => c.itemUrl}, GAP, [{ type: "text", content: c => c.userHandle }, GAP, {type: "text", content: c => c.itemId}]] @@ -171,8 +263,8 @@ function mapTree(node, fn) { } // A content leaf's resolved value counts as present only if every part of it is - a single -// string for "qrcode"/plain "text", every line for a multi-line "text" (see LABEL_TEMPLATES' -// "owner-id-text" and "item-url-qr-owner-id"). +// string for a QR-family leaf (any label.js QR_LEAF_TYPES entry) or plain "text", every line for a +// multi-line "text" (see LABEL_TEMPLATES' "owner-id-text" and "item-url-qr-owner-id"). function isResolved(value) { return Array.isArray(value) ? value.every(isResolved) : value !== undefined && value !== null; } diff --git a/frontend/src/label.js b/frontend/src/label.js index 404e3e5..d095b0a 100644 --- a/frontend/src/label.js +++ b/frontend/src/label.js @@ -4,21 +4,57 @@ import {encodeHandleForUrl} from "@/router" // anyd-qr.js's own loadAnyDCode() memoizes the wasm instantiation itself, so calling it more // than once (each of Print.vue and LabelLayoutPreview.vue does, on mount) is free - `anyd` just // mirrors its resolved value so buildRenderTree below can use it synchronously. Until it -// resolves, a "qrcode" leaf throws (see encodeQr) the same way an oversized value already does - -// callers already have to handle layoutContent throwing, so this reuses that path rather than -// adding a second failure mode. +// resolves, a QR-family leaf (any QR_LEAF_TYPES entry) throws (see encodeQr) the same way an +// oversized value already does - callers already have to handle layoutContent throwing, so this +// reuses that path rather than adding a second failure mode. let anyd = null; export function preloadQrEncoder() { return loadAnyDCode().then(instance => { anyd = instance; }); } -// The three symbologies anyd-qr.js exposes (see its CodeType) - Print.vue's code-type selector -// offers exactly these. rMQR's matrix isn't square (see encodeQr's width/height below), unlike -// qr/micro-qr, which always are. -export const QR_CODE_TYPES = ["qr", "micro-qr", "rmqr"]; +// Maps each of label-layouts.js's LABEL_TEMPLATES leaf types that draw a code to the anyd-qr.js +// symbology/error-correction level (and, for rMQR, size strategy) it renders as (see anyd's +// EncodeOptions - `ecc`/`size` - and its per-symbology EcLevel enums, `wasm.rs`'s +// qr_ec/micro_ec/rmqr_ec/rmqr_size) - which combination a given label uses is baked into its +// layout tree (see label-layouts.js's "qr"-prefixed templates), rather than a single choice +// applied to every code leaf alike, so there's no longer a global selector for any of them (see +// Print.vue). A plain symbology id (no suffix) always means anyd's own defaults - ecc "M", rMQR +// size "balanced" - every other value gets a "-" suffix naming it: +// - ecc: the same letter anyd itself uses (qr_ec/micro_ec's L/M/Q/H), except micro-qr's +// "Detection" (`MicroEcLevel::Detection`, an M1-only error-*detection*-but-not-correction mode +// with no plain single-letter grade of its own). Coverage isn't uniform across symbologies +// (see qr_ec/micro_ec/rmqr_ec) - full QR takes all four grades, Micro QR swaps "L" (QR's +// actual lowest) for "Detection" (lower still, but M1-only) and has no "H" at all, and rMQR +// only ever supports "M" or "H". +// - size (rMQR only, see rmqr_size/SizeStrategy): "min"/"max" prefer the shortest (flattest, +// widest) or tallest (narrowest) symbol that fits the text, over the default "balanced" +// (smallest total module area) - which shape to prefer depends on which of the tape's two +// axes (across vs. along the feed) is more constrained. +// rMQR's matrix isn't square (see encodeQr's width/height below), unlike qr/micro-qr, which +// always are. +const QR_LEAF_TYPES = { + "qr-l": {codeType: "qr", ecc: "L"}, + qr: {codeType: "qr", ecc: "M"}, + "qr-q": {codeType: "qr", ecc: "Q"}, + "qr-h": {codeType: "qr", ecc: "H"}, + "mqr-d": {codeType: "micro-qr", ecc: "Detection"}, + "mqr-l": {codeType: "micro-qr", ecc: "L"}, + mqr: {codeType: "micro-qr", ecc: "M"}, + "mqr-q": {codeType: "micro-qr", ecc: "Q"}, + rmqr: {codeType: "rmqr", ecc: "M"}, + "rmqr-min": {codeType: "rmqr", ecc: "M", size: "min"}, + "rmqr-max": {codeType: "rmqr", ecc: "M", size: "max"}, + "rmqr-h": {codeType: "rmqr", ecc: "H"}, + "rmqr-h-min": {codeType: "rmqr", ecc: "H", size: "min"}, + "rmqr-h-max": {codeType: "rmqr", ecc: "H", size: "max"}, +}; -function encodeQr(text, codeType) { +function isQrLeaf(node) { + return node.type in QR_LEAF_TYPES; +} + +function encodeQr(text, codeType, options) { if (!anyd) { throw new Error("The QR encoder is still loading — try again in a moment."); } @@ -28,7 +64,7 @@ function encodeQr(text, codeType) { // width/height (see its ModuleMatrix type), same as the old library's BitMatrix. width/height // are kept separate rather than a single `size` (the old library's own shape, always square) // since rMQR symbols are rectangular. - const {width, height, modules} = anyd.encode(codeType, new TextEncoder().encode(text), {ecc: "M"}).matrix; + const {width, height, modules} = anyd.encode(codeType, new TextEncoder().encode(text), options).matrix; return {width, height, get: (row, col) => modules[row * width + col] !== 0}; } @@ -60,9 +96,11 @@ export function tapeFromStatus(status) { (the root, depth 0, is always a row), or stacked (a *column*) at odd depth. To turn a row into a column, wrap it in an extra one-element array - that array is one depth deeper, so its lone child (the original row) is now read at odd depth. - - An object is a leaf: {type: "qrcode", content} / {type: "text", content} draw a QR code - or text block, where `content` is a function from the resolved field values to the - string (or, for "text", an array of strings - one per line) to render. {type: "empty", + - An object is a leaf: {type, content} where `type` is one of QR_LEAF_TYPES' keys draws a + QR/Micro QR/rMQR code at that id's symbology/error-correction level (see QR_LEAF_TYPES + above), {type: "text", content} draws a text block - either way `content` is a function + from the resolved field values to the string (or, for "text", an array of strings - one + per line) to render. {type: "empty", "min-width": "2mm"} / {type: "empty", "min-height": "2mm"} is a spacer with no ink of its own - the *only* way padding/gaps enter a layout, since nothing here draws a border, margin or gap on its own. An "empty" leaf's dimension always names the axis its @@ -140,10 +178,10 @@ function parseMm(value, key) { requesting the direction a split doesn't naturally combine in just inverts its own relation. */ function relation(node, ownAxis, wantWidth, pxPerMm) { if (!isSplit(node)) { - if (node.type === "qrcode" && node.crispWidth !== undefined) { + if (isQrLeaf(node) && node.crispWidth !== undefined) { return {a: 0, b: wantWidth ? node.crispWidth : node.crispHeight}; } - if (node.type === "qrcode" || node.type === "text") { + if (isQrLeaf(node) || node.type === "text") { const aspect = node.aspect; return wantWidth ? {a: aspect, b: 0} : {a: 1 / aspect, b: 0}; } @@ -206,7 +244,7 @@ function positionTree(node, ownAxis, x, y) { /* A QR code needs an integer number of pixels per module to render crisply rather than blurring at a fractional scale, so its true size is whatever that rounds down to - almost never the - scale-free box its aspect ratio alone would suggest. Called once every qrcode leaf has a + scale-free box its aspect ratio alone would suggest. Called once every QR-family leaf has a provisional (scale-free) box from a first layoutTree pass, this pins each one's real box.width/box.height as `crispWidth`/`crispHeight`, so relation() above starts treating it as a fixed size, the same as an "empty" leaf, instead of one that scales with whatever height/width @@ -220,7 +258,7 @@ function snapQrToCrispSize(node) { node.forEach(snapQrToCrispSize); return; } - if (node.type === "qrcode") { + if (isQrLeaf(node)) { const {width: modulesW, height: modulesH} = node.qr; const scale = Math.floor(Math.min(node.box.width / modulesW, node.box.height / modulesH)); if (!(scale >= 1)) { @@ -246,22 +284,22 @@ function measureTextBlock(ctx, lines, referencePx) { } /* Turns a resolved content tree (see templateContent below - leaf objects carry a `value` - rather than a `content` function) into one ready for layout: a QR leaf gets its actual encoded - modules (see encodeQr) and an aspect ratio taken from their real width/height - 1 (square) for - qr/micro-qr, but not for rMQR, whose symbols are rectangular - a text leaf gets its measured - natural aspect ratio, and an "empty" leaf passes through untouched. Multi-line text (`value` is - an array) measures as one leaf, not one per line - splitting it into a column of independently- - sized leaves would let each line grow to its own full width, ending up at a different font size - than its neighbors, which is legible but not what "one text field" should look like. `codeType` - is Print.vue's global qr/micro-qr/rmqr choice - see QR_CODE_TYPES - applied to every qrcode leaf - in the tree alike, the same way `orientation` applies to the whole tree in layoutContent. */ -function buildRenderTree(ctx, node, referencePx, codeType) { + rather than a `content` function) into one ready for layout: a QR-family leaf gets its + actual encoded modules (see encodeQr, keyed off the leaf's own type via QR_LEAF_TYPES) and an + aspect ratio taken from their real width/height - 1 (square) for qr/micro-qr, but not for rmqr, + whose symbols are rectangular - a text leaf gets its measured natural aspect ratio, and an + "empty" leaf passes through untouched. Multi-line text (`value` is an array) measures as one + leaf, not one per line - splitting it into a column of independently-sized leaves would let + each line grow to its own full width, ending up at a different font size than its neighbors, + which is legible but not what "one text field" should look like. */ +function buildRenderTree(ctx, node, referencePx) { if (isSplit(node)) { - return node.map(child => buildRenderTree(ctx, child, referencePx, codeType)); + return node.map(child => buildRenderTree(ctx, child, referencePx)); } - if (node.type === "qrcode") { - const qr = encodeQr(node.value, codeType); - return {type: "qrcode", aspect: qr.width / qr.height, qr}; + if (isQrLeaf(node)) { + const {codeType, ...options} = QR_LEAF_TYPES[node.type]; + const qr = encodeQr(node.value, codeType, options); + return {type: node.type, aspect: qr.width / qr.height, qr}; } if (node.type === "text") { const lines = Array.isArray(node.value) ? node.value : [node.value]; @@ -372,7 +410,7 @@ function drawTree(ctx, node, referencePx, textSizesPx) { node.forEach(child => drawTree(ctx, child, referencePx, textSizesPx)); return; } - if (node.type === "qrcode") { + if (isQrLeaf(node)) { drawQrLeaf(ctx, node); } else if (node.type === "text") { textSizesPx.push(drawTextLeaf(ctx, node, referencePx)); @@ -398,14 +436,14 @@ function drawTree(ctx, node, referencePx, textSizesPx) { here needs to know about that rotation, since relation()/layoutTree() below already solve the tree in either direction symmetrically. - Sizing runs twice: a first pass treats every qrcode leaf as the scale-free box its real + Sizing runs twice: a first pass treats every QR-family leaf as the scale-free box its real width/height ratio suggests, purely to find out how much room each one would actually be offered; from that, snapQrToCrispSize pins each one's real (smaller, crisp-pixel) size. The second pass then resolves the whole tree again with that real size fixed in, so every sibling and the overall size reflect what's actually drawn rather than the idealized box no code ever - quite fills. `codeType`, see buildRenderTree. */ -function layoutContent(ctx, content, fixedSize, maxLength, referencePx, pxPerMm, orientation, codeType) { - const tree = buildRenderTree(ctx, content, referencePx, codeType); + quite fills. */ +function layoutContent(ctx, content, fixedSize, maxLength, referencePx, pxPerMm, orientation) { + const tree = buildRenderTree(ctx, content, referencePx); const alongTape = orientation !== "across"; const solve = () => { @@ -438,15 +476,15 @@ function layoutContent(ctx, content, fixedSize, maxLength, referencePx, pxPerMm, canvas transform so it lands correctly in that same raster, rather than transposing every box the tree itself computed. See DEBUG_LEAF_BORDERS above to outline every leaf's box. Returns {textSizesPx}: each "text" leaf's effective font size, in the tree's own left-to-right, - top-to-bottom order. `codeType` (default "qr"), see buildRenderTree/QR_CODE_TYPES. */ -export function drawLabel(canvas, tape, content, orientation = "along", codeType = "qr") { + top-to-bottom order. */ +export function drawLabel(canvas, tape, content, orientation = "along") { const maxLength = tape.printLengthPx ? tape.printLengthPx - tape.leadPx - TRAILING_PADDING_PX : Infinity; const measureCtx = canvas.getContext("2d"); const pxPerMm = tape.dpi / 25.4; const {tree, length: contentLength} = layoutContent( - measureCtx, content, tape.printAreaPx, maxLength, TEXT_REFERENCE_PX, pxPerMm, orientation, codeType); + measureCtx, content, tape.printAreaPx, maxLength, TEXT_REFERENCE_PX, pxPerMm, orientation); const printedLength = tape.printLengthPx || Math.ceil(contentLength + tape.leadPx + TRAILING_PADDING_PX); canvas.width = printedLength; @@ -484,13 +522,13 @@ const FALLBACK_DPI = 203; /* reference resolution for turning "empty" leaves' m /* The no-webusb preview/PNG - same layout tree and renderer as drawLabel, just scaled from a fixed reference height instead of a real tape's, and with no maxLength (there's no physical tape to run out of, so the canvas just grows to fit) and no printer feed margin, since there's - no real print head here to keep clear of. `orientation`/`codeType`, see drawLabel. Returns - {textSizesPx}, see drawLabel. */ -export function drawFallbackLabel(canvas, content, orientation = "along", codeType = "qr") { + no real print head here to keep clear of. `orientation`, see drawLabel. Returns {textSizesPx}, + see drawLabel. */ +export function drawFallbackLabel(canvas, content, orientation = "along") { const measureCtx = canvas.getContext("2d"); const pxPerMm = FALLBACK_DPI / 25.4; const {tree, length: contentLength} = layoutContent( - measureCtx, content, FALLBACK_LABEL_HEIGHT_PX, Infinity, TEXT_REFERENCE_PX, pxPerMm, orientation, codeType); + measureCtx, content, FALLBACK_LABEL_HEIGHT_PX, Infinity, TEXT_REFERENCE_PX, pxPerMm, orientation); canvas.width = Math.ceil(contentLength); canvas.height = FALLBACK_LABEL_HEIGHT_PX; @@ -522,8 +560,15 @@ export function drawFallbackLabel(canvas, content, orientation = "along", codeTy export const LABEL_CONTENT_BUILDERS = { // The self-contained Item URL (see docs/design-in-progress/items-labels.md) - what a // printed label actually encodes, since scanning it has to resolve the right - // frontend/backend/item with no other context, not just this browser's history. - "item-url": ({user, id}) => `${window.location.origin}/i/${encodeHandleForUrl(user)}/${id}`, + // frontend/backend/item with no other context, not just this browser's history. Nothing here + // needs anything beyond the prefill's own {userHandle, id} - the short link (see Print.vue's + // `shortUrl` computed) needs a store lookup no synchronous builder can do, so it's never baked + // into `text` this way; it's just another field/template a user can pick once the page is up. + "item": ({userHandle, id}) => `${window.location.origin}/i/${encodeHandleForUrl(userHandle)}/${id}`, + // Storage locations have no long-form URL route of their own (see router.js - only items get + // an /i/:handle/:id) - so there's nothing to bake synchronously here. Its base vars (below) + // still populate normally, so the short link (Print.vue's `shortUrl`) and any future + // location template are still available; `text` just starts blank until one is picked. }; export function buildLabelContent(prefill) { @@ -534,27 +579,42 @@ export function buildLabelContent(prefill) { return build ? build(prefill.components) : ""; } +// A prefill's {userHandle, id} is the same raw identity for either resource kind below - this +// just splits the handle into label-layouts.js's separate `user`/`domain` base vars the same way +// store.js's own lookupServer does, and tags on whichever id field the resource's own templates +// key their required_vars by. +function splitUserHandle(userHandle) { + if (!userHandle) { + return null; + } + const at = userHandle.indexOf("@"); + return { + user: at === -1 ? userHandle : userHandle.slice(0, at), + domain: at === -1 ? "" : userHandle.slice(at + 1), + }; +} + // Seeds for the *base* label-layouts.js vars (see BASE_VARS there) - keyed by `kind` for the same -// reason LABEL_CONTENT_BUILDERS is. Format-string vars derived from these (itemUrl, itemHandle) -// aren't built here; they're calculated live from whatever the base vars currently are (see -// label-layouts.js's DERIVED_VARS), prefill or hand-typed alike. A field missing from the result -// (rather than present-but-empty) is what label-layouts.js's templateIsAvailable treats as "not -// available", so builders should only include a field once its inputs actually check out. +// reason LABEL_CONTENT_BUILDERS is. Format-string vars derived from these (userHandle, itemUrl, +// itemHandle, …) aren't built here; they're calculated live from whatever the base vars currently +// are (see label-layouts.js's DERIVED_VARS and Print.vue's `shortUrl`), prefill or hand-typed +// alike. A field missing from the result (rather than present-but-empty) is what +// label-layouts.js's templateIsAvailable treats as "not available", so builders should only +// include a field once its inputs actually check out. const LABEL_FIELD_BUILDERS = { - // `user` here is already a full "user@domain" handle (that's the form login usernames take - - // see Login.vue/store.js), so it's split into label-layouts.js's separate `user`/`domain` - // base vars the same way store.js's own lookupServer does, rather than stuffing the whole - // handle into one field the way userHandle (now derived from these two) used to be. - "item-url": ({user, id}) => { - if (!user || !id) { + "item": ({userHandle, id}) => { + const split = splitUserHandle(userHandle); + if (!split || !id) { return {}; } - const at = user.indexOf("@"); - return { - user: at === -1 ? user : user.slice(0, at), - domain: at === -1 ? "" : user.slice(at + 1), - itemId: String(id), - }; + return {...split, itemId: String(id)}; + }, + "storage-location": ({userHandle, id}) => { + const split = splitUserHandle(userHandle); + if (!split || !id) { + return {}; + } + return {...split, locationId: String(id)}; }, }; diff --git a/frontend/src/views/Inventory.vue b/frontend/src/views/Inventory.vue index d157a3a..257f4ba 100644 --- a/frontend/src/views/Inventory.vue +++ b/frontend/src/views/Inventory.vue @@ -43,6 +43,9 @@ + + + @@ -77,6 +80,10 @@ class="btn btn-secondary btn-sm"> + + + @@ -138,6 +145,17 @@ export default { if (owner_identity_id === undefined) return null return shortenedRoute({kind: 'item', owner_identity_id, item_local_id: item.id}) }, + // Routes to Print.vue with this item's own raw identity - userHandle + id, the same shape + // InventoryDetail.vue's own Print label button sends - rather than any pre-built link, so + // the print page can derive every item template (item-handle, owner-handle, item-url, + // the short link, …) itself and isn't tied to whichever one this button "suggests". + // Group-owned items have no individual owner handle - short-id.js's group_item kind + // resolves them via owner_group instead (see shortIdLink above) - so there's no + // {userHandle, id} to build here yet; they get no print link until that's supported too. + printLinkFor(item) { + if (!item.owner) return null + return {path: '/print', query: {kind: 'item', userHandle: item.owner, id: item.id}} + }, }, async mounted() { await this.fetchInventoryItems() diff --git a/frontend/src/views/InventoryDetail.vue b/frontend/src/views/InventoryDetail.vue index 6de684b..bc3bf20 100644 --- a/frontend/src/views/InventoryDetail.vue +++ b/frontend/src/views/InventoryDetail.vue @@ -47,7 +47,7 @@ Delete + @click="$router.push({path: '/print', query: {kind: 'item', userHandle: user, id}})"> Print label diff --git a/frontend/src/views/Print.vue b/frontend/src/views/Print.vue index e71f3eb..f8e9020 100644 --- a/frontend/src/views/Print.vue +++ b/frontend/src/views/Print.vue @@ -102,21 +102,6 @@ - - Code type - - - - - {{ opt.label }} - - - - - Download label as PNG @@ -207,19 +192,6 @@ - - Code type - - - - - {{ opt.label }} - - - - Copies - @@ -287,12 +259,27 @@