This commit is contained in:
j3d1 2026-08-24 15:57:17 +02:00
parent 8d96bc97c4
commit ed04d98bf1
54 changed files with 661 additions and 1214 deletions

View file

@ -1,7 +1,5 @@
// 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.
// Shared camera stream manager for webcam access (WebcamFileSource, Scan) - centralizes device
// enumeration, preferred-camera memory, stream reuse, and disconnect/reconnect handling.
class CameraManager {
constructor() {
this.availableCameras = [];

View file

@ -73,9 +73,8 @@ export default {
return;
}
try {
// Cached by src alone (content is hash-addressed and immutable - see
// fileCache.js) so every AuthenticatedImage instance showing the same
// file, across the whole app, shares one fetch and one decoded blob.
// Cached by src alone: content is hash-addressed and immutable (see fileCache.js),
// so every instance showing the same file shares one fetch and blob.
const url = await fileCache.get(this.src, async () => {
this.servers = await this.getFriendServers({username: this.owner});
const response = await this.servers.getRaw(this.signAuth, this.src);

View file

@ -6,9 +6,9 @@
<div class="card-body">
<div class="template-grid d-flex flex-wrap align-items-start">
<div v-for="t in labelTemplates" :key="t.id" class="template-option d-flex flex-column text-center"
:class="{'template-option-disabled': !isAvailable(t)}"
:title="isAvailable(t) ? '' : 'Not available - fill in the fields this layout needs above.'"
role="button" @click="isAvailable(t) && $emit('input', t.id)">
:class="{'template-option-disabled': !isSelectable(t)}"
:title="unavailableReason(t)"
role="button" @click="isSelectable(t) && $emit('input', t.id)">
<canvas :ref="el => setTemplateCanvasRef(t.id, el)"
class="img-thumbnail template-thumb-canvas"
:class="{'border-primary': value === t.id}"></canvas>
@ -24,8 +24,7 @@
</template>
<style scoped>
/* This build pins Bootstrap 4 (no gap-* utilities, those are Bootstrap 5.1+), so the spacing
here is plain CSS gap rather than a Bootstrap gap-N class. */
/* This build pins Bootstrap 4 (no gap-* utilities, those are 5.1+) - hence plain CSS gap here. */
.template-grid {
gap: 1rem;
}
@ -43,9 +42,8 @@
display: block;
width: 100%;
height: 10rem;
/* The canvas itself is drawn at whatever size fits its content (see redraw/drawFallbackLabel)
- object-fit scales that down to the thumbnail box the same way it would for an <img>,
no manual zoom math needed. */
/* Canvas draws at whatever size fits its content (see redraw/drawFallbackLabel); object-fit
scales it into the thumbnail box like it would an <img>, no manual zoom math needed. */
object-fit: contain;
background: #fff;
}
@ -58,9 +56,9 @@ import {LABEL_TEMPLATES, templateIsAvailable, templateContent} from "@/label-lay
export default {
name: "LabelLayoutPreview",
props: {
// Named content fields the templates draw from (see label.js's buildLabelFields)
// - kept in sync by the parent, not owned here. A field missing from this object (rather
// than present-but-empty) means a template that needs it is unavailable right now.
// Named content fields templates draw from (see label.js's buildLabelFields), kept in
// sync by the parent. A field's absence (not just empty) means a template needing it is
// unavailable.
fields: {
type: Object,
required: true
@ -70,12 +68,11 @@ export default {
type: String,
required: true
},
// Print.vue's global qr/micro-qr/rmqr choice (see label.js's QR_CODE_TYPES) - passed
// straight through to drawFallbackLabel so these thumbnails match whatever symbology the
// main preview is actually using.
codeType: {
type: String,
default: "qr"
// Ids of the most-recently printed/downloaded templates, most recent first (see
// Print.vue's rememberPrintedTemplate); bubbled to the front of the grid below.
recentTemplateIds: {
type: Array,
default: () => []
}
},
model: {
@ -83,17 +80,29 @@ export default {
event: "input"
},
emits: ["input"],
data() {
return {
// Keyed by template id, holding the error message from its most recent redraw()
// failure (e.g. text too long, or too many QR modules for the thumbnail's fixed
// reference size - see label.js's snapQrToCrispSize). Absent, not just falsy, for a
// template that last drew fine, so `t.id in failed` matches "has a message".
failed: {},
};
},
computed: {
// LABEL_TEMPLATES with recentTemplateIds' entries pulled to the front (most recent
// first), everything else following in its original order.
labelTemplates() {
return LABEL_TEMPLATES;
const recent = this.recentTemplateIds
.map(id => LABEL_TEMPLATES.find(t => t.id === id))
.filter(Boolean);
const recentIds = new Set(recent.map(t => t.id));
return [...recent, ...LABEL_TEMPLATES.filter(t => !recentIds.has(t.id))];
}
},
watch: {
fields() {
this.redraw();
},
codeType() {
this.redraw();
}
},
methods: {
@ -109,10 +118,24 @@ export default {
return templateIsAvailable(t, this.fields);
},
/* Live per-template thumbnails. Always uses the content-fit fallback renderer (rather
than the tape-fed one), regardless of whether a real printer is connected - these are
illustrative previews sized by CSS object-fit, not the accurate to-be-printed canvas
the main preview is. */
// Greyed out (and unclickable) either because a needed field isn't filled in yet
// (isAvailable) or its content failed to render (see redraw()'s catch) - either way
// there's nothing a click could select that would actually show anything.
isSelectable(t) {
return this.isAvailable(t) && !(t.id in this.failed);
},
// The disabled thumbnail's tooltip - empty once it's selectable again.
unavailableReason(t) {
if (!this.isAvailable(t)) {
return "Not available - fill in the fields this layout needs above.";
}
return this.failed[t.id] ?? "";
},
// Live per-template thumbnails. Always uses the content-fit fallback renderer (not the
// tape-fed one) regardless of printer connection - illustrative previews via CSS
// object-fit, not the to-be-printed-accurate canvas the main preview is.
redraw() {
for (const t of LABEL_TEMPLATES) {
const canvas = this.templateCanvases[t.id];
@ -123,27 +146,32 @@ export default {
if (!this.isAvailable(t) || !content) {
canvas.width = 1;
canvas.height = 1;
delete this.failed[t.id];
continue;
}
try {
drawFallbackLabel(canvas, content, "along", this.codeType);
drawFallbackLabel(canvas, content, "along");
delete this.failed[t.id];
} catch (e) {
// A thumbnail that can't render at this content length just stays blank
// rather than surfacing an error for every keystroke.
// Grey the thumbnail out (see isSelectable/unavailableReason) rather than
// leaving it blank - selecting a template that can't render here would only
// hand Print.vue's own redraw the exact same failure.
canvas.width = 1;
canvas.height = 1;
this.failed[t.id] = e.message;
}
}
}
},
created() {
// Keyed by template id, populated by setTemplateCanvasRef() - a plain :ref="t.id" string
// inside v-for would still get Vue's refInFor array-collecting behavior even though
// each iteration uses a different name, turning this.$refs[t.id] into a one-element
// array rather than the canvas itself. A function ref sidesteps that entirely.
// in v-for still gets Vue's refInFor array-collecting behavior despite distinct names per
// iteration, turning this.$refs[t.id] into a one-element array; a function ref avoids that.
this.templateCanvases = {};
},
async mounted() {
// See Print.vue's mounted() - every thumbnail here has a "qrcode" leaf, so there's
// nothing worth drawing before this resolves.
// See Print.vue's mounted() - every thumbnail here has a qr/mqr/rmqr leaf, so nothing's
// worth drawing before the wasm resource resolves.
await preloadQrEncoder();
this.redraw();
}

View file

@ -38,9 +38,7 @@ export default {
return;
}
const data = new Uint8Array(buffer);
// SHA-256 via Web Crypto - must match the backend's own content hash
// (files/models.py, hashlib.sha256) so a hash computed here can later be
// used to identify the same File row server-side without a mismatch.
// SHA-256 must match the backend's content hash for file identification. See docs/implementation.md#sha-256-file-hashing-must-match-the-backend.
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, "0")).join("");

View file

@ -61,9 +61,7 @@ export default {
return;
}
const data = new Uint8Array(buffer);
// SHA-256 via Web Crypto - must match the backend's own content hash
// (files/models.py, hashlib.sha256) so a hash computed here can later
// be used to identify the same File row server-side without a mismatch.
// SHA-256 must match the backend's content hash for file identification. See docs/implementation.md#sha-256-file-hashing-must-match-the-backend.
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, "0")).join("");

View file

@ -41,9 +41,7 @@ export default {
return;
}
const data = new Uint8Array(buffer);
// SHA-256 via Web Crypto - must match the backend's own content hash
// (files/models.py, hashlib.sha256) so a hash computed here can later be
// used to identify the same File row server-side without a mismatch.
// SHA-256 must match the backend's content hash for file identification. See docs/implementation.md#sha-256-file-hashing-must-match-the-backend.
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, "0")).join("");

View file

@ -206,9 +206,7 @@ export default {
const mimeType = this.dataImage.split(';')[0].split(':')[1];
const data = this.dataImage.split(',')[1];
const raw_data = atob(data);
// SHA-256 via Web Crypto - must match the backend's own content hash (files/models.py,
// hashlib.sha256) so a hash computed here can later be used to identify the same File
// row server-side without a mismatch.
// SHA-256 must match the backend's content hash for file identification. See docs/implementation.md#sha-256-file-hashing-must-match-the-backend.
const bytes = Uint8Array.from(raw_data, c => c.charCodeAt(0));
const hashBuffer = await crypto.subtle.digest('SHA-256', bytes);
const hash = Array.from(new Uint8Array(hashBuffer))

View file

@ -263,21 +263,10 @@
import * as BIcons from "bootstrap-icons-vue";
import { mapActions } from 'vuex';
/**
* Bulk Item Import Workflow
*
* This single component implements every step of the 'import-items' workflow.
* Steps 1 (File Upload) and 6 (Import Items) have fully custom UI; the
* remaining steps (2-5, 7) currently fall back to a generic "in progress"
* placeholder driven by this workflow's own step metadata, but can be
* fleshed out here later without touching any other file.
*/
// Implements every step of 'import-items'; steps 2-5,7 use a generic placeholder. See docs/implementation.md#bulk-item-import-workflow.
export default {
name: 'BulkItemImportWorkflow',
// Metadata describing this workflow, co-located with its implementation
// so there is a single source of truth per workflow type. Consumed by
// `@/workflows.js` (via `Component.meta`) to assemble the catalog used
// by the Workflows and WorkflowDetail views.
// Co-located workflow metadata, single source of truth per workflow type. See docs/implementation.md#workflow-meta-co-location.
meta: {
slug: 'import-items',
title: 'Bulk Item Import',
@ -426,15 +415,12 @@ export default {
},
async analyzeFile(file) {
// Parsing happens entirely client-side. The backend never sees the
// raw file - only the structured `items` list produced here, sent
// later as generic payload/request body.
// Parsing happens entirely client-side; the backend only ever sees the resulting `items` list.
if (file.name.endsWith('.csv')) {
const text = await file.text();
this.parsedRows = this.parseCsv(text);
} else {
// For Excel files, you'd use a library like SheetJS to parse
// client-side. This is a mock implementation.
// Mock implementation; a real Excel parser would use a library like SheetJS.
this.detectedColumns = ['Name', 'Category', 'Quantity', 'Unit', 'Description'];
this.parsedRows = [
{ Name: 'Sample Item 1', Category: 'Tools', Quantity: '1', Unit: 'piece', Description: 'Sample description' },
@ -472,9 +458,7 @@ export default {
});
},
// Convert the fully parsed rows + column mapping into the generic item
// dicts consumed by the "Import Items" step, which creates each one via
// the standard generic InventoryItem create endpoint.
// Converts parsed rows + column mapping into item dicts for the "Import Items" step.
buildItemsFromMapping() {
return this.parsedRows.map(row => ({
name: this.columnMapping.name ? row[this.columnMapping.name] : '',
@ -595,10 +579,7 @@ export default {
this.importError = null;
const created_item_ids = [];
const errors = [];
// Items were fully parsed client-side (File Upload step). The backend
// never sees the source file or any bulk-import-specific endpoint -
// each row is created through the same generic
// POST /api/inventory_items/ endpoint any other client would use.
// Each row is created via the same generic POST /api/inventory_items/ endpoint any client would use.
for (const [index, row] of this.items.entries()) {
if (!row.name) {
errors.push(`Row ${index + 1}: missing required "name" field, skipped.`);

View file

@ -890,11 +890,7 @@ export default {
methods: {
...mapActions(['stageFile', 'unstageFile']),
loadFromPayload() {
// `photos`' durable state is the WorkflowInstance.staged_files relation itself (kept
// in sync directly by stageFile()/unstageFile(), not by writing to payload) - so it's
// seeded from the prop, not from payload. Entries restored this way have no local
// bytes yet (this session never uploaded them), so `dataUrl` stays null - the gallery
// falls back to fetching a thumbnail by hash via AuthenticatedImage (see below).
// `photos` is seeded from workflowInstance.staged_files, not payload. See docs/implementation.md#staged-photos-are-the-durable-state.
this.photos = (this.workflowInstance.staged_files || []).map(hash => ({
hash,
name: null,
@ -919,11 +915,7 @@ export default {
// --- Step 1: Photo capture ---
thumbnailPathForHash(hash, size = 256) {
// files/media_urls.py's thumbnail_urls generates (and disk-caches) a resized JPEG
// on first request - a gallery card only needs a small image, not the full-size
// original. Looked up by the derived storage path, mirroring hash_upload()
// (files/models.py) - matches how FileSerializer.name already builds file URLs
// elsewhere in the app (e.g. AuthenticatedImage's `src` for item files).
// Derived storage path for a disk-cached resized thumbnail. See docs/implementation.md#thumbnail-lookup-by-hash.
return `/media/${size}/${hash.slice(0, 2)}/${hash.slice(2, 4)}/${hash.slice(4, 6)}/${hash.slice(6)}/`;
},
@ -943,21 +935,14 @@ export default {
}));
this.photos.push(...staged);
// Persist each photo server-side right away, keyed to this workflow instance, so it
// survives a reload or a switch to another device. WorkflowInstance.staged_files is
// the durable record of this - nothing about photos needs to go into payload too.
// Persists each photo server-side immediately so it survives a reload/device switch. See docs/implementation.md#staged-photos-are-the-durable-state.
await Promise.all(staged.map(async ({hash, data, mime_type}) => {
try {
await this.stageFile({
lifetime_id: this.workflowInstance.id,
file: {data, mime_type}
});
// Once persisted, the gallery can show the server-fetched thumbnail instead
// of the local dataUrl (kept around for step 2's client-side processing).
// Re-lookup by hash rather than mutating the closed-over `photo` object -
// that reference predates this.photos.push() above, so it's the raw object,
// not the reactive proxy Vue tracks; writing to it wouldn't trigger a
// re-render.
// Re-lookup by hash rather than mutate the closed-over `photo`, which predates this.photos.push() and isn't Vue's reactive proxy. See docs/implementation.md#thumbnail-lookup-by-hash.
const photo = this.photos.find(p => p.hash === hash);
if (photo) photo.uploaded = true;
} catch (error) {
@ -1254,8 +1239,7 @@ export default {
object-fit: cover;
}
/* Stacks the local dataUrl preview and the server-fetched AuthenticatedImage on top of each
other during their crossfade, instead of one disappearing before the other lays out. */
/* Stacks the dataUrl preview and server-fetched image during their crossfade so neither disappears before the other lays out. */
.photo-thumb-wrap {
position: relative;
height: 150px;

View file

@ -756,21 +756,10 @@
<script>
import * as BIcons from "bootstrap-icons-vue";
/**
* Foto First Bulk Import Workflow
*
* This single component implements every step of the 'foto-first-bulk-import'
* workflow (photo capture, image processing, item detail entry and import
* completion). Keeping the whole workflow in one file avoids splitting
* closely related state (photos, processed images, completed items) across
* many small step components and their prop/emit boundaries.
*/
// Implements every step of 'foto-first-bulk-import' in one file. See docs/implementation.md#foto-first-bulk-import-workflow.
export default {
name: 'FotoFirstBulkImportWorkflow',
// Metadata describing this workflow, co-located with its implementation
// so there is a single source of truth per workflow type. Consumed by
// `@/workflows.js` (via `Component.meta`) to assemble the catalog used
// by the Workflows and WorkflowDetail views.
// Co-located workflow metadata, single source of truth per workflow type. See docs/implementation.md#workflow-meta-co-location.
meta: {
slug: 'foto-first-bulk-import',
title: 'Foto First Bulk Import',

View file

@ -282,11 +282,9 @@ class ServerSet {
function ServerSetUnion(serverSets) {
return new Proxy(serverSets, {
get: function (target, prop, receiver) {
// Note: 'add' must be checked before the generic funcs-forwarding branch below,
// because ServerSet.prototype also defines its own `add(server)` method (for
// adding a raw server address string to a single ServerSet). Without this check
// first, `funcs.includes('add')` would always be true and the union-specific
// "add a ServerSet to this union" logic below would never be reached.
// Must precede the generic forwarding check below: ServerSet.prototype also has its
// own add(server), so funcs.includes('add') would otherwise always be true and this
// union-specific add would never run.
if (prop === 'add') {
return function (serverset) {
if (!serverset || !(serverset instanceof ServerSet)) {

View file

@ -1,12 +1,4 @@
// Shared, session-lifetime cache for the bytes behind AuthenticatedImage's `src` (a
// `/media/...` hash-addressed path - see backend/files/media_urls.py). Content there is
// immutable and hash-addressed (SHA-256), so a cache hit never needs revalidation: the
// same `src` string can only ever resolve to the same bytes, for any owner/requester.
//
// Deliberately NOT Vuex state - this holds Blob/object-URL data that nothing needs
// reactive access to (components only bind the resulting object-URL string, which they
// hold in their own local state), so a plain module-level Map avoids Vue's reactivity
// overhead entirely and sidesteps proxying Blob instances for no benefit.
// Session cache for hash-addressed image bytes, deliberately not Vuex. See docs/implementation.md#filecache-design-rationale.
const MAX_BYTES = 150 * 1024 * 1024; // budget for decoded image bytes before evicting LRU entries
@ -18,8 +10,7 @@ class FileCache {
}
_touch(key) {
// Delete+re-insert moves this entry to the "most recently used" end of the
// Map's iteration order, without needing a separate linked list.
// Delete+re-insert moves this entry to the MRU end of the Map's iteration order.
const entry = this._entries.get(key);
this._entries.delete(key);
this._entries.set(key, entry);
@ -40,8 +31,7 @@ class FileCache {
}
}
// fetcher: () => Promise<Blob>. Called at most once per key even if many components
// ask for the same key while the first request is still in flight.
// fetcher: () => Promise<Blob>, called at most once per key even under concurrent callers.
async get(key, fetcher) {
if (this._entries.has(key)) {
this._touch(key);

View file

@ -1,9 +1,3 @@
// Embeds/extracts a handle in a URL path segment. See docs/federation.md's "Embedding a
// `#`-bearing handle in a URL": `#` starts a URI's fragment component, so a group handle
// (`#name@domain`) or classification handle (`origin#type:name`) can't appear unescaped in a
// path segment. `+` stands in for `#` there instead of the usual %23 - safe to reverse
// unambiguously because every field a handle is built from is already required to exclude `+`
// (see federation.md's Reserved characters). The canonical handle itself never changes; this only
// affects how one gets embedded in, or read back out of, a URL path segment.
// Escapes `#` as `+` for use in a URL path segment. See docs/implementation.md#escaping-hash-in-handles-for-url-path-segments.

View file

@ -1,20 +1,9 @@
// 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.
// A template's layout tree, content resolution, and selectability contract. See
// docs/implementation.md#template-layout-tree.
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.
// Generated matrix of "just the code" templates covering every QR_LEAF_TYPES combo. See
// docs/implementation.md#generated-qr-only-template-matrix.
const QR_ONLY_TEMPLATES = [
{
id: "qr-l", name: "QR code only (low error correction)",
@ -194,52 +183,40 @@ export const LABEL_TEMPLATES = [
// Every field name any template's required_vars names, in first-seen order.
export const KNOWN_VARS = [...new Set(LABEL_TEMPLATES.flatMap(t => t.required_vars))];
// A derived var is a format string calculated from other vars rather than typed directly - it
// doesn't get its own input, just a read-only, live-recalculated display next to the ones that
// do (see Print.vue and withDerivedVars below). `inputs` names every var (base or, in principle,
// another derived one - see itemUrl/itemHandle below, which both read the derived userHandle)
// `calc` reads - declared up front rather than inferred from calc's body so BASE_VARS below can
// include a var like "webdomain" that only feeds a calculation and that no template ever
// references directly. Declaration order matters here: withDerivedVars runs these in a single
// pass, so a derived var must be declared after every other derived var it depends on.
// DERIVED_VARS shape and declaration-order invariant. See
// docs/implementation.md#derived-vars-shape-and-ordering.
export const DERIVED_VARS = {
// The full owner handle (see federation.md's Unique Handles section / ToolshedUser's
// separate username/domain columns) - kept as two base vars (user, domain) rather than one,
// since that's how the account itself is actually shaped, with this just the display/URL form.
// Full user@domain handle, kept as separate user/domain base vars since that's how the
// account is actually shaped (see federation.md's Unique Handles); this is just the
// display/URL form.
userHandle: {
inputs: ["user", "domain"],
calc: (f) => `${f.user}@${f.domain}`,
},
// 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. `webdomain` defaults to this
// browser's own origin (see Print.vue) but is editable, since any frontend can resolve any
// handle - the label doesn't have to point back at whichever frontend happened to print it.
// Self-contained Item URL (see docs/design-in-progress/items-labels.md) - what a printed
// label encodes, since scanning it must resolve everything with no other context. `webdomain`
// defaults to this origin but is editable, since any frontend can resolve any handle.
itemUrl: {
inputs: ["webdomain", "userHandle", "itemId"],
calc: (f) => `${f.webdomain}/i/${f.userHandle}/${f.itemId}`,
},
// The compact "owner handle + id" form from docs/design-in-progress/items-labels.md -
// meaningful only where context already makes clear it's a Toolshed item, unlike itemUrl.
// Compact "owner handle + id" form (see docs/design-in-progress/items-labels.md) - meaningful
// only where context already makes clear it's a Toolshed item, unlike itemUrl.
itemHandle: {
inputs: ["userHandle", "itemId"],
calc: (f) => `${f.userHandle}:${f.itemId}`,
},
};
// What Print.vue's content form offers a plain text input for: every KNOWN_VAR a template
// references directly, minus the derived ones, plus every var a DERIVED_VARS calculation itself
// needs (like "webdomain", which no template ever names). A template still lights up only once
// every one of its own required_vars, base or derived, has a value (see templateIsAvailable
// below).
// Text-input vars = template KNOWN_VARS minus derived ones, plus any var a DERIVED_VARS calc
// needs (e.g. "webdomain") even if no template names it directly.
export const BASE_VARS = [...new Set([
...KNOWN_VARS.filter(v => !(v in DERIVED_VARS)),
...Object.values(DERIVED_VARS).flatMap(d => d.inputs).filter(v => !(v in DERIVED_VARS)),
])];
// Runs every DERIVED_VARS calculation against `fields` (already holding the base vars - see
// Print.vue), returning a copy with each one's result added wherever all of its own inputs are
// present, so a caller never has to know DERIVED_VARS' internal {inputs, calc} shape.
// Runs each DERIVED_VARS calc against `fields`, adding the result wherever its inputs are
// present, so callers never need to know DERIVED_VARS' {inputs, calc} shape.
export function withDerivedVars(fields) {
const result = {...fields};
for (const [name, {inputs, calc}] of Object.entries(DERIVED_VARS)) {
@ -262,16 +239,14 @@ function mapTree(node, fn) {
return Array.isArray(node) ? node.map(child => mapTree(child, fn)) : fn(node);
}
// A content leaf's resolved value counts as present only if every part of it is - a single
// 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").
// Resolved only if every part is - a single string for a QR-family/"text" leaf, every line for a
// multi-line "text" (see "owner-id-text" and "item-url-qr-owner-id" above).
function isResolved(value) {
return Array.isArray(value) ? value.every(isResolved) : value !== undefined && value !== null;
}
// LabelLayoutPreview.vue's thumbnail grid and Print.vue's big preview both resolve a template
// through these two functions rather than each re-implementing the leaf-walking/field-resolving
// logic itself.
// Shared by LabelLayoutPreview.vue's grid and Print.vue's preview, so neither reimplements
// leaf-walking/field-resolving itself.
export function templateIsAvailable(t, fields) {
let available = true;
walkLeaves(t.layout, leaf => {
@ -282,9 +257,8 @@ export function templateIsAvailable(t, fields) {
return available;
}
/* Resolves a template's `content` functions against actual field values, turning its layout
tree into one ready for label.js's drawLabel/drawFallbackLabel - or null if there's nothing to
render yet (every leaf's value is still empty, e.g. before the user has typed anything). */
// Resolves t's content leaves against fields into a tree for label.js's
// drawLabel/drawFallbackLabel, or null if nothing to render yet.
export function templateContent(t, fields) {
const tree = mapTree(t.layout, leaf => leaf.type === "empty" ? leaf : {...leaf, value: leaf.content(fields)});
let hasContent = false;

View file

@ -1,38 +1,16 @@
import {loadAnyDCode} from "../vendor/anyd-qr.js";
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 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.
// Mirrors loadAnyDCode()'s memoized wasm instance for synchronous use in buildRenderTree. See docs/implementation.md#qr-encoder-loading.
let anyd = null;
export function preloadQrEncoder() {
return loadAnyDCode().then(instance => { anyd = instance; });
}
// 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 "-<name>" 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.
// Maps label-layouts.js leaf types to anyd-qr.js symbology/ecc/size options, via a naming
// convention (plain id = anyd defaults; "-<name>" suffix names an ecc letter or rMQR size
// strategy). See docs/implementation.md#qr-leaf-type-mapping.
const QR_LEAF_TYPES = {
"qr-l": {codeType: "qr", ecc: "L"},
qr: {codeType: "qr", ecc: "M"},
@ -58,12 +36,9 @@ function encodeQr(text, codeType, options) {
if (!anyd) {
throw new Error("The QR encoder is still loading — try again in a moment.");
}
// BitMatrix-alike view over anyd's row-major Uint8Array, matching the shape drawQrLeaf/
// snapQrToCrispSize below expect (they predate this and were written against the "qrcode"
// package's own modules.size/get()). anyd's matrix already excludes the quiet zone from
// 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.
// BitMatrix-alike shim over anyd's row-major matrix, matching the old "qrcode" package's
// modules.size/get() shape that drawQrLeaf/snapQrToCrispSize expect. See
// docs/implementation.md#qr-module-matrix-shim.
const {width, height, modules} = anyd.encode(codeType, new TextEncoder().encode(text), options).matrix;
return {width, height, get: (row, col) => modules[row * width + col] !== 0};
}
@ -89,51 +64,13 @@ export function tapeFromStatus(status) {
};
}
/*
A layout is a tree built from two shapes, alternating orientation by nesting depth:
- An array is a "split" node: its children sit side by side (a *row*) at even depth
(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, 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
enclosing split flows along: "min-width" inside a row, "min-height" inside a column.
See label-layouts.js's LABEL_TEMPLATES for concrete trees.
*/
// A layout tree alternates row/column split nodes by nesting depth, with QR/text/empty leaves.
// See docs/implementation.md#layout-tree-structure.
const TEXT_REFERENCE_PX = 100; /* font size text leaves measure their natural aspect ratio at */
// Below 10px, a general-purpose sans-serif gets blurry/illegible, so drawTextLeaf switches to one
// of these bitmap-style fonts instead (see ../scss/_pixel-fonts.scss) - Tom Thumb for the smallest
// sizes, Silkscreen once there's enough room for its more conventional letterforms.
//
// Both were chosen only after rendering single letters in a real browser *at raw canvas pixel
// sizes* and inspecting the actual pixels - checking that fillText was merely *called* doesn't
// confirm anything legible got drawn, and neither does a DPI-adjusted size that was never the
// number actually handed to ctx.font. Silkscreen confirmed clean at 8px+. A third candidate,
// PICO-8, also rendered cleanly across the whole range, but has no lowercase glyphs at all - it
// silently draws lowercase input as uppercase - which rules it out for real label content (item
// handles, URLs) that isn't reliably all-caps. Tom Thumb's declared ascent/descent (0 / ~fontPx,
// backwards from a normal font) turned out not to be a centering quirk: its actual visible ink is
// only ~1/3.2 of its own nominal font-size (confirmed both by measuring actualBoundingBox at
// several sizes and by a live-browser check - "16px" reads as roughly 5px of real glyph height),
// hence the `scale` below - whatever logical size is requested, the font is actually drawn that
// many times larger so its real ink comes out at the intended size. Silkscreen's declared size
// already matches its ink, so it has no `scale` (equivalent to 1).
//
// belowPx and MIN_READABLE_TEXT_PX below are both compared against the *logical* (unscaled)
// fontPx, deliberately not adjusted for the tape's dpi: a browser's font rasterizer only ever
// sees a raw pixel count, with no notion of "physical size" at all, so that's what determines
// whether a glyph's fine detail survives - confirmed by the same real-Chromium testing, where a
// raw 4.35px render was a solid blob regardless of what a dpi-scaled version of that number would
// have implied.
// Below 10px, a general-purpose sans-serif gets illegible, so drawTextLeaf switches to a bitmap
// font (Tom Thumb/Silkscreen) instead; see the empirical rationale (font choice, `scale`, and why
// sizes aren't dpi-adjusted) at docs/implementation.md#pixel-font-selection.
const PIXEL_FONT_TIERS = [
{belowPx: 8, family: "Tom Thumb", scale: 3.2},
{belowPx: 10, family: "Silkscreen"},
@ -143,11 +80,7 @@ function fontFamilyFor(fontPx) {
return PIXEL_FONT_TIERS.find(t => fontPx < t.belowPx) ?? {family: "sans-serif"};
}
// Tom Thumb (see PIXEL_FONT_TIERS above) held up down to 5px in the same real-Chromium pixel-level
// verification - a plain sans-serif this small would fail the old MIN_READABLE_TEXT_PX=8 floor
// that predates it. Below this, drawTextLeaf leaves that one field blank rather than drawing
// illegible ink - see there for why that's a quieter failure than rejecting the whole label over
// it.
// Tom Thumb reads clearly down to 5px per the same real-Chromium testing as PIXEL_FONT_TIERS; below this, drawTextLeaf blanks the field instead of rejecting the whole label.
const MIN_READABLE_TEXT_PX = 5;
function isSplit(node) {
@ -162,20 +95,9 @@ function parseMm(value, key) {
return parseFloat(match[1]);
}
/* Every node's width/height relate to each other affinely - width = A*height + B for a node
read in row context, height = A*width + B in column context - because a leaf is either
scale-free (a text block, whose aspect ratio holds at any size: A = aspect or 1/aspect,
B = 0) or a fixed physical size (an "empty" spacer, or a QR code once its crisp pixel size is
known - see snapQrToCrispSize below: A = 0, B = the size in px). Splits combine their
children's relations by addition (a row's total width is the sum of each child's width for
the shared height, and symmetrically for a column), which stays affine, so the same two
numbers describe a whole subtree no matter how deeply it nests.
`ownAxis` is true if the split directly containing `node` is a row, false if a column - for
a leaf, that's what "empty" measures itself against; for a split, its own axis (and thus how
it combines its children) is always the opposite, per the alternating-depth rule. `wantWidth`
is true to ask for {A, B} such that width = A*height + B, false for height = A*width + B;
requesting the direction a split doesn't naturally combine in just inverts its own relation. */
// Every node's width/height relate affinely (width = A*height + B, or symmetrically); `ownAxis`
// and `wantWidth` pick which direction and against which split axis. See
// docs/implementation.md#affine-width-height-relations.
function relation(node, ownAxis, wantWidth, pxPerMm) {
if (!isSplit(node)) {
if (isQrLeaf(node) && node.crispWidth !== undefined) {
@ -198,23 +120,16 @@ function relation(node, ownAxis, wantWidth, pxPerMm) {
return {a, b};
}
if (a === 0) {
// Every child is a fixed size (a === 0) in the combining direction - e.g. a row that's
// just one crisp QR leaf, with no scale-free (text) sibling to invert against. Inverting
// "width = b" for an a of 0 would divide by zero: a constant width genuinely doesn't
// determine a height, since nothing here actually scales with it. Ask each child directly
// for its own size in the wanted direction instead (every one of them must be similarly
// fixed, since only a fixed leaf ever contributes a === 0), and take the largest - the
// shared dimension has to fit whichever child needs the most room, with any child that
// ends up with room to spare centered within it (see drawQrLeaf).
// Every child is fixed-size (a === 0) in the combining direction, so inverting would
// divide by zero. See docs/implementation.md#fixed-size-relation-edge-case.
const otherParts = node.map(child => relation(child, axis, wantWidth, pxPerMm));
return {a: 0, b: Math.max(...otherParts.map(p => p.b))};
}
return {a: 1 / a, b: -b / a}; // invert: solve the affine relation the other way
}
/* Top-down: given the fixed (width, height) box `node` must exactly fill, assigns that box to
it and, recursively, an appropriately-shaped box to every descendant. `ownAxis` carries the
same meaning as in relation() above. */
// Top-down: assigns the fixed (width, height) box `node` must exactly fill, recursively, to
// every descendant; `ownAxis` carries the same meaning as in relation() above.
function layoutTree(node, ownAxis, width, height, pxPerMm) {
node.box = {width, height};
if (!isSplit(node)) {
@ -232,9 +147,8 @@ function layoutTree(node, ownAxis, width, height, pxPerMm) {
}
}
/* Second top-down pass: turns each node's already-sized box into an absolute (x, y) position,
placing a row's children left to right and a column's top to bottom. Kept separate from
layoutTree since a node's size doesn't depend on its position, only on its box dimensions. */
// Second top-down pass: turns each already-sized box into an absolute (x, y) position; kept
// separate from layoutTree since a node's size doesn't depend on its position.
function positionTree(node, ownAxis, x, y) {
node.box.x = x;
node.box.y = y;
@ -254,17 +168,8 @@ 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 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
it's offered. A second relation()/layoutTree() pass (see layoutContent) then resizes everything
else around that real footprint, so nothing downstream reserves - and leaves unfilled - room
for a squarer/differently-shaped code than what actually gets drawn. Kept as two independent
dimensions rather than one `crispSize` (as when every code here was a square QR) since an rMQR
symbol isn't square - see encodeQr. */
// Pins each QR-family leaf's real crisp-pixel box.width/box.height so relation() above starts
// treating it as fixed-size. See docs/implementation.md#crisp-qr-sizing.
function snapQrToCrispSize(node) {
if (isSplit(node)) {
node.forEach(snapQrToCrispSize);
@ -282,12 +187,9 @@ function snapQrToCrispSize(node) {
}
}
// Always measures in sans-serif at the fixed reference size, even though drawTextLeaf may end up
// actually drawing in one of PIXEL_FONT_TIERS' fonts - the final effective size (and so which
// font applies) isn't known until layoutTree has already sized the box this aspect ratio feeds
// into. The pixel fonts are close enough in proportion for basic Latin/digits that the tiny
// resulting mismatch is invisible in practice at these sizes, and the MIN_READABLE_TEXT_PX check
// still catches anything that genuinely doesn't fit.
// Always measures in sans-serif at the reference size, since the eventual font (see
// PIXEL_FONT_TIERS) isn't known until layoutTree sizes the box this aspect ratio feeds into; the
// resulting mismatch is invisible in practice, and MIN_READABLE_TEXT_PX still catches real failures.
function measureTextBlock(ctx, lines, referencePx) {
ctx.font = `${referencePx}px sans-serif`;
const width = Math.max(...lines.map(line => ctx.measureText(line).width));
@ -295,15 +197,8 @@ function measureTextBlock(ctx, lines, referencePx) {
return {width, height};
}
/* 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-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. */
// Converts a resolved content tree (see templateContent) into one ready for layout. See
// docs/implementation.md#render-tree-construction.
function buildRenderTree(ctx, node, referencePx) {
if (isSplit(node)) {
return node.map(child => buildRenderTree(ctx, child, referencePx));
@ -337,54 +232,40 @@ function drawQrLeaf(ctx, node) {
}
}
// Returns the effective (raw, un-normalized) font size drawn at - or that would have been, if
// it's too small to draw, see below - drawTree collects these into drawLabel/drawFallbackLabel's
// textSizesPx.
// Returns the effective (un-normalized) font size drawn at, or that would have been if too small
// to draw (see below); drawTree collects these into drawLabel/drawFallbackLabel's textSizesPx.
function drawTextLeaf(ctx, node, referencePx) {
const fontPx = referencePx * (node.box.height / node.naturalHeight);
// Even the smallest PIXEL_FONT_TIERS entry stops being legible below this - rather than
// reject the whole label over one field that's too small (the old behavior), just leave this
// leaf blank; its box was already accounted for, so nothing else in the layout shifts.
// Below the smallest legible size, leave this leaf blank rather than reject the whole label;
// its box was already accounted for, so nothing else in the layout shifts.
if (fontPx < MIN_READABLE_TEXT_PX) {
return fontPx;
}
const {family, scale = 1} = fontFamilyFor(fontPx);
const isPixelFont = family !== "sans-serif";
// A pixel font's glyphs are meant to land exactly on the pixel grid - node.box.x/y are
// ordinary layout math (sums/quotients of affine-solved sizes) and essentially never land on
// a whole pixel, so drawing at their exact fractional size/position would misalign a pixel
// font's 1px-wide strokes the same as it would any other font. Snapping size and position to
// the nearest whole pixel fixes that; sans-serif is left at its exact fractional fit, since
// ordinary anti-aliased text is expected to (and looks fine) regardless of position.
// Pixel-font glyphs need whole-pixel size/position to stay grid-aligned, since node.box.x/y
// are ordinary (fractional) layout math; sans-serif is left exact since anti-aliasing handles
// fractional positions fine.
const snap = isPixelFont ? Math.round : (v) => v;
const drawFontPx = snap(fontPx);
// `scale` (Tom Thumb only, see PIXEL_FONT_TIERS above) corrects for a font whose declared
// size doesn't match its real visible ink - the size actually handed to ctx.font, not
// drawFontPx itself, which stays the logical size everything else here (box centering, line
// stacking) is measured against.
// `scale` (Tom Thumb only, see PIXEL_FONT_TIERS above) corrects the size handed to ctx.font
// for its real ink; drawFontPx itself stays the logical size used for centering/stacking math.
ctx.font = `${drawFontPx * scale}px "${family}"`;
// A @font-face family already in use elsewhere on the page loads in time for this, but canvas
// text silently falls back to the next font in the stack (there isn't one here, so the
// browser default) if drawn before its first-ever load finishes - unlike DOM text, a canvas
// fillText never waits or repaints on its own once the real font arrives. Kicking off the load
// here means only that very first draw at a given size risks the fallback; every redraw after
// it (Print.vue's live preview redraws on every keystroke) picks up the real font.
// Canvas text silently falls back if drawn before a not-yet-loaded font resolves, unlike DOM
// text. See docs/implementation.md#canvas-font-loading.
if (isPixelFont) {
document.fonts.load(ctx.font);
}
ctx.textAlign = "center";
const centerX = snap(node.box.x + node.box.width / 2);
const lineHeight = node.box.height / node.lines.length;
// Lines stack as a block, each centered under the last - keeps a multi-line field reading as
// one unit rather than drifting apart.
// Lines stack as a block, each centered under the last, so a multi-line field reads as one unit.
let sliceTop = node.box.y;
for (const line of node.lines) {
if (isPixelFont) {
// textBaseline:"middle" centers on the font's *declared* ascent/descent (its line
// height) - Tom Thumb's are backwards (see PIXEL_FONT_TIERS above) and would center on
// nonsense. Centering on actualBoundingBox{Ascent,Descent} instead - this specific
// string's real rendered ink (its character height) - costs nothing and stays correct
// regardless of whether a pixel font's declared metrics can be trusted.
// textBaseline:"middle" centers on declared ascent/descent, which is backwards for
// Tom Thumb; centering on actualBoundingBox{Ascent,Descent} instead measures this
// string's real rendered ink and stays correct regardless.
ctx.textBaseline = "alphabetic";
const {actualBoundingBoxAscent: up, actualBoundingBoxDescent: down} = ctx.measureText(line);
ctx.fillText(line, centerX, snap(sliceTop + (lineHeight + up - down) / 2));
@ -397,26 +278,22 @@ function drawTextLeaf(ctx, node, referencePx) {
return fontPx;
}
// Flip this to true (in a debugger or a local edit) to outline every leaf's box - including
// "empty" ones, normally invisible - in a color that can't be mistaken for real label ink. Handy
// for checking a layout's actual padding/alignment; never wanted on a real printed label, so it's
// a manual toggle rather than something wired up to any UI.
// Manual debug toggle (flip in a debugger) to outline every leaf's box, including
// normally-invisible "empty" ones, in a color that can't be mistaken for real label ink; never
// wired up to any UI.
let DEBUG_LEAF_BORDERS = false;
function drawDebugBorder(ctx, node) {
ctx.save();
ctx.strokeStyle = "red";
ctx.lineWidth = 1;
// Inset by half a pixel so the 1px stroke lands crisply on-pixel instead of straddling the
// box edge and rendering as a blurry 2px line.
// Inset by half a pixel so the 1px stroke lands crisply on-pixel instead of straddling the edge.
ctx.strokeRect(node.box.x + 0.5, node.box.y + 0.5, node.box.width - 1, node.box.height - 1);
ctx.restore();
}
// `textSizesPx` collects each "text" leaf's effective font size as drawTree walks the tree - see
// drawLabel/drawFallbackLabel, which hand it back to the caller (Print.vue shows it alongside the
// tape width) so a field rendering blank (see drawTextLeaf's MIN_READABLE_TEXT_PX check) shows up
// as a suspiciously small size here rather than just silently not being there.
// Collects each text leaf's effective font size so callers (Print.vue) can spot a blank-rendered
// field (see drawTextLeaf's MIN_READABLE_TEXT_PX check) as suspiciously small rather than silently missing.
function drawTree(ctx, node, referencePx, textSizesPx) {
if (isSplit(node)) {
node.forEach(child => drawTree(ctx, child, referencePx, textSizesPx));
@ -433,27 +310,9 @@ function drawTree(ctx, node, referencePx, textSizesPx) {
}
}
/* Builds, sizes and validates the tree for a fixed `fixedSize` (the tape's cross-web printAreaPx,
or the fallback preview's reference height) - the one dimension every layout scales from, plus
`pxPerMm` to turn "empty" leaves' physical sizes into pixels. `fixedSize` and the tree's content
fully determine its overall size along the other, growing axis (the one that runs along the
tape as it feeds); `maxLength`, when finite (a fixed-length/die-cut tape), rejects content that
doesn't fit rather than shrinking it.
`orientation` picks which axis `fixedSize` binds to: "along" (the default) fixes the tree's
height - the tape's cross-web width - and grows its width along the feed direction, same as a
plain read top-to-bottom design. "across" fixes the tree's width instead and grows its height,
so the design is built turned 90deg from how it'd read "along" - drawLabel/drawFallbackLabel
are what actually rotate the drawing back into the physical raster's fixed orientation; nothing
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 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. */
// Builds, sizes and validates the tree for a fixed dimension plus pxPerMm; runs sizing twice so
// QR-family leaves' real crisp size is known before the tree is finally resolved. See
// docs/implementation.md#label-content-layout.
function layoutContent(ctx, content, fixedSize, maxLength, referencePx, pxPerMm, orientation) {
const tree = buildRenderTree(ctx, content, referencePx);
const alongTape = orientation !== "across";
@ -479,16 +338,10 @@ function layoutContent(ctx, content, fixedSize, maxLength, referencePx, pxPerMm,
return {tree, length};
}
/* The tape-fed layout - draws a fully resolved content tree (see templateContent) at the tape's
real pixel dimensions. `orientation` is "along" (the default) to lay the design out reading
along the tape's feed direction, or "across" to turn it 90deg so it reads across the tape
instead - either way the physical raster this returns is still exactly
printedLength x tape.printAreaPx (that's fixed by the tape/print head, not a choice this
makes); "across" just draws the (now width-fixed, see layoutContent) tree through a rotated
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. */
// The tape-fed layout: draws a fully resolved content tree (see templateContent) at the tape's
// real pixel dimensions. See docs/implementation.md#tape-fed-label-drawing. Returns
// {textSizesPx}: each "text" leaf's effective font size, in the tree's own left-to-right,
// top-to-bottom order.
export function drawLabel(canvas, tape, content, orientation = "along") {
const maxLength = tape.printLengthPx
? tape.printLengthPx - tape.leadPx - TRAILING_PADDING_PX
@ -511,10 +364,8 @@ export function drawLabel(canvas, tape, content, orientation = "along") {
+ Math.floor((printedLength - tape.leadPx - TRAILING_PADDING_PX - contentLength) / 2);
const textSizesPx = [];
if (orientation === "across") {
// The tree was solved width-fixed (see layoutContent) - its width already exactly fills
// tape.printAreaPx, so only its (growing) height needs the same along-the-feed centering
// originX got above; translate+rotate then carries that tree-local (x, y) box straight
// into the physical (printedLength x printAreaPx) raster, a quarter turn at a time.
// Rotates/translates the width-fixed tree into the physical raster a quarter turn at a
// time. See docs/implementation.md#across-orientation-rotation.
positionTree(tree, false, 0, origin);
ctx.save();
ctx.translate(0, tape.printAreaPx);
@ -531,11 +382,9 @@ export function drawLabel(canvas, tape, content, orientation = "along") {
const FALLBACK_LABEL_HEIGHT_PX = 200; /* reference height the no-webusb preview/PNG scales from */
const FALLBACK_DPI = 203; /* reference resolution for turning "empty" leaves' mm sizes into px */
/* 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`, see drawLabel. Returns {textSizesPx},
see drawLabel. */
// The no-webusb preview/PNG: same layout tree/renderer as drawLabel, scaled from a fixed
// reference height instead. See docs/implementation.md#fallback-label-preview. `orientation` and
// the {textSizesPx} return, see drawLabel.
export function drawFallbackLabel(canvas, content, orientation = "along") {
const measureCtx = canvas.getContext("2d");
const pxPerMm = FALLBACK_DPI / 25.4;
@ -566,21 +415,14 @@ export function drawFallbackLabel(canvas, content, orientation = "along") {
}
// Turns a {kind, components} prefill (see Print.vue's `prefill` prop) into the literal string a
// print label should show/encode. Keeping this keyed by `kind` rather than having each caller
// build its own string means the format for a given kind of label content only has to be gotten
// right in one place.
// print label should show/encode; keyed by `kind` so each kind's format is defined in one place.
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. 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.
// The self-contained Item URL (see docs/design-in-progress/items-labels.md), built from just
// the prefill's {userHandle, id}; the short link (Print.vue's `shortUrl`) needs an async store
// lookup, so it stays a separate field/template rather than being baked in here.
"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.
// Storage locations have no long-form URL route yet (see router.js), so `text` starts blank;
// the short link and any future location template still work via the base vars below.
};
export function buildLabelContent(prefill) {
@ -591,10 +433,9 @@ 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.
// Splits a prefill's {userHandle, id} into label-layouts.js's user/domain base vars (the same way
// store.js's lookupServer does), tagging on whichever id field the resource's templates key
// required_vars by.
function splitUserHandle(userHandle) {
if (!userHandle) {
return null;
@ -606,13 +447,9 @@ function splitUserHandle(userHandle) {
};
}
// 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 (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.
// Seeds label-layouts.js's BASE_VARS, keyed by `kind`; derived vars (userHandle, itemUrl, …) are
// computed live elsewhere (see DERIVED_VARS, Print.vue's `shortUrl`), and omitting a field
// (rather than leaving it present-but-empty) signals "not available" to templateIsAvailable.
const LABEL_FIELD_BUILDERS = {
"item": ({userHandle, id}) => {
const split = splitUserHandle(userHandle);

View file

@ -46,9 +46,7 @@ export function decodeHandleFromUrl(segment) {
return segment.replace(/\+/g, "#");
}
// Both item-ish kinds land on the same /inventory/:handle/:id shape - only how they resolve
// their owner's handle differs (a personal owner vs. a group, see identityHandleById/
// groupHandleById in store.js), so that resolution is the only part that stays separate.
// item/group_item share this /inventory/:handle/:id shape; only owner-handle resolution (identity vs. group, see store.js) differs.
function itemDetailRoute(handle, item_local_id) {
return handle ? `/inventory/${encodeHandleForUrl(handle)}/${item_local_id}` : null;
}
@ -63,10 +61,7 @@ const EXPANDED_ROUTE_BUILDERS = {
workflow: ({workflow_id}) => `/workflows/${workflow_id}`,
};
// Only these two builders read identityHandleById/groupHandleById (derived from state.idmap) -
// ShortId.vue checks this to decide whether a cold-open fetch of idmap is worth waiting on before
// giving up, so a storage_location/group/workflow/file short id never waits on an unrelated
// network call.
// Kinds whose route needs identityHandleById/groupHandleById (from state.idmap); ShortId.vue only waits on an idmap fetch for these.
export const NEEDS_IDMAP = new Set(['item', 'group_item']);
export function expandedRoute({kind, ...fields}) {
@ -93,24 +88,11 @@ const routes = [{path: '/', component: Dashboard, meta: {requiresAuth: true}}, {
meta: {requiresAuth: true},
props: true
}, {
// The self-contained label/short-link entry point (see label.js's LABEL_CONTENT_BUILDERS
// and docs/design-in-progress/items-labels.md) - :handle is already URL-escaped the same
// way /inventory/:handle/:id expects it, so this is just a shorter alias for that route,
// with no owner-is-the-viewer special case: get_shared_item (and friends_or_self()) already
// treat "it's the viewer's own item" as one case of "the viewer may see this owner's item",
// not a separate path.
// Label/short-link entry point; alias of /inventory/:handle/:id. See docs/implementation.md#item-short-link-redirect-route.
path: '/i/:handle/:id',
redirect: to => `/inventory/${to.params.handle}/${to.params.id}`
}, {
// A beforeEnter guard, not `redirect`: `redirect` is called synchronously and its return value
// is used as-is (never awaited), and it also *must* resolve to a valid location on every match
// (an unresolvable one throws, see vue-router's handleRedirectRecord) - it can't itself wait on
// fetchIdMap (see NEEDS_IDMAP) for the item/group_item kinds whose owner handle isn't
// resolvable from the token alone. A guard can return `null`/undefined to mean "proceed to the
// component instead", which is exactly what's needed here: when expandedRoute can't resolve yet
// (or ever - an unrecognized kind), stay on this same URL and mount ShortId.vue in place, which
// has full component-lifecycle async support and takes it from there - fetch idmap, retry,
// redirect once resolved, or keep showing the decode view.
// beforeEnter, not redirect: falls through to ShortId.vue when the route can't resolve synchronously. See docs/implementation.md#beforeenter-guard-vs-redirect-for-short_id.
path: '/:short_id',
component: ShortId,
props: true,

View file

@ -1,19 +1,12 @@
// Specialized bitmap-style fonts label.js's drawTextLeaf switches to below an effective text
// size of 10px, where a general-purpose sans-serif gets blurry/illegible - each is designed for
// (and named after) roughly the pixel size it's used at. See
// ../assets/fonts/pixel/LICENSE.md for sources/licenses.
// Bitmap-style fonts label.js's drawTextLeaf switches to below 10px, where sans-serif gets
// illegible (see ../assets/fonts/pixel/LICENSE.md for sources); label.js's PIXEL_FONT_TIERS uses
// only these two of three candidates - the third, PICO-8, has no lowercase glyphs.
@font-face {
font-family: "Tom Thumb";
src: url("../assets/fonts/pixel/TomThumb.ttf") format("truetype");
font-display: block;
}
@font-face {
font-family: "PICO-8";
src: url("../assets/fonts/pixel/PICO-8.ttf") format("truetype");
font-display: block;
}
@font-face {
font-family: "Silkscreen";
src: url("../assets/fonts/pixel/Silkscreen-Regular.woff2") format("woff2");

View file

@ -93,6 +93,7 @@ $body-color: $gray-700;
@import "tags";
@import "dropdown";
@import "pixel-fonts";
@import "pixel-fonts-candidates";
#root, body, html {
height: 100%;

View file

@ -329,22 +329,17 @@ export default createStore({
const request = '_toolshed-server._tcp.' + domain + '.'
return await state.resolver.query(request, 'SRV').then(
(result) => result.map(
// Must match what the browser actually puts in the Host header for
// the request this gets used to build (federation.js always signs
// and fetches "https://" + server + target) - it omits a :443 for
// the default HTTPS port, so keeping it here would make every
// signature check on the receiving end fail against the real request.
// Must match the browser's real Host header (federation.js signs/fetches
// "https://"+server+target); browser omits :443 for default HTTPS, so
// keeping it here would break signature checks on the receiving end.
(answer) => answer.port === 443 ? answer.target : answer.target + ':' + answer.port))
},
async getHomeServers({state, dispatch, commit, getters}) {
if (state.home_servers)
return state.home_servers
// isLoggedIn (store.js's getters) is what lazily hydrates state.user/token/keypair
// from localStorage on first read - a route with no requiresAuth meta (e.g. the
// short-id redirect) never triggers that beforeEach check, so state.user can still be
// null here even for an actually-logged-in visitor. Reading the getter first forces
// that hydration; if it's still false afterwards, the visitor really isn't logged in,
// so fail with a clear error instead of lookupServer crashing on username.split(...).
// Reading isLoggedIn first forces its lazy hydration of state.user from localStorage,
// needed here since routes without requiresAuth (e.g. short-id redirect) skip that
// check; fail clearly if still not logged in rather than crashing on username.split.
if (!getters.isLoggedIn) {
throw new Error('Not logged in')
}
@ -365,8 +360,7 @@ export default createStore({
const s = await dispatch('lookupServer', {username: friend.username})
servers.add(new ServerSet(s, state.unreachable_neighbors))
} catch (e) {
// Don't let a single unresolvable/unreachable friend abort the whole
// search/federation lookup - just skip them and continue.
// Skip an unresolvable/unreachable friend rather than aborting the whole lookup.
console.error('could not resolve server for friend', friend.username, e)
}
}
@ -442,9 +436,8 @@ export default createStore({
async fetchForeignItem({dispatch, getters}, {owner, id}) {
try {
const servers = await dispatch('getFriendServers', {username: owner});
// owner here is a full handle (username@domain) - see the /api/inventory_items/<handle>/<id>/
// endpoint (toolshed/api/inventory.py get_shared_item), which looks the item up by owner rather
// than by requester, unlike the plain /api/inventory_items/ list/detail endpoints.
// owner is a full handle (username@domain); this endpoint looks the item up by
// owner, not requester (see toolshed/api/inventory.py get_shared_item).
const item = await servers.get(getters.signAuth, '/api/inventory_items/' + owner + '/' + id + '/');
if (item && item.files) {
item.files.forEach(file => file.owner = item.owner)
@ -455,21 +448,12 @@ export default createStore({
return null;
}
},
// A group handle (leading '#') has no working owner-handle GET route yet
// (get_shared_item, which fetchForeignItem calls, only resolves a personal
// ToolshedUser handle) - resolve it instead via the already-correct, already-
// authenticated group listing (?group=<id>, see fetchGroupInventoryItems) and pick the
// matching item out of that, which only ever contains this one group's own items, so an
// id collision with anything else can't happen. A personal/friend handle still goes
// through fetchForeignItem as before.
// Group handles have no owner-handle GET route yet, so they resolve differently than
// personal handles here. See docs/implementation.md#fetch-item-by-handle-group-vs-personal-handles.
async fetchItemByHandle({dispatch, getters}, {handle, id}) {
if (handle.startsWith('#')) {
// groupIdByHandle is derived from state.idmap (see store.js's getters), which
// nothing guarantees is loaded yet at this point - unlike Inventory.vue/
// StorageLocation.vue/Print.vue, a direct or refreshed visit to an item's own
// detail/edit page never fetched it. Loading it here, every time, is simplest;
// fetchIdMap is cheap and already called unconditionally (no cache check) by
// every other caller too.
// idmap isn't guaranteed loaded on a direct/refreshed visit here; fetchIdMap is
// cheap and already called unconditionally by every other caller too.
await dispatch('fetchIdMap')
const groupId = getters.groupIdByHandle[handle]
if (groupId === undefined) {
@ -528,10 +512,8 @@ export default createStore({
return await servers.delete(getters.signAuth, '/api/friends/' + id + '/')
},
// Groups are only ever hosted on the current user's own home backend for now (see
// docs/design-in-progress/groups-mvp.md) - a remote member's edit/delete rights on a
// group-owned item work regardless, but "My Groups" has no way to discover a group hosted
// elsewhere, so every group action below talks to getHomeServers rather than resolving a
// per-group domain.
// docs/design-in-progress/groups-mvp.md), so every group action below uses getHomeServers
// rather than resolving a per-group domain.
async fetchGroups({commit, dispatch, getters}) {
const servers = await dispatch('getHomeServers')
const data = await servers.get(getters.signAuth, '/api/groups/')
@ -769,8 +751,8 @@ export default createStore({
},
async createWorkflow({state, commit, dispatch, getters}, workflowData) {
const servers = await dispatch('getHomeServers')
// The backend stores `payload` as an opaque string - the frontend is
// responsible for serializing/deserializing the JSON itself.
// The backend stores payload as an opaque string; the frontend (de)serializes it.
// See docs/implementation.md#workflow-payload-is-an-opaque-string.
const data = await servers.post(getters.signAuth, '/api/workflows/', serializeWorkflowPayload(workflowData))
state.last_load.active_workflows = 0 // Invalidate cache
return deserializeWorkflowPayload(data)
@ -838,9 +820,8 @@ export default createStore({
groupIdByHandle(state) {
return Object.fromEntries(state.idmap.groups.map(g => [g.handle, g.id]))
},
// Reverse of the two getters above - turns a short-id's raw owner_identity_id/
// owner_group_id back into a handle (see router.js's EXPANDED_ROUTE_BUILDERS), without
// a separate backend lookup since the idmap already has both directions of this data.
// Reverse of the two getters above: turns a short-id's raw owner_identity_id/owner_group_id
// back into a handle (see router.js EXPANDED_ROUTE_BUILDERS), no backend lookup needed.
identityHandleById(state) {
return Object.fromEntries(state.idmap.identities.map(i => [i.id, i.username]))
},
@ -901,11 +882,7 @@ export default createStore({
}
return fallbackDefault
},
/**
* Extracts the human-readable name from a fully qualified handle.
* Handles look like "git:tools#tag:drill" or "git:base#property:length".
* If the given value does not look like a handle, it is returned unchanged.
*/
/** Extracts the name from a handle like "git:tools#tag:drill"; returns non-handles unchanged. */
getNameFromHandle: () => (handle) => {
if (typeof handle !== 'string') {
return handle;

View file

@ -46,9 +46,7 @@ test('rejects a 0 last-field value, for a multi-field kind', () => {
test('decoding never over-reads: a single-chunk field that exactly exhausts padding is not ' +
'mistaken for a second field', () => {
// category_id: 5 encodes as kind-tag(2 bits) + one 5-bit chunk = 7 bits, padded with exactly
// 5 zero bits - the same 5 bits as a genuine one-chunk field of value 0. This is the concrete
// case the last-field-nonzero rule exists to disambiguate.
// category_id 5 -> 7 bits + 5 zero padding bits, identical to a genuine one-chunk zero field - the case the last-field-nonzero rule disambiguates.
const token = encodeShortId([0, 5])
expect(token).toBe('~Cg')
expect(decodeShortId(token)).toEqual([0, 5])

View file

@ -128,9 +128,8 @@ export default {
},
methods: {
...mapActions(["fetchInventoryItems", "deleteInventoryItem", "fetchStorageLocations", "fetchIdMap"]),
// This list is always the viewer's own personal items (fetchInventoryItems has no
// group filter) - the owner handle is always their own, but it's always included
// rather than special-cased, so /inventory/:handle/:id has exactly one shape.
// Always the viewer's own items (fetchInventoryItems has no group filter); the owner
// handle is always included so /inventory/:handle/:id has exactly one shape.
itemRoute(item) {
return `/inventory/${encodeHandleForUrl(this.user)}/${item.id}`
},
@ -151,13 +150,8 @@ 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.
// Routes to Print.vue with this item's raw identity rather than a pre-built link.
// See docs/implementation.md#print-link-shape-for-personal-items.
printLinkFor(item) {
if (!item.owner) return null
return {path: '/print', query: {kind: 'item', userHandle: item.owner, id: item.id}}

View file

@ -98,16 +98,13 @@ export default {
decodedHandle() {
return decodeHandleFromUrl(this.handle)
},
// Edit/Delete apply once the viewer is actually authorized to act on this item - their
// own item, or a group they belong to - not just anyone who can view it
// (get_shared_item's friends_or_self() also lets a friend view a shared item, but never
// act on it).
// Edit/Delete require actual authorization (own item or member group), not just view
// access - get_shared_item's friends_or_self() lets a friend view but never act.
canEdit() {
return this.decodedHandle === this.user || this.decodedHandle in this.groupIdByHandle
},
// Printed labels only support a personal owner handle so far (see label.js's
// splitUserHandle/Inventory.vue's printLinkFor) - group items don't get a print link
// until that's supported too.
// splitUserHandle); group items get no print link until that's supported too.
canPrint() {
return this.decodedHandle === this.user
}

View file

@ -98,9 +98,9 @@ export default {
},
data() {
return {
// Fetched fresh by {handle, id} on mount rather than found by id alone in whatever
// happens to already be cached (loaded_items mixes personal, group and search
// fetches, and id is only unique within one owner's own items - see InventoryDetail.vue).
// Fetched fresh by {handle, id} on mount rather than looked up by id alone -
// loaded_items mixes personal/group/search fetches, and id is only unique per owner
// (see InventoryDetail.vue).
item: {
tags: [],
properties: [],

View file

@ -163,10 +163,7 @@
:key="'label-' + t.mm" class="tick-label"
:style="{left: t.pos + 'px'}">{{ t.mm }}</span>
</div>
<!-- The tape's full physical width, printable area included - the
print head can't mark all the way to the tape's outer edges, so
the canvas (printAreaPx tall) is narrower than this and centered
within it; the rest is real, if unprintable, tape margin. -->
<!-- Tape's full physical width; canvas is narrower/centered, margin is real tape. See docs/implementation.md#tape-full-print-margin. -->
<div class="tape-full"
:style="{height: (tape.mediaWidthMm * tapePxPerMm) + 'px'}">
<div class="label-preview">
@ -248,6 +245,7 @@
<div class="row">
<div class="col-12">
<label-layout-preview :fields="fields" :value="selectedTemplate"
:recent-template-ids="recentTemplateIds"
@input="selectedTemplate = $event"></label-layout-preview>
</div>
</div>
@ -268,33 +266,23 @@ import {tapeFromStatus, drawLabel, drawFallbackLabel, buildLabelContent, buildLa
import {LABEL_TEMPLATES, BASE_VARS, DERIVED_VARS, withDerivedVars, templateContent} from "@/label-layouts.js";
import {shortenedRoute} from "@/router";
// The extra "Calculated" fields (and label-layouts.js "Short link (QR code)" template input) this
// view adds on top of label-layouts.js's own DERIVED_VARS - resolving either needs the current
// identityIdByHandle map (see store.js's fetchIdMap) to turn a handle into the numeric
// owner_identity_id short-id.js's 'item'/'storage_location' kinds encode, so neither can be a pure
// fields->value calc like the others and both live here instead of in label-layouts.js. Excluded
// from baseVars below since, unlike every other entry KNOWN_VARS picks up from a template's
// required_vars, neither is ever typed directly.
// Print.vue-local calculated fields on top of label-layouts.js's DERIVED_VARS. See
// docs/implementation.md#calculated-short-link-fields.
const SHORT_URL_VAR = "shortUrl";
// The bare short-id.js token itself (e.g. "~AbCd12"), with no domain or leading "/" - what
// shortUrl's own path is built from (see fields()/the shortId method below), for a label that
// wants just the compact code rather than a full scannable URL.
// See docs/implementation.md#calculated-short-link-fields.
const SHORT_ID_VAR = "shortId";
// Served verbatim from public/vendor/ rather than bundled: libweblabel.js's
// own emscripten glue resolves its .wasm sibling relative to *its own*
// import.meta.url at runtime, so both files need to keep sitting together,
// unhashed, at a stable URL - not a Vite-fingerprinted asset path.
// Served unbundled so its wasm sibling stays resolvable. See docs/implementation.md#libweblabel-served-unbundled.
const BLOB_URL = "/vendor/libweblabel.js";
// localStorage key for the most-recently-printed template ids (see rememberPrintedTemplate/loadRecentTemplateIds), same naming style as cameraManager.js's recentCameraIds.
const RECENT_TEMPLATES_KEY = "recentLabelTemplateIds";
// How many recently-printed templates LabelLayoutPreview.vue bubbles to the front of the grid.
const MAX_RECENT_TEMPLATES = 4;
const MAX_ZOOM = 4; /* never magnify the preview more than this */
const MAX_PREVIEW_HEIGHT_PX = 300; /* never let the on-screen preview grow taller than this */
// How far apart plain and labeled/major ticks sit, both coarser the longer the ruler itself runs
// - tightly spaced ticks (and their labels) get too cramped to read/render once there are enough
// of them. Ordered smallest threshold first; rulerTicks below uses the last entry whose `aboveMm`
// the ruler's own length clears, so add a finer/coarser tier here rather than growing a pile of
// separate constants. Every tier's majorEveryMm is a multiple of its own tickMm, so major ticks
// always land on a tick that's actually drawn.
// Tick spacing tiers, coarser the longer the ruler runs. See docs/implementation.md#ruler-tier-selection.
const RULER_TIERS = [
{aboveMm: 0, tickMm: 1, majorEveryMm: 5},
{aboveMm: 100, tickMm: 1, majorEveryMm: 10},
@ -309,10 +297,7 @@ export default {
...BIcons
},
props: {
// {kind, components} prefilled from the ?kind=& query params when arriving from e.g.
// an item's "Print label" button (see InventoryDetail.vue) - the router turns those
// query params into this prop (router.js's /print route), rather than the component
// reading $route directly. buildLabelContent turns it into the literal string below.
// {kind, components} from the ?kind=& query params (router.js's /print route builds this prop); buildLabelContent turns it into the text field below.
prefill: {
type: Object,
default: null
@ -329,40 +314,25 @@ export default {
connected: null,
tape: null,
labelBitmap: null,
// The tape-fed preview's current on-screen scale and printed pixel width (see
// fitZoom/redraw) - tracked reactively, rather than read straight off the canvas
// element, purely so the mm ruler below can recompute its tick positions whenever
// either one changes.
// Tracked reactively (not read off the canvas) so the mm ruler can recompute tick positions when either changes (see fitZoom/redraw).
zoom: 1,
printedWidthPx: 0,
// Each "text" leaf's effective font size in the current render (see label.js's
// drawLabel) - shown alongside the tape width so a field rendering blank (too small
// even for the smallest pixel font) shows up as a suspiciously tiny number here rather
// than just silently not being there.
// Each "text" leaf's effective font size (see label.js's drawLabel), shown beside the tape width so a too-small-to-render field reads as a suspiciously tiny number rather than silently absent.
textSizesPx: [],
// One input per *base* template variable (see label-layouts.js's BASE_VARS) - the
// derived ones (userHandle, itemUrl, itemHandle) are format strings calculated from
// these, not typed directly, so they're only ever shown (see the `fields` computed
// below), never stored here. Prefilled from the ?kind=& query params where
// buildLabelContent/buildLabelFields have a value for them, editable from there so a
// template needing e.g. domain isn't stuck depending on a prefill that never arrives.
// One input per BASE_VARS entry; derived vars (userHandle/itemUrl/itemHandle) are calculated-only (see the `fields` computed), never stored here. Prefilled from query params but left editable.
varValues: {
...Object.fromEntries(BASE_VARS.map(v => [v, ""])),
text: buildLabelContent(this.prefill),
// Defaults to wherever this page itself is being served from - editable since any
// frontend can resolve any handle (see label-layouts.js's DERIVED_VARS.itemUrl),
// so a label doesn't have to point back at this particular one.
// Defaults to this page's own origin; editable since any frontend can resolve any handle, so a label needn't point back at this one.
webdomain: window.location.origin,
...buildLabelFields(this.prefill),
},
copies: 1,
selectedTemplate: LABEL_TEMPLATES[0].id,
// "along" draws a layout reading along the tape's feed direction (the usual case -
// constrained by the tape's cross-web width, growing as long as the content needs);
// "across" turns it 90deg, constrained by that same width but along the *other* axis
// instead, so it reads across the tape rather than along it. See label.js's
// drawLabel/drawFallbackLabel for how that turn is actually drawn.
// Ids of the last MAX_RECENT_TEMPLATES distinct templates printed/downloaded, most recent first. See rememberPrintedTemplate/loadRecentTemplateIds.
recentTemplateIds: [],
// "along" reads along the tape's feed direction (usual case, width-constrained); "across" turns 90deg on that same width instead. See label.js's drawLabel/drawFallbackLabel.
orientation: "along",
fallbackReady: false,
@ -370,11 +340,7 @@ export default {
brotherCliExample: "brother_ql --model QL-000 --printer usb://0000:0000 print --label 00 label.png",
niimbotCliExample: "niimprint --model b00 --conn usb print --density 3 --image label.png",
// Nine pixel/bitmap-style font candidates found in frontend/public (see
// ../assets/fonts/pixel-candidates/LICENSE.md) - none of these are used by label.js's
// real PIXEL_FONT_TIERS; this card exists purely so they can be judged the same way
// Tom Thumb/Silkscreen were, against real (live-typed) content instead of a fixed
// example.
// Nine pixel/bitmap font candidates for legibility testing only (see the disabled card above); not used by label.js's real PIXEL_FONT_TIERS.
candidateFonts: [
{family: "Pixelon"},
{family: "Pixelbasel"},
@ -392,27 +358,16 @@ export default {
},
computed: {
...mapGetters(["identityIdByHandle"]),
// The base variables the "Label content" form renders an input for, and the derived ones
// it instead calculates and lists read-only beside that form - plain passthroughs, but
// keep the template from importing label-layouts.js just for these. SHORT_URL_VAR is
// excluded here even though the "Short link (QR code)" template's required_vars puts it in
// BASE_VARS (it isn't a label-layouts.js DERIVED_VARS entry) - see fields() below for why
// it's calculated, not typed. SHORT_ID_VAR isn't referenced by any template's
// required_vars (so isn't actually in BASE_VARS today), filtered out too in case one ever
// is.
// Plain passthroughs of the form's base/derived vars, keeping the template from importing
// label-layouts.js just for these. SHORT_URL_VAR/SHORT_ID_VAR exclusion: see
// docs/implementation.md#calculated-short-link-fields.
baseVars() {
return BASE_VARS.filter(v => v !== SHORT_URL_VAR && v !== SHORT_ID_VAR);
},
derivedVars() {
return [...Object.keys(DERIVED_VARS), SHORT_ID_VAR, SHORT_URL_VAR];
},
// Named content fields the templates draw from: the form's own base vars, plus every
// DERIVED_VARS format string calculated live from those - so typing a userHandle and
// itemId (whether by hand or via prefill) recalculates itemUrl/itemHandle the same way
// either way. A blank/uncalculated value is dropped rather than passed through as an
// empty string, so it reads as *absent* to templateIsAvailable/templateContent the same
// way a prefill that never supplied it would - that's what LabelLayoutPreview.vue greys a
// template's thumbnail out on.
// Named content fields the templates draw from, dropping blank values. See docs/implementation.md#fields-computed-dropping-blank-values.
fields() {
const base = {};
for (const v of BASE_VARS) {
@ -454,48 +409,34 @@ export default {
canPrint() {
return Boolean(this.tape && this.labelBitmap && !this.busy);
},
// On-screen pixels per real millimeter of tape, at the preview's current zoom - what
// turns a physical mm into a tick position the ruler can actually draw. Only meaningful
// for the tape-fed preview (see redraw's printedWidthPx) - the no-webusb fallback preview
// isn't fed from any particular real tape/dpi, so it gets no ruler (see the template).
// px per real mm at current zoom; meaningful only for the tape-fed preview (the no-webusb fallback has no real tape/dpi, so no ruler).
tapePxPerMm() {
return this.tape ? (this.tape.dpi / 25.4) * this.zoom : 0;
},
// The physical length, in mm, each ruler axis actually needs to cover - see
// horizontalRulerTicks/verticalRulerTicks below for what each one measures and why.
// Physical mm length each ruler axis must cover; see horizontal/verticalRulerTicks for what each measures.
horizontalTotalMm() {
return (this.tape && this.printedWidthPx) ? this.printedWidthPx / (this.tape.dpi / 25.4) : 0;
},
verticalTotalMm() {
return this.tape ? this.tape.mediaWidthMm : 0;
},
// The single RULER_TIERS entry both rulers draw from, keyed off whichever axis is
// physically longer - so a long label's ruler doesn't end up coarser (or finer) than the
// tape-width ruler right next to it just because the other axis happens to be shorter.
// Shared tier keyed off whichever axis is longer. See docs/implementation.md#ruler-tier-selection.
rulerTier() {
return RULER_TIERS.filter(t => Math.max(this.horizontalTotalMm, this.verticalTotalMm) >= t.aboveMm)
.at(-1);
},
// Ticks along the tape's length (the printed bitmap's actual width, lead/trailing feed
// margin included, since that's real physical tape too).
// Ticks along the tape's printed length, feed margins included (still real tape).
horizontalRulerTicks() {
if (!this.tape || !this.printedWidthPx) {
return [];
}
return this.rulerTicks(this.horizontalTotalMm);
},
// Ticks across the tape's full physical width, mediaWidthMm - not printAreaPx/dpi: a
// print head can't reach the tape's outer edges, so the printable area (see .tape-full in
// the template) is genuinely narrower than the tape itself, by an amount that isn't a
// fixed/predictable fraction of it. The ruler still has to show the *whole* tape - its
// container is sized from mediaWidthMm too (see the template's inline height) precisely so
// these ticks can't run past it, the way they did when both were sized from printAreaPx.
// Ticks across the tape's full width, not just the printable area. See docs/implementation.md#tape-full-print-margin.
verticalRulerTicks() {
return this.tape ? this.rulerTicks(this.verticalTotalMm) : [];
},
// "(5px, 23px)" for the current render's text leaves (see data's textSizesPx), or "" once
// there's nothing to show - appended straight onto the tape-width <small>, so the blank
// string here just means that text is left with no trailing space.
// e.g. "(5px, 23px)", or "" so it appends cleanly onto the tape-width <small> with nothing shown.
textSizesSummary() {
if (!this.textSizesPx.length) {
return "";
@ -529,10 +470,7 @@ export default {
this.redrawFallback();
}
},
// Covers connecting/disconnecting/switching printers - anything that changes the
// tape dimensions redraw() sizes the canvas from. flush: 'post' because the canvas
// itself only exists once `tape` is truthy (see the v-if/v-else in the template), so
// this has to run after Vue has actually mounted it, not before.
// Catches printer connect/disconnect/switch; flush:'post' since the canvas only exists once `tape` is truthy (template's v-if).
tape: {
handler() {
this.redraw();
@ -543,24 +481,12 @@ export default {
methods: {
...mapActions(["fetchIdMap"]),
// Turns a camelCase variable name (see label-layouts.js's KNOWN_VARS) into a form label,
// e.g. "itemHandle" -> "Item Handle" - so adding a new template variable doesn't also
// require hand-writing a label for it here.
// camelCase -> Title Case (e.g. "itemHandle" -> "Item Handle") so a new template var needs no hand-written label.
varLabel(v) {
return v.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, c => c.toUpperCase());
},
// The same shortened link Inventory.vue/StorageLocation.vue's own shortIdLink builds for
// one of their rows, but as the bare token (see short-id.js's encodeShortId) rather than a
// router target or full URL - shortenedRoute's own leading "/" is stripped since this is a
// plain display field/potential label content, not something this view itself navigates
// to; fields() below reattaches a domain and slash to build shortUrl from this same value,
// so the two can never disagree. Which short-id.js kind applies depends on which id field
// the current prefill's LABEL_FIELD_BUILDERS populated (see label.js) - itemId for an
// item, locationId for a storage location - rather than trusting the prefill's own `kind`
// directly, so hand-typing userHandle+itemId with no prefill at all still resolves this
// the same way. Falls back to no value - same as an unresolved DERIVED_VARS entry - until
// identityIdByHandle has loaded (see mounted's fetchIdMap) or if the handle isn't in it.
// Builds the bare short-id.js token for the current fields. See docs/implementation.md#shortid-resolution.
shortId(f) {
if (!f.userHandle) {
return null;
@ -580,10 +506,7 @@ export default {
return null;
},
// Ticks from 0 up to totalMm, each positioned in on-screen pixels via tapePxPerMm - shared
// by the horizontal/vertical ruler computeds above. Both the plain tick spacing and the
// labeled/major one come from the shared rulerTier (see above), not from this totalMm, so
// both rulers always coarsen together once *either* axis is long enough to need it.
// Ticks 0..totalMm via tapePxPerMm, shared by both ruler computeds; spacing comes from the shared rulerTier, so both rulers coarsen together.
rulerTicks(totalMm) {
const {tickMm, majorEveryMm} = this.rulerTier;
const ticks = [];
@ -593,6 +516,31 @@ export default {
return ticks;
},
// Reads the recently-printed template ids back from localStorage; same try/catch shape as
// cameraManager.js's getRecentCameras since either a disabled/full localStorage shouldn't
// break printing.
loadRecentTemplateIds() {
try {
const saved = localStorage.getItem(RECENT_TEMPLATES_KEY);
return saved ? JSON.parse(saved) : [];
} catch (e) {
return [];
}
},
// Moves `id` to the front of the recent-templates list (deduping any earlier occurrence),
// capped to MAX_RECENT_TEMPLATES, so LabelLayoutPreview.vue's grid always bubbles the
// last four printed/downloaded layouts to the top.
rememberPrintedTemplate(id) {
const updated = [id, ...this.recentTemplateIds.filter(t => t !== id)].slice(0, MAX_RECENT_TEMPLATES);
this.recentTemplateIds = updated;
try {
localStorage.setItem(RECENT_TEMPLATES_KEY, JSON.stringify(updated));
} catch (e) {
// Best-effort only - a disabled/full localStorage shouldn't block printing.
}
},
async guard(fn) {
this.error = null;
this.busy = true;
@ -607,9 +555,7 @@ export default {
async refreshDevices() {
this.devices = (await navigator.usb.getDevices()).map((d) => markRaw(d));
/* A printer unplugged while open is off the list: the handle it was
opened through is gone, so drop it rather than keep the label
card open on a connection that no longer exists. */
/* A printer unplugged while open drops from the list: its handle is gone, so close the card rather than keep it open on a dead connection. */
if (this.connected !== null && !this.devices.includes(this.connected)) {
this.connected = null;
this.tape = null;
@ -640,9 +586,7 @@ export default {
connect(index) {
this.guard(async () => {
// Only one open device connection at a time - pressing Connect on a different
// printer while one is already open implicitly disconnects it first, rather
// than requiring an explicit Disconnect click.
// Only one open connection at a time: connecting a different printer disconnects the current one first.
await this.closeConnection();
const device = this.devices[index];
this.blob.setDevices([device]);
@ -716,29 +660,17 @@ export default {
link.download = "label.png";
link.href = canvas.toDataURL("image/png");
link.click();
this.rememberPrintedTemplate(this.selectedTemplate);
},
/* Fit the preview to its card without ever needing a horizontal
scrollbar for a label this small, magnifying short labels up to
MAX_ZOOM rather than showing them at native (tiny) size - and never
past MAX_PREVIEW_HEIGHT_PX tall, however long/wide the label itself
runs. Returns the zoom actually used, so callers that care (see
redraw's ruler bookkeeping) don't have to re-derive it. */
// Fits the preview to its card, magnifying up to MAX_ZOOM/MAX_PREVIEW_HEIGHT_PX. See docs/implementation.md#fit-zoom-preview-scaling.
fitZoom(canvas) {
const available = canvas.parentElement.clientWidth;
if (!(available > 0)) {
return 1;
}
const rawZoom = Math.min(MAX_ZOOM, available / canvas.width, MAX_PREVIEW_HEIGHT_PX / canvas.height);
// When magnifying, round DOWN to a whole number: image-rendering:pixelated below
// only actually looks crisp when every source pixel maps to the *same* number of
// screen pixels - at a fractional zoom (the overwhelmingly common case, since rawZoom
// is just whatever ratio the tape/card happen to produce) some source pixels get
// rounded up to one extra screen pixel and others don't, unevenly warping fine,
// already-pixel-perfect detail like a crisp QR module or a tiny bitmap font glyph.
// Flooring (never rounding/ceiling) keeps the same "never bigger than available
// space" guarantee rawZoom already had. Shrinking (zoom < 1) has no equivalent "whole
// factor" to snap to - downsampling always blends source pixels - so it's left as-is.
// Floors rather than rounds/ceils when magnifying, to keep image-rendering:pixelated crisp. See docs/implementation.md#fit-zoom-preview-scaling.
const zoom = rawZoom >= 1 ? Math.max(1, Math.floor(rawZoom)) : rawZoom;
canvas.style.width = `${canvas.width * zoom}px`;
canvas.style.height = `${canvas.height * zoom}px`;
@ -750,12 +682,11 @@ export default {
this.guard(async () => {
const copies = Math.max(1, Math.min(20, Number(this.copies) || 1));
await this.blob.printBitmap(this.labelBitmap, {copies});
this.rememberPrintedTemplate(this.selectedTemplate);
});
},
/* Re-fits whichever canvas sits in a resized container - covers a window resize, but
also a sidebar toggle, a font finishing loading, or any other layout change that
isn't a window resize at all. Debounced since ResizeObserver can fire in bursts. */
// Re-fits the resized container's canvas (window resize, sidebar toggle, font load, etc.); debounced since ResizeObserver can fire in bursts.
handleContainerResize(entries) {
clearTimeout(this.resizeTimer);
this.resizeTimer = setTimeout(() => {
@ -772,9 +703,7 @@ export default {
this.guard(() => this.refreshDevices());
},
// A plain :ref="key" inside v-for would still get Vue's refInFor array-collecting
// behavior (see LabelLayoutPreview.vue's setTemplateCanvasRef for the same pattern), so
// this keys the canvases by the caller's own composite key string explicitly instead.
// Works around Vue's refInFor array-collecting behavior for :ref in v-for, same as LabelLayoutPreview.vue's setTemplateCanvasRef.
setCandidateCanvasRef(key, el) {
if (el) {
this.candidateCanvases[key] = el;
@ -783,12 +712,7 @@ export default {
}
},
// Draws the live "Text" field's value into a single canvas at the exact size/family
// given - no layout math, no snapping, just ctx.font as requested, so what's judged here
// is the font itself rather than anything label.js's real pipeline does to it. Canvas size
// is measured from the text itself, and ink-centered vertically (see label.js's
// drawTextLeaf for the same idea) so a font with unreliable declared metrics still lands
// fully inside the canvas instead of clipped off the top/bottom.
// Renders the "Text" field at exact size/family with no layout snapping, so the font itself is judged; ink-centered vertically (like label.js's drawTextLeaf) so unreliable metrics don't clip.
drawCandidateCell(canvas, family, fontPx) {
if (!canvas) {
return;
@ -828,20 +752,16 @@ export default {
this.resizeObserver = null;
this.resizeTimer = null;
this.candidateCanvases = {};
this.recentTemplateIds = this.loadRecentTemplateIds();
},
async mounted() {
this.drawCandidateFontTests();
// Not awaited: itemShortUrl just reads whatever identityIdByHandle currently holds (see
// the fields computed), so this resolving after first render only means it shows ""
// briefly rather than blocking the rest of mounted's (unrelated) printer/wasm setup.
// Not awaited: resolving late just means shortUrl briefly shows "" instead of blocking the unrelated printer/wasm setup below.
this.fetchIdMap().catch(e => {
this.error = e.message;
});
this.resizeObserver = new ResizeObserver(this.handleContainerResize);
// Kicked off here rather than awaited immediately, so it loads concurrently with
// MultiPrinterBlob below instead of serializing two independent wasm fetches - every
// redraw()/redrawFallback() call below still waits on it first, since a qr/mqr/rmqr leaf
// throws (see label.js's encodeQr) until it resolves.
// Loaded concurrently with MultiPrinterBlob below rather than serialized. See docs/implementation.md#concurrent-wasm-loading.
const qrReady = preloadQrEncoder();
if (!("usb" in navigator)) {
this.usbSupported = false;
@ -888,40 +808,26 @@ export default {
//box-shadow: 0 0 0 1px rgba(127, 127, 127, .5);
}
/* The tape-fed preview's mm ruler (see Print.vue's template/script) - a horizontal track above
the canvas and a vertical one to its left, both ticked in real physical millimeters rather than
preview pixels, since what they're measuring is the actual label. */
/* The tape-fed preview's mm ruler: horizontal track above canvas, vertical to its left, both ticked in real physical mm. See docs/implementation.md#mm-ruler-layout. */
.preview-row {
display: flex;
align-items: flex-start;
}
/* Holds the horizontal ruler and the canvas - deliberately never scrollable (no overflow-x:auto):
fitZoom's zoom always satisfies `canvas.width * zoom <= available`, so the canvas can never
actually be wider than this has room for, and a scrollbar here would let the ruler and canvas
drift apart (or just look broken) for no reason. min-width:0 only lets this flex item shrink
to the card's real available width - it doesn't enable scrolling. */
/* Ruler/canvas container deliberately never scrollable. See docs/implementation.md#preview-track-no-scroll-invariant. */
.preview-track {
flex: 1 1 auto;
min-width: 0;
}
/* Overrides the standalone rule above: nested here, .label-preview must neither scroll nor center
its canvas - overflow-x:visible (never auto) rules out a second, inner scrollbar, and
text-align:left keeps the canvas flush with the ruler's zero tick instead of drifting to the
middle of whatever spare width this card has. padding:0 so the canvas's own edges are exactly
this box's edges too - the ruler's ticks (see .ruler-h/.ruler-v-ticks below) line up with those
same edges, so any padding here would leave the ticks and the actual canvas misaligned. */
/* Nested override: .label-preview must neither scroll nor center its canvas here. See docs/implementation.md#label-preview-override-in-preview-track. */
.preview-track .label-preview {
overflow-x: visible;
text-align: left;
padding: 0;
}
/* The tape's full physical width (see the template) - a print head can't mark all the way to a
tape's outer edges, so .label-preview/the canvas is narrower than this and centered within it
(the print area sits centered on the tape, with equal margin on both sides); a faint tint
distinguishes the margin as real (if blank, unprintable) tape rather than empty space. */
/* Tape's full physical width; canvas is narrower/centered, faint tint marks the real unprintable margin. See docs/implementation.md#tape-full-print-margin. */
.tape-full {
display: flex;
flex-direction: column;
@ -936,8 +842,7 @@ export default {
color: rgba(127, 127, 127, .9);
}
/* Matches .ruler-h's own height below - the vertical ruler's ticks start only after this, so tick
0 lines up with the canvas's top edge rather than the horizontal ruler sitting above it. */
/* Matches .ruler-h's height so the vertical ruler's tick 0 lines up with the canvas's top edge. */
.ruler-v-corner {
height: 1.6rem;
}
@ -957,9 +862,7 @@ export default {
background: currentColor;
}
/* Ticks anchor to the edge nearest the canvas (right for the vertical ruler, bottom for the
horizontal one) and grow outward from it, so they read as pointing at the label; the mm labels
sit on the opposite, outer edge, out of the ticks' way. */
/* Ticks anchor to the edge nearest the canvas and grow outward (pointing at the label); mm labels sit on the opposite outer edge. */
.ruler-v-ticks .tick {
right: 0;
width: .4rem;
@ -987,8 +890,7 @@ export default {
white-space: nowrap;
}
/* transform, not a fixed em nudge, so the label's actual center - not its edge - lands on the
tick's mm position (t.pos, set inline), whatever the text's width/height happens to be. */
/* transform (not a fixed em nudge) centers the label on the tick's mm position regardless of text size. */
.ruler-v-ticks .tick-label {
left: 0;
transform: translateY(-50%);

View file

@ -4,6 +4,12 @@
<div class="container-fluid p-0">
<h1 class="h3 mb-3">Scan a code</h1>
<div class="form-check form-switch mb-3">
<input class="form-check-input" type="checkbox" role="switch" id="visitFirstMatch"
v-model="visitFirstMatch">
<label class="form-check-label" for="visitFirstMatch">Visit first match</label>
</div>
<div v-if="error" class="alert alert-danger" role="alert">{{ error }}</div>
<div v-if="!insecureContext" class="alert alert-warning">
@ -24,7 +30,17 @@
<span class="scan-result-type">{{ c.type }}</span>
<span v-if="c.metaText" class="text-muted"> {{ c.metaText }}</span>
<span class="text-muted"> @ {{ c.time }}</span>
<div class="text-break">{{ c.text }}</div>
<div class="text-break">
<a v-if="c.link?.href" :href="c.link.href" target="_blank"
rel="noopener noreferrer">{{ c.text }}</a>
<template v-else-if="c.link">
<router-link :to="c.link.to">{{ c.text }}</router-link>
<span v-if="c.error" class="text-danger"> &rarr; {{ c.error }}</span>
<span v-else-if="c.description" class="text-muted"> &rarr; {{ c.description }}</span>
<span v-else-if="c.description === undefined" class="text-muted"> &rarr; resolving&hellip;</span>
</template>
<template v-else>{{ c.text }}</template>
</div>
</li>
</ul>
</div>
@ -81,7 +97,17 @@
<li v-for="(r, i) in fileResults" :key="i">
<span class="scan-result-type">{{ r.type }}</span>
<span v-if="r.metaText" class="text-muted"> {{ r.metaText }}</span>
<div class="text-break">{{ r.text }}</div>
<div class="text-break">
<a v-if="r.link?.href" :href="r.link.href" target="_blank"
rel="noopener noreferrer">{{ r.text }}</a>
<template v-else-if="r.link">
<router-link :to="r.link.to">{{ r.text }}</router-link>
<span v-if="r.error" class="text-danger"> &rarr; {{ r.error }}</span>
<span v-else-if="r.description" class="text-muted"> &rarr; {{ r.description }}</span>
<span v-else-if="r.description === undefined" class="text-muted"> &rarr; resolving&hellip;</span>
</template>
<template v-else>{{ r.text }}</template>
</div>
</li>
</ul>
</div>
@ -94,14 +120,61 @@
</template>
<script>
import {mapActions} from "vuex";
import * as BIcons from "bootstrap-icons-vue";
import BaseLayout from "@/components/BaseLayout.vue";
import {loadAnyDCode} from "../../vendor/anyd-qr.js";
import cameraManager from "@/cameraManager.js";
import {encodeHandleForUrl, expandedRoute} from "@/router";
import {decodeShortId, deserializeShortId} from "@/short-id";
// A decode result's metadata (see anyd-qr.js's SymbolMetadata) as one short, human-readable
// string, e.g. "(v7, ec=M, mask=3)" - shared by both the "from image" and "from camera" result
// lists below rather than each formatting it its own way.
// A scanned label can encode any of these (see label-layouts.js's DERIVED_VARS): a full
// self-contained URL (itemUrl/shortUrl), a bare short-id.js token with no domain at all (the
// "mqr"/id-only layout), or the compact no-URL "<userHandle>:<itemId>" form (itemHandle). Detects
// which and returns a link target, or null if the text doesn't match any known format. `decoded`/
// `itemHandle` carry enough of the parsed token for describeLink (below) to also resolve a
// human-readable "what this points at" - not needed for the two URL cases, which link to
// somewhere already showing that.
const ITEM_HANDLE_RE = /^(#?[^\s@:/#+~]+@[^\s@:/#+~]+):(\d+)$/;
function classifyScanText(text) {
if (!text) {
return null;
}
try {
const url = new URL(text);
// Same-origin URLs (the common case - a label printed by this same app) get routed
// in-app instead of forcing a full page reload through an <a> tag. `immediate`: a URL
// needs no async lookup to confirm it's real (unlike the token/handle formats below), so
// it's already "resolved" the moment it's classified - see resolveDescription and
// maybeVisitFirstMatch.
return url.origin === window.location.origin
? {to: url.pathname + url.search + url.hash, immediate: true}
: {href: url.href};
} catch {
// Not an absolute URL - fall through to the other known formats below.
}
if (text.startsWith('~')) {
try {
const decoded = deserializeShortId(decodeShortId(text));
// expandedRoute needs idmap already loaded to resolve item/group_item (see
// router.js's NEEDS_IDMAP) - fall back to the token's own URL (ShortId.vue resolves
// it from there, same as a cold-opened short link) when it can't yet.
return {to: expandedRoute(decoded) || '/' + text, decoded};
} catch {
return null; // starts with '~' but isn't a real short id - leave as plain text
}
}
const handleMatch = text.match(ITEM_HANDLE_RE);
if (handleMatch) {
const [, handle, id] = handleMatch;
return {to: `/inventory/${encodeHandleForUrl(handle)}/${id}`, itemHandle: {handle, id}};
}
return null;
}
// Formats a decode result's metadata (see anyd-qr.js's SymbolMetadata) as a short string like
// "(v7, ec=M, mask=3)"; shared by the "from image" and "from camera" result lists below.
function metaSummary(metadata) {
const parts = [];
if (metadata.version != null) {
@ -119,8 +192,8 @@ function metaSummary(metadata) {
return parts.length ? `(${parts.join(", ")})` : "";
}
// How long a camera-detected code's bounding box stays drawn on the overlay before fading, so a
// one-off decode doesn't leave a stale box on screen once the code's moved out of frame.
// How long a detected code's overlay box stays drawn before fading, so it doesn't linger once
// the code has moved out of frame.
const OVERLAY_CLEAR_MS = 2000;
export default {
@ -135,6 +208,10 @@ export default {
insecureContext: window.isSecureContext,
insecureOrigin: `${window.location.protocol}//${window.location.hostname}`,
// One-shot: cleared by maybeVisitFirstMatch as soon as it navigates, so it doesn't
// keep firing router.push for every later scan/decode while left switched on.
visitFirstMatch: false,
dropHover: false,
hasFileImage: false,
fileResults: [],
@ -148,8 +225,8 @@ export default {
};
},
computed: {
// Switches camera the moment the select changes, rather than waiting for an explicit
// "apply" step - matches prototypes/camera-inputs/InputPhoto.vue's selectedCameraId.
// Switches camera immediately on selection change (no explicit "apply" step), matching
// prototypes/camera-inputs/InputPhoto.vue's selectedCameraId.
selectedCameraId: {
get() {
return this.localSelectedCameraId;
@ -163,9 +240,109 @@ export default {
},
},
methods: {
// Draws `file`/a pasted or dropped Blob onto fileCanvas and decodes whatever's in it -
// shared by the file input, drag&drop and paste handlers below rather than each
// duplicating the createImageBitmap/getImageData/decodeImage sequence.
...mapActions(["fetchItemByHandle", "fetchGroup", "fetchStorageLocations", "fetchIdMap"]),
// Resolves entry.link into entry.description ("[#7] Cordless drill") for the non-URL
// formats classifyScanText recognizes - mutates the already-rendered entry in place once
// the lookup lands, rather than delaying the log/result list from showing the raw scanned
// text and link immediately. Left as `undefined` (template shows "resolving...") while in
// flight, and settles to a string or `null` (nothing else known to show, e.g. a workflow
// short id, or the owner/item genuinely couldn't be resolved).
//
// descriptionCache (keyed by the raw scanned text, shared across cameraLog and
// fileResults) memoizes the outcome - a still-in-frame code gets re-decoded and
// re-logged several times a second (see logDecode), and re-scanning the same printed
// label later is common too, so without this every repeat would re-fire the same
// fetchItemByHandle/fetchGroup/fetchStorageLocations/fetchIdMap round trip. Caching the
// in-flight promise itself (not just its settled value) also dedupes concurrent lookups
// for the same still-in-frame code, rather than firing one request per decode.
resolveDescription(entry) {
const {link, text} = entry;
if (!link || link.href) {
return; // full URLs already show where they go - see this feature's ask
}
if (link.immediate) {
this.maybeVisitFirstMatch(link);
return;
}
if (!this.descriptionCache.has(text)) {
// Wrapped as {error} rather than swallowed to null: a lookup can fail for very
// different reasons (not logged in, item not shared with this viewer, a genuine
// network error) and collapsing them all to "no description" made every one of
// them look identical to "nothing to show" - undiagnosable from the UI.
this.descriptionCache.set(text, this.describeLink(link).catch(e => ({error: e.message ?? String(e)})));
}
this.descriptionCache.get(text).then(result => {
if (result && typeof result === "object") {
entry.description = null;
entry.error = result.error;
return;
}
entry.description = result;
// Only a truthy description confirms the target actually exists - a null/empty
// one (unresolvable, or a kind with no title lookup wired up) shouldn't count as
// a "match" to auto-visit.
if (result) {
this.maybeVisitFirstMatch(link);
}
});
},
// Sends the viewer straight to the first scan this session that's confirmed to resolve
// (immediately for a plain URL, or once resolveDescription confirms a real target for a
// token/handle) while the "Visit first match" toggle is on. One-shot: switches the toggle
// back off so it doesn't fire again for every later scan of the same or another code.
maybeVisitFirstMatch(link) {
if (!this.visitFirstMatch || !link?.to) {
return;
}
this.visitFirstMatch = false;
this.$router.push(link.to);
},
async describeLink(link) {
if (link.itemHandle) {
return this.describeItem(link.itemHandle.handle, link.itemHandle.id);
}
const decoded = link.decoded;
if (!decoded) {
return null;
}
if (decoded.kind === "item" || decoded.kind === "group_item") {
const byId = decoded.kind === "item"
? this.$store.getters.identityHandleById
: this.$store.getters.groupHandleById;
const ownerId = decoded.kind === "item" ? decoded.owner_identity_id : decoded.owner_group_id;
let handle = byId[ownerId];
if (handle === undefined) {
await this.fetchIdMap();
handle = (decoded.kind === "item"
? this.$store.getters.identityHandleById
: this.$store.getters.groupHandleById)[ownerId];
}
return handle === undefined ? null : this.describeItem(handle, decoded.item_local_id);
}
if (decoded.kind === "group") {
const group = await this.fetchGroup({id: decoded.group_id});
return group ? group.handle : null;
}
if (decoded.kind === "storage_location") {
if (!this.$store.state.storage_locations.length) {
await this.fetchStorageLocations();
}
const location = this.$store.state.storage_locations.find(l => l.id === decoded.storage_location_id);
return location ? `[#${location.id}] ${location.name}` : null;
}
return null; // workflow, category, file: no per-item title lookup wired up yet
},
async describeItem(handle, id) {
const item = await this.fetchItemByHandle({handle, id});
return item ? `[#${item.id}] ${item.name}` : null;
},
// Draws `file`/a pasted or dropped Blob onto fileCanvas and decodes it; shared by the file
// input, drag&drop, and paste handlers below to avoid duplicating this sequence.
async decodeBlob(file) {
this.error = null;
try {
@ -180,7 +357,11 @@ export default {
const results = anyd.decodeImage(imageData);
this.drawBoxes(ctx, results);
this.hasFileImage = true;
this.fileResults = results.map(r => ({...r, metaText: metaSummary(r.metadata)}));
this.fileResults = results.map(r => ({
...r, metaText: metaSummary(r.metadata), link: classifyScanText(r.text),
description: undefined, error: null
}));
this.fileResults.forEach(this.resolveDescription);
} catch (e) {
this.error = e.message ?? String(e);
}
@ -233,9 +414,8 @@ export default {
}
},
// Device labels are only populated once camera permission has actually been granted, so
// this is called again right after getUserMedia resolves in startCamera, not just once
// up front.
// Device labels only populate once permission is granted, so this is called again right
// after getUserMedia resolves in startCamera, not just once up front.
async populateCameraList() {
if (!navigator.mediaDevices?.enumerateDevices) {
return;
@ -264,21 +444,30 @@ export default {
},
logDecode(code) {
this.cameraLog.unshift({
const text = code.text ?? "";
const entry = {
type: code.type,
text: code.text ?? "",
text,
metaText: metaSummary(code.metadata),
time: new Date().toLocaleTimeString(),
});
// Caps the log rather than letting it grow forever - old entries are trimmed off the
// end, same as CameraScanner's own dedupe window makes them stale for re-matching.
link: classifyScanText(text),
description: undefined,
error: null,
};
this.cameraLog.unshift(entry);
// Resolve against cameraLog[0], not the plain `entry` object above: Vue's reactivity
// tracks property sets through the reactive proxy unshift() just installed, and
// mutating the pre-insertion raw object later bypasses that proxy entirely, so the
// description would never appear to update (stuck on "resolving...") even once the
// lookup actually finished.
this.resolveDescription(this.cameraLog[0]);
// Caps the log (old entries trimmed) rather than growing forever, matching
// CameraScanner's own dedupe window that makes them stale for re-matching.
this.cameraLog.length = Math.min(this.cameraLog.length, 20);
},
// Draws every detected code's box (in the video's own native pixel space, scaled to
// however large the overlay is actually displayed) and fades them out after
// OVERLAY_CLEAR_MS - a one-off decode shouldn't leave a stale box on screen once the code
// has moved out of frame.
// Draws each detected code's box (video's native pixel space, scaled to the overlay's
// displayed size) and fades it out after OVERLAY_CLEAR_MS.
drawOverlay(codes) {
console.log("drawOverlay", codes);
const overlay = this.$refs.overlay;
@ -307,12 +496,8 @@ export default {
() => ctx.clearRect(0, 0, overlay.width, overlay.height), OVERLAY_CLEAR_MS);
},
// Attaches `stream` to the video element - shared by startCamera and the
// camera-switch/reconnect paths so the scanner (which just keeps reading frames off the
// same video element) never needs to be recreated. videoWidth/videoHeight aren't known yet
// right after play() - the video's own "resize" event (see onVideoResize) is what tells us
// the new aspect ratio has actually taken effect, which is also when the overlay needs to
// be resized to match.
// Attaches `stream` to the video element so the scanner never needs recreating. See
// docs/implementation.md#video-stream-attach-and-resize-sync.
setupVideoStream(stream) {
const video = this.$refs.video;
if (!video) return;
@ -320,10 +505,8 @@ export default {
video.play();
},
// Fires on the video element's own "resize"/"loadedmetadata" events - i.e. whenever its
// intrinsic width/height actually change (initial load, or switching to a camera with a
// different native resolution/aspect ratio) - so the overlay canvas is resized to match the
// video's *new* rendered size rather than the stale one from before the switch.
// Resizes the overlay to match the video's new size once its intrinsic dimensions change.
// See docs/implementation.md#video-stream-attach-and-resize-sync.
onVideoResize() {
const video = this.$refs.video;
if (!video || !video.videoWidth) {
@ -382,9 +565,8 @@ export default {
}
},
// The camera manager already tries a fallback device on disconnect (see cameraManager.js)
// and only fires 'camera-disconnected' once none is left, so by the time this runs there's
// nothing left to fall back to and the running scan session has to stop.
// cameraManager already tries a fallback device and only fires this event once none
// remain, so the running scan session has to stop here.
handleCameraDisconnected(event) {
if (!this.cameraRunning) return;
this.error = `Camera error: ${event.detail?.error || "Camera disconnected"}`;
@ -401,12 +583,14 @@ export default {
},
},
created() {
// Kept as a promise (rather than awaited here) so every caller - decodeBlob, startCamera -
// shares the same in-flight load instead of each triggering its own; loadAnyDCode's own
// memoization (see anyd-qr.js) means a second call anywhere else in the app is free too.
// Kept as a promise (not awaited) so decodeBlob and startCamera share one in-flight load;
// loadAnyDCode also memoizes, so later calls elsewhere in the app are free too.
this.anydPromise = loadAnyDCode();
this.scanner = null;
this.clearOverlayTimer = null;
// Not component data: resolveDescription's cached values are read back into each entry's
// own (reactive) `description` field, so the cache itself never needs to be reactive.
this.descriptionCache = new Map();
},
mounted() {
window.addEventListener("paste", this.onPaste);

View file

@ -107,9 +107,9 @@ export default {
return files.filter(file => file.mime_type.startsWith("image/"));
},
loadResults() {
// Search results are always personal-or-friend (see inventory_items() in
// toolshed/api/inventory.py - it never yields a group's items), so the owner is
// always a plain user handle - one route shape, no owner-is-me special case.
// Search results are always personal-or-friend (inventory_items() in
// toolshed/api/inventory.py never yields group items), so owner is always a plain
// user handle - one route shape, no owner-is-me special case.
this.fetchSearchResults({query: this.query}).then((results) => {
this.search_results = results.map(e => (
{...e, route: `/inventory/${encodeHandleForUrl(e.owner)}/${e.id}`}))

View file

@ -77,10 +77,7 @@ const EXAMPLES = [
{kind: 'workflow', owner_identity_id: 2, workflow_id: 9},
];
// Debug-only display helper, kept out of short-id.js's production library: mirrors its bit-packing
// rules (2-bit kind tag with an all-ones escape, 4-bit continuation chunks, see
// docs/handles-and-shortids.md) just to show them, recomputed straight from an already-serialized
// `ints` list rather than re-parsing a token.
// Debug-only mirror of short-id.js's bit-packing (2-bit kind tag + 4-bit chunks, see docs/handles-and-shortids.md), recomputed from `ints` for display only.
const KIND_TAG_BITS = 2;
const CHUNK_BITS = 4;
const DIRECT_KIND_COUNT = 2 ** KIND_TAG_BITS - 1;
@ -159,10 +156,7 @@ export default {
}
},
watch: {
// expandedRoute reads Vuex getters derived from state.idmap (see buildExpandedRoute in
// router.js), so it re-evaluates on its own once fetchIdMap resolves below - this just
// catches that and finishes the redirect the router's own (synchronous, can't-await)
// redirect couldn't.
// expandedRoute re-evaluates once fetchIdMap resolves (see buildExpandedRoute in router.js); finishes the redirect the router's synchronous guard couldn't.
expandedRoute(url) {
if (url) {
this.$router.replace(url);

View file

@ -133,11 +133,8 @@ export default {
if (owner_identity_id === undefined) return null
return shortenedRoute({kind: 'storage_location', owner_identity_id, storage_location_id: location.id})
},
// Routes to Print.vue with this location's own raw identity - userHandle + id - rather
// than any pre-built link, the same shape Inventory.vue's printLinkFor sends for an item
// (see label.js's "storage-location" LABEL_FIELD_BUILDERS entry). Locations are always
// individually owned (see StorageLocationViewSet.get_queryset), so unlike Inventory.vue's
// version this never has to fall back to "no metadata available".
// Routes to Print.vue with this location's raw identity, same shape as Inventory.vue's
// printLinkFor. See docs/implementation.md#print-link-shape-for-storage-locations.
printLinkFor(location) {
return {path: '/print', query: {kind: 'storage-location', userHandle: location.owner, id: location.id}}
},

View file

@ -3395,8 +3395,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Navbar
================================================== -->
<!-- Navbar -->
<div class="bs-docs-section clearfix">
<div class="row">
<div class="col-sm-12">
@ -3507,8 +3506,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Typography
================================================== -->
<!-- Typography -->
<div class="bs-docs-section">
<div class="row">
<div class="col-sm-12">
@ -3613,8 +3611,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Tables
================================================== -->
<!-- Tables -->
<div class="bs-docs-section">
<div class="row">
@ -3701,8 +3698,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Forms
================================================== -->
<!-- Forms -->
<div class="bs-docs-section">
<div class="row">
<div class="col-sm-12">
@ -3969,8 +3965,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Navs
================================================== -->
<!-- Navs -->
<div class="bs-docs-section">
<div class="row">
@ -4224,8 +4219,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Indicators
================================================== -->
<!-- Indicators -->
<div class="bs-docs-section">
<div class="row">
@ -4343,8 +4337,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Progress
================================================== -->
<!-- Progress -->
<div class="bs-docs-section">
<div class="row">
@ -4443,8 +4436,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
</div>
<!-- Containers
================================================== -->
<!-- Containers -->
<div class="bs-docs-section">
<div class="row">
@ -4765,8 +4757,7 @@ sagittis lacus vel augue laoreet rutrum faucibus.">
</div>
<!-- Dialogs
================================================== -->
<!-- Dialogs -->
<div class="bs-docs-section">
<div class="row">

View file

@ -260,9 +260,7 @@ export default {
},
workflowComponent() {
// Return the single component implementing the whole workflow, if any,
// using the workflow component registry. The component itself decides
// what to render based on the `step` prop it receives.
// The returned component decides what to render itself, based on the `step` prop it receives.
const workflowType = this.workflowInstance?.slug;
return workflowType ? getWorkflowComponent(workflowType) : null;
},

View file

@ -231,8 +231,6 @@ export default {
const newWorkflow = await this.createWorkflow(workflowData);
// Immediately navigate to the workflow detail view
// Get the first step from the workflow definition
const firstStep = workflow.stepDefinitions?.[0]?.step || 1;
this.$router.push({
name: 'workflow-detail',
@ -251,8 +249,6 @@ export default {
},
async viewWorkflowDetails(workflow) {
console.log('Viewing details for workflow:', workflow);
// Navigate to the workflow detail view
// Use the workflow's current step if available, otherwise use the first step
const currentStep = workflow.current_step ||
workflow.payload?.current_step ||
getWorkflow(workflow.name)?.stepDefinitions?.[0]?.step ||

View file

@ -1,22 +1,4 @@
/**
* Workflow Catalog
*
* Single source of truth for every workflow type known to the frontend:
* what it's called, what category/description/icons it has, how many steps
* it has and what they're called, what its initial payload looks like, and
* which Vue component renders it.
*
* Each workflow has a fully co-located component + metadata as a static
* `meta` option on the component (`Component.meta`, right next to
* `name`/`props`/etc.) in `@/components/workflow/workflows/*.vue` - this
* file simply imports those components and reads `.meta` off of them to
* build the catalog below.
*
* This replaces the previous design of a parallel `BaseWorkflow` class
* hierarchy (metadata) plus a separate per-step `ComponentRegistry.js`
* (components) - both concerns now live in one flat array with each
* component responsible for its own metadata and UI implementation.
*/
// Workflow catalog: single source of truth built from each component's `meta`. See docs/implementation.md#workflow-catalog.
import FotoFirstBulkImportWorkflow from '@/components/workflow/workflows/FotoFirstBulkImportWorkflow.vue';
import BulkItemImportWorkflow from '@/components/workflow/workflows/BulkItemImportWorkflow.vue';
import InventoryAuditWorkflow from '@/components/workflow/workflows/InventoryAuditWorkflow.vue';
@ -25,9 +7,6 @@ import MaintenanceScheduleWorkflow from '@/components/workflow/workflows/Mainten
import ExpiryCheckWorkflow from '@/components/workflow/workflows/ExpiryCheckWorkflow.vue';
import BackupRestoreWorkflow from '@/components/workflow/workflows/BackupRestoreWorkflow.vue';
/**
* Workflows with a fully co-located component + metadata.
*/
const workflows = [
{...FotoFirstBulkImportWorkflow.meta, component: FotoFirstBulkImportWorkflow},
{...BulkItemImportWorkflow.meta, component: BulkItemImportWorkflow},
@ -38,56 +17,27 @@ const workflows = [
{...BackupRestoreWorkflow.meta, component: BackupRestoreWorkflow},
];
/**
* Get every workflow in the catalog.
* @returns {Array<Object>}
*/
export function getAllWorkflows() {
return workflows;
}
/**
* Get a single workflow definition by id.
* @param {string} id
* @returns {Object|undefined}
*/
export function getWorkflow(slug) {
return workflows.find(workflow => workflow.slug === slug);
}
/**
* Get the Vue component implementing a workflow's UI, if any.
* @param {string} id
* @returns {Object|null}
*/
export function getWorkflowComponent(id) {
return getWorkflow(id)?.component || null;
}
/**
* Get all workflows belonging to a category.
* @param {string} category
* @returns {Array<Object>}
*/
export function getWorkflowsByCategory(category) {
return workflows.filter(workflow => workflow.category === category);
}
/**
* Get all unique categories present in the catalog.
* @returns {Array<string>}
*/
export function getWorkflowCategories() {
return [...new Set(workflows.map(workflow => workflow.category))];
}
/**
* Build the payload sent to the backend to start a new instance of a
* workflow, merging the common `workflow_config` metadata block with the
* workflow's own initial payload fields.
* @param {Object} workflow - A workflow definition, e.g. from getWorkflow()
* @returns {Object}
*/
// Builds the payload sent to the backend to start a new instance of this workflow.
export function buildWorkflowApiPayload(workflow) {
const ownPayload = workflow.getInitialPayload ? workflow.getInitialPayload() : {};
return {
@ -102,11 +52,7 @@ export function buildWorkflowApiPayload(workflow) {
};
}
/**
* The backend stores WorkflowInstance.payload as an opaque string - it never
* parses or understands it as JSON. The frontend is fully responsible for
* serializing it before sending and deserializing it after receiving.
*/
// Payload is an opaque string to the backend; frontend serializes/deserializes it. See docs/implementation.md#workflow-payload-is-an-opaque-string.
export function serializeWorkflowPayload(workflow) {
console.log(workflow);
if (!workflow || !('payload' in workflow)) return workflow;