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

@ -18,9 +18,8 @@ from hostadmin.models import Domain
router = routers.SimpleRouter()
# Schema for the account-level preferences a client may store on the server (see
# AccountPreference). Device-level preferences are never sent here - they stay in the
# browser's local storage since they describe the device, not the account.
# Schema for account-level preferences a client may store server-side (see AccountPreference);
# device-level preferences stay in the browser's local storage instead.
PREFERENCE_DEFINITIONS = [
{
'key': 'ui.compact_mode',
@ -102,9 +101,8 @@ class UserViewSet(viewsets.ModelViewSet):
@permission_classes([IsAuthenticated])
@authentication_classes([SignatureAuthenticationLocal])
def getUserInfo(request):
"""Get or update the authenticated local user's own account info. Only usable by the
account owner on their own home server - see getUserProfile for viewing another (friend)
user's public profile."""
"""Get or update the authenticated local user's own account info; only the account owner may
call this on their own home server (see getUserProfile for viewing a friend's public profile)."""
user = request.user
if request.method == 'PATCH':
old_file = user.profile_picture
@ -147,9 +145,9 @@ def getUserInfo(request):
@permission_classes([IsAuthenticated])
@authentication_classes([SignatureAuthentication])
def getUserProfile(request, handle):
"""Get another local user's public profile by handle (username@domain), e.g. so a friend
can look up someone's avatar. The caller must be a friend of that user (or the user
itself, signing with their own known identity rather than their local credentials)."""
"""Get another local user's public profile by handle, e.g. so a friend can look up an avatar;
caller must be a friend of that user (or the user itself, signing with their own known
identity rather than local credentials)."""
try:
username, domain = split_userhandle_or_throw(handle)
except ValueError:
@ -213,11 +211,9 @@ def preference_definitions(request):
@permission_classes([IsAuthenticated])
@authentication_classes([SignatureAuthenticationLocal])
def account_preferences(request):
"""Get or bulk-upsert the authenticated user's account-level preferences.
GET returns the current preferences as a {key: value} dict. PUT accepts a {key: value}
dict of one or more preferences to set/overwrite; unspecified keys are left untouched.
"""
"""Get or bulk-upsert the authenticated user's account-level preferences: GET returns the
current preferences as {key: value}; PUT sets/overwrites one or more, leaving unspecified
keys untouched."""
if request.method == 'PUT':
if not isinstance(request.data, dict):
return Response({'detail': 'Expected an object of key/value pairs.'}, status=400)

View file

@ -114,11 +114,8 @@ class ToolshedUser(AbstractUser):
class AccountPreference(models.Model):
"""A single account-level (server-synced, cross-device) user preference, stored as a key/value pair.
Device-level preferences are intentionally *not* stored here - they stay in the browser's
local storage since they describe the device, not the account.
"""
"""A single account-level (server-synced, cross-device) preference as a key/value pair;
device-level preferences are intentionally *not* stored here."""
user = models.ForeignKey(ToolshedUser, on_delete=models.CASCADE, related_name='preferences')
key = models.CharField(max_length=255)
value = models.JSONField()
@ -165,9 +162,9 @@ class Group(models.Model):
class GroupInvite(models.Model):
"""A pending invite tracked on the group's own home backend, checked when the invitee's
accept request arrives (see GroupInviteIncoming for the mirror record on the invitee's own
backend, and docs/design-in-progress/groups-mvp.md for the full invite/accept dance)."""
"""A pending invite tracked on the group's own home backend, checked when the invitee's accept
request arrives (mirror: GroupInviteIncoming on the invitee's backend; see
docs/design-in-progress/groups-mvp.md)."""
secret = models.CharField(max_length=255)
group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='invites')
invitee_username = models.CharField(max_length=255)

View file

@ -81,12 +81,8 @@ def verify_incoming_friend_request(request, raw_request_body):
def verify_incoming_group_invite(request, raw_request_body, handle_field, key_field):
"""Self-certifying verifier for the two legs of the group invite/accept dance that land on a
backend which doesn't have the caller cached as a KnownIdentity yet (see
docs/design-in-progress/groups-mvp.md): the inviter delivering an invite to the invitee's own
backend (handle_field='inviter', key_field='inviter_key'), and the invitee accepting on the
group's home backend (handle_field='invitee', key_field='invitee_key'). Mirrors
verify_incoming_friend_request exactly, just with configurable field names."""
"""Self-certifying verifier for the group invite/accept dance. See
docs/implementation.md#group-invite-and-accept-self-certifying-verification."""
try:
username, domain, signed_data, signature_bytes_hex = verify_request(request, raw_request_body)
except ValueError:
@ -143,10 +139,8 @@ def authenticate_request_against_local_users(request, raw_request_body):
class SignatureAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
identity = authenticate_request_against_known_identities(request, request.body.decode('utf-8'))
# Returning a bare None (rather than a (None, None) tuple) tells DRF this
# authenticator doesn't apply, so it moves on to the next authenticator in the
# authentication_classes list instead of treating the request as authenticated
# with an empty user.
# Bare None (not a (None, None) tuple) tells DRF to try the next authenticator, instead
# of treating the request as authenticated with an empty user.
if identity is None:
return None
return identity, None

View file

@ -1,12 +1,3 @@
"""
ASGI config for backend project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application

View file

@ -1,14 +1,3 @@
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 4.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
import os
import subprocess
import dotenv
@ -19,13 +8,9 @@ BASE_DIR = Path(__file__).resolve().parent.parent
def _git_commit():
# deploy/dev/docker-compose.yml bind-mounts the repo's real .git dir at
# /git (separate from BASE_DIR, which only has the backend/ subtree) -
# point git at it explicitly there. Bare-metal dev has no such mount, but
# BASE_DIR sits inside the real checkout so plain rev-parse finds it by
# walking up. In prod, the build context is backend/ alone with no .git
# anywhere, so both fail and we fall back to the GIT_COMMIT build-arg/env
# var (see deploy/prod/Dockerfile.backend and playbook.yml).
# Docker dev bind-mounts the real .git dir at /git (see docker-compose.yml); bare-metal dev
# finds it by walking up from BASE_DIR instead. Prod has no .git at all, so both fail and we
# fall back to the GIT_COMMIT build-arg/env var (see Dockerfile.backend/playbook.yml).
cmd = ['git', '--git-dir=/git'] if os.path.isdir('/git') else ['git']
try:
return subprocess.check_output(
@ -36,9 +21,6 @@ def _git_commit():
dotenv.load_dotenv(BASE_DIR / '.env')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
SECRET_KEY = os.environ.get('SECRET_KEY', None)
if SECRET_KEY is None:
raise Exception('environment variable SECRET_KEY not set. try running `configure.py` or setting it manually')
@ -127,9 +109,6 @@ TEMPLATES = [
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
@ -139,9 +118,6 @@ DATABASES = {
AUTH_USER_MODEL = 'authentication.ToolshedUser'
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
@ -157,9 +133,6 @@ AUTH_PASSWORD_VALIDATORS = [
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
@ -168,26 +141,18 @@ USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
MEDIA_ROOT = os.environ.get('TOOLSHED_USERFILES_PATH', 'userfiles')
MEDIA_URL = '/media/'
# In prod, nginx (running as www-data) reads these files directly - see
# Pinned explicitly (rather than left to the backend process's ambient umask) so group-read
# is guaranteed for nginx/www-data regardless of how the container is started - see
# SERVE_X_ACCEL_REDIRECT and playbook.yml's `location /redirect_media/`.
# Pinned explicitly rather than left to the backend process's ambient umask,
# so group-read (www-data is added to the backend's system group) is
# guaranteed regardless of how the container is started.
FILE_UPLOAD_PERMISSIONS = 0o640
FILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o750
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
STORAGES = {

View file

@ -1,18 +1,3 @@
"""backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from drf_yasg import openapi

View file

@ -1,12 +1,3 @@
"""
WSGI config for backend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application

View file

@ -32,11 +32,8 @@ def yesno(prompt, default=False):
def configure():
# Keys this function may generate/update, tracked so that if .env turns
# out to be unwritable (e.g. a prod container running as an unprivileged
# user, whose real config comes from --env-file instead) we can still
# print the resulting configuration for the operator to apply manually,
# rather than silently discarding it or crashing.
# Keys this function may generate/update; tracked so an unwritable .env (e.g. a prod
# container configured via --env-file) can still print them for the operator to apply manually.
tracked_keys = ['SECRET_KEY', 'ALLOWED_HOSTS']
unwritable = False

View file

@ -24,9 +24,8 @@ THUMBNAIL_SIZES = (32, 64, 256)
def _accessible_files(request):
# Shared by media_urls and thumbnail_urls so both endpoints always agree on who can see
# what - a file is visible if the requester is friends-or-self with whatever currently
# references it (an inventory item, a profile picture) or it's their own staged photo.
# Shared by media_urls and thumbnail_urls: a file is visible if the requester is
# friends-or-self with whatever references it (item, profile picture), or it's their own staged photo.
return File.objects.filter(
Q(connected_items__owner__in=request.user.friends_or_self()) |
Q(profile_picture_users__in=request.user.friends_or_self()) |
@ -35,8 +34,7 @@ def _accessible_files(request):
def _cache_headers(etag):
# Content is addressed by its own hash and can never change under a given URL, so caches
# (and the conditional-GET checks in both views below) can treat it as immutable forever.
# Content is hash-addressed and can never change under a given URL, so it's cacheable forever.
return {
'ETag': etag,
'Cache-Control': 'max-age=31536000, private, immutable',
@ -49,23 +47,16 @@ def _cache_headers(etag):
@permission_classes([IsAuthenticated])
@authentication_classes([SignatureAuthentication])
def media_urls(request, hash_path):
# Note: CORS headers are NOT set here - django-cors-headers (CorsMiddleware,
# configured in settings.py) adds them to every Django response automatically, so
# setting them manually on these responses would just be redundant. The one exception
# is the SERVE_X_ACCEL_REDIRECT path: nginx replaces this response entirely when it
# follows the X-Accel-Redirect and serves the file itself, so the CORS header for that
# case has to be configured in nginx's `location /redirect_media/` block instead.
# CORS is added automatically by middleware, except via X-Accel-Redirect, where nginx's
# /redirect_media/ block must set it instead.
#
# Looked up by the derived storage path (not by raw hash) because FileSerializer.name
# (files/serializers.py) - used everywhere a file URL is handed to the frontend, e.g.
# AuthenticatedImage's `src` - already returns this path via Django's FileField.url, and
# the existing test suite (files/tests.py MediaUrlTestCase) exercises it this way too.
# Looked up by the derived storage path, not the raw hash, to match FileSerializer.name
# (used for AuthenticatedImage's `src`) and the existing test suite (MediaUrlTestCase).
try:
file = _accessible_files(request).get(file=hash_path)
# The access-control lookup above must happen before this check - otherwise a bare
# hash + If-None-Match would let anyone probe "does a file with this hash exist" for
# files they can't actually see.
# Must run before this check, else a bare hash + If-None-Match would let anyone probe
# file existence for files they can't see.
if request.META.get('HTTP_IF_NONE_MATCH') == file.hash:
return HttpResponse(status=status.HTTP_304_NOT_MODIFIED)
@ -79,9 +70,7 @@ def media_urls(request, hash_path):
**cache_headers,
})
else:
# Read via the FieldFile itself (works against whatever storage backend is
# actually configured) rather than assuming file.file.path is a real filesystem
# path - the test suite swaps in an in-memory backend where that isn't true.
# Reads via FieldFile.open() (not file.file.path) since tests swap in an in-memory storage backend.
with file.file.open('rb') as fh:
content = fh.read()
return HttpResponse(status=status.HTTP_200_OK,
@ -94,9 +83,7 @@ def media_urls(request, hash_path):
def _thumbnail_rel_path(file_hash, size):
# Mirrors files/models.py's hash_upload() sharding, under its own `thumbnails/<size>/`
# subtree - reachable through the same nginx `/redirect_media/` alias as originals when
# served from real disk, no separate nginx location needed.
# Mirrors hash_upload()'s sharding under thumbnails/<size>/, reachable via the same nginx alias as originals.
return os.path.join('thumbnails', str(size), file_hash[:2], file_hash[2:4], file_hash[4:6],
file_hash[6:] + '.jpg')
@ -116,22 +103,15 @@ def thumbnail_urls(request, size, hash_path):
if request.META.get('HTTP_IF_NONE_MATCH') == etag:
return HttpResponse(status=status.HTTP_304_NOT_MODIFIED)
# Read/write through the default storage backend, same as File.file itself, rather
# than a hand-rolled filesystem path - correct regardless of storage backend (real
# disk in production, in-memory under the test runner) and keeps the cache in the
# same place originals live.
# Read/write via default_storage, not a hand-rolled path, to work with both real-disk
# and in-memory test storage.
rel_path = _thumbnail_rel_path(file.hash, size)
if not default_storage.exists(rel_path):
# Thumbnails are always re-encoded as JPEG regardless of the original format -
# smaller and simpler than preserving e.g. PNG transparency at this scale.
# Always re-encoded as JPEG regardless of original format - simpler than preserving transparency at this scale.
with file.file.open('rb') as fh:
image = Image.open(fh)
image.thumbnail((size, size))
# Flatten through RGBA before dropping to RGB - some modes (grayscale+alpha,
# palette-with-transparency, RGBA) store meaningless color/luminance data under
# fully transparent pixels (often zeroed out, i.e. black). Converting straight
# to RGB reveals that instead of "nothing there"; compositing onto an opaque
# background first shows what the image is actually supposed to look like.
# Flatten through RGBA before dropping to RGB. See docs/implementation.md#rgba-flattening-avoids-revealing-black-under-transparent-pixels.
rgba = image.convert('RGBA')
flattened = Image.new('RGB', rgba.size, (255, 255, 255))
flattened.paste(rgba, mask=rgba.getchannel('A'))

View file

@ -43,15 +43,7 @@ class FileManager(models.Manager):
else:
raise ValueError('data must be a base64 encoded string or file and hash must be provided')
if not self.filter(hash=kwargs['hash']).exists():
# The upload path is derived entirely from the hash (hash_upload, above), and hash
# is DB-unique - so if no File row owns this hash yet, anything already sitting at
# its computed path is necessarily a stale orphan (e.g. left behind by a bug in
# cleanup code that deleted a File row without removing its stored bytes, or a
# crashed upload). Clear it before saving instead of letting Django's storage layer
# invent an alternate filename to avoid the "collision" - a suffixed name would
# silently break every part of the app that derives this file's URL purely from its
# hash (media serving, thumbnail generation, item/avatar attachment), and no future
# caller could ever discover it again.
# Clears a stale orphan already at this hash's canonical path before saving. See docs/implementation.md#stale-orphan-cleanup-at-the-canonical-hash-path.
expected_path = hash_upload(SimpleNamespace(hash=kwargs['hash']), '')
if default_storage.exists(expected_path):
default_storage.delete(expected_path)

View file

@ -113,12 +113,7 @@ class FilesTestCase(FilesTestMixin, ToolshedTestCase):
self.assertEqual(countdir(DefaultStorage(), ''), 3)
def test_file_upload_reclaims_stale_orphan_at_canonical_path(self):
# Reproduces a real incident: a File row gets deleted without its underlying stored
# bytes being removed (e.g. a bug in some cleanup call site), leaving an orphan sitting
# at the exact path hash_upload() would compute for that content. A later upload of the
# same content must land back on that canonical path - not get silently suffixed by
# Django's default collision-avoidance, which would make it unreachable to every part
# of the app that derives a file's URL purely from its hash.
# Regression test for a stale orphan at the canonical hash path. See docs/implementation.md#stale-orphan-cleanup-at-the-canonical-hash-path.
expected_path = f"{self.f['hash4'][:2]}/{self.f['hash4'][2:4]}/{self.f['hash4'][4:6]}/{self.f['hash4'][6:]}"
default_storage.save(expected_path, ContentFile(self.f['test_content4']))
self.assertTrue(default_storage.exists(expected_path))
@ -231,11 +226,8 @@ class ThumbnailUrlTestCase(FilesTestMixin, UserTestMixin, InventoryTestMixin, To
self.prepare_properties()
self.prepare_inventory()
# Each test method gets its own distinct image content (and therefore its own content
# hash / thumbnail cache path) - InMemoryStorage isn't reset between test methods within
# a run, so sharing one fixed image across methods risks one test's cached (or, in
# test_thumbnail_served_from_cache_on_second_request's case, deliberately corrupted)
# thumbnail leaking into another test's assertions.
# Each test uses a distinct seeded image (own hash/cache path) since InMemoryStorage
# isn't reset between test methods, so a shared image risks one test's cached thumbnail leaking into another's assertions.
seed = zlib.crc32(self._testMethodName.encode()) % 256
buffer = io.BytesIO()
Image.new('RGB', (800, 600), (seed, 255 - seed, 128)).save(buffer, 'PNG')
@ -254,8 +246,7 @@ class ThumbnailUrlTestCase(FilesTestMixin, UserTestMixin, InventoryTestMixin, To
return os.path.join('thumbnails', str(size), h[:2], h[2:4], h[4:6], h[6:] + '.jpg')
def test_thumbnail_sizes_available(self):
# Documents the fixed size allow-list this test suite exercises against - update both
# if files/media_urls.py's THUMBNAIL_SIZES ever changes.
# Fixed size allow-list this suite exercises - update both if media_urls.py's THUMBNAIL_SIZES changes.
self.assertEqual(THUMBNAIL_SIZES, (32, 64, 256))
@override_settings(SERVE_X_ACCEL_REDIRECT=False)
@ -274,10 +265,7 @@ class ThumbnailUrlTestCase(FilesTestMixin, UserTestMixin, InventoryTestMixin, To
@override_settings(SERVE_X_ACCEL_REDIRECT=False)
def test_thumbnail_flattens_transparency_instead_of_going_black(self):
# Reproduces a real incident: an 'LA' (grayscale + alpha) source whose fully-transparent
# region has zeroed-out luminance underneath, as many image tools produce. Converting
# straight to RGB (dropping alpha without compositing) reveals that zeroed data - the
# whole thumbnail comes out solid black even though the visible (opaque) content isn't.
# Regression test for an 'LA' source with zeroed transparent-region luminance. See docs/implementation.md#rgba-flattening-avoids-revealing-black-under-transparent-pixels.
half_transparent = Image.new('LA', (200, 200))
pixels = half_transparent.load()
for x in range(200):
@ -310,8 +298,7 @@ class ThumbnailUrlTestCase(FilesTestMixin, UserTestMixin, InventoryTestMixin, To
with default_storage.open(rel_path, 'rb') as f:
cached_bytes = f.read()
# Overwrite the cached file with a marker so a correct implementation must serve this
# exact content back rather than regenerating it from the original.
# Overwrites the cache with a marker so a correct implementation must serve it back, not regenerate.
default_storage.delete(rel_path)
default_storage.save(rel_path, ContentFile(cached_bytes + b'MARKER'))
@ -333,8 +320,7 @@ class ThumbnailUrlTestCase(FilesTestMixin, UserTestMixin, InventoryTestMixin, To
self.assertEqual(reply.status_code, 403)
def test_thumbnail_not_friend(self):
# local_user1/local_user2 are friends in these fixtures (see prepare_inventory) - the
# denied case needs a stranger to that friendship instead.
# local_user1/local_user2 are friends here (see prepare_inventory), so the denied case needs a stranger instead.
reply = client.get(self._thumb_url(64), self.f['ext_user1'])
self.assertEqual(reply.status_code, 404)
self.assertFalse(default_storage.exists(self._thumb_rel_path(64)))

View file

@ -50,10 +50,7 @@ def post_item_file(request, item_id):
if item is None:
return Response(status=status.HTTP_404_NOT_FOUND)
if 'file_hash' in request.data:
# Attach a file the caller already staged on one of their own workflows, identified
# by its content hash (which the client already computed before ever uploading it),
# instead of re-uploading bytes that are already stored server-side. Workflows are
# always personally owned, so this only applies to a caller with a local account.
# Attaches an already-staged file by hash instead of re-uploading it. See docs/implementation.md#staged-files-are-identified-by-hash-alone.
if not request.user.user.exists():
return Response(status=status.HTTP_404_NOT_FOUND)
try:
@ -74,10 +71,7 @@ def post_item_file(request, item_id):
def get_staged_files(request, workflow_id):
try:
workflow = WorkflowInstance.objects.get(id=workflow_id, owner=request.user)
# Hash alone identifies a staged file (client and server hash content the same way, and
# bytes are fetchable from a hash-derived storage path) - useful mainly for discovering
# what another session/device already staged on this workflow, unlike the fuller
# FileSerializer representation item_files uses.
# Hash alone is enough to discover what another session/device already staged. See docs/implementation.md#staged-files-are-identified-by-hash-alone.
return Response(list(workflow.staged_files.values_list('hash', flat=True)))
except WorkflowInstance.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)

View file

@ -35,26 +35,22 @@ class InventoryItemViewSet(viewsets.ModelViewSet):
serializer_class = InventoryItemSerializer
authentication_classes = [SignatureAuthentication]
permission_classes = [IsAuthenticated]
# Detail routes address an item by its owner-scoped id, not the internal row id - the
# router still names the URL capture group 'pk', so keep that as lookup_url_kwarg and just
# change which model field it's matched against. get_queryset() below is always already
# scoped to the requester's own items/groups, so this can't cross into another owner's ids.
# Detail routes address an item by its owner-scoped id, not the internal row id. See
# docs/implementation.md#inventory-detail-routes-use-owner-scoped-ids.
lookup_field = 'id'
lookup_url_kwarg = 'pk'
def get_queryset(self):
# A KnownIdentity acting purely as a group member (e.g. a remote member on a group
# hosted on this backend) never has a local ToolshedUser account here - group-owned
# items must stay reachable for such an identity, only personal ("owner=...") items
# require .user.exists().
# A pure group-member KnownIdentity may have no local ToolshedUser account; only
# personal items require .user.exists(). See
# docs/implementation.md#group-member-identities-without-local-accounts.
if type(self.request.user) != KnownIdentity:
return InventoryItem.objects.none()
identity = self.request.user
group_items = InventoryItem.objects.filter(owner_group__in=identity.member_of_groups.all())
if self.action != 'list':
# retrieve/update/destroy: anything the caller may act on - their own items, or any
# group they're currently a member of. The narrower per-group listing below is only
# for the list action, so the main Inventory page stays scoped to personal items.
# retrieve/update/destroy: any item the caller may act on, own or group. See
# docs/implementation.md#inventory-queryset-scope-by-action.
if identity.user.exists():
return InventoryItem.objects.filter(owner=identity.user.get()) | group_items
return group_items
@ -127,13 +123,8 @@ def search_inventory_items(request):
@authentication_classes([SignatureAuthentication])
@permission_classes([IsAuthenticated])
def get_shared_item(request, handle, id):
"""Fetch a single item by its owner's handle (username@domain) and local id, e.g. for the
/i/<handle>/<id> item URL (see docs/design-in-progress/items-labels.md) or the
/inventory/shared/<handle>/<id> in-app view. Unlike InventoryItemViewSet, which only ever
returns the requester's own items, this looks the item up by owner instead of by requester,
so it's the only endpoint that can serve a friend's item - subject to the same
friends-or-self and availability_policy checks getUserProfile/_accessible_files already
use elsewhere."""
"""Fetch a single item by its owner's handle and local id, for /i/<handle>/<id> or
/inventory/shared/<handle>/<id>. See docs/implementation.md#get-shared-item-looks-up-by-owner."""
try:
username, domain = split_userhandle_or_throw(handle)
except ValueError:

View file

@ -83,9 +83,9 @@ class Tag(models.Model):
class OwnerItemSequence(models.Model):
"""Tracks the last InventoryItem id handed out to a given owner or owner_group, so ids can
be allocated sequentially and without gaps within that scope (see InventoryItem.create_for_owner).
Exactly one of owner/owner_group is set, mirroring InventoryItem's own owner/owner_group split."""
"""Tracks the last InventoryItem id handed out per owner/owner_group scope for sequential,
gapless allocation (see InventoryItem.create_for_owner); exactly one of owner/owner_group is
set, mirroring InventoryItem's own split."""
owner = models.ForeignKey(ToolshedUser, on_delete=models.CASCADE, null=True, blank=True, related_name='+')
owner_group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True, related_name='+')
last_id = models.PositiveIntegerField(default=0)
@ -117,9 +117,8 @@ class InventoryItem(SoftDeleteModel):
)
internal_id = models.AutoField(primary_key=True)
# The externally visible identifier: sequential and gapless within owner/owner_group's own
# items (see OwnerItemSequence), never the internal_id above. Always allocate through
# create_for_owner rather than InventoryItem.objects.create() directly.
# Externally visible id, sequential/gapless within owner/owner_group's own items (see
# OwnerItemSequence), never internal_id; always allocate via create_for_owner, not .objects.create().
id = models.PositiveIntegerField(editable=False)
published = models.BooleanField(default=False)
name = models.CharField(max_length=255, null=True, blank=True)
@ -152,8 +151,8 @@ class InventoryItem(SoftDeleteModel):
@classmethod
def create_for_owner(cls, *, owner=None, owner_group=None, **kwargs):
"""The only supported way to create an InventoryItem: allocates the next id for this
owner/owner_group scope and creates the item with it, atomically."""
"""The only supported way to create an InventoryItem: atomically allocates the next id
for this owner/owner_group scope."""
with transaction.atomic():
next_id = OwnerItemSequence.allocate(owner=owner, owner_group=owner_group)
return cls.objects.create(owner=owner, owner_group=owner_group, id=next_id, **kwargs)

View file

@ -1,9 +1,4 @@
"""Data helpers for building/importing a user's offline export.
These functions deal with the toolshed models and CSV row shapes only - they know nothing
about the zip container format or how the request is authenticated. See toolshed/api/offlinedata.py
for the zip-building/parsing and the API views themselves.
"""
"""Data helpers for building/importing a user's offline export; deal with toolshed models and CSV row shapes only, and know nothing about the zip container format or request auth - see toolshed/api/offlinedata.py for that."""
def inventory_rows(user):
@ -76,11 +71,7 @@ def location_rows(user):
def inventory_files(user):
"""Generator that yields (arcname, data) for each unique file attached to the user's inventory items.
Files are deduplicated by hash and placed under a 'files/' subfolder, keeping their original
extension (guessed from mime_type) so attachments and images remain viewable once extracted.
"""
"""Yields (arcname, data) for each unique file attached to the user's inventory items, deduplicated by hash. See docs/implementation.md#file-naming-convention-in-exports for the naming scheme."""
import mimetypes
from toolshed.models import InventoryItem
@ -125,11 +116,7 @@ def profile_data(user):
def profile_picture_files(user):
"""Generator that yields (arcname, data) for the user's profile picture, if one is set.
Kept separate from `inventory_files()` so the profile picture is included in the export
even for users with no inventory items or whose picture isn't attached to any item.
"""
"""Generator that yields (arcname, data) for the user's profile picture, if one is set. Kept separate from `inventory_files()` so the picture is included even for users with no inventory items or whose picture isn't attached to any item."""
import mimetypes
if not user.profile_picture:
@ -148,21 +135,12 @@ def profile_picture_files(user):
def settings_data(user):
"""Return the given user's account-level preferences as a {key: value} dict for settings.json.
Only account preferences (AccountPreference) are exported; device-level preferences stay
in the browser's local storage since they describe the device, not the account.
"""
"""Return the given user's account-level preferences as a {key: value} dict for settings.json. Only account preferences are exported; device-level preferences stay in the browser's local storage since they describe the device, not the account."""
return {pref.key: pref.value for pref in user.preferences.all()}
def import_profile(user, data, available_files):
"""Fault-tolerant import of profile.json, updating the user's editable profile fields.
Only 'first_name', 'last_name', 'email' and 'profile_picture' (a 'files/...' path present in
`available_files`) are applied; 'username' and 'domain' are ignored since they identify the
account itself and can't be changed by an import.
"""
"""Fault-tolerant import of profile.json, updating the user's editable profile fields. See docs/implementation.md#profile-import-semantics for which fields are applied and why."""
import json
try:
@ -189,11 +167,7 @@ def import_profile(user, data, available_files):
def import_settings(user, data):
"""Fault-tolerant import of settings.json into the user's account-level preferences.
Each top-level key/value pair is upserted as an AccountPreference; unreadable data or a
non-object payload is skipped rather than aborting the whole import.
"""
"""Fault-tolerant import of settings.json; each top-level key/value pair is upserted as an AccountPreference, and unreadable data or a non-object payload is skipped rather than aborting the whole import."""
import json
from authentication.models import AccountPreference
@ -217,18 +191,7 @@ def import_settings(user, data):
def delete_user_data(user):
"""Permanently delete everything that `user_data()` exports, keeping the account itself intact.
This removes the user's inventory items (hard delete, bypassing soft-delete), storage
locations, account preferences, the friends relation on their public identity, the profile
picture, and any File blobs (profile picture / inventory attachments) that would otherwise be
orphaned - i.e. not referenced by any other inventory item or user. Files still referenced
elsewhere (they're deduplicated by content hash) are left untouched. The ToolshedUser account
(and its underlying KnownIdentity) is *not* deleted - this only wipes the account's data, it
doesn't close the account. See `delete_account()` in toolshed/api/offlinedata.py for that.
Returns a summary dict describing what was removed.
"""
"""Permanently delete everything that `user_data()` exports, keeping the account itself intact. Returns a summary dict describing what was removed. See docs/implementation.md#account-data-deletion for exactly what's removed and why the account itself survives."""
from django.db import transaction
from toolshed.models import InventoryItem, StorageLocation
@ -262,15 +225,7 @@ def delete_user_data(user):
def delete_user_account(user):
"""Permanently delete the local user's account, after wiping all of its data.
This first calls `delete_user_data()` to remove everything covered by the data export
(inventory, locations, settings, friends relation, profile picture and orphaned files),
then deletes the ToolshedUser row itself. The underlying KnownIdentity is kept so remote
friends/history relating to this identity remain intact - only the local account is closed.
Returns a summary dict describing what was removed, with `account` set to True.
"""
"""Permanently delete the local user's account, after wiping all of its data via `delete_user_data()`. Returns a summary dict with `account` set to True. See docs/implementation.md#account-data-deletion for why the underlying KnownIdentity is kept."""
from django.db import transaction
with transaction.atomic():
@ -282,11 +237,7 @@ def delete_user_account(user):
def _delete_orphaned_files(file_ids):
"""Delete File rows (and their underlying blobs) in `file_ids` that are no longer referenced.
A File is considered orphaned once no InventoryItem, no ToolshedUser (profile picture), and no
WorkflowInstance (staged file) references it anymore. Returns the number of files deleted.
"""
"""Delete File rows (and their underlying blobs) in `file_ids` that are no longer referenced. Returns the number of files deleted. See docs/implementation.md#account-data-deletion for the orphan definition."""
from files.models import File
deleted = 0
@ -360,15 +311,7 @@ def get_or_create_category(path):
def import_locations(user, data):
"""Fault-tolerant import of locations.csv into StorageLocations owned by `user`.
Rows are read by header label. Rows missing the required 'name' column are skipped.
Optional columns ('description', 'category') are simply omitted if absent. Locations are
processed in path-depth order so a child's parent already exists by the time it's needed.
Each row runs in its own transaction savepoint so a DB-level failure on one row (e.g. a
constraint violation) can't poison the surrounding transaction and silently break every
subsequent row.
"""
"""Fault-tolerant import of locations.csv into StorageLocations owned by `user`. See docs/implementation.md#location-import-ordering-and-savepoints for row ordering and error-isolation rules."""
from django.db import transaction
from toolshed.models import StorageLocation
@ -444,22 +387,11 @@ def import_friends(user, data):
class _HandleNotFound(Exception):
"""Raised when a fully qualified handle (e.g. 'git:base#tag:drill') can't be resolved.
This intentionally aborts the whole row (rather than falling back to creating a new
entity), since a handle references a *specific* entity from a *specific* origin - silently
creating a new local entity named after the raw handle string would be incorrect.
"""
"""Raised when a fully qualified handle (e.g. 'git:base#tag:drill') can't be resolved, aborting the row rather than creating a new entity. See docs/implementation.md#handle-resolution-semantics."""
def _resolve_handle(value, entity_type, model):
"""Resolve a fully qualified handle (e.g. 'git:base#tag:drill') to an *existing* model instance.
Never creates anything: a handle references a specific entity from a specific origin, so
silently creating a new local entity named after the raw handle string would be incorrect.
Raises `_HandleNotFound` if the handle's entity type doesn't match or no such object exists,
so the caller can skip the row and report a helpful error instead.
"""
"""Resolve a fully qualified handle (e.g. 'git:base#tag:drill') to an *existing* model instance; never creates one. See docs/implementation.md#handle-resolution-semantics for the rationale."""
origin, rest = value.split('#', 1)
if ':' in rest:
found_type, name = rest.split(':', 1)
@ -475,20 +407,14 @@ def _resolve_handle(value, entity_type, model):
def _quote_value_if_needed(value):
"""Wrap `value` in double quotes (CSV-style, doubling any embedded quotes) if it contains a
comma or a quote character, so it survives sitting inside a comma-separated "handle=value"
list unambiguously.
"""
"""Wrap `value` in double quotes (CSV-style, doubling embedded quotes) if it contains a comma or quote character. See docs/implementation.md#properties-csv-encoding."""
if any(ch in value for ch in ',"'):
return '"' + value.replace('"', '""') + '"'
return value
def _encode_properties_cell(item_properties):
"""Encode an item's properties as a comma-separated "handle=value" list for the 'properties'
CSV cell, quoting a value (CSV-style) when it contains a comma or a quote character so it
still round-trips correctly. See `_parse_properties_cell()` for the reader side.
"""
"""Encode an item's properties as a comma-separated "handle=value" list for the 'properties' CSV cell. See docs/implementation.md#properties-csv-encoding and `_parse_properties_cell()` for the reader side."""
entries = [
f"{ip.property.get_handle()}={_quote_value_if_needed(ip.value or '')}"
for ip in item_properties
@ -497,15 +423,7 @@ def _encode_properties_cell(item_properties):
def _split_quoted_comma_list(raw_value):
"""Split a comma-separated list into entries, honouring double-quoted substrings (CSV-style,
wherever they appear in an entry) so a quoted value's own commas aren't mistaken for
separators. Doubled quotes ("") inside a quoted substring are unescaped to a single literal
quote, and the surrounding quotes themselves are stripped from the result.
Only the single space after each ", " separator (as written by `_encode_properties_cell()`)
is dropped - unlike a blanket `.strip()`, this preserves any leading/trailing whitespace that
is genuinely part of a (quoted) value.
"""
"""Split a comma-separated list into entries, honouring double-quoted substrings (CSV-style) so a quoted value's own commas aren't mistaken for separators. See docs/implementation.md#properties-csv-encoding for the quoting/whitespace rules this implements."""
entries = []
current = []
in_quotes = False
@ -537,12 +455,7 @@ def _split_quoted_comma_list(raw_value):
def _parse_properties_cell(raw_value, resolve_property):
"""Parse the 'properties' CSV cell into a list of (Property, value) tuples.
The cell is a comma-separated list of "handle=value" entries; a value containing a comma or
a quote character is double-quoted (CSV-style) by `_encode_properties_cell()` so it survives
the round trip intact.
"""
"""Parse the 'properties' CSV cell into a list of (Property, value) tuples. See docs/implementation.md#properties-csv-encoding for how the cell is encoded by `_encode_properties_cell()`."""
raw_value = (raw_value or '').strip()
if not raw_value:
return []
@ -561,17 +474,7 @@ def _parse_properties_cell(raw_value, resolve_property):
def import_inventory(user, data, available_files):
"""Fault-tolerant import of inventory.csv into InventoryItems owned by `user`.
`available_files` maps the 'files' column's paths to File instances successfully extracted
from the zip; references to missing files are ignored rather than failing the row.
If a row references a fully qualified tag/property/category handle that doesn't exist
locally, the whole item is skipped (rather than creating a bogus local entity named after
the raw handle) and a helpful message is added to the returned `errors` list. Each row runs
in its own transaction savepoint so a DB-level failure on one row can't poison the
surrounding transaction and silently break every subsequent row.
"""
"""Fault-tolerant import of inventory.csv into InventoryItems owned by `user`. See docs/implementation.md#inventory-import-semantics for file/handle resolution and error-isolation rules."""
from django.db import transaction
from toolshed.models import Category, InventoryItem, ItemProperty, StorageLocation, Tag, Property

View file

@ -255,11 +255,7 @@ class InventoryItemSerializer(serializers.ModelSerializer):
class WorkflowInstanceSerializer(serializers.ModelSerializer):
owner = serializers.StringRelatedField(read_only=True)
# Hash is enough to identify a staged file (the client computes the same SHA-256 the backend
# does, and can fetch bytes from a hash-derived storage path) - for anything staged by *this*
# session there's nothing more to say, and for a file staged elsewhere (another device/tab),
# hash is what lets this session recognize and fetch it. Unlike InventoryItemSerializer.files,
# no fuller FileSerializer representation is needed here.
# Only the hash is needed to identify a staged file, unlike InventoryItemSerializer.files. See docs/implementation.md#staged-files-are-identified-by-hash-alone.
staged_files = serializers.SerializerMethodField()
class Meta:

View file

@ -85,20 +85,8 @@ class FriendApiTestCase(UserTestMixin, ToolshedTestCase):
self.assertEqual(self.f['local_user1'].friends.count(), 1)
# what ~should~ happen:
# 1. user x@A sends a friend request to user y@B
# 1.1. x@A's client sends a POST request to A/api/friendrequests/ with body {from: x@A, to: y@B}
# 1.2. A's backend creates a FriendRequestOutgoing object, containing x@A's identity and y@B's name
# 1.3. x@A's client sends a POST request to B/api/friendrequests/ with body
# {from: x@A, to: y@B, public_key: x@A's public key}
# 1.4. B's backend creates a FriendRequestIncoming object, containing y@B's and x@A's identities
# 2. user y@B accepts the friend request
# 2.1. y@B's client sends a POST request to A/api/friendsrequests/ with body
# {from: x@A, to: y@B, public_key: y@B's public key}
# 2.2. A's backend matches the data to the FriendRequestOutgoing object, deletes both and creates a Friend object,
# containing x@A's and y@B's identities
# 2.3. y@B's client sends a POST request to B/api/friends/ containing the id of the FriendRequestIncoming object
# 2.4. B's backend creates a Friend object, using the identities from the FriendRequestIncoming object
# Friend request/accept protocol walkthrough. See
# docs/implementation.md#friend-request-and-accept-protocol-flow.
class FriendRequestListTestCase(UserTestMixin, ToolshedTestCase):

View file

@ -388,9 +388,8 @@ class GroupOwnedInventoryApiTestCase(UserTestMixin, GroupTestMixin, CategoryTest
self.assertEqual(InventoryItem.objects.filter(id=item_id).count(), 0)
def test_remote_member_without_local_account_can_edit(self):
# A remote member (no ToolshedUser row at all on this backend, only a KnownIdentity -
# see docs/design-in-progress/groups-mvp.md) must still be able to act on group-owned
# items here; it must not be treated as unauthorized just because .user.exists() is False.
# A remote member (KnownIdentity, no ToolshedUser row) must still act on group-owned
# items - not unauthorized just because .user.exists() is False.
self.f['group1'].members.add(self.f['ext_user1'].public_identity)
item_id = self.create_group_item().json()['id']
reply = client.get('/api/inventory_items/{}/'.format(item_id), self.f['ext_user1'])
@ -426,8 +425,8 @@ class GroupOwnedInventoryApiTestCase(UserTestMixin, GroupTestMixin, CategoryTest
self.assertEqual(len(reply.json()), 0)
def test_create_group_owned_item_with_full_fields(self):
# Parity with InventoryApiTestCase.test_post_new_item - tags/properties/category must
# attach to a group-owned item exactly the same way they do for a personal one.
# Parity with InventoryApiTestCase.test_post_new_item: tags/properties/category attach
# to a group-owned item the same way as a personal one.
reply = client.post('/api/inventory_items/', self.f['local_user1'], {
'availability_policy': 'rent',
'category': 'cat2',
@ -450,8 +449,7 @@ class GroupOwnedInventoryApiTestCase(UserTestMixin, GroupTestMixin, CategoryTest
self.assertEqual([p.value for p in item.itemproperty_set.all()], ['value1', 'value2'])
def test_create_group_owned_item_empty_fails(self):
# Parity with InventoryApiTestCase.test_post_new_item_empty - clean()'s name-or-files
# validation must still apply to group-owned items.
# Parity with InventoryApiTestCase.test_post_new_item_empty: clean()'s name-or-files validation still applies.
reply = client.post('/api/inventory_items/', self.f['local_user1'], {
'availability_policy': 'private', 'owned_quantity': 1, 'owner_group': self.f['group1'].id,
})
@ -471,9 +469,8 @@ class GroupOwnedInventoryApiTestCase(UserTestMixin, GroupTestMixin, CategoryTest
self.assertEqual(len(reply.json()), 0)
def test_put_group_item(self):
# Parity with InventoryApiTestCase.test_put_item - full replace, by a different member
# than the one who created it, exercising the group_items_id -> _is_authorized branch
# in perform_update for a PUT (not just PATCH).
# Parity with InventoryApiTestCase.test_put_item, but as a PUT by a different member than
# the creator, to exercise the _is_authorized branch in perform_update for PUT too.
item_id = self.create_group_item().json()['id']
reply = client.put('/api/inventory_items/{}/'.format(item_id), self.f['local_user2'], {
'availability_policy': 'sell',
@ -539,9 +536,8 @@ class GroupOwnedInventoryApiTestCase(UserTestMixin, GroupTestMixin, CategoryTest
self.assertEqual([f for f in item.files.all()], [self.f['test_file3']])
def test_group_items_excluded_from_search(self):
# Group-owned items are only ever reachable via the group's own detail page for MVP
# (see docs/design-in-progress/groups-mvp.md) - search must not surface them, same as
# the main Inventory list already doesn't.
# Group-owned items are reachable only via the group's own detail page for MVP (see
# docs/design-in-progress/groups-mvp.md) - search must not surface them either.
self.create_group_item(name='searchable-drill')
InventoryItem.create_for_owner(owner=self.f['local_user1'], owned_quantity=1, name='searchable-personal')
reply = client.get('/api/search/?query=searchable', self.f['local_user1'])
@ -551,8 +547,8 @@ class GroupOwnedInventoryApiTestCase(UserTestMixin, GroupTestMixin, CategoryTest
class InventoryItemIdAllocationTestCase(UserTestMixin, ToolshedTestCase):
"""InventoryItem.id is sequential and gapless within each owner/owner_group's own items,
never reused, and allocated independently per scope - see OwnerItemSequence."""
"""InventoryItem.id is sequential, gapless, and never reused within each owner/owner_group's
own items, allocated independently per scope (see OwnerItemSequence)."""
def setUp(self):
super().setUp()

View file

@ -123,10 +123,7 @@ class DeleteAccountTestCase(_DeleteTestDataMixin, ToolshedTestCase):
class ImportInventoryPropertiesTestCase(UserTestMixin, CategoryTestMixin, TagTestMixin, PropertyTestMixin,
ToolshedTestCase):
"""Properties must round-trip through export/import even when their value contains a
comma or an '=' sign - characters that a naive "handle=value, handle2=value2" encoding of
the 'properties' CSV cell would misinterpret as a field/entry separator.
"""
"""Properties must round-trip through export/import even when their value contains a comma or '=' sign, which a naive "handle=value, handle2=value2" encoding would otherwise misinterpret as a separator."""
def setUp(self):
super().setUp()
@ -222,10 +219,7 @@ class ImportInventoryPropertiesTestCase(UserTestMixin, CategoryTestMixin, TagTes
class ExportImportApiRoundTripTestCase(UserTestMixin, CategoryTestMixin, TagTestMixin, PropertyTestMixin,
ToolshedTestCase):
"""End-to-end coverage of the /api/export/ + /api/import/ endpoints (as actually used by
clients), rather than calling the internal helper functions directly - this is what a real
export/import round trip between two accounts looks like.
"""
"""End-to-end coverage of the /api/export/ + /api/import/ endpoints (as actually used by clients), rather than calling the internal helper functions directly - this is what a real export/import round trip between two accounts looks like."""
def setUp(self):
super().setUp()

View file

@ -1,14 +1 @@
FROM nginx:bookworm
# snakeoil for localhost
RUN apt-get update && \
apt-get install -y openssl && \
openssl genrsa -des3 -passout pass:x -out server.pass.key 2048 && \
openssl rsa -passin pass:x -in server.pass.key -out server.key && \
rm server.pass.key && \
openssl req -new -key server.key -out server.csr \
-subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=localhost" && \
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt &&\
mv server.crt /etc/nginx/nginx.crt && \
mv server.key /etc/nginx/nginx.key \

View file

@ -72,6 +72,14 @@ services:
- ./instance_a/dns.json:/var/www/dns.json:ro
- ./instance_a/domains.json:/var/www/domains.json:ro
- ./instance_a/userfiles:/var/www/userfiles:ro
# A stable, CA-signed cert (see frontend/.local/make_localhost.sh) covering localhost plus
# every loopback IP a dev proxy binds to below, instead of Dockerfile.proxy generating a
# fresh throwaway self-signed one on every image build - that regenerated cert invalidated
# any trust exception you'd added in your browser on the previous build. Trust
# frontend/.local/RootCA.crt once (see docs/development.md) and it keeps working across
# rebuilds.
- ../../frontend/.local/localhost.crt:/etc/nginx/nginx.crt:ro
- ../../frontend/.local/localhost.key:/etc/nginx/nginx.key:ro
ports:
- "127.0.0.1:8080:8080"
- "127.0.0.3:5353:5353"
@ -83,6 +91,8 @@ services:
volumes:
- ./instance_b/nginx-b.dev.conf:/etc/nginx/nginx.conf:ro
- ./instance_b/userfiles:/var/www/userfiles:ro
- ../../frontend/.local/localhost.crt:/etc/nginx/nginx.crt:ro
- ../../frontend/.local/localhost.key:/etc/nginx/nginx.key:ro
ports:
- "127.0.0.2:8080:8080"

View file

@ -10,5 +10,6 @@ This is the documentation for the Toolshed project. It is a work in progress.
- [Development Setup](development.md)
- [About Federation](federation.md)
- [Handles and Short IDs](handles-and-shortids.md)
- [Implementation Notes](implementation.md)

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;