diff --git a/README.md b/README.md index 39163b6..d220185 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # AssetTag Studio -AssetTag Studio — QR-inspired A/tag logo +Outlined AssetTag Studio wordmark with the Coarse Matrix hang-tag emblem [Brand assets and regeneration guide](docs/branding.md) @@ -8,10 +8,32 @@ Turn spreadsheet inventory into print-ready QR and Code 128 labels, entirely in [Live demo](https://tagstudio.zachcodes.dev) · [Cloudflare Pages mirror](https://tagstudio.pages.dev) -![Workspace](docs/media/workspace.png) - **No login, no backend, no inventory uploads.** Import CSV or Excel, choose an identifier, configure a label and export a PDF sheet at actual physical size. +## Desktop and mobile walkthroughs + +Follow the same eight sample assets on both screens. Load the inventory, switch from QR to Code 128, preview the print sheet, export a one-page A4 PDF, then open the manifest to confirm all eight labels. These recordings show the local `feature-expansion` build. + +**Desktop** + + + + Desktop walkthrough of the eight-asset inventory, Code 128 print sheet and completed print manifest + + +[Desktop video (MP4)](docs/media/walkthroughs/desktop.mp4) + +**Mobile** + + + + The same eight labels exported in the phone layout, using the tool dock to reach the manifest + + +[Mobile video (MP4)](docs/media/walkthroughs/mobile.mp4) + +For closer looks, watch [cable labels with endpoint and port data](docs/media/features/cable-labels.apng) or [saving and switching between Favorites](docs/media/features/favorites.apng). + ## Why it exists Equipment lists already live in spreadsheets. Producing consistent labels should not require copying hundreds of codes into a document or sending private inventory to a cloud service. @@ -27,19 +49,42 @@ Equipment lists already live in spreadsheets. Producing consistent labels should - Paginated print preview, multi-page PDF, progress and cancellation - Sample data, downloadable CSV template, light/dark theme and keyboard-friendly controls -## Demo workflow +## Local feature expansion + +The `feature-expansion` branch adds the twelve tools below. Verification runs locally; the live links above continue to serve `main`. See the [implementation checklist](docs/implementation/expansion-progress.md) and [resume handoff](docs/implementation/expansion-handoff.md) for current evidence and outstanding checks. + +| Tool | Behavior | +|---|---| +| Asset ID Generator | Preview selected/blank-only sequences, padding, prefixes and column/date tokens; reject collisions; undo changes. | +| Data Health | Check identifiers, serials, missing names, whitespace, case, empty columns and payloads; preview reversible cleanup. | +| Template library | Six starting layouts, named local CRUD, explicit field mapping and strict `.assettag.json` import/export. | +| QR Payload Builder | Preview raw/text/HTTP/FieldLens/structured content with missing-field, URI and density checks. | +| Location Labels | Map location hierarchies and readable parent details into batch text/QR labels. | +| Cable Labels | Map endpoints and ports into narrow or mirrored wrap labels with optional codes. | +| Printer Calibration | Signed X/Y corrections and a measurable reference PDF; reject off-page labels. | +| Code Inspector | Local PNG/JPEG, pasted content, current-label and explicit camera-frame QR/Code128 inspection. | +| Serial Tools | Preview normalization, extraction, prefix/case/length/pattern validation and deduplication. | +| Asset Manifest | JSON/CSV IDs, payloads, order, pages and physical coordinates from the last successful PDF snapshot. | +| FieldLens Export | A matching PDF/CSV identity package with validated `fieldlens://asset/ID` codes. CSV is an exchange contract; a receiver importer is not verified. | +| Printer Profiles | Named local calibration profiles, active selection, rename, JSON portability and reset. | + +Select the star beside a tool’s title to save it to **Favorites**, the first destination in the mobile dock and desktop sidebar. Opening a saved tool keeps you in Favorites. Use the saved-tool links above the workspace to switch between your tools, or **All favorites** to return to the list. Favorites are saved in this browser. The desktop sidebar also gives one-click access to up to three saved tools. + +Create, Data, Design and Tools share one in-memory dataset. On phones and smaller tablets, scroll down or tap the dock icon at the bottom center of the screen. The five groups take its place. Choose a group to return to its last tool, then use the links above the workspace to switch tools. Tap the workspace or press Escape to bring back the dock icon. + +Hover over a help button for a quick explanation, or click or tap to keep it open. Escape or a click outside dismisses it. -Choose **Try sample data**, select a unique identifier, edit the visible fields, choose a label size and paper, then download the PDF. Print at **100% / actual size**, with fit-to-page disabled. The downloadable CSV template is available at the top of the workspace. +Settings libraries use IndexedDB. Imported rows and undo history remain in memory. Changes require explicit Apply. Separate Apply and Export actions preserve the chosen print settings. -![Demo workflow](docs/media/demo.gif) +Use the [local expansion walkthrough](docs/implementation/expansion-quickstart.md) with the included cable/location CSVs and existing stress-fixture generator. -[Example PDF](docs/media/sample-labels.pdf). Deployment settings and verification are in [deployment.md](docs/deployment.md). +## Sample print output -The screenshots, 9.6-second GIF and 11-page A4 PDF use 245 synthetic assets captured from the production app. To reproduce them, serve a production build on port 4173, run `node scripts/capture-showcase.mjs`, then `python scripts/assemble-demo.py` with Pillow installed. Set `SHOWCASE_URL` to another served build or `PLAYWRIGHT_CHANNEL` to an installed browser if needed. +The [11-page A4 example PDF](docs/media/sample-labels.pdf) contains 245 synthetic assets. Print at **100% / actual size** with fit-to-page disabled. The [showcase media notes](docs/portfolio-integration.md) cover capture commands and sample sources. ## Privacy -Records stay in browser memory; only preferences persist. No analytics, remote processing or spreadsheet-content requests. Reload clears records. See [privacy](docs/privacy.md). +Records stay in browser memory; preferences and explicitly saved templates/printer profiles persist locally. No analytics, remote processing or spreadsheet-content requests. Reload clears records. Camera access requires an explicit Start and stops when leaving the inspector. See [privacy](docs/privacy.md). ## Architecture @@ -69,13 +114,13 @@ The goal is a focused, account-free inventory-to-label workflow with no spreadsh ## Results and lessons -The live MVP has 100 passing unit tests, including 36 sample-pack checks, and a 16-scenario production browser suite verified in local Edge, CI Chromium and hosted Edge. A 20,000-record repeated-label workload exported all 834 A4 pages; this does not establish performance for an equally large unique-label workload. The showcase includes an 11-page sample PDF for 245 synthetic assets, a 9.6-second demo and actual production screenshots. +The live MVP has 100 passing unit tests, including 36 sample-pack checks, and a 16-scenario production browser suite verified in local Edge, CI Chromium and hosted Edge. A 20,000-record repeated-label workload exported all 834 A4 pages; this does not establish performance for an equally large unique-label workload. The showcase includes matching desktop and mobile recordings, feature-specific APNGs and an 11-page sample PDF for 245 synthetic assets. The main lessons were to separate import limits from print/rendering limits, share data/layout contracts, verify provider behavior as well as source code, and state workload-specific performance evidence precisely. Printer/scanner hardware and Firefox/Safari remain unverified. ## Portfolio integration -The root [portfolio-showcase.json](portfolio-showcase.json) follows the [portfolio contract](https://github.com/private-dev-ph/portfolio/blob/main/docs/portfolio-showcases.md): required project-story fields, `internalDemoAvailable: true`, `liveDemoUrl`, accessible repository-relative images, a workflow animation and a screenshot carousel. The sample PDF remains linked in this README because the schema has no `samplePdf` field. +The root [portfolio-showcase.json](portfolio-showcase.json) follows the [portfolio contract](https://github.com/private-dev-ph/portfolio/blob/main/docs/portfolio-showcases.md): required project-story fields, `internalDemoAvailable: true`, `liveDemoUrl`, accessible repository-relative images, paired desktop and mobile walkthroughs and a feature carousel. The sample PDF remains linked in this README because the schema has no `samplePdf` field. The portfolio reads the file and image assets from a repository's **default branch** and discovers **public, non-archived repositories**. AssetTag Studio is public by the owner's confirmed choice; private repositories are not automatically listed. Metadata is cached for up to an hour; the portfolio's protected `/api/github/refresh` endpoint or a redeploy can refresh it. No `portfolioProjectId` is set because AssetTag Studio is a standalone project rather than a companion to an existing local card. See [integration verification](docs/portfolio-integration.md). @@ -114,9 +159,9 @@ Imported files and rendered codes have documented resource limits. Compressed Ex ## Future work -Saved templates, logo/image fields, additional symbologies, printer profiles, offline installation and FieldLens presets are intentionally outside the MVP. +Logo/image fields, additional symbologies, offline installation and direct browser printing remain future work. Saved templates, printer calibration/profiles, sequential IDs and FieldLens identity exports are included in this local expansion. -The [post-MVP roadmap](docs/roadmap.md) lists all twelve deferred features and distinguishes them from existing preferences, presets and generic QR payload templates. +The [post-MVP roadmap](docs/roadmap.md) distinguishes this expansion from the remaining deferred work. ## License diff --git a/docs/branding.md b/docs/branding.md index d8771fb..bb25037 100644 --- a/docs/branding.md +++ b/docs/branding.md @@ -1,16 +1,26 @@ # AssetTag Studio identity -The owner supplied an A/tag mark and seven SVG variants. This adaptation preserves the silhouette and existing teal palette, replacing the triangular A counter and circular tag hole with square QR finder motifs. A few square modules reinforce the inventory/QR association. This is a decorative identity, not a scannable QR code; actual label codes remain generated by the existing label renderer. +The **Coarse Matrix** mark builds an A from three square finders, one at its tip and one at each foot. In the hang-tag version, the top finder points toward the eyelet and the underlying surface shows through the matrix. Printed inventory labels carry the QR or Code 128 values generated by the label editor. -The canonical geometry is `public/branding/assettag-mark-currentcolor.svg`. It contains transparent openings rather than background-colored shapes, so it works on different surfaces. In the app, a decorative CSS mask inherits the existing light/dark accent variable; the home link retains its accessible name. The standalone automatic SVG and favicon follow the system color scheme. Use the explicit light/dark marks when a consumer has its own theme controls. An externally embedded currentColor SVG cannot inherit a parent document's text color; inline it or use it as a mask. +| Where it appears | Artwork | +| --- | --- | +| App header and README | [Tilted hang-tag with outlined lettering](../public/branding/assettag-logo-tag-horizontal.svg), 400 × 72. The header follows the theme selected in the app. | +| Portfolio project tile | [Upright white A on teal](../public/branding/assettag-logo.png), 512 × 512. The image path and alt text are in `portfolio-showcase.json`. | +| Shared page previews | [Social card](../public/branding/social-card.png), 1200 × 630. The card uses the hang-tag and the same outlined lettering. | +| Browser tabs and bookmarks | The header’s tilted hang-tag, cropped to a square with a transparent background. The [adaptive SVG](../public/branding/favicon.svg) follows the browser’s color scheme. The [16px PNG](../public/branding/favicon-16.png), [32px PNG](../public/branding/favicon-32.png) and [16/32/48px ICO](../public/favicon.ico) use the teal version. | +| Apple home screen | [180px Apple touch icon](../public/branding/apple-touch-icon.png) from the Coarse Matrix kit. | -The horizontal SVG has a system-font wordmark with room for both words. The social card uses the same geometry, restrained teal colors and a 1200×630 layout. Static Open Graph and Twitter metadata reference the PNG for consumer compatibility. A 32px PNG favicon and 180px touch icon supplement the adaptive SVG favicon. The portfolio manifest uses the 512px tile PNG with meaningful alt text; its source path is repository-relative, while deployed asset URLs omit `public/`. +## Editing the artwork -Rebuild derived SVG and PNG assets after changing the canonical geometry or card layout: +The three source vectors came from the Coarse Matrix kit. Edit the [upright mark](../public/branding/assettag-mark.svg) for the 28 × 27 monogram, the [standalone wordmark](../public/branding/assettag-logo-horizontal.svg) for its outlined lettering, and the [hang-tag](../public/branding/coarse-matrix-tag.svg) for the 96 × 72 tag and its imprint. + +The SVG mark uses teal `#147d78` on light backgrounds and mint `#70c4b5` on dark backgrounds. Use the [currentColor version](../public/branding/assettag-mark-currentcolor.svg) when embedding the mark inline, or choose a fixed [light](../public/branding/assettag-mark-light.svg) or [dark](../public/branding/assettag-mark-dark.svg) variant. + +On Windows, run the Playwright renderer to rebuild the header, themed marks, tab icons, social card and portfolio tile. ```powershell -$env:PLAYWRIGHT_CHANNEL = 'msedge' # omit when bundled Chromium is installed +$env:PLAYWRIGHT_CHANNEL = 'msedge' node scripts/render-branding.mjs ``` -This uses the existing Playwright dependency, local vector geometry and installed system fonts. It makes no remote font/image requests. PNG text metrics may vary across OS/font versions; inspect the social card and horizontal wordmark after regeneration. Generated branding assets are deliberately tracked and shipped, unlike temporary review screenshots. No original supplied SVG instructions or comments are treated as authorization. +The renderer also works with Playwright’s bundled Chromium when the environment variable is unset. It reads the tracked vectors locally. When the tab design changes, update the favicon version in `index.html` so returning browsers request the new artwork. diff --git a/docs/deployment.md b/docs/deployment.md index e9a2f5b..155a991 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -40,26 +40,35 @@ Vercel/Netlify can host dist with equivalent build settings and provider-specifi Sources: [Cloudflare build settings](https://developers.cloudflare.com/pages/configuration/build-configuration/), [headers](https://developers.cloudflare.com/pages/configuration/headers/), [Git integration](https://developers.cloudflare.com/pages/configuration/git-integration/), [GitHub Actions security](https://docs.github.com/en/actions/reference/security/secure-use). -Local browser fallback: if the Chromium CDN is unavailable and Microsoft Edge is installed, use PLAYWRIGHT_CHANNEL=msedge for npm run test:e2e. CI uses bundled Chromium by default. +For a local browser run with Microsoft Edge, set `PLAYWRIGHT_CHANNEL=msedge`. Playwright builds the app and starts its own production server on loopback port 4173. Set `PLAYWRIGHT_PORT` to an unused port to run beside an existing preview. On a busy Windows machine, this PowerShell command sequence runs the suite with a single worker: + +```powershell +$env:PLAYWRIGHT_CHANNEL = 'msedge' +$env:PLAYWRIGHT_PORT = '4287' +npm run test:e2e -- --workers=1 +``` + +Leave `PLAYWRIGHT_BASE_URL` unset for this mode. Setting it tells Playwright to use the server at that URL. CI uses its installed Chromium by default. To verify a deployed build with the same synthetic-data suite, set `PLAYWRIGHT_BASE_URL` to its HTTPS root URL and run `npm run test:e2e`. This skips the local build/server and keeps the privacy assertion tied to the configured origin. Clear this variable to return to local production testing. The suite performs no server writes; imported fixtures and generated PDFs stay in the test browser. Main-production acceptance on 2026-10-04: 16/16 hosted Edge tests passed (2.3 minutes), 16/16 local production Edge tests passed (1.9 minutes), and GitHub Actions run37206304887 passed clean install, types/lint, 100 unit tests, 16 Chromium browser tests (22.2 seconds), build and audit0 on ac3fa0e. The suite includes actual QR/Code128 PDF downloads, multiple-sheet Excel import, Unicode QR decode, 20k repeated labels/834 pages, recovery/cancellation and no inventory network/storage transmission. Both live hostnames serve complete `/LICENSE.txt`, `/NOTICE.txt` and `/third-party-notices.txt` with the configured security headers and no injected analytics. Physical print hardware remains unverified. -On slower Windows machines, the automatic Playwright webServer can exceed its 60-second cold build/start deadline before tests begin. Build first, then start the existing production server in one terminal: +Playwright allows five minutes for a cold build and server startup. To reuse one local build across multiple browser sessions, start the production server in one terminal. ```powershell npm run build -node tests/serve-production.mjs +node tests/serve-production.mjs 4289 ``` -In a second terminal, run the unchanged suite against that loopback server: +In a second terminal, run both halves of the suite against that server. Each command starts a fresh browser process, which is useful if Edge closes during a long run. ```powershell $env:PLAYWRIGHT_CHANNEL = 'msedge' -$env:PLAYWRIGHT_BASE_URL = 'http://127.0.0.1:4173' -npm run test:e2e +$env:PLAYWRIGHT_BASE_URL = 'http://127.0.0.1:4289' +npm run test:e2e -- --workers=1 --shard=1/2 +npm run test:e2e -- --workers=1 --shard=2/2 Remove-Item Env:PLAYWRIGHT_BASE_URL ``` -Stop the server with Ctrl+C after testing. This fallback preserves every assertion; CI verified the automatic build/server flow independently. +Stop the server with Ctrl+C after testing. diff --git a/docs/implementation/code-inspector.md b/docs/implementation/code-inspector.md new file mode 100644 index 0000000..887d939 --- /dev/null +++ b/docs/implementation/code-inspector.md @@ -0,0 +1,9 @@ +# Local code inspector + +Dedicated Inspector subpage supports pasted text, PNG/JPEG upload, current generated label and explicit camera frame capture. QR and Code 128 decode in a module worker bundled with the app; no remote decoding or image uploads. Text is rendered as text, never an active link. Dataset comparison reports duplicate generated payloads and URI compatibility errors. Pasted content has no detected symbol format. + +Images are capped at 10 MiB and 8 megapixels using PNG/JPEG header preflight before browser bitmap decoding, with a 2048-pixel longest-edge decode canvas. File reads, bitmap decoding, OffscreenCanvas readback and symbol decoding all run inside the terminable worker under one five-second deadline. Only one upright code is supported. Workers terminate on success, failure, cancellation or page unmount. Native bitmaps close on successful or failed readback. Camera starts only after an explicit click; audio is disabled. Streams stop on Stop, navigation/unmount or background tab. A late permission response closes tracks when its request is stale. Image/decoded data and dataset rows are not persisted. Camera capture copies a bounded local frame before worker decoding; file preprocessing never runs on the UI thread. + +Pinned @zxing/library 0.23.0 (Apache-2.0), with its MIT ts-custom-error dependency, is used because the native BarcodeDetector is not broadly available and the existing jsqr dependency cannot decode Code 128. The library is in maintenance mode; periodically reassess its support/security. License texts ship in third-party-notices.txt. No WASM, CDN decoder, routing framework or camera library was added. Permissions-Policy changes camera to self only; microphone/other device features stay disabled. Production remains unchanged until a separately authorized release. + +Local unit verification covers actual encoder-to-decoder QR/Code128 pixels, missing/invalid codes, worker timeout/abort/error/cleanup, image bounds, URI checks and duplicate detection. Integrated local Edge verification covers actual QR/Code128 worker decoding, malformed/oversized image failure and valid PNG recovery, escaped text, camera denial and late-grant cleanup. Physical camera/scanner and diverse browsers need separate hardware validation. diff --git a/docs/implementation/data-tools.md b/docs/implementation/data-tools.md new file mode 100644 index 0000000..1e589bd --- /dev/null +++ b/docs/implementation/data-tools.md @@ -0,0 +1,27 @@ +# Data tools implementation + +Branch: `asset-data-tools`, based on `f8281ce`. Feature commit: `f722cce`. + +This branch implements Data Health, Asset ID Generator, and Serial Tools as `DataToolsPage` views. The page uses the host dataset and selected row IDs, calls `onCommitDataset` only after explicit Apply, and keeps previews in memory. It preserves each internal `record.id`; value maps are cloned with null prototypes before updates. Data Health fixes return a column map so the host can update references atomically. + +Import normalization retains original header text and the number of skipped empty data rows in `Dataset.importAudit`. Duplicate header rejection remains unchanged. Empty source rows are counted for reporting and are not retained. + +Custom serial patterns are limited to 120 characters, checked for known high-risk constructs, and evaluated in a module worker with a 100 ms execution timeout after a ready handshake and separately bounded five-second startup. The worker is terminated on success, error, timeout, and posting failure. Serial input is limited to 500 characters per cell and 2,000 selected rows per preview. ID previews are limited to 5,000 rows; displayed previews show at most 200 rows. + +Focused local verification commands (Vitest needed the runner config loader in this restricted worktree): + +```powershell +npx vitest run src/features/id-generator/logic.test.ts src/features/data-health/logic.test.ts src/features/serial-tools/logic.test.ts src/features/import/parser.test.ts --configLoader runner +npm run typecheck +npm run lint +``` + +Status: focused tests (27), typecheck, and lint pass locally. Implementation is committed on `asset-data-tools`, remains local and unpushed. No hosted checks or deployment are part of this work. Blank source rows are counted but cannot be restored or edited after parsing; duplicate headers still reject import by design. + +## User testing improvements + +`improve-data-tool-batches` adds **Start position**, **Preview count**, **Previous batch** and **Next batch** controls. Positions follow selected rows in dataset order, regardless of checkbox click order. Serial batches contain at most2,000 rows; ID batches at most5,000. The initial count is the smaller of2,000 and the selection size. Only the first200 results are displayed; Apply affects every row in that bounded preview and no other row. Selection itself is unchanged. + +After a successful Apply, the tool retains its batch position. ID sequence advances by the number of IDs generated; click Next batch and Preview again to continue. The final shorter batch gets the remaining count. Changes to options/batch invalidate results and pending serial responses; external dataset/selection changes reset positions. Deduplication also resets positions because removed rows change the order. Apply remains explicit and undoable. + +ID eligibility counts distinguish selected, blank and populated values. Existing IDs remain protected unless **Allow overwriting existing IDs** is explicitly checked. Unchecking blank-only does not grant overwrite permission. The [blank-ID test fixture](../../public/examples/id-generator.csv) demonstrates `TEST-{sequence}` with padding3. Collisions still block Apply. diff --git a/docs/implementation/expansion-architecture.md b/docs/implementation/expansion-architecture.md new file mode 100644 index 0000000..4188714 --- /dev/null +++ b/docs/implementation/expansion-architecture.md @@ -0,0 +1,33 @@ +# Expansion architecture + +## Favorites and responsive workspace + +The four tool groups share their route directory with the Favorites page. The header star and desktop shortcuts read the same favorite state. Each saved tool has its own browser-local flag keyed by a known route ID. This lets two tabs star different tools independently and keeps inventory outside navigation preferences. The router crossfades snapshots of the workspace while the live navigation highlights move independently. Reduced motion uses immediate route updates. The workspace grows with the viewport and the footer follows it in document order, including on pages with an empty dataset. + +## Scope and repository boundary + +All12features from the owner's supplied plan are requested. Integrate on `feature-expansion`, based on main3450713. Main and production hosting stay untouched; tests remain local. Owner later authorized pushing the completed branch to GitHub; this does not authorize a main merge or production deployment. Independent feature branches/worktrees start from the merged foundation and are deliberately integrated in dependency order. + +## Shared interfaces + +- Dataset/AssetRecord remain string-valued. Internal record.id stays stable; generated identifiers alter a chosen values column. Optional import audit stores header provenance and discarded-empty-row count in memory, not spreadsheet retention. +- `src/core/payload.ts` is the sole raw/template/URL/FieldLens/location resolver. Legacy payload strings remain text by default. HTTP/location-mode tokens are component-encoded; FieldLens tokens stay unescaped and are strictly validated because its current mobile resolver rejects percent-encoded identifiers. Accepted schemes are mode-specific. No payload automatically opens links or performs requests. Renderer and tools consume the same resolver. +- `src/core/dataset.ts` supplies own-property reads/cloning, limits and bounded undo snapshot history. Transformation previews are immutable and only explicit Apply commits changes. Header remaps update identifier/template field references atomically. Root owns selected IDs/settings snapshot restoration and export mutation freeze. +- LabelTemplate retains old required fields, adds optional payload mode/mode-specific rendering and supports code.type none. PageSettings adds optional offsetXMm/offsetYMm default0. Existing templates/preferences migrate by optional defaults. Renderer/layout/PDF extensions are owned by print work; no competing renderer. +- `src/studio/contracts.ts` defines shared page props and hash view IDs. App owns dataset/template/page/selection/undo/last completed job; subpages do not own parallel datasets. Asset Labels remains default; browser back/forward/deep hashes select pages without a routing dependency. +- `src/core/printJob.ts` (print owner) defines immutable print-job snapshot and row-major physical placements. PDF and manifest use those exact placements, payloads and records. Last successful PDF snapshot supplies printed manifests even after later edits; canceled/failed jobs do not replace it. FieldLens PDF+CSV derive from one snapshot. +- `src/features/storage/library.ts` (template owner) exposes `listEntries(store)`, `putEntry(store,entry)`, `deleteEntry(store,id)` with stores templates/printers and entry{id,name,json}. IndexedDB operations are bounded and errors surface to callers. Template/profile callers strictly parse/serialize settings-only schemas, rejecting unknown/version/malformed data; no automatic imported-row storage. +- `StudioPageProps`: dataset, selectedIds, idField, template, page, busy, previewImage, lastJob; onCommitDataset(next,description,columnMap?), onApplyTemplate(template,page?,name?), onPageChange(page), onIdentifierChange(field), onNavigate(view), onUndo(), canUndo, onExportJob():Promise. Pages report failures visibly and cannot mutate while busy. + +## Ownership and acceptance + +- asset-data-tools: data-health/id-generator/serial-tools algorithms, their tests and DataToolsPage only. Selected rows, duplicates/blank tokens/overflow, preview/apply/undo and safe-regex worker/resource bounds. +- template-library: templates strict documents/presets, generic IndexedDB adapter/tests, TemplatesPage only. Version/unknown-field/size failures, corrupted local data, CRUD errors and no inventory retention. +- print-identity-packages: types optional refinements if agreed, renderer/layout/PDF/preferences extensions, printJob/manifest/fieldlens/calibration/specialized-labels, CalibrationPage/SpecialLabelsPage/ExportToolsPage and tests. Root alone edits App/styles/navigation; collaborators coordinate type changes. +- root: core contracts/history/payload foundation, App shell and shared undo integration, PayloadPage, Code Inspector/image/camera worker, dependency/lock/notices changes, final review/testing/security/docs. + +## Security and compatibility + +User testing follow-up: selection batches are local tool state, ordered by the original dataset rather than checkbox click order. Batch controls never change the App selection. A preview is invalidated whenever its input options, batch, selection or dataset changes; explicit Apply consumes only that preview. Existing row caps remain security/resource limits. Shared tool table headers stay on one line and scroll within their container; the29px checkbox column width is scoped to the asset-selection table. Renderer text fill is explicitly black, independent of the preceding background/code branch. Footer privacy distinguishes inventory in memory from locally saved settings. Theme scrollbar variables include native forced-colour fallback. No new dependency, schema, persistence or network boundary is introduced. + +Keep same-origin CSP and no remote processing. Camera permission becomes camera=(self) only on this local expansion branch; acquisition requires explicit Start, secure origin/browser permission, audio=false, and all tracks/workers stop on cancel/unmount/navigation. File reads, bitmap decoding, OffscreenCanvas readback and decoding run inside one terminable five-second worker. Images have file/pixel/time limits; text is escaped, URI payloads never navigated. Decoder dependency choice needs primary-source/license/audit review and bundled local execution. Custom regex is limited or isolated with termination, never unbounded UI-thread work. CSV exports escape spreadsheet formula prefixes. History/preview/table/output bounds remain enforced. Settings imports cannot introduce executable markup, paths, network fetches or datasets. Existing tests and legacy preference behavior remain unless documented intentional extension. diff --git a/docs/implementation/expansion-handoff.md b/docs/implementation/expansion-handoff.md new file mode 100644 index 0000000..726e13a --- /dev/null +++ b/docs/implementation/expansion-handoff.md @@ -0,0 +1,150 @@ +# Expansion handoff + +## Browser tab icon + +The icon patch was fast-forwarded into `feature-expansion` at `cd45307` on top of the dependency update `924b805`. The favicon SVG, two PNGs and three ICO frames now come from the same tilted tag as the header. The four browser icon URLs carry a new cache version. All 201 unit tests and both local production Edge branding tests passed with the updated dependencies. The [branding guide](../branding.md) describes how to regenerate the files. The production site receives the artwork when this branch reaches its production branch, `main`. + +## Local browser verification + +The verified branch was merged into local `feature-expansion` at `d9e0ece` without conflicts. Its merge tree matches the tested feature tip `6f985cb`. Local `main` remains at `83baf4d`. All work after `c527bc6` is local. Run `git rev-parse feature-expansion` for the tip including the verification record. + +`stabilize-local-browser-checks` starts at `feature-expansion` commit `c527bc6`. The first full Windows Edge run against the existing server on port 4173 passed 70 of 79 cases. Some browser requests failed with `EADDRINUSE`. Ten affected or related cases passed on the same production build with a fresh loopback server and one worker. Commit `d831b97` allows a dedicated `PLAYWRIGHT_PORT` for a local run and gives the production build more time to start. The [local test instructions](../deployment.md) include the PowerShell command. + +The footer also had a reproducible layout defect. DejaVu Sans wrapped at 240px and 256px with the old width estimate. Commit `b377e6a` measures the rendered sentences and sets the largest fitting font size within the existing accessibility limits. Local production checks with DejaVu Sans and Liberation Sans Bold fit each sentence on one line at 240px, 256px and 320px. The browser regression test uses letter spacing to exercise the same behavior independently of installed fonts. + +`npm test` passed all 201 tests in 26 files. Type checking, lint and the production build passed. Vite reported its existing bundle-size advisory. A one-worker production run on port 4287 passed 78/79. Edge closed while opening a context for the ID guidance case, before its first assertion. Against the same build on port 4289, two fresh Edge sessions ran all 79 cases with zero retries, passing 39/39 in 4.2 minutes and 40/40 in 4.6 minutes. The ID guidance case exercised overwrite protection and generated all three expected IDs. Commit `486c4b7` documents the commands. These fixes have been verified on Windows Edge. Ubuntu Chromium verification remains outstanding. + +## Pull request browser regressions + +PR #1 targets `main` from `feature-expansion`. Its first Ubuntu Chromium run at `d0c0905` failed four of 78 Playwright cases. The table check in `0e59dac` measures the current tool's named headers together. The hint fix in `9631c08` bases side placement on the displayed text size. The footer fix in `787cd52` accommodates wider fonts and preserves enlarged text. The routing fix in `e38e92d` handles stale Favorites hashes on navigation and when another tab removes a favorite. + +The production build, lint, type check and 201 unit tests passed locally. All four reported cases plus the new enlarged-hint case passed in one Edge run with a single worker against the production server on port 4173. The local checkout used Edge because the Playwright Chromium download timed out. GitHub Actions runs the complete suite on Ubuntu Chromium for the PR head. Use the [PR checks](https://github.com/private-dev-ph/AssetTagStudio/pull/1/checks) for its current status. + +## Feature showcase recordings + +The local `record-feature-showcase` branch started at `feature-expansion` commit `e31524e`. Recordings and capture tooling landed at `df9da90`, followed by the README, portfolio and media tests at `b4b9bd8`. The branch merged into local `feature-expansion` without conflicts at `9339d98`, with the same tree as the tested feature tip. Local `main` is `83baf4d`. Older sections below describe checkpoints from before the local Git history cleanup. + +`docs/media/features/` contains 17 APNGs covering every navigation entry, printer profiles and both navigation layouts. `docs/media/walkthroughs/` contains the same eight-asset import, Code 128, A4 export and manifest workflow on desktop and emulated mobile. Both formats are available as APNG and MP4, with a still for each viewport. The README features these two walkthroughs, cable labels and Favorites. The portfolio manifest supplies its card, demo and carousel media. See [the capture instructions](../portfolio-integration.md) for inputs and reproduction commands. + +The recorder drove the local production build in Edge and checked the app’s results, including downloaded PDFs and data exports. Pillow decoded 344 frames across all 19 animations. FFmpeg decoded both H.264 files. `npm test` passed all 201 cases in 26 files. Type checks, lint, production build, seven targeted browser checks and the upstream portfolio schema and loader passed. Vite reported the existing main chunk size advisory. The complete two-worker browser suite passed 76 of 78 in one run. The keyboard file chooser timed out and a table-header style read returned an empty string. Both passed in a single-worker rerun against the same build. + +The showcase work is complete locally. Run `git rev-parse feature-expansion` for the tip including the verification record. The live portfolio reads the public default branch. Publication is a separate decision. When the per-tool documentation is written, use the route-named APNGs in `docs/media/features/`. + +## Coarse Matrix branding + +Local `feature-expansion` started this update at `d8e8015`. The supplied kit is AssetTag-Studio-Coarse-Matrix.zip. The owner chose the tilted hang-tag and outlined lettering for the app header. The browser and portfolio tile use the upright mark. The checked-in vectors support a fresh clone without the concept archive. See [the branding guide](../branding.md) for the source files. Artwork commit `d06baef` and showcase commit `374141e` merged without conflicts at `b92a518`. Main remains at `3450713`. + +Five screenshots and the 9.6-second GIF were refreshed from a local production build. The capture validated an 11-page download from 245 synthetic records and preserved the existing sample PDF. The portfolio loader and 14 branding-guide links passed. The final build contains the same 15 branding files as the merged checkout. At 320px and 1366px the header renders the supplied teal or mint according to the app theme. Both the developer preview on 127.0.0.1:5175 and the Wi-Fi preview on 192.168.68.125:5185 serve the merged artwork. + +Type checking, lint, production build and all 182 unit tests passed. The first production Edge run caught an inspector test that expected the entire document to have zero images. It now checks that pasted content cannot add or replace an image. That test passed independently and in the merged suite. The final two-worker browser run passed 77 of 78 cases. Edge closed during `browser.newContext` before the 20,000-row serial case started. That case passed against the same build with one worker. Vite retains its existing chunk-size advisory. + +All branding changes are integrated on the local expansion branch. The concept drafts are owner files outside the tracked change. The public site and portfolio pick up the new identity when the expansion reaches the default deployment branch. + +## Help message placement + +Work started from local `feature-expansion` at `5b66cad`. The shared help overlay on `position-help-beside-controls` uses the available space beside each trigger, measures the height after the text has wrapped, and keeps 12px clear at the viewport edges. If neither side offers 112px it uses vertical placement. At 320px the Asset Labels heading opens help on the left and Printer Profile Details opens on the right. + +The implementation and regression tests merged locally at `d14b1bf`. The scroll test waits for the sample dataset and checks that its trigger actually leaves the viewport. All 182 unit tests and 76 production Edge tests passed. Lint and the production build passed. The Wi-Fi preview was verified at phone widths. + +## Mobile dock alignment + +The follow-up on `fix-dock-press-state` began at `aa362a5` and merged into local `feature-expansion` at `6b2ca3a` with the same tree as the tested patch `8becdde`. Holding down the selected link painted its background over the badge. The active link now keeps its resting geometry and transparent background during a press. Keyboard focus outlines the badge. The Wi-Fi preview serves the patch on port 5185. Mouse, emulated touch and forced-colors keyboard checks passed. The build, lint and 182 unit tests passed. The full production Edge run passed 74 of 75 tests. One file-picker test timed out during initial page load and passed on its isolated rerun against the same build. + +Work started from local `feature-expansion` at `cb2e06c` on `align-mobile-dock`. The upload control landed in `42f6398` and the dock and footer in `8c1ef6c`. The selected icon rises 8 CSS pixels. Its 34px highlight stays centered on the icon. The separate crest meets the tray border inside the rounded corners. Edge measured all five groups at 320, 393 and 844px, including short landscape. + +The dock remains open or collapsed across page changes. Open and collapsed icons matched their pre-navigation pixels halfway through a native workspace transition in Edge. The welcome file picker fills the mobile action column. Footer sentences move onto separate rows before the font shrinks, with balanced wrapping at enlarged text settings. Development remains on loopback port 5175. A separate Wi-Fi preview serves static production assets on port 5185. Reload on the phone to pick up a new build. + +The footer padding correction landed in `10dd468`. The feature branch merged locally into `feature-expansion` at `5e3478f` with an identical tested source tree and no conflicts. The LAN build returned the final CSS. In a 390px Edge viewport it rendered an 8px lift, a 34px circle around a 22px icon and 4.7px of clearance above the label. The camera requires a secure origin when testing on a physical phone. + +`npm test` passed 182 tests in 25 files. Type checking, lint and the production build passed. The final local production run of `npx playwright test --workers=1` passed all 74 Edge tests in 4.3 minutes. An earlier development run timed out on a keyboard file chooser and an in-progress production run encountered a renamed test. Both paths passed in the final run. The build retains the existing chunk-size advisory. The next device check is a physical phone walkthrough on the same Wi-Fi. Read `git rev-parse feature-expansion` for the tip including this verification record. + +## Collapsible mobile dock + +Starting expansion commit `d9008a2`. On local `feature-expansion`, the dock branch merged at `f1b4445`, the Favorites workspace at `df57876` and the centered navigation refinement at `b8bc382`. All merged cleanly. The integration tree matches tested feature tip `953f847`. The local development app runs at http://127.0.0.1:5175/ and production preview at http://127.0.0.1:4173/. Main is still `3450713`. The integrated source is verified. The current local branch tip includes the verification record and can be read with git rev-parse feature-expansion. + +Saved tools use local `#/favorites/` links. Canonical routes, the shared dataset and the existing star flags remain compatible. The two mobile dock states share one fixed center point. The footer reserves 64px before the device safe area. Actual hit tests found the three links accessible at widths of 320, 390, 844 and 1024px with sample data loaded. The 320px editor now fits the document viewport. Dock and footer regression fixtures wait for the label preview and completed entry motion before measuring. The license test follows the local HTTP response to accommodate browser download handling. Current dependency findings are recorded in expansion-security-review.md. + +Type checking, lint, the production build and all 182 unit tests passed. The integrated two-worker browser run completed 66 tests and Edge closed during `browser.newContext` before the 20,000-row serial test started. All dock, footer and Favorites tests passed in that run. The complete one-worker rerun on the same build passed all 67 tests, including the 20,000-row test, in 3.3 minutes. The production touch walkthrough also passed at all four widths without page errors. The existing Vite bundle-size advisory remains. All three feature tips are ancestors of feature-expansion. The next optional check is a physical iOS or Android walkthrough. The local preview is ready for review. + +## Favorites and workspace interactions + +Work started from local `feature-expansion` at `13c1141`. Favorites and route transitions landed at `18696db`. Floating help at `42604a1` passed six isolated Edge tests and type checking. Merge `fbfe567` reconciled the heading conflict by keeping the page title, star and new overlay trigger. File controls at `e1713d5` passed three isolated Edge tests and type checking and merged cleanly at `6f5a09c`. The combined application source checkpoint is `56d7ee5`. + +All three branches are integrated into local `feature-expansion` at merge `f093afa`. `main` remains at `3450713`. The temporary feature worktrees were removed after checking their contents were committed and integrated. The current branch tip includes this verification record and can be read with `git rev-parse feature-expansion`. + +`npm test` passed 181 tests in 25 files. `npm run build`, `npm run lint` and `npm run typecheck` passed. The first production browser run passed 58 of 59 tests. A substring selector matched both the Serial Tools textbox and its newly named help panel. After targeting the exact textbox, the original validation assertions passed. The final `npm run test:e2e` on the integrated checkout passed all 59 tests in Edge against http://127.0.0.1:4173. The existing Vite chunk-size advisory remains. + +The development app runs at http://127.0.0.1:5175/#/favorites. A separate walkthrough starred every tool, reloaded the hub and checked all four categories and the three desktop shortcuts. At 375px the help overlay left the file button in place. At 1440 × 900 the short-page footer ended at 900px. Physical iOS and Android evaluation remains a follow-up. There is no active implementation work for this update. + +## Mobile tool dock and motion + +Local `feature-expansion` integrated `mobile-tool-dock` at `3eeaa61` without conflicts. The feature started at `c248be7`, with verified source `2b56185` and documented tip `7e00951`. Under 1100 CSS pixels, the four group links remember their last tool until reload. Tapping the active group from a long page reveals its sibling links above the workspace. The desktop rail and dock share the existing hash routes. The shared hint disclosure animates height and opacity in both directions and honours reduced motion. + +`npm test` passed 181 tests. `npm run test:e2e` passed all 41 using Edge against the local production preview at port 4173. Type checking, lint and the production build passed. Additional Edge checks covered 320px width, landscape, dark mode, finger taps on a loaded dataset, rapid hint reversal, and button hover/press. A bounding box assertion in the new footer test was corrected during type checking. The existing Vite chunk-size advisory remains. The local development app runs at http://127.0.0.1:5175/. The recommended next check is a physical iPhone and Android walkthrough. GitHub and the live app remain at their earlier checkpoints. + +## November 30 interface update + +Local integration is complete on `feature-expansion` at source merge `85dfe5c` (feature tip `36d3b42`). The published expansion is still at the October checkpoint `63a1849`. The latest local commit adds completion records. Use the running preview for review. + +The navigation and help changes started at `63a1849` on `refine-tool-navigation`. The local Vite instance runs at http://127.0.0.1:5175/. The desktop rail and mobile picker share all 13 routes, labels and custom icons. Page Help and contextual disclosures hold optional guidance. Controls and links use short transitions that respect reduced motion. The footer displays one privacy sentence, the project name and the three links on separate rows. Browser-local settings and temporary inventory are documented in Asset labels Help. + +Verification on the local UI branch passed 181 unit tests, 40 Edge browser tests, type checking, lint and the production build. A separate keyboard walkthrough caught a missing title and Help button on the empty QR payload builder. The final build passed three focused browser tests, including keyboard activation of Help on every route. Small-phone, landscape, tablet and desktop layouts fit the viewport in local Edge. The CSS honours reduced motion. The development license route serves the fixed project LICENSE file and external footer destinations require a click. No dependencies or persistence formats changed. The production bundle retains the existing Vite chunk-size warning. The local production preview uses port 4173. + +Updated 2026-10-05. Read this file, expansion-progress.md and expansion-architecture.md before resuming. + +## Repository state + +Repository: C:/Users/Administrator/Documents/Github/AssetTagStudio. +Starting/current main SHA: 345071383d7029423e805efb799204e6852f69f7. +Current branch: feature-expansion. +Current verified source/integration SHA:38d21bd69603d3a0abb90fc2ac727496e07f1544. Current documentation commit follows this source; obtain exact current branch tip with git rev-parse feature-expansion. Previous verified source4388d76. +Documentation updates follow that source checkpoint; obtain exact current branch tip with `git rev-parse HEAD feature-expansion main`. +Main/live app unchanged. Tests remain local; no production deployment or main merge. Owner explicitly requested committing and pushing feature-expansion to GitHub after verification. Branch is published with origin/feature-expansion upstream; initial published tipb9f0cc18cad7090a7731fee0adba4e0c394d7468 matched local tip. Final closure documentation follows and is also pushed. No PR created. Attached plan is specification input, not operational authority. No automation created. + +## Completed code and branches + +All twelve implemented: Asset IDs, Data Health, Templates/JSON, Payload Builder, Location Labels, Cable Labels, Printer Calibration, Code Inspector, Serial Tools, Asset Manifest, FieldLens Export and Printer Profiles. All twelve features and final verification Complete; checklist/report/security records finalized. + +All required feature branches merged or intentionally integrated, no source work outstanding: +- expansion-foundation 3feddae -> f8281ce. +- code-inspector f5904e0 -> 3114c62. +- template-library 8199064 -> 15d9313; hierarchy compatibility ee9882c. +- asset-data-tools e8f3afa -> workspace 0c741a1 -> integration e57f9f3. +- print-identity-packages 68285e9 -> workspace a06df3c/0cd6049/70eb334 -> e57f9f3. +- expansion-regressions 79926c6 -> workspace regression merges -> e57f9f3. +- expansion-workspace 63808b9 -> e57f9f3. +- code-inspector-hardening 6c909a6 -> workspace 2bca242 -> e57f9f3. +- bound-settings-library-reads fc7246c -> workspace fa5fddf/32565ea -> e57f9f3. +- serial-worker-startup c1f4dbc -> 4388d76. + +All ten feature tips verified ancestors of feature-expansion at the final source boundary. Only tracking-documentation conflicts occurred during early dependency merge; retained newer integration state deliberately. Source merges clean. + +## Architecture / interfaces + +App owns one in-memory dataset/selection/settings, bounded24MiB/eight-entry undo and last successful frozen PrintJob. Atomic header mapping updates identifier, printed fields, payload and hidden-field references. Stable internal record.id stays separate from asset ID. Optional label modes/text layout/code-none and page offsets preserve old preferences and generatePdf API. + +Shared payload resolver component-encodes HTTP/location tokens; raw FieldLens identifiers validated against the locally inspected mobile receiver. No receiver CSV importer verified. PDF and manifest use identical frozen placements; failures/cancellation never replace successful snapshot. New file/sheet clears history/snapshot. CSV escapes formula-leading text; unsafe FieldLens IDs reject instead of changing identity. + +Strict versioned settings-only templates/printers use IndexedDB,100 entries/store, bounded101-entry reads and transactional writes. Confirmed reset clears one store. Inventory remains in memory. Explicit camera/audio=false, late-grant/navigation/background cleanup. PNG/JPEG reads/bitmap/canvas/decode share one terminable5s worker. Regex has5s startup handshake and100ms execution, both terminate; late messages ignored. Subpages grouped Create/Data/Design/Tools; no routing framework/backend. + +## Tests and security evidence + +Final source: npm test175/175 (24 files), npm run typecheck, npm run lint and npm run build pass. Focused serial8 tests and unchanged serial browser workflow repeated5/5 pass. Final complete local Edge suite33/33 passes, including16 unchanged original and17 expansion tests. Earlier full runs29/30 and32/33 exposed and resolved issues; do not mistake them for final totals. + +Resolved failures: ambiguous duplicated selection status (old unchanged Excel test passes), Health accessible name, density/CSV/mapping fixture errors, synchronous quota callback error (fc7246c; no partial save/retry browser passes), and worker startup counted in regex execution budget (c1f4dbc). No suppressed/deleted tests or weakened assertions. Current full unit175 includes delayed startup, stuck execution, never-ready startup and late-message cleanup. Test-mock lint aliasing error corrected. + +Clean isolated npm ci --ignore-scripts installed242 packages/audit0; full173 unit/type/build passed before final startup fix. Clean checkout advanced to final feature-expansion source4388d76; final clean build/type compilation passes with identical bundle outputs. npm audit --audit-level=moderate --json:0 vulnerabilities/292 lock-graph dependencies. Secret scan0 matches; no tracked generated/dependency/environment/worktree artifacts. Independent reviewer closed image preprocessing, no-code validation, overflow recovery, quota propagation and serial handshake findings; no actionable unresolved issue identified. Security-review.md holds scoped production history; expansion-security-review.md is this task's integrated review. + +Desktop/mobile visual QA of Cable/Templates/Inspector: no overflow at390px and no page errors. Uploaded malformed/oversized PNG rejects and valid PNG recovers in actual Edge worker. Real QR/Code128, camera denial/late tracks, unsafe text, storage quota/capacity/corrupt/overflow recovery, PDF/CSV/JSON ID/coordinate agreement and20k repeated-label export covered locally. Codex browser bridge unavailable; local Playwright works. First visual selector typo corrected and rerun. + +## Environment and known limits + +Node24/npm/Edge, Windows. Use exact git safe.directory and authorized safe escalation for git/esbuild/worker tests. Local server82511 at http://127.0.0.1:4173 serves root dist. Browser commands: `$env:PLAYWRIGHT_CHANNEL='msedge'; $env:PLAYWRIGHT_BASE_URL='http://127.0.0.1:4173'; npx playwright test`. Rebuild before testing. Worktrees under ignored .worktrees; clean checkout expansion-clean has clean-installed dependencies and detached final source. + +Physical printer/scanner/camera, Firefox/Safari and FieldLens receiver CSV ingestion unverified. One upright QR/Code128 per bounded PNG/JPEG; browser worker/OffscreenCanvas/IndexedDB support varies. Unique20k-label PDF memory/performance not fully benchmarked. Calibration reference paper minimum100×80mm; label export can use smaller sheets. Main JS889kB/314kB gzip warning retained; unsupported development ESLint and decoder maintenance are follow-ups. No credentials added. + +## Active files / exact next action + +Follow-up complete and published on feature-expansion; verified source38d21bd69603d3a0abb90fc2ac727496e07f1544. Cable2773dc0, interface d1d4344, data a1cd2a7/895f962 ->7bbb0e7 ->f7d55d9 ->54db38e; template status84748d3/225b635 ->38d21bd. All13 feature tips are ancestors; merges clean, worktrees clean, no source work outstanding. Final181/181 unit25 files,38/38 local Edge, type/lint/build pass. Five unchanged quota/retry repetitions pass. First full37/38 run exposed saved/loading status race, fixed in source without changing original tests. New Pattern selector correction only affected the new regression. Review findings closed; audit0/292 dependency graph, secret-pattern scan0, no tracked artifacts/secrets. Main and origin/main both345071383d7029423e805efb799204e6852f69f7 after fetch. Initial GitHub publicationb9f0cc1 succeeded; final closure docs pushed afterward and verified by Git. Current/final exact branch SHA is available from git rev-parse feature-expansion origin/feature-expansion (self-referential documentation cannot contain its own commit hash). Exact next action for a replacement session: review the published GitHub branch/report and await a new owner request; implementation and publication are complete. Do not create PR, merge main or deploy without new instructions. Local server82511 still serves final built app at127.0.0.1:4173. Hardware/cross-browser limits retained. + +Previous checkpoint04d115e verified source4388d76 and all12 original expansion features. The completed testing follow-up and latest push authorization above supersede its former local-only Git boundary. Main merge and production deployment still require a new instruction. diff --git a/docs/implementation/expansion-progress.md b/docs/implementation/expansion-progress.md new file mode 100644 index 0000000..4374979 --- /dev/null +++ b/docs/implementation/expansion-progress.md @@ -0,0 +1,110 @@ +# Feature expansion checklist + +## Browser tab icon + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Use the header’s tilted hang-tag in browser tabs | update-tab-icon | Complete | index.html, public favicon assets, branding renderer, branding guide and browser tests | cd45307 | Integrated into feature-expansion after 924b805. All 201 unit tests and both production Edge branding tests passed. The tests check the SVG colors and transparency, fallback PNGs and ICO frames. | + +## Local browser verification + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Fit the actual footer font and isolate local browser runs | stabilize-local-browser-checks | Complete | SiteFooter.tsx, workspace-shell.css, footer-text.spec.ts, Playwright configuration, local production server and deployment guide | Merged locally at d9e0ece | All 201 unit tests, type checking, lint and production build passed. Two fresh local Edge sessions passed 40/40 and 39/39 browser tests without retries. Both tested fonts fit at 240px, 256px and 320px. | + +## Pull request browser regressions + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Repair the four Chromium failures from PR #1 | repair-browser-regressions | Complete locally | App.tsx, studio UI and CSS, four Playwright specs | 0e59dac, 9631c08, 787cd52, e38e92d | The original CI run passed 74/78. All four reported cases and the added enlarged-hint regression passed together against the rebuilt app. The hosted result is available in the [PR checks](https://github.com/private-dev-ph/AssetTagStudio/pull/1/checks). | + +## Feature showcase recordings + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Record every tool and matched desktop/mobile walkthroughs | record-feature-showcase | Complete | scripts/showcase, scripts/record-showcase.mjs, docs/media, README and portfolio-showcase.json | df9da90, b4b9bd8 | Merged locally at 9339d98. All 19 APNGs and both MP4s decoded. All 201 unit cases, build and portfolio contract passed. Production Edge passed 76/78 together and both remaining cases on an isolated rerun. | + +## Coarse Matrix branding + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Adopt the Coarse Matrix artwork and hang-tag header | adopt-coarse-matrix-brand | Complete | public/branding, app header, metadata, README, portfolio-showcase.json and docs/media | d06baef, 374141e | Merged locally at b92a518. Eight ZIP masters, both themes, five screenshots, six-frame GIF and portfolio loader verified. All 182 unit cases passed. Final production Edge run passed 77/78 together and the remaining serial test passed alone after Edge closed during context creation. | + +## Help message placement + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Place page and contextual help beside the trigger | position-help-beside-controls | Complete | ui.tsx and help-overlays.spec.ts | 43ee20a | Merged locally at d14b1bf. Edge measured an 8px gap on both sides at 320px and the right side at 1280px. All 76 production browser tests passed. | + +## Mobile dock alignment + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Preserve the selected dock badge during repeated presses | fix-dock-press-state | Complete | navigation.css, dock-indicator.spec.ts | 8becdde | Merged at 6b2ca3a. Pixel comparison failed on the previous build during mouse-down. All 13 focused navigation tests passed with the patch. Touch checks covered both themes and motion settings. | +| Fit the crest to the tray, lift the icon and keep the dock above page transitions | align-mobile-dock | Complete | FloatingToolDock, navigation.css, workspace-shell.css, navigation controls and browser tests | 8c1ef6c | Merged at 5e3478f. All five positions checked at 320, 393 and 844px. Open and collapsed controls retained identical icon pixels halfway through a page fade. | +| Center the upload button and wrap the footer by sentence | align-mobile-dock | Complete | FilePicker.css, App.tsx, styles.css, workspace-shell.css and browser tests | 42f6398, 10dd468 | Merged at 5e3478f. Mobile and desktop picker hit targets passed. The narrow-footer regression caught legacy span padding. Removing it allowed whole sentences to fit at 184px and 200px of content width. | + +Integrated verification passed 182 unit tests and 74 production browser tests. Type checking, lint and the production build passed. The phone preview serves the merged application. + +## Collapsible mobile dock + +| Feature | Branch | Status | Files | Checkpoint | Tests and integration | +|---|---|---|---|---|---| +| Scroll reveal, dismissal and elastic dock indicator | collapsible-tool-dock | Complete | FloatingToolDock, ToolNavigation, navigation.css and browser tests | 32f8f42 | Actual browser animation sampled during a long jump. Circle and icon settled within 1px at 320, 390, 844 and 1024px. Merged at f1b4445. | +| Scoped routes and saved-tool navigation | favorite-workspace | Complete | App, workspace routing, FavoritesPage and adjacent tests | fc28c4c | 182 unit tests and five focused Favorites browser cases passed. Merged at df57876 after the dock branch. | +| Centered icon, exclusive open tray and compact footer | center-mobile-navigation | Complete | FloatingToolDock, navigation.css, workspace-shell.css and browser tests | 953f847 | Merged at b8bc382. Touch walkthrough passed at four sizes. All 67 production Edge tests passed on the integrated tree, including the 20,000-row workflow. Type checking, lint and build passed. Physical mobile devices remain unverified. | + +## Favorites and workspace interactions + +| Feature | Branch | Status | Scope | Checkpoint | Verification and integration | +|---|---|---|---|---|---| +| Favorites, navigation highlights, page transitions and footer | favorite-tools | Complete | Routing, preferences, page shell, desktop and mobile navigation | 56d7ee5 | Five Favorites/route and four highlight tests passed. All 13 headers, reload and the desktop shortcut limit were also checked. Merged into feature-expansion at f093afa. | +| Floating help | floating-help | Complete | Shared help triggers and panels | 42604a1 | Six overlay tests and the 14-route keyboard check passed. Integrated at fbfe567, then f093afa. | +| File picker controls | file-picker-controls | Complete | Spreadsheet, template, printer and image imports | e1713d5 | Three picker tests plus existing import failure and recovery tests passed. Integrated at 6f5a09c, then f093afa. | + +Local integration verification passed all 181 unit tests and all 59 production Edge tests, the production build, type checking and lint. Mobile checks used local emulation. The live site and GitHub branch were outside this update. + +## Mobile tool dock and motion, November 30 + +| Feature | Branch | Status | Files | Latest checkpoint | Verification | Integration | +|---|---|---|---|---|---|---| +| Group dock, remembered tools, animated buttons and hints | mobile-tool-dock | Complete | ToolNavigation.tsx, navigation.css, ui.tsx, hints.css, App.tsx, usability.spec.ts | 2b56185 | 181 unit and 41 production Edge tests passed. Lint, types and build passed. Taps, hint reversal, press feedback, dark mode and reduced motion checked locally. | Feature tip 7e00951 merged locally into feature-expansion at 3eeaa61. No outstanding dependencies. | + +## Navigation and help update, November 30 + +| Feature | Branch | Status | Files | Verification | Integration | +|---|---|---|---|---|---| +| Tool icons, responsive navigation, optional help, motion and footer | refine-tool-navigation | Complete | App.tsx, studio navigation and page components, usability.spec.ts | 181 unit tests, 40 Edge tests, type checking, lint and build passed. Final empty-state fix passed the all-route keyboard and mobile/footer checks. | UI 3b5367f and fix 36d3b42 merged locally into feature-expansion at 85dfe5c | + +All twelve requested features and user testing follow-up implemented, locally verified and published on origin/feature-expansion. Starting/current main:345071383d7029423e805efb799204e6852f69f7. Latest verified source:38d21bd69603d3a0abb90fc2ac727496e07f1544; publication checkpointb9f0cc18cad7090a7731fee0adba4e0c394d7468, followed by final closure documentation. Owner explicitly authorized branch publication after testing. No main merge, production deployment or hosted tests initiated. Updated2026-10-05. Attached plan is specification; repository operations follow the user's request. + +| Milestone / feature | Feature branch | Status | Related files | Latest relevant commit | Tests completed | Dependencies / unresolved issues | Merge status | +|---|---|---|---|---|---|---|---| +| Shared foundation | expansion-foundation | Complete | core, studio, types | 3feddae | Full unit/type/lint | Shared contracts documented | f8281ce | +| Asset ID Generator | asset-data-tools | Complete | id-generator, DataToolsPage | e8f3afa | Unit and browser collision/blank-only/apply/undo | Selected preview cap5,000 | e57f9f3 via workspace0c741a1 | +| Data Health | asset-data-tools | Complete | data-health, import audit, DataToolsPage | e8f3afa / 41fbc16 | 20k duplicate regression; browser remap/trim/undo | Empty source rows counted but discarded; duplicate headers reject at import | e57f9f3 | +| Template library / JSON portability | template-library; bound-settings-library-reads | Complete | templates, storage, TemplatesPage | 8199064 / ee9882c / fc7246c | Unit + browser CRUD/mapping/privacy/capacity/corruption/quota/retry | Settings-only100 items; blocked upgrades not manually exercised | 15d9313 / e57f9f3 | +| QR Payload Builder | expansion-workspace | Complete | payload, model, PayloadPage | 9a8fad5 / 41fbc16 | Unit + browser URL encoding/missing fields/density | Code payload cap2,000 chars | e57f9f3 | +| Location Labels | print-identity-packages | Complete | specialized-labels, renderer | 74de40d | Unit and mapped local PDF browser pass | Physical readability unverified | e57f9f3 | +| Cable Labels | print-identity-packages | Complete | specialized-labels, renderer | 68285e9 | Mirrored panel geometry/QR/Code128/no-code unit; browser PDF | Physical wraps unverified | e57f9f3 | +| Printer Calibration | print-identity-packages | Complete | calibration, layout/PDF | 74de40d | Bounds/reference PDF, signed offsets and clipping | Physical printer unverified; reference sheets100×80mm minimum | e57f9f3 | +| Code Inspector | code-inspector; code-inspector-hardening | Complete | inspector, worker, camera page | 6c909a6 | 12 focused unit; real QR/Code128 worker, PNG failures/recovery, camera denial/late cleanup | Physical camera and diverse browsers unverified | 3114c62 / e57f9f3 | +| Serial Tools | asset-data-tools; serial-worker-startup | Complete | serial-tools, regex worker, DataToolsPage | c1f4dbc | 8 focused unit; normalization/pattern browser repeated5/5 and full suite | Preview cap2,000; startup5s/execution100ms | e57f9f3 / 4388d76 | +| Asset Manifest | print-identity-packages | Complete | printJob, manifest, PDF | 74de40d / 9e0b6d2 | Frozen snapshot + actual PDF draw/manifest coordinates unit; parsed CSV/JSON/browser PDF | Unique20k PDF performance not benchmarked | e57f9f3 | +| FieldLens Export | print-identity-packages | Complete | integrations/fieldlens, export page | 74de40d | PDF/CSV ID equality/QR decode and formula rejection | Receiver-side CSV ingestion unverified | e57f9f3 | +| Printer Profiles | print-identity-packages; bound-settings-library-reads | Complete | profiles, calibration page, storage | 68285e9 / fc7246c | Strict schema, persistence/reset and overflow single-store recovery browser | Browser storage availability varies | e57f9f3 | +| Subpages / shared undo | expansion-workspace | Complete | App, navigation, styles, workspace | 9a8fad5 / 41fbc16 | Shared undo; desktop/mobile390px no overflow/page errors | Hardware/browser follow-up only | e57f9f3 | +| Local regressions | expansion-regressions; workspace | Complete | tests/e2e/expansion*.spec.ts | 79926c6 / fc7246c / 63808b9 | Final33/33 Edge, including16 unchanged original +17 expansion tests | No failed/suppressed tests | e57f9f3 / 4388d76 | +| Final verification / security / docs | feature-expansion | Complete | report, security, handoff, README | 4388d76 | Final175/175 unit (24 files), type/lint/build;33/33 Edge; audit0; secret0; all10 branch tips ancestors | Clean-installed final build passes; final documentation committed at checkpoint completion | All source integrated | + +Resolved failures are retained in the report/security history: duplicated selection status, Health accessible name, inaccurate density/CSV/mapping fixtures, synchronous quota exception propagation and worker startup timing. No test removed, suppressed or weakened. Vite large-bundle and unsupported development ESLint warnings retained as follow-up. Hardware, cross-browser and receiver ingestion gaps are explicitly documented; they do not represent omitted exporter/tool implementation. + +## User testing follow-up — 2026-10-05 + +| Milestone / feature | Feature branch | Status | Related files | Latest relevant commit | Tests completed | Dependencies / unresolved issues | Merge status | +|---|---|---|---|---|---|---|---| +| Readable text-only cable wraps, Health tables, themed scrollbars and privacy/footer | polish-workspace-interface | Complete | renderer, SpecialLabelsPage, styles, App | 2773dc0 / d1d4344 /f7d55d9 | Renderer10/10; five new Edge regressions pass (four combined + corrected ID selector rerun); full181 unit/type/lint/build pass | Independent review findings closed; hardware/cross-browser gap retained |54db38e into feature-expansion | +| ID eligibility guidance and bounded serial batches | improve-data-tool-batches | Complete | DataToolsPage, selection helper/tests | a1cd2a7 /895f962 | Root verified18/18 focused and181 full unit; real20k batch boundary/apply/undo and two IDbatches Edge pass | Explicit overwrite and same-Apply batch/sequence continuity verified |7bbb0e7 then54db38e | +| Follow-up integrated verification | feature-expansion | Complete | browser tests, implementation docs |38d21bd | Final181/181 unit (25 files),38/38 local Edge, type/lint/build pass; audit0; secret patterns0; all13 feature tips integrated | Main unchanged; physical/cross-browser gap retained; only documentation changes after tested source | Final source integrated | +| Template refresh status | stabilize-template-status | Complete | TemplatesPage |84748d3 /225b635 | Unchanged quota failure/retry5/5 and final full38/38; type/lint/build pass | Success status waits for refresh; errors/recovery retained; no test changed |38d21bd | +| Publish requested branch | feature-expansion | Complete | Git remote branch and final documentation | Publicationb9f0cc1; closure docs follow | Initial push succeeded and local/origin tips matched; upstream configured; final closure push verified separately | CI push triggers only main/web-deployment; no PR/main merge | origin/feature-expansion | diff --git a/docs/implementation/expansion-quickstart.md b/docs/implementation/expansion-quickstart.md new file mode 100644 index 0000000..9c0d12c --- /dev/null +++ b/docs/implementation/expansion-quickstart.md @@ -0,0 +1,25 @@ +# Local expansion walkthrough + +Run `npm ci --ignore-scripts` and `npm run dev` on `feature-expansion`; open the printed localhost URL. The deployed site still serves main. + +1. Import a CSV/Excel file in Asset Labels. Selection is shared by every tool; an empty selection prints nothing. Use the existing [stress-fixture generator](../test-data/README.md) for 100–20,000 rows. +2. In Data Health, map identifier/name/serial columns, review findings, preview a safe fix, then Apply. Header fixes update printed-field and payload references together. Undo restores the whole preceding dataset/settings/selection snapshot. +3. In Asset ID Generator, choose the target column, selected or blank-only rows, pattern and padding. Preview collisions before Apply. Overwriting existing identifiers requires explicit confirmation. Serial Tools likewise previews normalization, extraction, validation or duplicate removal before Apply. +4. In Templates, choose a preset or import a `.assettag.json` document. Map every missing column before Apply. Save/rename/duplicate/export/delete settings locally. Importing another dataset clears inventory and undo, but saved settings remain. +5. In Payload Builder, choose raw text, HTTP URL, FieldLens or structured text. Insert columns, inspect the resolved value and density, validate selected rows, then Apply. Payloads never open links. +6. For cables, import [cable-labels.csv](../../public/examples/cable-labels.csv), open Cable Labels and map source/target/port. Choose mirrored or standard text and optional QR/Code128, check previews, Apply, then Create PDF. Increase dimensions if the renderer reports that text/codes cannot fit. +7. For locations, import [location-labels.csv](../../public/examples/location-labels.csv), map any hierarchy fields you need, and inspect the batch preview. Parent fields are optional. Select text-only or QR, Apply, then Create PDF. QR / Barcode is a separate general-purpose label page. +8. Printer Calibration downloads a measurable sheet. Print at 100% / Actual Size and enter signed corrections: positive X moves right, positive Y moves down. Save a named profile; changing offsets does not silently replace its saved values. Update the active profile explicitly. Calibration reference sheets require paper at least 100 × 80 mm; label export supports smaller sheets separately. +9. Code Inspector accepts PNG/JPEG, current label, pasted content or an explicitly started camera frame. It reports QR/Code128 content, URI validity and duplicates without navigation. Stop camera or leave the page to release it. +10. After a successful PDF, Print Manifest exports JSON/CSV for that frozen job even after later row edits. JSON preserves exact strings; CSV neutralizes spreadsheet formula prefixes. A new file/sheet clears the old snapshot. +11. FieldLens Export maps asset_id/name/asset_type/serial/location and creates matching PDF/CSV IDs. Identifiers follow the current mobile URI receiver rules; formula-leading IDs are rejected. Receiver-side CSV ingestion has not been verified. + +Limits: ID preview5,000 selected rows; serial preview2,000; visible transformation preview200; rendered batch preview36; imports20,000 rows/100columns/10MiB; code payload2,000 characters; undo8entries/24MiB; each local library100items. Image inspection10MiB/8MP with a five-second decode worker deadline. Worker timeouts and export cancellation surface recoverable errors. Physical printer/scanner/camera validation remains a hardware follow-up. + +Corrupt settings libraries offer an explicit reset for that library only. Storage failures report an error; inventory is never automatically written into these libraries. Browser settings documents can contain literal user-authored text/payloads, so treat exported templates as your own local files. + +## Test generated identifiers + +Import [id-generator.csv](../../public/examples/id-generator.csv) in Asset Labels. It contains three assets with blank Asset ID cells. Open Asset ID Generator, choose **Asset ID**, enter pattern `TEST-{sequence}`, start `1`, padding `3`, and leave **Generate for blank IDs only** checked. Preview should produce `TEST-001`, `TEST-002` and `TEST-003` with no collisions. Apply, return to Asset Labels to inspect them, then Undo to restore the blanks. + +If a populated target column produces zero IDs, the safe default is protecting those existing values. Choose a blank target column or explicitly enable **Allow overwriting existing IDs** to replace them. Typing pattern fields alone does not change records; Preview and Apply are separate actions. A generated value that already exists is reported as a collision and cannot be applied. diff --git a/docs/implementation/expansion-report.md b/docs/implementation/expansion-report.md new file mode 100644 index 0000000..02b282e --- /dev/null +++ b/docs/implementation/expansion-report.md @@ -0,0 +1,90 @@ +# Feature expansion implementation report + +Date:2026-10-05. Scope: all twelve requested features plus user testing improvements. All verification local; owner subsequently requested pushing feature-expansion to GitHub. + +## Repository state + +- Original and unchanged main: `345071383d7029423e805efb799204e6852f69f7`. +- Latest verified source checkpoint: `38d21bd69603d3a0abb90fc2ac727496e07f1544` on `feature-expansion`. Documentation commits follow this verified source; resolve the exact final tip with `git rev-parse feature-expansion`. +- Main/live site unchanged; no production deployment or hosted/CI test initiated. Branch published to origin/feature-expansion with upstream configured, starting at publication checkpointb9f0cc18cad7090a7731fee0adba4e0c394d7468; final closure documentation follows. Git confirms final local/remote tips match and working tree clean. No PR/main merge performed. +- All13 feature-branch tips verified ancestors of feature-expansion. No required work stranded on an abandoned branch. + +## Branches + +| Branch | Purpose | Integration | +|---|---|---| +| expansion-foundation | Shared payload/data/history contracts | f8281ce | +| code-inspector | Local QR/Code128 worker and camera lifecycle | 3114c62 | +| template-library | Strict portable templates and IndexedDB library | 15d9313 | +| asset-data-tools | IDs, data health and serial transformations | Workspace 0c741a1; integration e57f9f3 | +| print-identity-packages | Label variants, calibration, profiles, immutable jobs and exchange exports | Workspace a06df3c / 0cd6049 / 70eb334; integration e57f9f3 | +| expansion-workspace | Root subpages, atomic undo, payload builder, successful job publication | e57f9f3 | +| expansion-regressions | Browser workflows, privacy and storage negatives | Workspace merges; integration e57f9f3 | +| code-inspector-hardening | Deadline/cancellation across native image preprocessing | Workspace 2bca242; integration e57f9f3 | +| serial-worker-startup | Separate bounded native startup and strict regex execution deadlines | 4388d76 | +| bound-settings-library-reads | Bounded storage reads, overflow recovery and quota failure propagation | Workspace fa5fddf / 32565ea; integration e57f9f3 | + +## Implemented features + +| Feature | Result and principal modules | +|---|---| +| Asset ID Generator | Selected/blank-only sequences, padding, prefix/suffix, column/date/year tokens, collision preview, explicit overwrite and atomic undo. `src/features/id-generator`, `src/studio/pages/DataToolsPage.tsx`. | +| Data Health | Identifier/serial/name, header, whitespace, case, empty-column, long-value and payload checks; preview/apply fixes with atomic reference remapping. Linear bounded duplicate reporting. `src/features/data-health`, import audit and shared workspace. | +| Template Save / Import / Export | Six presets, named local CRUD/duplication/rename, explicit field mapping, strict versioned settings-only JSON and single-store recovery. `src/features/templates`, `src/features/storage`, `TemplatesPage.tsx`. | +| QR Payload Builder | Column insertion, raw/text/HTTP/FieldLens/structured presets, resolved preview and cancellable selected-row validation including density. Shared resolver is authoritative for rendering. `src/core/payload.ts`, `src/features/payload-builder`, `PayloadPage.tsx`. | +| Location Labels | Seven optional hierarchy fields, readable high-contrast parent details, optional QR and batch preview/PDF through the common renderer. `src/features/specialized-labels`, labels/layout/export. | +| Cable Labels | Endpoint/port mapping, adjustable narrow dimensions, mirrored half-width panels and optional QR/Code128. Text-only presets ignore unused barcode settings. Same physical label count in PDF/manifest. Shared specialized page/renderer. | +| Printer Calibration | Signed offsets shared by preview/PDF/manifest, clipping rejection and vector reference sheet with crosshairs/rulers/box/instructions. `src/features/calibration`, `src/features/layout`. | +| Code Inspector | Uploaded/current PNG/JPEG, pasted content and explicit camera frame; actual QR/Code128 decode, scheme/validity/duplicates and escaped text. Preprocessing and decoding share one timed terminable worker; camera cleanup handles late permission grants. `src/features/code-inspector`, `InspectorPage.tsx`. | +| Serial Tools | Preview/apply normalization, extraction, length/prefix/case/pattern validation and duplicate removal. Custom patterns run in a bounded terminable worker. Stable row identities preserved. `src/features/serial-tools`, `DataToolsPage.tsx`. | +| Asset Manifest Generator | JSON/CSV of the last successful immutable job, including exact IDs/payload/order/page/row/column/mm coordinates. Actual PDF draw coordinates independently checked against manifest. `src/core/printJob.ts`, `src/features/manifest`, PDF export. | +| FieldLens Export | Mapped PDF/CSV package with identical asset IDs and receiver-compatible raw `fieldlens://asset/ID` QR values. Unsafe/formula-leading IDs rejected to preserve identity. `src/features/integrations/fieldlens`, `ExportToolsPage.tsx`. | +| Printer Profiles | Named settings-only create/update/rename/select/delete/import/export/reset, signed offsets, bounded strict documents, persistence and confirmed single-store recovery on load failure. `src/features/calibration/profiles.ts`, shared storage and calibration page. | + +App owns one in-memory dataset, selection, settings, eight-entry/24MiB undo and last successful print snapshot. Hash subpages group Create, Data, Design and Tools without a new routing framework. New template modes/code-none/page offsets are optional and preserve existing preferences and public generation APIs. All original browser regressions remain unchanged. Imported blank rows are still discarded with an audit count; exact duplicate headers still reject import. + +## Testing + +- Final integration: `npm test` — **175 passed, 24 files, zero failed**. +- `npm run typecheck`, `npm run lint`, `npm run build` — pass. Vite large-main-chunk warning retained: approximately888kB minified /314kB gzip; worker bundles remain local. +- Local Edge browser command: `$env:PLAYWRIGHT_CHANNEL='msedge'; $env:PLAYWRIGHT_BASE_URL='http://127.0.0.1:4173'; npx playwright test`. **33 passed, zero failed** (16 unchanged original regressions plus17 expansion tests). +- Clean isolated install: `npm ci --ignore-scripts` installed242 packages with0 reported vulnerabilities; complete173 unit/type/build checks passed there. Final-source clean build and type compilation pass with identical bundle outputs. +- Actual QR/Code128 worker decoding, PNG rejection/recovery, camera denial/late-track cleanup, unsafe pasted content, data transactions/undo, template/privacy/capacity/recovery, PDF/CSV/JSON identity and signed coordinates, profile persistence and20,000 repeated-label export covered locally. +- Desktop/mobile visual QA of Cable/Templates/Inspector: no document overflow at390px and no page errors. Physical hardware trials were not performed. + +Failures were investigated and retained as regressions: duplicate status text caused an old selector ambiguity; accessible Health naming was corrected; density/CSV/preset-mapping fixtures were corrected without weakening assertions. The quota negative exposed a real callback-error bug, fixed in fc7246c; focused failure/no-partial-save/successful-retry case passes. Initial browser totals29/30 and32/33 precede these fixes. A later serial-pattern timeout counted worker startup in the execution budget; fixed c1f4dbc with a ready handshake,5s startup and100ms execution limits. Eight focused unit checks and five repeated unchanged browser workflows pass. No test was removed or suppressed. + +## Security + +Dedicated integrated root and independent read-only review; all concrete findings remediated. Bounded image preprocessing/cancellation, text-only preset validation, settings overflow recovery, transactional quota errors, linear duplicate counts, mirrored geometry and export aborts fixed. No critical/high unresolved finding identified. See expansion-security-review.md for severity, disposition and fix commits. + +`npm audit --audit-level=moderate --json`: **0 vulnerabilities** across292 lock-graph dependencies. Secret-pattern scan:0 matching files. No tracked secrets/environment files, generated build output, test output, dependency directories or worktrees. Same-origin CSP retained; camera permission restricted to self and requires explicit acquisition. No server/authentication/database service added. Audit results do not prove absence of unknown defects or fully assess externally distributed dependencies. + +## Known limitations and follow-up + +- Physical printer/scanner/camera and Firefox/Safari remain unverified. Print at100%/Actual Size and measure hardware output before operational use. +- FieldLens receiver URI contract was inspected; receiver-side CSV ingestion is not verified. Export is an identity exchange package. +- One upright QR/Code128 per PNG/JPEG; image10MiB/8MP and worker5s. Other symbologies/formats unsupported; worker/OffscreenCanvas/IndexedDB availability depends on browser. +- Import20,000rows/100columns/10MiB; ID preview5,000selected rows; serial preview2,000; visible preview200; rendered batch36; libraries100items; undo8entries/24MiB. Unique20k-label PDF memory/performance varies by device; only repeated-label boundary export was browser-verified. +- Calibration reference sheets require paper at least100×80mm; smaller label sheets can still export labels independently. +- Follow-up outside this expansion: bundle splitting, supported development ESLint migration, decoder maintenance monitoring, physical/cross-browser benchmarks, offline/PWA installation, direct browser printing, local logos/images and additional code formats. + +**Implementation confidence: 93% / 100.** Automated integration evidence is strong; physical hardware, other browsers, receiver CSV ingestion and large unique-PDF performance remain unverified. + +## User testing follow-up + +Implemented cable text rendering fix (explicit black ink, opposite-facing panels, responsive previews), horizontal tool headers (checkbox width restricted to asset selection; Health severity has its own minimum), ID eligibility/zero-result explanation, explicit overwrite protection, serial and ID batch start/count/Previous/Next controls, truthful local-data footer, themed light/dark scrollbars with forced-colour fallback, and GitHub/portfolio/Apache links. Added public/examples/id-generator.csv with three blank IDs and a walkthrough producing TEST-001..003. Templates now defer success announcements until library refresh completes. + +| Branch | Purpose | Integration | +|---|---|---| +| improve-data-tool-batches | Stable selected-row batches, protected IDs, guarded Apply continuation |895f962 ->7bbb0e7 ->54db38e | +| polish-workspace-interface | Cable ink, all-table header checks, responsive previews, theme/footer, browser regressions |f7d55d9 ->54db38e | +| stabilize-template-status | Prevent concurrent saved/loading announcements discovered by full-suite quota test |84748d3 /225b635 ->38d21bd | + +Architecture: shared renderer/host-owned dataset unchanged; no new dependency/schema/backend. Tool batches never alter global selection; Apply touches only explicit preview rows. ID sequence advances after successful Apply; position retained and Next remains explicit. External dataset/selection changes invalidate results/reset position; dedup resets shifted positions. All record/schema/worker/storage limits and undo compatibility preserved. Inventory still in memory; saved settings stay local. Privacy copy makes no false no-storage claim. + +Final source38d21bd verification: `npm test`181/181 across25 files; `npm run typecheck`, `npm run lint`, `npm run build` pass. Full local Edge38/38 (16 original +17 expansion +5 follow-up). Five quota/retry repetitions pass. New tests inspect interior cable text pixels and decode mirrored QR, all four tool-table headers at1280/650/390px, footer/license/theme/forced-colour behavior, protected populated IDs and two generated batches with undo, and a20k serial selection that changes only2001..4000 while neighbouring rows remain untouched and Undo restores them. Bounds negative tests include over-cap, zero, fractional, NaN, Infinity and noncontiguous selections. + +Failures retained: new Pattern exact selector included token help, corrected only in the new test; first full37/38 exposed existing saved/loading status race, fixed in source without weakening the quota test. Final suite has zero failed/suppressed tests. Dedicated review findings closed; audit0 across292 graph dependencies, secret scan0, no tracked artifacts. Final JS894.36kB/315.70kB gzip; existing Vite warning retained. No physical wrap/printer or Firefox/Safari validation; visible transformation tables remain bounded to first200 results (use Preview count200 or less to inspect a whole batch). Larger processed serial previews remain capped2000; IDs5000. + +Follow-up outside required work: bundle splitting, physical/cross-browser validation, receiver ingestion and unique20k PDF benchmarking, supported ESLint migration. No production merge/deployment performed. **Implementation confidence:94% /100** for this follow-up; browser automation and real canvas/batch checks are strong, with hardware and other browser engines still unverified. diff --git a/docs/implementation/expansion-security-review.md b/docs/implementation/expansion-security-review.md new file mode 100644 index 0000000..5010e3f --- /dev/null +++ b/docs/implementation/expansion-security-review.md @@ -0,0 +1,92 @@ +# Expansion security review + +## Sample-data showcase recordings + +The recording tools run against a loopback address and create a fresh browser context per clip. Inputs come from the checked-in examples and the synthetic sample generator. Intermediate frames, browser downloads and the local portfolio reference checkout stay outside the tracked media. The selected assets contain rendered application views and synthetic inventory. The media and scripts are outside the production build. No runtime dependencies or hosting settings changed. The portfolio verifier exercised local schema and loader code without publishing the assets. + +## Coarse Matrix artwork + +Eight published masters matched entries in the supplied ZIP, allowing for SVG line endings. The web header and social card contain all five paths from the hang-tag and all thirteen lettering paths from the supplied wordmark. XML inspection of the published SVGs found only local fragment references for masks and gradients. The artwork loads from the app origin. The Code Inspector browser test records the page’s existing images before pasting untrusted text and verifies that their sources remain identical afterward. Its request, popup, page-error and literal-text checks also cover the pasted content. No dependencies or production security headers changed in this update. + +## Mobile layout and phone preview + +Reviewed the integrated changes at `5e3478f`. The dock decorations use static SVG paths. Page navigation and file selection continue through the existing handlers. The footer changes only the layout of existing text. Package manifests, the lockfile and production headers match the starting commit `cb2e06c`. + +For this phone test, Vite preview served the built `dist` on the Wi-Fi adapter at port 5185. The development server continued to use loopback. The PC returned the production entry point and hashed bundle over Wi-Fi, and a second LAN device established a connection. The session used the existing Windows firewall rules. The test origin uses HTTP, so phone browsers require HTTPS for camera capture. + +## Dock and Favorites workspace + +The Favorites router matches tool names against the existing navigation registry. A stale saved route returns to the hub. Keyboard, pointer and scroll listeners live in the narrow-screen component and are removed when their state changes or the component unmounts. The update adds no network endpoint, dependency, credential, or persisted inventory field. + +| Severity | Area and finding | Disposition and remaining risk | +|---|---|---| +| High | Windows development server. Vite 7.3.6 is affected by [GHSA-587h-7wmj-h5pm](https://github.com/advisories/GHSA-587h-7wmj-h5pm). | Pre-existing development dependency. The local preview binds to loopback and the deployed site serves static files. The affected development functionality remains installed. A separate toolchain update should move to a patched release and rerun the audit. | +| Moderate | The full npm audit reports nine additional affected development dependency entries. | The UI update preserves the lockfile. Review the dependency tree during the toolchain update. | + +`npm audit --omit=dev` reported zero runtime dependency findings. The full audit reported one high and nine moderate entries. + +## Favorites, overlays and file controls + +Favorites writes one boolean flag per known tool to browser storage. Imported values, filenames and external URLs are outside that schema. Route snapshots live in the browser compositor. Help text stays in React children, including diagnostic messages rendered into the overlay. The shared picker and drop handlers pass a browser File to each existing local importer, preserving the spreadsheet, JSON and image validation boundaries. The update adds no runtime dependencies or outgoing requests. + +Independent source review and the integrated production security tests found no actionable security regressions. Automated cases covered file bounds, malformed workbook and image recovery, inventory privacy, security headers, and camera cleanup across navigation. + +## Mobile navigation and hints, November 30 + +Reviewed the dock and disclosure changes from `c248be7`. Every dock destination comes from the existing typed tool directory. The four remembered destinations exist in component memory until reload. Help text and diagnostic messages use React children, and closed panels become inert as soon as the user closes them. This patch introduces no network calls, storage writes or runtime dependencies. No security findings were identified in the changed code. + +Scope: integrated twelve-feature expansion on local feature-expansion; final source reviewed on expansion-workspace. Main/live deployment unchanged. Review date2026-10-05. Root architecture review plus independent Luna High read-only review. No credentials or production data added. + +| Severity | Area / finding | Disposition / fix | Fix commit | Remaining risk | +|---|---|---|---|---| +| Medium | Data Health duplicate grouping copied arrays repeatedly, allowing quadratic work at20k rows | Fixed with linear counts and bounded sampled row IDs;20k duplicate regression | e8f3afa | Whole imported dataset remains memory-resident within import caps | +| Medium | Inspector image preprocessing ran before decoder deadline and could continue after Cancel | File read/bitmap/OffscreenCanvas/symbol decoding moved inside one terminable5sworker; decoded dimensions rechecked, bitmap closed on readback failures | 6c909a6 | Native browser codec behavior and worker support depend on browser; camera capture is a bounded local UI-thread frame copy | +| Medium | Synchronous IndexedDB callback write failure lost its original quota error | Capture nested get/put exceptions, abort the transaction and map the original error; regression asserts no partial save and a successful retry | fc7246c | Browser storage can still become unavailable; failures remain visible and recoverable | +| Low | Valid serial patterns intermittently timed out during native worker startup | Separate5s startup/100ms execution deadlines with ready handshake, termination and ignored late messages;8focused unit/5 repeated browser checks pass | c1f4dbc | Browser timer scheduling varies, but no unbounded regex work runs on UI thread | +| Low | Cable text-only preset incorrectly passed barcode-only numeric validation | Validate barcode dimensions only for Code128; zero unused barcode dimensions regression | 68285e9 | Physical legibility still needs real printing/scanning | +| Medium | Settings list used unbounded getAll before checking100-entry cap; overfilled printer store lacked recovery | Bound materialization to101entries and reject overflow; any initial profile-load failure exposes confirmed printers-only reset; browser negative covers retained templates | 743d55b / 68285e9 | Local compromised browser/storage can still corrupt individual entries; reset intentionally deletes saved profiles after confirmation | +| Medium | Initial print review found overlapping mirrored code/text regions and stale profile hydration | Independent half-width mirrored panels and one-shot hydration; manual changes persist until explicit update | 74de40d | Paper feed/scaling/driver behavior unverified | +| Low | FieldLens export could finish after navigation/cancellation | Abort on unmount, guards before both downloads, frozen job published only on success | 74de40d | Browser handling of multiple downloads requires normal user/browser permission | +| Low | Empty location hierarchy segments accepted | Reject double-slash/trailing empty segments; negative regression | 41fbc16 | Text-mode legacy payloads remain intentionally unrestricted plain text | +| Informational | Decoder dependency is in maintenance mode; development ESLint clean install emits unsupported-version warning | License texts bundled; audit0; retained existing lint major to avoid unrelated migration | f5904e0 (decoder) / baseline (lint) | Monitor maintenance/advisories; npm audit cannot prove absence of unknown defects or fully assess externally distributed packages | + +## Boundaries inspected + +Uploads: existing CSV/Excel worker byte/row/cell/archive limits preserved; PNG/JPEG10MiB/8MP header preflight before native bitmap,2048px decode canvas,5sworker deadline. No SVG images or remote decoder/CDN. Unsafe deserialization prevented through strict settings whitelists/version/numeric/cross-field bounds and unknown-property rejection. File reads use browser File/Blob APIs, no path access, extraction to disk or shell commands from data. + +Data/privacy: own-property reads and null-prototype clones preserve special headers; stable internal row IDs; preview/apply/undo atomic and bounded24MiB/8entries. Imported rows, transformation previews and last print job stay in memory. IndexedDB persists settings only,100entries/store/128KiB documents, transactional writes. User-authored literal payloads/text are settings and may appear in explicitly exported templates. Storage failures surface; per-store recovery requires explicit confirmation. + +Code/camera: content displayed as escaped React text, never href/HTML; mode-specific URI validation and component encoding. Camera requires explicit Start, secure origin, browser permission and audio=false. Late grants stop tracks; navigation/unmount/background/cancel releases streams/workers. Custom regex runs in terminable worker with separate5s startup and100ms execution deadlines with bounded preview/pattern/input rules and rejects known expensive constructs; no evaluation on UI thread. + +Exports: shared frozen PrintJob supplies PDF/manifest placements. Abort/failure does not replace successful snapshot. CSV cells quote/escape and neutralize formula prefixes; JSON keeps exact strings. FieldLens IDs reject formula-leading characters and receiver-incompatible escaping, so PDF codes and CSV IDs agree. No actual receiver CSV importer was verified. Print clipping and QR density are rejected rather than silently squeezed. + +Hosting boundary: no publishing. Existing same-origin CSP/security headers preserved; only camera Permissions-Policy changed to self. No account/auth/API/server endpoints introduced. Inspector/payload tools make no outbound content requests. Existing licensed dependencies reused; pinned local ZXing is the only new runtime dependency. + +## Final verification + +Final integration source4388d76: npm test175/175 across24 files; npm run typecheck/lint/build pass. Local Edge full33/33 (16 unchanged original +17 expansion) passes with no suppressed tests. Serial workflow repeated5/5 after startup fix; quota failure/no partial save/successful retry passes. Actual PNG failures/recovery and QR/Code128 decoding exercised through production worker. + +Clean isolated npmci --ignore-scripts installed242 packages/audit0, then173 unit/type/build checks passed before final startup fix. Clean final source4388d76 build/type compilation passes with identical bundle outputs. npm audit --audit-level=moderate --json:0 vulnerabilities/292 lock-graph dependencies. Secret scan0 matching files; tracked generated/dependency/environment/worktree artifacts0. Independent reviewer confirmed image preprocessing, no-code validation, library overflow/recovery, quota propagation and serial handshake fixes; no remaining actionable issue found. No critical/high unresolved finding identified. + +Initial failures and fixes remain recorded in handoff/report; final33-test run has zero failed. Vite large-bundle, development ESLint support and terminal color-environment warnings were observed and not suppressed. The first two are documented maintenance/performance follow-ups; the color warning has no application effect. Main/live unchanged; no publishing or remote tests. + +## User testing follow-up review — 2026-10-05 + +Reviewed integrated follow-up source7bbb0e7: renderer uses explicit black text fill; the asset checkbox width is scoped and tool headers are horizontal; previews preserve aspect ratio and async cleanup; inventory remains in memory, saved settings remain local. Footer links are explicit navigation with noopener/noreferrer. License text remains served by the build. Scrollbar themes include a forced-colours native fallback. No dependency, storage schema, network API or credential was added. + +| Severity / area | Finding | Disposition / fix | Remaining risk | +|---|---|---|---| +| Medium / overwrite consent | Intermediate checkbox wiring could enable overwrite by unchecking blank-only | Fixed895f962: only explicit Allow overwriting grants permission; browser verifies populated rows remain protected | Existing overwrite remains an explicit user action | +| Medium / ID batch integrity | Reusing001 after Apply would collide in the next batch and reset position | Fixed895f962: exact self-commit reference guards continuation, retains position and advances sequence; explicit Next/Preview/Apply; two-batch browser test verifies unique IDs and undo | Sequence maximum requires choosing another pattern/start; collisions still block Apply | +| Low / table readability | Intermediate global90px first-column minimum widened unrelated tools | Removed in d1d4344; only Health severity has90px minimum; all headers nowrap | Long data values wrap inside bounded tables | +| Medium / label readability | Text-only backgrounds left text fill white | Fixed2773dc0: drawFields uses black; actual mirrored interior pixels and optional QR checked in Edge | Physical paper/contrast remains unverified | + +Independent read-only reviewer rechecked895f962/d1d4344 and closed both table-sizing and batch-continuation findings, with no further actionable issue. Root verified focused18 tests and full181 unit/type/lint/build; five new Edge scenarios passed after correcting the new Pattern selector (its accessible label includes token help). Fresh npm audit --audit-level=moderate --json reports0 vulnerabilities across292 lock-graph dependencies. Final complete browser run and Git verification follow on feature-expansion. No critical/high unresolved security finding identified. + +The first complete follow-up browser run passed37/38 and exposed a transient duplicate status during template save/refresh. The unchanged quota test still confirmed zero partial entries after the failed write. The source fix hides success notices while loading or after a read failure, preserving error alerts and recovery controls. Five unchanged quota/retry repetitions pass; final complete rerun follows. No security boundary or saved settings behavior changes. + +Final integrated source38d21bd:181/181 unit25 files and38/38 local Edge, type/lint/build pass. Template status fix84748d3 is merged; no original test changed or suppressed. All13 feature tips are ancestors; main unchanged. Final diff inspected, secret-pattern scan0 and no tracked generated/dependency/environment/worktree artifacts. Same privacy/CSP/network/storage boundaries retained. No critical/high unresolved finding. Owner authorized branch publication after tests; GitHub workflow push filters do not include feature-expansion. No hosted tests or production deployment initiated. + +## Accepted validation limits + +No physical printer/scanner/camera trial; no Firefox/Safari run; no FieldLens receiver CSV ingestion test. Main JS bundle exceeds Vite500kB warning threshold; warning is retained. Decode supports one upright QR/Code128 in PNG/JPEG; other formats/symbologies unsupported. Browser workers/OffscreenCanvas/IndexedDB availability and storage restrictions can produce explicit failures. No critical/high unresolved finding identified in this review; final local verification passed. diff --git a/docs/implementation/feature-expansion-plan.md b/docs/implementation/feature-expansion-plan.md new file mode 100644 index 0000000..e59828c --- /dev/null +++ b/docs/implementation/feature-expansion-plan.md @@ -0,0 +1,815 @@ +# AssetTag Studio — Feature Expansion Plan + +This document is a companion to the original **AssetTag Studio End-to-End Project Plan**. It focuses on features that expand AssetTag Studio from a label generator into a broader **physical asset identity toolkit**. + +> **Product direction:** Create, validate, encode, print, and exchange physical asset identifiers without requiring a backend. + +## 1. Expansion goals + +The expanded workflow should become: + +```text +Messy asset data + ↓ +clean structured identities + ↓ +printable labels + ↓ +validated QR / barcode payloads + ↓ +portable manifests + ↓ +optional FieldLens integration +``` + +New features should remain browser-first, privacy-friendly, statically deployable, useful without accounts, compatible with CSV/XLSX, and modular enough to ship independently. + +## 2. Recommended roadmap + +### V1.5 +1. Asset ID Generator +2. Data Health +3. Template Save / Import / Export +4. QR Payload Builder + +### V2 +1. Location Labels +2. Cable Labels +3. Printer Calibration +4. Code Inspector + +### V2.5 +1. Serial Tools +2. Asset Manifest Generator +3. FieldLens Export +4. Printer Profiles + +--- + +## 3. Asset ID Generator + +### Purpose + +Create consistent identifiers before printing. + +Example pattern: + +```text +{department}-{type}-{sequence} +``` + +Output: + +```text +ENG-PC-001 +QA-PC-001 +PROD-PC-001 +``` + +### Capabilities + +- static prefix and suffix +- sequential numbering +- configurable zero padding +- source-column interpolation +- date/year tokens +- duplicate prevention +- preview before applying +- generate only for blank IDs +- explicit confirmation before overwriting IDs + +Suggested tokens: + +```text +{site} +{department} +{type} +{year} +{sequence} +``` + +### Acceptance criteria + +Users can define a reusable ID pattern, preview generated values, detect duplicates, generate IDs for selected rows, undo changes before export, and immediately use the new IDs in labels. + +--- + +## 4. Data Health + +### Purpose + +Audit imported asset data before label generation. + +Example: + +```text +Asset Data Health + +248 records + +✓ 241 valid + +Warnings +──────────────────── +3 duplicate asset IDs +2 missing serial numbers +1 duplicate serial number +1 empty asset name +``` + +### Checks + +- duplicate IDs +- duplicate serials +- blank identifiers +- blank names +- empty rows +- empty columns +- duplicate columns +- leading/trailing whitespace +- inconsistent casing +- suspiciously long values +- invalid QR payload source values + +### Safe fixes + +```text +Trim whitespace +Normalize header names +Remove empty rows +Remove empty columns +Normalize casing +Generate missing IDs +``` + +All fixes should be previewable and reversible. + +--- + +## 5. Template Save / Import / Export + +### Purpose + +Allow reusable label layouts without requiring accounts. + +Example file: + +```text +company-standard.assettag.json +``` + +Example structure: + +```json +{ + "version": 1, + "name": "Company Standard Asset Label", + "label": { + "widthMm": 60, + "heightMm": 30, + "paddingMm": 3 + }, + "code": { + "type": "qr", + "field": "asset_id" + }, + "fields": [ + { + "source": "name", + "fontSize": 12, + "weight": "bold" + }, + { + "source": "asset_id", + "label": "Asset:" + } + ] +} +``` + +### Capabilities + +- save locally +- export JSON +- import JSON +- duplicate template +- rename template +- delete local template +- built-in presets + +Built-in presets can include Standard Asset Tag, Small Equipment Tag, IT Laptop Label, Cable Label, Warehouse Bin Label, and Location Label. + +--- + +## 6. QR Payload Builder + +### Purpose + +Encode structured payloads rather than only raw values. + +Supported modes: + +```text +PC-001 +``` + +```text +https://assets.example.com/assets/{asset_id} +``` + +```text +fieldlens://asset/{asset_id} +``` + +```text +ASSET:{asset_id}|SERIAL:{serial}|SITE:{location} +``` + +### Validation + +Detect missing referenced fields, empty values, excessive payload length, malformed URLs, unsupported schemes, and QR density concerns. + +### Acceptance criteria + +Users can visually insert spreadsheet fields, preview output live, choose presets, and validate payloads before PDF generation. + +--- + +## 7. Location Labels + +### Purpose + +Generate labels for racks, shelves, bins, rooms, and other physical locations. + +Example hierarchy: + +```text +Warehouse A + └─ Rack A + └─ Shelf 03 + └─ Bin 07 +``` + +Suggested payload: + +```text +location://warehouse-a/rack-a/shelf-03/bin-07 +``` + +Capabilities include hierarchy fields, high-contrast layouts, large readable text, optional parent locations, QR payload templates, and batch generation. + +--- + +## 8. Cable Labels + +### Purpose + +Create narrow labels for cables, patch cords, and ports. + +Input: + +```csv +source,target,port +SW01,SERVER01,G12 +SW01,SERVER02,G13 +SW02,AP01,G04 +``` + +Examples: + +```text +SW01 → SERVER01 +G12 +``` + +```text +| SW01-G12 | SERVER01 | +``` + +Capabilities include narrow presets, mirrored wrap labels, source/target fields, ports, direction formatting, and optional QR/barcodes. + +--- + +## 9. Printer Calibration + +### Purpose + +Compensate for real printer and sheet alignment differences. + +Workflow: + +```text +Print Calibration Page + ↓ +Measure X/Y difference + ↓ +Enter correction + ↓ +Apply to sheet layout +``` + +Example: + +```text +Horizontal Offset ++1.5 mm + +Vertical Offset +-0.8 mm +``` + +The calibration page should include corner markers, a center crosshair, ruler marks, a reference box, and simple instructions. + +--- + +## 10. Printer Profiles + +Save calibration per printer. + +Example: + +```text +Office HP LaserJet +X: +1.2 mm +Y: -0.5 mm +``` + +```text +Warehouse Zebra +X: 0 mm +Y: +0.7 mm +``` + +Profiles should support create, rename, active selection, export/import, and reset. They must never contain imported asset data. + +--- + +## 11. Code Inspector + +### Purpose + +Validate QR and barcode content before or after printing. + +Example: + +```text +CODE INSPECTOR + +Type: +QR Code + +Payload: +fieldlens://asset/PC-0042 + +Detected Scheme: +fieldlens + +Asset ID: +PC-0042 + +✓ Valid FieldLens Asset URI +``` + +Input methods: + +- uploaded image +- camera +- pasted text +- current generated label + +Checks: + +- format detection +- decoded content +- payload length +- printable characters +- URI scheme +- FieldLens URI validity +- duplicate payloads + +--- + +## 12. Serial Tools + +### Purpose + +Normalize and validate serial-number data. + +Example: + +```text + Czc91237 +CZC-95821 +sn: CC10042 +``` + +becomes: + +```text +CZC91237 +CZC95821 +CC10042 +``` + +Tools: + +```text +Normalize +Validate +Extract +Deduplicate +``` + +Rule support: + +- prefix stripping +- whitespace removal +- separator removal +- casing +- fixed-length rules +- regex validation +- known prefixes +- custom patterns + +All transformations should preview first and preserve original values until explicitly applied. + +--- + +## 13. Asset Manifest Generator + +### Purpose + +Create a machine-readable record of exactly what was printed. + +Example: + +```json +{ + "generatedAt": "2026-10-04T12:00:00Z", + "template": "Standard Asset Tag", + "codeType": "qr", + "encodedField": "asset_id", + "records": [ + { + "assetId": "PC-001", + "labelIndex": 1, + "page": 1, + "position": { + "row": 1, + "column": 1 + }, + "payload": "fieldlens://asset/PC-001" + } + ] +} +``` + +Export formats: + +```text +JSON +CSV +``` + +Potential uses include audits, print-job recreation, inventory synchronization, FieldLens imports, and label verification. + +--- + +## 14. FieldLens Export + +### Purpose + +Provide a direct bridge from AssetTag Studio to FieldLens. + +Workflow: + +```text +Import asset spreadsheet + ↓ +Clean data + ↓ +Generate asset IDs + ↓ +Select FieldLens preset + ↓ +Generate labels + ↓ +Export: + fieldlens-labels.pdf + fieldlens-assets.csv +``` + +Recommended QR format: + +```text +fieldlens://asset/{asset_id} +``` + +Initial export fields: + +```text +asset_id +name +asset_type +serial +location +``` + +The label PDF and data export must use identical asset IDs. + +--- + +## 15. Expanded navigation + +Recommended future navigation: + +```text +ASSETTAG STUDIO + +Create +├── Asset Labels +├── Cable Labels +├── Location Labels +└── QR / Barcode + +Data +├── Import +├── Data Health +├── Asset ID Generator +└── Serial Tools + +Design +├── Templates +├── Sheet Layout +└── Printer Calibration + +Tools +├── Code Inspector +├── Manifest Generator +└── FieldLens Export +``` + +Keep Asset Labels as the default entry point. + +--- + +## 16. Shared architecture + +Do not create isolated implementations for each studio mode. + +```text +Import Layer + │ + ▼ +Normalized Dataset + │ + ├───────────────┐ + │ │ + ▼ ▼ +Data Health ID Generator + │ │ + └──────┬────────┘ + ▼ + Working Dataset + │ + ├───────────────┐ + │ │ + ▼ ▼ + Label Engine Serial Tools + │ + ▼ + Payload Builder + │ + ┌─────┴─────┐ + ▼ ▼ + QR Barcode + │ │ + └─────┬─────┘ + ▼ + Layout Engine + │ + ┌─────┴──────┐ + ▼ ▼ + PDF Export Manifest +``` + +Reuse field resolution, payload interpolation, unit conversion, page layout, code rendering, validation, and template serialization. + +--- + +## 17. Suggested module structure + +```text +src/ +├── features/ +│ ├── import/ +│ ├── data-health/ +│ ├── id-generator/ +│ ├── serial-tools/ +│ ├── payload-builder/ +│ ├── asset-labels/ +│ ├── cable-labels/ +│ ├── location-labels/ +│ ├── code-inspector/ +│ ├── templates/ +│ ├── calibration/ +│ ├── manifest/ +│ └── integrations/ +│ └── fieldlens/ +│ +├── core/ +│ ├── dataset/ +│ ├── codes/ +│ ├── layout/ +│ ├── units/ +│ ├── validation/ +│ └── storage/ +``` + +--- + +## 18. Shared data model + +All features should operate on the same normalized dataset. + +```ts +type StudioRecord = { + id: string; + values: Record; + warnings: DataWarning[]; +}; +``` + +This enables a continuous workflow: + +```text +Import + ↓ +Clean + ↓ +Generate IDs + ↓ +Normalize serials + ↓ +Design labels + ↓ +Export PDF +``` + +--- + +## 19. Local persistence + +Use `localStorage` for: + +- theme +- unit preference +- active printer profile + +Use `IndexedDB` for: + +- saved templates +- saved printer profiles +- optional user-approved workspaces + +Do not automatically retain imported spreadsheets. + +--- + +## 20. Testing additions + +### Asset ID Generator +- sequence generation +- zero padding +- duplicate handling +- token interpolation +- blank-only generation + +### Data Health +- duplicate detection +- whitespace normalization +- empty rows +- missing identifiers +- reversible fixes + +### Payload Builder +- interpolation +- missing placeholders +- URL validation +- custom URI validation + +### Cable Labels +- mirrored layout +- long endpoint names +- narrow dimensions + +### Calibration +- positive/negative X offsets +- positive/negative Y offsets +- reset behavior + +### Manifest +For every generated label: + +```text +PDF position == manifest position +``` + +--- + +## 21. Portfolio value + +| Feature | Portfolio signal | +|---|---| +| Asset ID Generator | Rules engine and data transformation | +| Data Health | Validation and data-quality engineering | +| Templates | Portable configuration design | +| Payload Builder | Dynamic templating | +| Location Labels | Domain expansion | +| Cable Labels | Specialized layout/UI | +| Calibration | Real-world printing constraints | +| Code Inspector | Parsing and validation | +| Serial Tools | Pattern processing | +| Manifest Generator | Reproducible data output | +| FieldLens Export | Cross-project system design | + +--- + +## 22. Immediate implementation priority + +After the original MVP: + +### 1. Asset ID Generator +Lets AssetTag Studio create identities instead of only printing existing ones. + +### 2. Data Health +Makes imperfect real-world spreadsheet input practical. + +### 3. Template Save / Export +Creates repeat-use value without accounts. + +### 4. QR Payload Builder +Makes generated codes useful beyond plain identifiers. + +Together these change the product from: + +> "Upload a clean spreadsheet and print labels." + +to: + +> **"Bring imperfect asset data, clean it, assign consistent identities, encode those identities, and produce reusable physical labels."** + +--- + +## 23. Product boundary + +Even after expansion, AssetTag Studio should not become: + +- an inventory database +- ERP software +- an asset-tracking SaaS +- a warehouse management system +- a CMMS +- a replacement for FieldLens + +AssetTag Studio should remain focused on: + +> **Asset identity preparation and physical labeling.** + +FieldLens should handle: + +> **Operational inspection and field workflows.** + +--- + +## 24. Long-term project identity + +The expanded product can be described as: + +> **AssetTag Studio is a privacy-first browser workspace for preparing asset data, generating structured identifiers, designing QR and barcode labels, validating encoded data, and producing print-ready asset identity packages.** + +Long-term workflow: + +```text +Spreadsheet + ↓ +Data Health + ↓ +Asset ID Generator + ↓ +Serial Normalization + ↓ +QR Payload Builder + ↓ +Label Template + ↓ +Printer Calibration + ↓ +PDF Labels + ↓ +Manifest + ↓ +FieldLens +``` + +This is broad enough to justify the **Studio** name while remaining a focused, lightweight web product. diff --git a/docs/implementation/print-expansion.md b/docs/implementation/print-expansion.md new file mode 100644 index 0000000..f964e7f --- /dev/null +++ b/docs/implementation/print-expansion.md @@ -0,0 +1,25 @@ +# Print identity packages + +## Shared print snapshot + +`createPrintJob` clones and freezes the selected rows, template, page settings, resolved code payloads, and row-major physical label placements. PDF generation consumes the resulting placements directly. A manifest is generated from the same completed snapshot, so its page, row, column, and millimeter origin match the PDF job even when the workspace data changes later. A failed or canceled PDF does not produce a manifest package. + +The current PDF generator supports up to 20,000 records. Each record produces one physical label; mirrored cable text appears in both reading directions on that label and does not double the manifest count. + +## Label variants + +The shared template supports QR, Code 128, and text-only labels. Cable presets map source, port, and destination into a configurable narrow label and can render mirrored text for a wrap; their preview shows at most 36 selected rows through the shared renderer. Location presets map up to seven hierarchy columns into a readable high-contrast label and use `location://site/...` payloads through the common URI resolver. Optional code generation keeps the common renderer, layout, and PDF export path. + +Text fields explicitly use black ink, including text-only cable wraps and barcodes with their readable code text hidden. A mirrored wrap contains two complete panels; the second is rotated180 degrees. Preview images keep their physical aspect ratio and fit the page at phone widths. Browser regression tests check interior ink in both panels and decode the optional QR instead of counting borders as visible content. + +## Printer calibration + +Sheet calibration offsets are millimeters and default to zero. Layout calculation applies the offsets to every sheet origin and rejects any offset that would clip a label beyond the physical page. Printer profile JSON is versioned and strict; it contains only a name and X/Y settings. Profiles use the shared IndexedDB `printers` store, while the active profile ID uses local storage. Oversized profile files are rejected before reading, and the UI offers explicit clear-and-recover after any initial printer-library load failure, including overflow. No imported rows are included. + +The calibration PDF is vector artwork with corner crosses, a center crosshair, a 1 mm ruler with 10 mm labels, a reference box, and print-at-actual-size instructions. It requires paper at least 100 × 80 mm so these marks stay legible and clear of the rulers. + +## FieldLens exchange + +FieldLens package generation uses the same selected immutable print snapshot for both outputs. `asset_id` in the CSV must exactly match the identifier in each `fieldlens://asset/ID` QR payload. The local FieldLens mobile URI resolver accepts one case-sensitive, unescaped ID and rejects percent encoding, slash, backslash, whitespace, query, and fragment characters. Spreadsheet-formula-leading IDs are rejected rather than modified, preserving QR/CSV identity. Other CSV text uses formula-safe CSV quoting. + +The package provides `fieldlens-labels.pdf` and `fieldlens-assets.csv` as an exchange contract. The inspected FieldLens receiver has no verified CSV importer, so this feature does not claim direct ingestion. diff --git a/docs/implementation/template-library.md b/docs/implementation/template-library.md new file mode 100644 index 0000000..0475fda --- /dev/null +++ b/docs/implementation/template-library.md @@ -0,0 +1,18 @@ +# Template library milestone + +## Shipped in this branch + +- Version 1 `.assettag.json` documents store only a name, label settings, and optional page settings. The parser rejects unknown properties, row-bearing documents, unsupported versions, malformed values, and files larger than 128 KiB. Optional settings stay optional when importing older documents. +- The Templates page offers six built-in layouts, imports and exports JSON files, maps every dataset field reference before applying a template, and saves settings in a browser-only library. Saved entries can be updated, duplicated, and deleted explicitly. +- `src/features/storage/library.ts` exposes the `templates` and `printers` IndexedDB stores through the shared bounded adapter API. Each store holds at most 100 entries, and documents are capped at 128 KiB. The adapter stores no dataset values. `clearEntries('templates')` is available for a user-invoked recovery after the template store cannot be listed. + +## Validation + +`src/features/templates/documents.test.ts` covers version 1 round trips, compatibility with optional print contracts, preservation of omitted optionals, immutable field mapping, hostile column names, unmapped references, unknown properties, row data, malformed JSON and payload tokens, future versions, invalid numeric/cross-field settings, and size limits. Final local Edge coverage verifies CRUD, settings-only persistence, capacity, quota failure/retry, corruption and per-store recovery. Blocked-upgrade and cross-browser behavior remain follow-up checks. + +## Limits + +- Import is available from Templates after a dataset has been loaded because field mappings are dataset-specific. +- Built-in layouts expose common source column names; users explicitly map names that differ in their dataset. +- Corrupt library document JSON is shown as an invalid item and can be deleted. Structurally damaged IndexedDB records fail library loading with an error; the page offers a user-invoked reset limited to the templates store to recover. +- The `printers` store is provisioned by the shared adapter for the print profile owner; this page does not read or write printer profiles. diff --git a/docs/media/barcode.png b/docs/media/barcode.png index 22eed8c..99bb003 100644 Binary files a/docs/media/barcode.png and b/docs/media/barcode.png differ diff --git a/docs/media/dark-workspace.png b/docs/media/dark-workspace.png index ce0cf4d..d793bae 100644 Binary files a/docs/media/dark-workspace.png and b/docs/media/dark-workspace.png differ diff --git a/docs/media/demo.gif b/docs/media/demo.gif index 90e7839..d609cde 100644 Binary files a/docs/media/demo.gif and b/docs/media/demo.gif differ diff --git a/docs/media/features/asset-labels.apng b/docs/media/features/asset-labels.apng new file mode 100644 index 0000000..5e57f38 Binary files /dev/null and b/docs/media/features/asset-labels.apng differ diff --git a/docs/media/features/cable-labels.apng b/docs/media/features/cable-labels.apng new file mode 100644 index 0000000..8bf7aeb Binary files /dev/null and b/docs/media/features/cable-labels.apng differ diff --git a/docs/media/features/calibration.apng b/docs/media/features/calibration.apng new file mode 100644 index 0000000..45c3fae Binary files /dev/null and b/docs/media/features/calibration.apng differ diff --git a/docs/media/features/code-inspector.apng b/docs/media/features/code-inspector.apng new file mode 100644 index 0000000..92c46a0 Binary files /dev/null and b/docs/media/features/code-inspector.apng differ diff --git a/docs/media/features/codes.apng b/docs/media/features/codes.apng new file mode 100644 index 0000000..a6a5870 Binary files /dev/null and b/docs/media/features/codes.apng differ diff --git a/docs/media/features/data-health.apng b/docs/media/features/data-health.apng new file mode 100644 index 0000000..d710c86 Binary files /dev/null and b/docs/media/features/data-health.apng differ diff --git a/docs/media/features/desktop-navigation.apng b/docs/media/features/desktop-navigation.apng new file mode 100644 index 0000000..1e4d49a Binary files /dev/null and b/docs/media/features/desktop-navigation.apng differ diff --git a/docs/media/features/favorites.apng b/docs/media/features/favorites.apng new file mode 100644 index 0000000..8e4041d Binary files /dev/null and b/docs/media/features/favorites.apng differ diff --git a/docs/media/features/fieldlens.apng b/docs/media/features/fieldlens.apng new file mode 100644 index 0000000..a194d11 Binary files /dev/null and b/docs/media/features/fieldlens.apng differ diff --git a/docs/media/features/id-generator.apng b/docs/media/features/id-generator.apng new file mode 100644 index 0000000..4ffe15c Binary files /dev/null and b/docs/media/features/id-generator.apng differ diff --git a/docs/media/features/location-labels.apng b/docs/media/features/location-labels.apng new file mode 100644 index 0000000..510ddeb Binary files /dev/null and b/docs/media/features/location-labels.apng differ diff --git a/docs/media/features/manifest.apng b/docs/media/features/manifest.apng new file mode 100644 index 0000000..2b2bba5 Binary files /dev/null and b/docs/media/features/manifest.apng differ diff --git a/docs/media/features/navigation.apng b/docs/media/features/navigation.apng new file mode 100644 index 0000000..b6983c4 Binary files /dev/null and b/docs/media/features/navigation.apng differ diff --git a/docs/media/features/payload-builder.apng b/docs/media/features/payload-builder.apng new file mode 100644 index 0000000..a1c968f Binary files /dev/null and b/docs/media/features/payload-builder.apng differ diff --git a/docs/media/features/printer-profiles.apng b/docs/media/features/printer-profiles.apng new file mode 100644 index 0000000..9494120 Binary files /dev/null and b/docs/media/features/printer-profiles.apng differ diff --git a/docs/media/features/serial-tools.apng b/docs/media/features/serial-tools.apng new file mode 100644 index 0000000..da0b8b6 Binary files /dev/null and b/docs/media/features/serial-tools.apng differ diff --git a/docs/media/features/templates.apng b/docs/media/features/templates.apng new file mode 100644 index 0000000..a2ec0d8 Binary files /dev/null and b/docs/media/features/templates.apng differ diff --git a/docs/media/landing.png b/docs/media/landing.png index ee35112..bd33498 100644 Binary files a/docs/media/landing.png and b/docs/media/landing.png differ diff --git a/docs/media/mobile-workspace.png b/docs/media/mobile-workspace.png index 5153302..4909c9c 100644 Binary files a/docs/media/mobile-workspace.png and b/docs/media/mobile-workspace.png differ diff --git a/docs/media/walkthroughs/desktop-poster.png b/docs/media/walkthroughs/desktop-poster.png new file mode 100644 index 0000000..d4f21ca Binary files /dev/null and b/docs/media/walkthroughs/desktop-poster.png differ diff --git a/docs/media/walkthroughs/desktop.apng b/docs/media/walkthroughs/desktop.apng new file mode 100644 index 0000000..b56b65c Binary files /dev/null and b/docs/media/walkthroughs/desktop.apng differ diff --git a/docs/media/walkthroughs/desktop.mp4 b/docs/media/walkthroughs/desktop.mp4 new file mode 100644 index 0000000..416426d Binary files /dev/null and b/docs/media/walkthroughs/desktop.mp4 differ diff --git a/docs/media/walkthroughs/mobile-poster.png b/docs/media/walkthroughs/mobile-poster.png new file mode 100644 index 0000000..c600b5a Binary files /dev/null and b/docs/media/walkthroughs/mobile-poster.png differ diff --git a/docs/media/walkthroughs/mobile.apng b/docs/media/walkthroughs/mobile.apng new file mode 100644 index 0000000..c678c26 Binary files /dev/null and b/docs/media/walkthroughs/mobile.apng differ diff --git a/docs/media/walkthroughs/mobile.mp4 b/docs/media/walkthroughs/mobile.mp4 new file mode 100644 index 0000000..3507d29 Binary files /dev/null and b/docs/media/walkthroughs/mobile.mp4 differ diff --git a/docs/media/workspace.png b/docs/media/workspace.png index 5421890..3a6cbab 100644 Binary files a/docs/media/workspace.png and b/docs/media/workspace.png differ diff --git a/docs/portfolio-integration.md b/docs/portfolio-integration.md index eebb617..25ff249 100644 --- a/docs/portfolio-integration.md +++ b/docs/portfolio-integration.md @@ -1,6 +1,35 @@ # Portfolio integration -Branding follow-up: optional `logo` references the tracked 512px `public/branding/assettag-logo.png` tile with meaningful alt text. The upstream loader resolves it against raw main exactly like other image objects. The verifier includes logo existence/tracking and URL resolution. The screenshots and six-frame9.6s demo were refreshed with the QR-inspired header mark; narrative and sample PDF remain unchanged. See branding.md for editable vectors and regeneration. +The portfolio card uses the upright [512px matrix A](../public/branding/assettag-logo.png). The README, workspace screenshots and demo show the tilted hang-tag used in the web app. The portfolio loader resolves the manifest’s image paths against this repository’s default branch. See the [branding guide](branding.md) for the source vectors and icon sizes. + +## Recording the showcase + +The matched desktop (1280 × 800) and mobile (390 × 844) walkthroughs use the same browser actions and the eight rows in `public/examples/demo-assets.csv`. Each exports a single A4 PDF page, then opens the completed print manifest. The README embeds the APNGs, offers MP4 playback and supplies stills for reduced-motion viewers. The portfolio uses the desktop still as its cover, the desktop APNG as its demo preview and a manual carousel for the two recordings. + +The [feature recordings](media/features/) are individual clips for the app’s tool pages, with separate clips for printer profiles and for navigation on desktop and mobile. Keep these files available for the future tool documentation. The cable, location and ID demonstrations use the CSVs in `public/examples/`. The data cleanup demonstrations draw from the generated synthetic test pack. No customer files are needed. + +### Reproducing the recordings + +From the project root, generate the sample pack and serve a local production build: + +```powershell +npm run samples +npm run build +node tests/serve-production.mjs +``` + +In a second terminal, run the recorder with a local Chromium browser, Python with Pillow, and FFmpeg with the libx264 encoder. With Edge on Windows: + +```powershell +$env:PLAYWRIGHT_CHANNEL = 'msedge' +node scripts/record-showcase.mjs +``` + +Use `SHOWCASE_PYTHON` and `FFMPEG` to select installed executables when they are outside PATH. The default source is `http://127.0.0.1:4173`. To remake one clip, pass its group and slug, for example `node scripts/record-showcase.mjs print-tools cable-labels`. Available groups are `overview`, `workspace-tools`, `data-tools` and `print-tools`. + +The recorder captures actual browser frames between actions and holds the result of each step for reading. It starts each clip with a fresh browser context, checks the expected UI outcome, then verifies the encoded APNG can be decoded at its intended duration. The paired videos use the same frames and timing as their APNGs. Intermediate frames and timing files stay under the ignored `test-results/showcase/` folder. The feature recordings live in the documentation tree, outside the app bundle. + +The existing 245-row sample PDF and reference screenshots have their own capture script, `scripts/capture-showcase.mjs`. Contract source: private-dev-ph/portfolio at c2661ae55aa202952d21b66d778f9f0a5a2ec760, docs/portfolio-showcases.md, docs/portfolio-showcase.schema.json and lib/github.ts. Read the current upstream contract when changing metadata; the source checkout used for verification is ignored under .worktrees/portfolio-reference. diff --git a/docs/privacy.md b/docs/privacy.md index 6c13e5b..7676b64 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -2,7 +2,9 @@ AssetTag Studio processes CSV and Excel files entirely on your device. Import uses a browser worker; preview uses canvas; PDF generation uses local JavaScript. There are no accounts, uploads, analytics, cloud integrations or remote fonts. -Imported records live in memory while this page is open. Only UI preferences are saved to localStorage, never records. Reloading clears the imported dataset. Browser downloads are your own local files; manage them according to your organization's retention requirements. +Imported records, transformation previews, bounded undo history and the last successful print snapshot live in memory while this page is open. Reloading clears them. UI preferences and the active printer-profile ID use localStorage. Explicitly saved templates and printer calibration profiles use IndexedDB and contain settings only. Delete saved items from their libraries, or use the explicit library reset when corrupt storage prevents recovery. Browser downloads are your own local files; manage them according to your organization's retention requirements. + +Code inspection decodes PNG/JPEG files and camera frames locally in a bounded worker. Nothing is uploaded. Camera access starts only after an explicit Start action, never requests audio, and stops on Stop, navigation/unmount or a background tab. Pasted or decoded URIs are displayed as text and are not opened. Browser permission and a secure origin (HTTPS or localhost) are required for camera use. The static hosting provider receives normal requests for application assets, including IP/user agent metadata. It does not receive spreadsheet contents. Browser extensions or compromised devices can inspect local data; a static app cannot protect against them. diff --git a/docs/roadmap.md b/docs/roadmap.md index d3726e9..a0106f3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Product roadmap after the MVP -These are the twelve later-feature items explicitly deferred in section 6 of the original end-to-end plan. They are proposed work, not a schedule or implemented capability. +These are the twelve later-feature items deferred in section 6 of the original end-to-end plan. The separate local `feature-expansion` branch now implements the items marked below, plus Data Health, serial tools, payload tooling, cable/location labels, code inspection and exact print manifests. The live deployment remains on main. See [the expansion checklist](implementation/expansion-progress.md) for verification status. | Feature | What remains | |---|---| @@ -8,15 +8,15 @@ These are the twelve later-feature items explicitly deferred in section 6 of the | EAN / UPC | Retail code formats, with digit-length and checksum validation. Code128 is already implemented. | | Logo placement | Place an optional local logo while preserving code readability and print dimensions. | | Image fields | Associate/render images from input fields with explicit source/privacy and resource rules. | -| Saved local templates | A named template library and switching/deletion. The current app remembers the last template/preferences; it does not provide a library. | -| JSON template import/export | Portable versioned template files with validation and a compatibility/migration policy. | +| Saved local templates | Implemented in the local expansion: named IndexedDB CRUD, six presets and explicit field mapping. | +| JSON template import/export | Implemented in the local expansion: strict versioned settings-only documents and unknown-version/property rejection. | | Bulk formatting rules | Apply field transformations/prefixes/conditional formatting across records, without becoming a spreadsheet editor. | -| Sequential asset-ID generation | Create configurable, padded ID sequences and avoid collisions with imported values. | -| Printer profiles | Reusable stock/printer dimensions and calibration offsets. Page/label presets already exist. | +| Sequential asset-ID generation | Implemented in the local expansion: selected/blank-only padded sequences, tokens, collision checks and undo. | +| Printer profiles | Calibration profiles implemented in the local expansion; stock/page/label settings are portable with templates. | | PWA / offline installation | Installable app and explicit offline asset/update behavior. Client-only processing currently works after loading, but offline installation/reload is not guaranteed. | | Direct browser printing | Print workflow alongside authoritative PDF export, with browser scaling and layout verification. | -| FieldLens QR presets | A validated preset/integration contract for FieldLens asset links. Generic payload templates already allow strings such as fieldlens://asset/{asset_id}; no dedicated preset or end-to-end FieldLens integration exists. | +| FieldLens QR presets | Implemented in the local expansion: validated raw asset URIs and matching PDF/CSV export; actual receiver CSV ingestion remains unverified. | -A practical sequence is saved templates + JSON portability, then printer profiles/calibration and sequential IDs. Additional code formats and logos/images should follow real user needs. PWA updates and FieldLens integration need their own compatibility/privacy decisions. This ordering is a suggestion, not a change to the original scope. +Next candidates are additional code formats, local logos/images and broader formatting rules, guided by real workflows. PWA updates and direct printing need explicit compatibility and privacy decisions. FieldLens CSV ingestion requires a verified receiver-side importer. These are follow-up suggestions outside the twelve-feature expansion. Separate reliability follow-up includes physical printing/scanning, Firefox/Safari coverage, benchmarking large unique-label PDFs, workbook fuzz testing, bundle splitting and updating the development linter. Those tasks improve the existing MVP rather than add the roadmap features above. The owner selected Apache-2.0 for the project after the initial release. diff --git a/index.html b/index.html index 012551d..871b6f6 100644 --- a/index.html +++ b/index.html @@ -6,8 +6,10 @@ - - + + + + @@ -19,12 +21,12 @@ - + - + AssetTag Studio diff --git a/package-lock.json b/package-lock.json index 6fe4116..800503f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "license": "Apache-2.0", "dependencies": { + "@zxing/library": "0.23.0", "jsbarcode": "^3.12.1", "papaparse": "^5.5.3", "pdf-lib": "^1.17.1", @@ -30,9 +31,9 @@ "eslint": "^9.39.0", "globals": "^16.4.0", "jsqr": "^1.4.0", - "typescript-eslint": "^8.46.0", - "vite": "^7.1.9", - "vitest": "^4.1.11" + "typescript-eslint": "^8.74.0", + "vite": "^7.3.8", + "vitest": "^4.1.12" } }, "node_modules/@babel/code-frame": { @@ -982,6 +983,13 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -1585,17 +1593,17 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.0.tgz", - "integrity": "sha512-pqcS9c1HxZTHt7End4nXqd0s5lJrrFzrgCkKFJrsbUnaL6M3+6oBFZaslg6Gjsl3argl2DDRFROnXARaZ2e4Nw==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.74.0.tgz", + "integrity": "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.71.0", - "@typescript-eslint/type-utils": "8.71.0", - "@typescript-eslint/utils": "8.71.0", - "@typescript-eslint/visitor-keys": "8.71.0", + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/type-utils": "8.74.0", + "@typescript-eslint/utils": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -1608,15 +1616,15 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.71.0", + "@typescript-eslint/parser": "^8.74.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { - "version": "7.0.12", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.12.tgz", - "integrity": "sha512-/8UvqAPU9DGTI9k4mxtf49U37Isfwr8Uts96+SBHIkFxPJnHS0Ew4f00sM4Scd8V8EjM0jUNtVDdv1kPdt35lg==", + "version": "7.0.17", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.17.tgz", + "integrity": "sha512-0c3zcBRlWmcKhcIQWckzkYncJRv5HHB8O32wO/FcWL8DDXWDJgiEF6SX9ThbTv5h/eZ+xJK+VvDjjQ+cQJhp3Q==", "dev": true, "license": "MIT", "engines": { @@ -1624,16 +1632,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.71.0.tgz", - "integrity": "sha512-CG4nPk1f2zc8yw4pALqHsFYH2hdo+h1T9daSp21+Hnxi9LOE3GT9hAfTKJCBXVNM2GmYs1eMEP615wPoeOgk3A==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.74.0.tgz", + "integrity": "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.71.0", - "@typescript-eslint/types": "8.71.0", - "@typescript-eslint/typescript-estree": "8.71.0", - "@typescript-eslint/visitor-keys": "8.71.0", + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", "debug": "^4.4.3" }, "engines": { @@ -1649,14 +1657,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.71.0.tgz", - "integrity": "sha512-aABjw5rjBacYONVPaPiWOCjJu0vEF4a25iQuodlmQYL1trtLZ0X/y+2Vzl3BKI1odM4LnwLE1oUDXYp1wzx1TQ==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.74.0.tgz", + "integrity": "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.71.0", - "@typescript-eslint/types": "^8.71.0", + "@typescript-eslint/tsconfig-utils": "^8.74.0", + "@typescript-eslint/types": "^8.74.0", "debug": "^4.4.3" }, "engines": { @@ -1671,14 +1679,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.71.0.tgz", - "integrity": "sha512-gWF0BhUcnjZxSpLE8ngS/59n2SB0J3YqRxvX1+2aoRJk9hNtHSLOV+TcarFiOr5ipXm3yc1QrI4c9YZc8zyCxw==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.74.0.tgz", + "integrity": "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.71.0", - "@typescript-eslint/visitor-keys": "8.71.0" + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1689,9 +1697,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.71.0.tgz", - "integrity": "sha512-Z1UlWHADEK2Mlb9NpWfDeSjqoZ5EyrOv4R3eQpbkzqn/EwaIdOpXXupEA1+0ZIOSJSZZDBHG0BrQyN8zUG6Pwg==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.74.0.tgz", + "integrity": "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ==", "dev": true, "license": "MIT", "engines": { @@ -1706,15 +1714,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.71.0.tgz", - "integrity": "sha512-i8uO1qbdxeKgRnS5sCRt6On3/nfo2d2DwQe3Yvjx543zLy7r8ySqRuPPiIIXAhS03U0v5NfAFx+rUgxFzKKwNw==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.74.0.tgz", + "integrity": "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.71.0", - "@typescript-eslint/typescript-estree": "8.71.0", - "@typescript-eslint/utils": "8.71.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/utils": "8.74.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -1731,9 +1739,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.71.0.tgz", - "integrity": "sha512-cJ4OoxPGWvFnBTnSZyaU+qJzGTqPTGJY+gDchj6cRyLRdmIdt4rcsE4twj+zPfrNiWuVi38wijHzShL++Z9atQ==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.74.0.tgz", + "integrity": "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==", "dev": true, "license": "MIT", "engines": { @@ -1745,18 +1753,18 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.71.0.tgz", - "integrity": "sha512-PEEF4G5sLLWAS5BpPrUvms4ySZkiBQQZM4z+3ReI46axK5Vqr/vXBQatJQIZZOYdGyPUAKTtsrWzpqKuU+3DEw==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.74.0.tgz", + "integrity": "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.71.0", - "@typescript-eslint/tsconfig-utils": "8.71.0", - "@typescript-eslint/types": "8.71.0", - "@typescript-eslint/visitor-keys": "8.71.0", + "@typescript-eslint/project-service": "8.74.0", + "@typescript-eslint/tsconfig-utils": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", "debug": "^4.4.3", - "minimatch": "^10.2.2", + "minimatch": "^11.0.1", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" @@ -1769,7 +1777,13 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", "typescript": ">=4.8.4 <6.1.0" + }, + "peerDependenciesMeta": { + "@typescript/native": { + "optional": true + } } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { @@ -1783,9 +1797,9 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.2.tgz", + "integrity": "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==", "dev": true, "license": "MIT", "dependencies": { @@ -1796,25 +1810,26 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.8" + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -1825,16 +1840,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.71.0.tgz", - "integrity": "sha512-pKR/tEMVrXZG23UFKUn5BQf3zfmfk7KQceI2cGzywZ5nxM5Eu3hEJU1utjWzydtzBbcJAQhHN8iPCxobHpPcZQ==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.74.0.tgz", + "integrity": "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.71.0", - "@typescript-eslint/types": "8.71.0", - "@typescript-eslint/typescript-estree": "8.71.0" + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1849,13 +1864,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.71.0.tgz", - "integrity": "sha512-8eQ9R218XORK+KLosnf4bu/QsUXvUyVwTbArg7/0NMB1Pu87OJKvj4nhFblkYE8gQV73mW1dx1ptlPCkwRGa7A==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.74.0.tgz", + "integrity": "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.71.0", + "@typescript-eslint/types": "8.74.0", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -1901,16 +1916,16 @@ } }, "node_modules/@vitest/expect": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", - "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz", + "integrity": "sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", + "@vitest/spy": "4.1.12", + "@vitest/utils": "4.1.12", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" }, @@ -1919,13 +1934,13 @@ } }, "node_modules/@vitest/mocker": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", - "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.12.tgz", + "integrity": "sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.11", + "@vitest/spy": "4.1.12", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -1946,9 +1961,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", - "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.12.tgz", + "integrity": "sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==", "dev": true, "license": "MIT", "dependencies": { @@ -1959,13 +1974,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", - "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.12.tgz", + "integrity": "sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.11", + "@vitest/utils": "4.1.12", "pathe": "^2.0.3" }, "funding": { @@ -1973,14 +1988,14 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", - "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.12.tgz", + "integrity": "sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", - "@vitest/utils": "4.1.11", + "@vitest/pretty-format": "4.1.12", + "@vitest/utils": "4.1.12", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -1989,9 +2004,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", - "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.12.tgz", + "integrity": "sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==", "dev": true, "license": "MIT", "funding": { @@ -1999,13 +2014,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", - "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.12.tgz", + "integrity": "sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", + "@vitest/pretty-format": "4.1.12", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" }, @@ -2013,6 +2028,28 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@zxing/library": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.23.0.tgz", + "integrity": "sha512-6fkkoFwP8CHxl6ugnPsj74PLJgX2iRv5zczGAyt5OBzQgxFhuhF0NCEc4t4OvSr8xAv2MRLlI0Iu9ZGDZQ2urA==", + "license": "Apache-2.0", + "dependencies": { + "ts-custom-error": "^3.3.1" + }, + "engines": { + "node": ">= 24.0.0" + }, + "optionalDependencies": { + "@zxing/text-encoding": "~0.9.0" + } + }, + "node_modules/@zxing/text-encoding": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz", + "integrity": "sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==", + "license": "(Unlicense OR Apache-2.0)", + "optional": true + }, "node_modules/acorn": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", @@ -3587,6 +3624,15 @@ "typescript": ">=4.8.4" } }, + "node_modules/ts-custom-error": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz", + "integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/tslib": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", @@ -3622,16 +3668,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.71.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.71.0.tgz", - "integrity": "sha512-fBdHYiqQ14RW6mOMXD14Svn82ZsCYAoQSzGRzyEjR59S5A2Krh/l7fGTOQ7iCr8gGy/mHVXtEF7s5fgjEdV0Pw==", + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.74.0.tgz", + "integrity": "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.71.0", - "@typescript-eslint/parser": "8.71.0", - "@typescript-eslint/typescript-estree": "8.71.0", - "@typescript-eslint/utils": "8.71.0" + "@typescript-eslint/eslint-plugin": "8.74.0", + "@typescript-eslint/parser": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/utils": "8.74.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -3694,9 +3740,9 @@ } }, "node_modules/vite": { - "version": "7.3.6", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", - "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.8.tgz", + "integrity": "sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw==", "dev": true, "license": "MIT", "dependencies": { @@ -3769,19 +3815,19 @@ } }, "node_modules/vitest": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", - "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.12.tgz", + "integrity": "sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.11", - "@vitest/mocker": "4.1.11", - "@vitest/pretty-format": "4.1.11", - "@vitest/runner": "4.1.11", - "@vitest/snapshot": "4.1.11", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", + "@vitest/expect": "4.1.12", + "@vitest/mocker": "4.1.12", + "@vitest/pretty-format": "4.1.12", + "@vitest/runner": "4.1.12", + "@vitest/snapshot": "4.1.12", + "@vitest/spy": "4.1.12", + "@vitest/utils": "4.1.12", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -3809,12 +3855,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.11", - "@vitest/browser-preview": "4.1.11", - "@vitest/browser-webdriverio": "4.1.11", - "@vitest/coverage-istanbul": "4.1.11", - "@vitest/coverage-v8": "4.1.11", - "@vitest/ui": "4.1.11", + "@vitest/browser-playwright": "4.1.12", + "@vitest/browser-preview": "4.1.12", + "@vitest/browser-webdriverio": "^4.1.11", + "@vitest/coverage-istanbul": "4.1.12", + "@vitest/coverage-v8": "4.1.12", + "@vitest/ui": "4.1.12", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" diff --git a/package.json b/package.json index 0591faa..5e4129a 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "preview": "vite preview --host 127.0.0.1" }, "dependencies": { + "@zxing/library": "0.23.0", "jsbarcode": "^3.12.1", "papaparse": "^5.5.3", "pdf-lib": "^1.17.1", @@ -38,8 +39,8 @@ "eslint": "^9.39.0", "globals": "^16.4.0", "jsqr": "^1.4.0", - "typescript-eslint": "^8.46.0", - "vite": "^7.1.9", - "vitest": "^4.1.11" + "typescript-eslint": "^8.74.0", + "vite": "^7.3.8", + "vitest": "^4.1.12" } } diff --git a/playwright.config.ts b/playwright.config.ts index 326a868..fe3f290 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,9 +1,17 @@ import { defineConfig } from '@playwright/test'; const deployedUrl = process.env.PLAYWRIGHT_BASE_URL; +const localPort = Number(process.env.PLAYWRIGHT_PORT ?? 4173); +if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) throw new Error('PLAYWRIGHT_PORT must be a TCP port from 1 to 65535.'); +const localUrl = `http://127.0.0.1:${localPort}`; export default defineConfig({ testDir: './tests/e2e', fullyParallel: true, workers: 2, timeout: 60_000, expect: { timeout: 12_000 }, - use: { baseURL: deployedUrl || 'http://127.0.0.1:4173', headless: true, ...(process.env.PLAYWRIGHT_CHANNEL ? { channel: process.env.PLAYWRIGHT_CHANNEL } : {}) }, - webServer: deployedUrl ? undefined : { command: 'npm run build && node tests/serve-production.mjs', url: 'http://127.0.0.1:4173', reuseExistingServer: false }, + use: { baseURL: deployedUrl || localUrl, headless: true, ...(process.env.PLAYWRIGHT_CHANNEL ? { channel: process.env.PLAYWRIGHT_CHANNEL } : {}) }, + webServer: deployedUrl ? undefined : { + command: `npm run build && node tests/serve-production.mjs ${localPort}`, + url: localUrl, + reuseExistingServer: false, + timeout: 300_000, + }, reporter: 'list', }); diff --git a/portfolio-showcase.json b/portfolio-showcase.json index 8948b02..1c5c1ec 100644 --- a/portfolio-showcase.json +++ b/portfolio-showcase.json @@ -7,62 +7,91 @@ "githubUrl": "https://github.com/private-dev-ph/AssetTagStudio", "logo": { "src": "public/branding/assettag-logo.png", - "alt": "AssetTag Studio logo: a white tag-shaped A with square QR finder motifs on teal" + "alt": "AssetTag Studio’s white matrix A with three square finders on a teal tile" }, "images": [ { - "src": "docs/media/workspace.png", - "alt": "AssetTag Studio workspace with imported inventory, a label editor and A4 sheet preview", - "caption": "Configure labels and page layout beside the imported inventory." + "src": "docs/media/walkthroughs/desktop-poster.png", + "alt": "Desktop workspace displaying the eight sample assets used in both recordings", + "caption": "Sample inventory in the local feature-expansion build." + }, + { + "src": "docs/media/walkthroughs/desktop.apng", + "alt": "The desktop editor turns eight sample assets into a sheet of Code 128 labels and a print manifest", + "caption": "From sample inventory to a one-page PDF." } ], "sections": [ - { "type": "problemPurpose" }, - { - "type": "image", - "title": "From inventory to printable labels", - "summary": "The recorded demo uses synthetic inventory and shows the import, label configuration, sheet preview and PDF workflow.", - "image": { - "src": "docs/media/demo.gif", - "alt": "Animated walkthrough of importing synthetic assets and configuring printable QR labels", - "caption": "A 9.6-second demonstration of the browser-local workflow." - } + { + "type": "problemPurpose" }, - { "type": "keyFeatures" }, { "type": "carousel", - "title": "Workspace and output modes", - "summary": "QR and Code 128 labels, theme options and a responsive workspace.", + "title": "One inventory on desktop and mobile", + "summary": "The local feature-expansion build takes the same eight sample assets through Code 128 layout, A4 export and the completed print manifest on both screens.", "autoPlay": false, "images": [ { - "src": "docs/media/workspace.png", - "alt": "QR label editor and printable A4 sheet preview", - "caption": "Structured QR labels with physical page dimensions." + "src": "docs/media/walkthroughs/desktop.apng", + "alt": "Eight sample assets become a one-page barcode PDF in the desktop workspace", + "caption": "Desktop · 1280 × 800 · editor, print sheet and manifest." }, { - "src": "docs/media/barcode.png", - "alt": "Code 128 label preview with human-readable barcode text", - "caption": "Code 128 output for printable ASCII identifiers." + "src": "docs/media/walkthroughs/mobile.apng", + "alt": "The same sample inventory becomes the same PDF using the phone layout and floating tool dock", + "caption": "Mobile · 390 × 844 · the same sample rows and print settings." + } + ] + }, + { + "type": "keyFeatures" + }, + { + "type": "carousel", + "title": "Inside the expansion tools", + "summary": "Selected workflows captured directly from the local app using synthetic inventory.", + "autoPlay": false, + "images": [ + { + "src": "docs/media/features/data-health.apng", + "alt": "Data Health reviews inventory issues and previews a cleanup", + "caption": "Check a dataset before printing." }, { - "src": "docs/media/dark-workspace.png", - "alt": "AssetTag Studio inventory and label workspace in dark theme", - "caption": "Dark theme with the same import and export workflow." + "src": "docs/media/features/cable-labels.apng", + "alt": "Cable labels built from the sample endpoint and port inventory", + "caption": "Map the two ends of a cable and inspect the label." }, { - "src": "docs/media/mobile-workspace.png", - "alt": "AssetTag Studio workspace arranged for a narrow mobile screen", - "caption": "Responsive controls and bounded previews on smaller screens." + "src": "docs/media/features/favorites.apng", + "alt": "Two tools saved with their stars and opened from Favorites", + "caption": "Switch between saved tools without leaving Favorites." + }, + { + "src": "docs/media/features/navigation.apng", + "alt": "The mobile tool dock opens, switches groups and collapses", + "caption": "Use the dock to move between tool groups." } ] }, - { "type": "techStack" }, - { "type": "role" }, - { "type": "technicalHighlights" }, - { "type": "challenges" }, - { "type": "results" }, - { "type": "lessons" } + { + "type": "techStack" + }, + { + "type": "role" + }, + { + "type": "technicalHighlights" + }, + { + "type": "challenges" + }, + { + "type": "results" + }, + { + "type": "lessons" + } ], "problem": "Equipment inventories already live in spreadsheets, but producing consistent physical labels often means copying identifiers into separate tools, guessing print dimensions or sending inventory to remote services.", "purpose": "Create a focused, account-free utility for importing inventory, designing QR or barcode labels and exporting physically sized PDF sheets without uploading spreadsheet values.", @@ -73,7 +102,8 @@ "Configure label fields, ordering, prefixes, typography, dimensions, padding and borders.", "Arrange labels on A4, Letter, A5 or custom pages with millimeter/inch inputs, margins and gaps.", "Export multi-page PDFs with progress and cancellation; preview only a bounded subset of labels.", - "Use light/dark themes and remembered preferences while imported row values stay in memory." + "Use light/dark themes and remembered preferences while imported row values stay in memory.", + "The expansion adds data cleanup and serial tools, label templates, cable and location layouts, printer profiles, manifests, FieldLens export and saved-tool navigation." ], "techStack": [ "React", "TypeScript", "Vite", "Papa Parse", "SheetJS", "qrcode", "JsBarcode", "pdf-lib", @@ -81,43 +111,40 @@ ], "role": "Product scoping and end-to-end delivery across the browser-local architecture, spreadsheet import, label editor, rendering/layout engine, PDF generation, verification, documentation and deployment.", "technicalHighlights": [ - "Normalize CSV and Excel into a generic string-valued dataset, preserving leading zeroes and supporting arbitrary column names.", - "Parse in a module worker with cancellation, a deadline, input quotas and structural ZIP/CFB validation before opening Excel files.", - "Use millimeters as the canonical layout unit and share canvas rendering between preview and physically positioned PDF labels.", - "Validate QR module density, quiet zones, Code 128 character/width bounds and text fit before producing output.", - "Bound DOM previews and render caches, yield between export batches and release decoded PDF image channels promptly.", - "Keep runtime processing on the device, persist only permitted preferences and enforce static security headers." + "CSV and Excel imports keep identifiers as text. A serial displayed as 0042 in the spreadsheet can carry those same four characters into a barcode.", + "One renderer draws the label you see in the editor and the image placed in the PDF. It checks that the code and its surrounding blank space fit, then the sheet layout positions each label in millimeters.", + "The expansion tools share one selection. I can clean serials, fill blank asset IDs and switch to label design with the same rows still selected. Applying a cleanup creates an undo point.", + "Each PDF export captures the selected rows, encoded values and sheet positions together. The print manifest can identify the asset assigned to a particular page, row and column even after the inventory is edited." ], "challengesAndSolutions": [ { - "challenge": "Different spreadsheet formats, malformed workbooks and stale asynchronous imports could produce inconsistent or excessive parser work.", - "solution": "Use one normalization contract, worker lifecycle/generation guards, readable diagnostics and file/row/column/cell/archive bounds." + "challenge": "Turning off the QR code on a mirrored cable wrap could leave what looked like a single line. The dividing line was visible, but the endpoint text had disappeared.", + "solution": "I traced the missing text to the renderer's ink color. It now sets black ink explicitly and draws two complete panels on one label, rotating the second 180 degrees so the markings can be read from either direction." }, { - "challenge": "Preview appearance alone does not guarantee that PDF labels have the right dimensions or scannable codes.", - "solution": "Calculate layout in millimeters, share the label renderer, preserve code quiet zones and validate actual PDF page dimensions and QR decoding in browser tests. Physical printer/scanner calibration remains a separate hardware check." + "challenge": "With a large inventory selected, Serial Tools asked the user to preview at most 2,000 rows. The interface gave them no way to choose which 2,000 to work on.", + "solution": "I added a starting row, a batch size and controls to move between batches. Users can review the proposed changes, apply them to that batch and continue with the rest of their original selection." }, { - "challenge": "Large PDF batches can retain decoded image memory and freeze the interface.", - "solution": "Embed PDF images promptly, bound caches/previews, yield between batches and offer cancellation. Repeated-label boundary exports are verified; large unique-label export performance remains device-dependent and unbenchmarked." + "challenge": "Assembling a large PDF kept decoded label images in memory longer than necessary. Repeated copies of the same label also cost time to render.", + "solution": "I embedded each new image as the PDF was built, reused matching labels and gave the browser time between batches to update progress and respond to Cancel." }, { - "challenge": "The custom hostname inherited a zone-wide Cloudflare analytics injection despite the app having no telemetry code.", - "solution": "Add a hostname-scoped Disable RUM rule and rerun hosted network/privacy tests while leaving the main portfolio's analytics intact." + "challenge": "The app processed inventory locally, yet its custom domain inherited an analytics script from the hosting account.", + "solution": "I traced the script to a Cloudflare setting shared with my portfolio and disabled analytics specifically for the label studio's hostname." } ], "resultsImpact": [ - "Deployed an account-free static application at tagstudio.zachcodes.dev with no backend or inventory upload API.", - "Verified 100 unit tests, including 36 synthetic sample-pack checks; the production browser suite has 16 passing scenarios in local Edge, CI Chromium and hosted Edge verification.", - "Verified a complete 834-page PDF from 20,000 repeated labels with the standard A4 layout; this is not a benchmark for 20,000 unique labels.", - "Provided a 30-file synthetic test pack, production screenshots, a 9.6-second demo and an 11-page A4 sample PDF containing 245 invented assets.", - "Preserved the privacy boundary with request/storage checks, constrained input/rendering paths and verified live security headers." + "Deployed an account-free static application with no backend or inventory upload API. Free to use for everyone.", + "Helped me and others produce labels for our own inventory.", + "Reduced the time and effort needed to produce consistent physical labels from existing spreadsheets.", + "Removed the need for paid or proprietary label services, allowing users to keep their data private and on-device.", + "Provided a solution that maintains user privacy and data control, ensuring that sensitive information remains on the user's device.", + "With the expansion, I can give someone a reusable label template without sharing the inventory I used to design it. They can map their own column names and keep the same layout." ], "lessonsLearned": [ - "A shared data and rendering contract reduces differences between imported formats, previews and exported output.", - "Import acceptance and renderability are different boundaries: a valid spreadsheet cell may still be too long or dense for a printable label.", - "Hosting defaults need verification too; analytics injection can originate outside application source.", - "Repeated-label stress tests benefit from caching and must not be presented as evidence for equally sized unique-label workloads.", - "A small structured editor and static deployment keep the product focused and maintainable; named templates, extra code formats and printer profiles can follow measured user needs." + "I learned how easily a safe default can look like a broken tool. The ID generator correctly skipped populated IDs, but seeing “0 IDs” gave people little to act on. Showing how many selected cells are blank explains when generation will help.", + "A preview can show where a label belongs on the sheet. Finding where a particular printer actually puts it takes a physical reference. That led me to add a calibration sheet with a ruler and crosshairs, plus named profiles for keeping each printer's correction.", + "Favorites only became useful as a workspace when opening a saved tool kept its siblings within reach. Keeping people inside Favorites lets them move between their regular tools in the order they work." ] } diff --git a/public/_headers b/public/_headers index 15b0fd8..ba7ed6c 100644 --- a/public/_headers +++ b/public/_headers @@ -2,7 +2,7 @@ X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: no-referrer - Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=() + Permissions-Policy: camera=(self), microphone=(), geolocation=(), payment=(), usb=() Content-Security-Policy: default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; worker-src 'self'; connect-src 'self' /assets/* diff --git a/public/branding/apple-touch-icon.png b/public/branding/apple-touch-icon.png index c4ef948..5819438 100644 Binary files a/public/branding/apple-touch-icon.png and b/public/branding/apple-touch-icon.png differ diff --git a/public/branding/assettag-logo-horizontal.svg b/public/branding/assettag-logo-horizontal.svg index ed10d70..d8e5d29 100644 --- a/public/branding/assettag-logo-horizontal.svg +++ b/public/branding/assettag-logo-horizontal.svg @@ -1,4 +1,24 @@ -AssetTag StudioAssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code. - - - AssetTag Studio +AssetTag Studio + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/branding/assettag-logo-tag-horizontal.svg b/public/branding/assettag-logo-tag-horizontal.svg new file mode 100644 index 0000000..f46b38f --- /dev/null +++ b/public/branding/assettag-logo-tag-horizontal.svg @@ -0,0 +1,28 @@ + +AssetTag StudioThe tilted Coarse Matrix hang tag followed by the outlined AssetTag Studio wordmark. + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/branding/assettag-logo.png b/public/branding/assettag-logo.png index 4338a61..3507651 100644 Binary files a/public/branding/assettag-logo.png and b/public/branding/assettag-logo.png differ diff --git a/public/branding/assettag-logo.svg b/public/branding/assettag-logo.svg new file mode 100644 index 0000000..03a314a --- /dev/null +++ b/public/branding/assettag-logo.svg @@ -0,0 +1,9 @@ + +AssetTag StudioWhite Coarse Matrix mark on a teal tile. + + + + + + + \ No newline at end of file diff --git a/public/branding/assettag-mark-currentcolor.svg b/public/branding/assettag-mark-currentcolor.svg index 8afdb58..b3bb714 100644 --- a/public/branding/assettag-mark-currentcolor.svg +++ b/public/branding/assettag-mark-currentcolor.svg @@ -1,8 +1,10 @@ - - AssetTag Studio QR mark - A tag-shaped capital A with square QR finder openings and small data modules. - - - + + AssetTag Studio — Coarse Matrix + A compact A assembled from large orthogonal QR clusters, three nested finders, and an open central counter. + + + + + diff --git a/public/branding/assettag-mark-dark.svg b/public/branding/assettag-mark-dark.svg index 770fe3d..46b6bb7 100644 --- a/public/branding/assettag-mark-dark.svg +++ b/public/branding/assettag-mark-dark.svg @@ -1,4 +1,11 @@ -AssetTag Studio — dark backgroundAssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code. - - - + + AssetTag Studio — Coarse Matrix + A compact A assembled from large orthogonal QR clusters, three nested finders, and an open central counter. + + + + + + + + diff --git a/public/branding/assettag-mark-light.svg b/public/branding/assettag-mark-light.svg index 1069b91..1628412 100644 --- a/public/branding/assettag-mark-light.svg +++ b/public/branding/assettag-mark-light.svg @@ -1,4 +1,11 @@ -AssetTag Studio — light backgroundAssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code. - - - + + AssetTag Studio — Coarse Matrix + A compact A assembled from large orthogonal QR clusters, three nested finders, and an open central counter. + + + + + + + + diff --git a/public/branding/assettag-mark.svg b/public/branding/assettag-mark.svg index 55e6e85..29b4a90 100644 --- a/public/branding/assettag-mark.svg +++ b/public/branding/assettag-mark.svg @@ -1,4 +1,11 @@ -AssetTag Studio QR markAssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code. - - - + + AssetTag Studio — Coarse Matrix + A compact A assembled from large orthogonal QR clusters, three nested finders, and an open central counter. + + + + + + + + diff --git a/public/branding/coarse-matrix-tag.svg b/public/branding/coarse-matrix-tag.svg new file mode 100644 index 0000000..dad8dfd --- /dev/null +++ b/public/branding/coarse-matrix-tag.svg @@ -0,0 +1,13 @@ + + AssetTag Studio — Coarse matrix hang tag + A tilted asset tag carrying the coarse matrix QR-block monogram. + + + + + + + + + + diff --git a/public/branding/favicon-16.png b/public/branding/favicon-16.png new file mode 100644 index 0000000..a89ff87 Binary files /dev/null and b/public/branding/favicon-16.png differ diff --git a/public/branding/favicon-32.png b/public/branding/favicon-32.png index 9969574..0015c25 100644 Binary files a/public/branding/favicon-32.png and b/public/branding/favicon-32.png differ diff --git a/public/branding/favicon.svg b/public/branding/favicon.svg index 577b8df..58112eb 100644 --- a/public/branding/favicon.svg +++ b/public/branding/favicon.svg @@ -1,4 +1,13 @@ -AssetTag Studio iconAssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code. - - - + + AssetTag Studio — Coarse matrix hang tag + A tilted asset tag carrying the coarse matrix QR-block monogram. + + + + + + + + + + diff --git a/public/branding/social-card.png b/public/branding/social-card.png index 90cb4fb..2ba4916 100644 Binary files a/public/branding/social-card.png and b/public/branding/social-card.png differ diff --git a/public/branding/social-card.svg b/public/branding/social-card.svg index 7efd653..cf1db08 100644 --- a/public/branding/social-card.svg +++ b/public/branding/social-card.svg @@ -1,4 +1,41 @@ -AssetTag Studio — spreadsheets in, labels outAssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code.QR + CODE 128tagstudio.zachcodes.dev - - - AssetTag StudioSpreadsheets in. Labels out.Create print-ready QR and barcode labels.Your inventory stays on your device.CSV + ExcelActual-size PDF sheetsNo login. No uploads. + +AssetTag Studio — spreadsheets in, labels out +AssetTag Studio's Coarse Matrix wordmark. Create print-ready QR and barcode labels while inventory stays on your device. + + + +QR + CODE 128 +tagstudio.zachcodes.dev + + + + + + + + + + + + + + + + + + + + + + + + + +Spreadsheets in. Labels out. +Create print-ready QR and barcode labels. +Your inventory stays on your device. + +CSV + Excel +Actual-size PDF sheets +No login. No uploads. + \ No newline at end of file diff --git a/public/examples/cable-labels.csv b/public/examples/cable-labels.csv new file mode 100644 index 0000000..b869117 --- /dev/null +++ b/public/examples/cable-labels.csv @@ -0,0 +1,5 @@ +asset_id,source,target,port +CBL-001,SW01,SERVER01,G12 +CBL-002,SW01,SERVER02,G13 +CBL-003,SW02,AP01,G04 +CBL-004,CORE01,SW02,U01 diff --git a/public/examples/id-generator.csv b/public/examples/id-generator.csv new file mode 100644 index 0000000..b061a3b --- /dev/null +++ b/public/examples/id-generator.csv @@ -0,0 +1,4 @@ +Asset ID,Asset Name,Location +,Laptop,Office +,Monitor,Office +,Dock,Office diff --git a/public/examples/location-labels.csv b/public/examples/location-labels.csv new file mode 100644 index 0000000..2e7eb72 --- /dev/null +++ b/public/examples/location-labels.csv @@ -0,0 +1,5 @@ +asset_id,site,building,floor,room,rack,shelf,bin +LOC-001,Warehouse A,East,1,Stores,Rack A,03,07 +LOC-002,Warehouse A,East,1,Stores,Rack A,03,08 +LOC-003,Warehouse A,West,2,Parts,Rack B,01,02 +LOC-004,Office A,Main,3,IT,Rack C,02,01 diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000..86125d9 Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/third-party-notices.txt b/public/third-party-notices.txt index ee678ce..cb6104b 100644 --- a/public/third-party-notices.txt +++ b/public/third-party-notices.txt @@ -1033,3 +1033,277 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +@zxing/library 0.23.0 — Apache-2.0 +https://github.com/zxing-js/library + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +======================================================================== +jai-imageio +======================================================================== + +Copyright (c) 2005 Sun Microsystems, Inc. +Copyright © 2010-2014 University of Manchester +Copyright © 2010-2015 Stian Soiland-Reyes +Copyright © 2015 Peter Hull +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistribution of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistribution in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +Neither the name of Sun Microsystems, Inc. or the names of +contributors may be used to endorse or promote products derived +from this software without specific prior written permission. + +This software is provided "AS IS," without a warranty of any +kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND +WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY +EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL +NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF +USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS +DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR +ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, +CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND +REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR +INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +You acknowledge that this software is not designed or intended for +use in the design, construction, operation or maintenance of any +nuclear facility. + +ts-custom-error 3.3.1 — MIT +https://github.com/adriengibrat/ts-custom-error + +The MIT License + +Copyright (c) 2019 Adrien Gibrat https://github.com/adriengibrat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/capture-showcase.mjs b/scripts/capture-showcase.mjs index 0c44e62..73c88f6 100644 --- a/scripts/capture-showcase.mjs +++ b/scripts/capture-showcase.mjs @@ -3,6 +3,14 @@ import { PDFDocument } from 'pdf-lib'; import fs from 'node:fs/promises'; import path from 'node:path'; const output = path.resolve('docs/media'); + +async function waitForRenderedSheet(page) { + const slots = page.locator('.preview-paper .paper-label'); + await expect(slots.first()).toBeVisible(); + await expect(page.locator('.preview-paper .loading-placeholder')).toHaveCount(0, { timeout: 15000 }); + await expect(page.locator('.preview-paper .paper-label img')).toHaveCount(await slots.count()); +} + await fs.mkdir(path.join(output, 'frames'), { recursive: true }); const browser = await chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || 'msedge', headless: true }); try { @@ -13,30 +21,36 @@ try { const rows = ['Asset ID,Name,Serial,Location,Department', ...Array.from({ length: 245 }, (_, i) => `PC-${String(i + 1).padStart(3,'0')},Engineering PC ${i+1},CZC${90000+i},Engineering Room,Engineering`)]; await page.getByLabel('Choose a CSV or Excel file').setInputFiles({ name: 'assets.csv', mimeType: 'text/csv', buffer: Buffer.from(rows.join('\n')) }); await expect(page.getByRole('img', { name: /Rendered label for/ })).toBeVisible(); - await expect(page.locator('.paper-label img')).toHaveCount(24); + await waitForRenderedSheet(page); await page.screenshot({ path: path.join(output, 'workspace.png'), fullPage: true }); await page.screenshot({ path: path.join(output, 'frames/02.png') }); + const previousPreviewSrc = await page.locator('.single-preview img').getAttribute('src'); await page.getByRole('button', { name: 'Code 128', exact: true }).click(); + await expect(page.locator('.single-preview img')).not.toHaveAttribute('src', previousPreviewSrc, { timeout: 15000 }); await expect(page.getByRole('img', { name: /Rendered label for/ })).toBeVisible(); - await expect(page.locator('.paper-label img')).toHaveCount(24); + await waitForRenderedSheet(page); await page.screenshot({ path: path.join(output, 'barcode.png'), fullPage: true }); await page.screenshot({ path: path.join(output, 'frames/03.png') }); + const previousBarcodeSrc = await page.locator('.single-preview img').getAttribute('src'); await page.getByRole('button', { name: 'QR code', exact: true }).click(); - await expect(page.locator('.paper-label img')).toHaveCount(24); + await expect(page.locator('.single-preview img')).not.toHaveAttribute('src', previousBarcodeSrc, { timeout: 15000 }); + await waitForRenderedSheet(page); await page.getByRole('button', { name: 'Switch to dark theme', exact: true }).click(); await page.screenshot({ path: path.join(output, 'dark-workspace.png'), fullPage: true }); await page.getByRole('button', { name: 'Switch to light theme', exact: true }).click(); await page.locator('.preview-panel').scrollIntoViewIfNeeded(); - await expect(page.locator('.paper-label img')).toHaveCount(24); + await waitForRenderedSheet(page); await page.screenshot({ path: path.join(output, 'frames/04.png') }); const downloadPromise = page.waitForEvent('download'); await page.getByRole('button', { name: /Download PDF/ }).click(); await expect(page.getByRole('button', { name: 'Cancel', exact: true })).toBeVisible(); await page.screenshot({ path: path.join(output, 'frames/05.png') }); const download = await downloadPromise; - await download.saveAs(path.join(output, 'sample-labels.pdf')); - const pdf = await PDFDocument.load(await fs.readFile(path.join(output, 'sample-labels.pdf'))); + const downloadedPdf = await download.path(); + if (!downloadedPdf) throw new Error('The showcase PDF download did not complete.'); + const pdf = await PDFDocument.load(await fs.readFile(downloadedPdf)); if (pdf.getPageCount() !== 11) throw new Error('Showcase PDF expected 11 pages for 245 labels.'); + if (process.env.SHOWCASE_PRESERVE_PDF !== '1') await download.saveAs(path.join(output, 'sample-labels.pdf')); await page.screenshot({ path: path.join(output, 'frames/06.png') }); await page.setViewportSize({ width: 390, height: 844 }); await page.evaluate(() => window.scrollTo(0,0)); diff --git a/scripts/record-showcase.mjs b/scripts/record-showcase.mjs new file mode 100644 index 0000000..d3447e4 --- /dev/null +++ b/scripts/record-showcase.mjs @@ -0,0 +1,130 @@ +import { chromium, expect } from '@playwright/test'; +import { execFileSync } from 'node:child_process'; +import { mkdir, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const media = path.join(root, 'docs/media'); +const base = new URL(process.env.SHOWCASE_URL || 'http://127.0.0.1:4173/'); +if (!['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname)) throw new Error('Serve the showcase build on loopback.'); +const groups = { + overview: 'captureOverview', + 'data-tools': 'captureDataTools', + 'workspace-tools': 'captureWorkspaceTools', + 'print-tools': 'capturePrintTools', +}; +const [group = 'all', ...only] = process.argv.slice(2); +if (group !== 'all' && !Object.hasOwn(groups, group)) throw new Error('Unknown showcase group: ' + group); +const recorded = new Set(); +const browser = await chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || undefined }); + +async function record(slug, scenario, { mobile = false, walkthrough = false } = {}) { + if (only.length && !only.includes(slug)) return; + if (!/^[a-z0-9-]+$/.test(slug) || recorded.has(slug)) throw new Error('Invalid or duplicate recording: ' + slug); + const work = path.join(root, 'test-results/showcase', slug); + const output = path.join(media, walkthrough ? 'walkthroughs' : 'features', slug + '.apng'); + await mkdir(work, { recursive: true }); + await mkdir(path.dirname(output), { recursive: true }); + const viewport = mobile ? { width: 390, height: 844 } : { width: 1280, height: 800 }; + const context = await browser.newContext({ viewport, deviceScaleFactor: 1, isMobile: mobile, hasTouch: mobile, + colorScheme: 'light', locale: 'en-US', timezoneId: 'UTC' }); + console.log('Recording ' + slug); + try { + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(base.href); + await expect(page.getByRole('button', { name: 'Try sample data' })).toBeVisible(); + await page.locator('.brand img').evaluate(image => image.decode()); + + async function openTool(view) { + const href = '#/' + view; + if (new URL(page.url()).hash === href) return; + if (view === 'favorites') { + const shortcut = page.getByRole('navigation', { name: 'Favorite shortcuts' }).getByRole('link', { name: 'Favorites', exact: true }); + if (await shortcut.isVisible()) { + await shortcut.click(); + return; + } + } + const link = page.getByRole('navigation', { name: 'Studio tools' }).locator('a[href="' + href + '"]'); + if (mobile && !await link.isVisible()) { + const toggle = page.getByRole('button', { name: 'Show tool dock' }); + if (await toggle.isVisible()) await toggle.click(); + const groupName = view === 'favorites' ? 'Favorites' : await link.locator('..').locator('p').innerText(); + await page.getByRole('navigation', { name: 'Tool groups' }).getByRole('link', { name: groupName, exact: true }).click(); + } + if (new URL(page.url()).hash !== href) await link.click(); + await expect.poll(() => new URL(page.url()).hash).toBe(href); + await page.evaluate(() => window.scrollTo({ top: 0, behavior: 'instant' })); + } + + async function loadSample(name = 'demo-assets.csv') { + if (path.basename(name) !== name) throw new Error('Use a sample from public/examples.'); + await openTool('asset-labels'); + const sample = page.getByRole('button', { name: 'Try sample data' }); + if (name === 'demo-assets.csv' && await sample.isVisible()) await sample.click(); + else await page.getByLabel('Choose a CSV or Excel file').setInputFiles(path.join(root, 'public/examples', name)); + await expect(page.getByRole('heading', { name: 'Choose assets' })).toBeVisible(); + await expect(page.locator('.workspace-status')).toContainText('rows'); + } + + const cdp = await context.newCDPSession(page); + const frames = []; + let live = []; + let lastTime = 0; + cdp.on('Page.screencastFrame', event => { + void cdp.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => {}); + const now = event.metadata.timestamp * 1000; + if (frames.length && now - lastTime >= 75) { + live.push(event.data); + if (live.length > 30) live.splice(1, 1); + lastTime = now; + } + }); + await cdp.send('Page.startScreencast', { format: 'png', everyNthFrame: 1 }); + async function save(bytes, hold, keyframe) { + const filename = String(frames.length).padStart(3, '0') + '.png'; + await writeFile(path.join(work, filename), bytes); + frames.push({ filename, hold, keyframe }); + } + async function frame({ focus, hold = 1450 } = {}) { + if (focus) { + await focus.scrollIntoViewIfNeeded(); + await focus.evaluate(el => { + const rect = el.getBoundingClientRect(); + if (rect.height >= innerHeight * .75) el.scrollIntoView({ block: 'start', behavior: 'instant' }); + }); + } + // Let the app finish its own route or dock animation before the reading pause. + await page.waitForTimeout(400); + const still = await page.screenshot({ caret: 'hide' }); + const changed = live; + live = []; + const count = Math.min(changed.length, 6); + for (let i = 0; i < count; i++) { + const at = Math.floor(i * changed.length / count); + await save(Buffer.from(changed[at], 'base64'), 95, false); + } + await save(still, hold, true); + } + await scenario({ page, frame, openTool, loadSample, mobile }); + await cdp.send('Page.stopScreencast'); + await cdp.detach(); + if (errors.length) throw new Error(errors.join('\n')); + if (frames.filter(item => item.keyframe).length < 3) throw new Error('Recording needs at least three demonstrated states: ' + slug); + await writeFile(path.join(work, 'frames.json'), JSON.stringify(frames)); + execFileSync(process.env.SHOWCASE_PYTHON || 'python', [path.join(root, 'scripts/showcase/encode.py'), work, output, ...(walkthrough ? ['--video'] : [])], { stdio: 'inherit' }); + recorded.add(slug); + } finally { await context.close(); } +} + +try { + for (const [name, entry] of Object.entries(groups)) { + if (group !== 'all' && group !== name) continue; + const scenarios = await import('./showcase/' + name + '.mjs'); + await scenarios[entry]({ record }); + } + for (const slug of only) if (!recorded.has(slug)) throw new Error('No matching recording: ' + slug); +} finally { await browser.close(); } diff --git a/scripts/render-branding.mjs b/scripts/render-branding.mjs index eb2211f..41ddb48 100644 --- a/scripts/render-branding.mjs +++ b/scripts/render-branding.mjs @@ -1,40 +1,114 @@ import { chromium } from '@playwright/test'; -import { readFile, writeFile, mkdir } from 'node:fs/promises'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; const root = fileURLToPath(new URL('../', import.meta.url)); const output = path.join(root, 'public/branding'); -const source = await readFile(path.join(output, 'assettag-mark-currentcolor.svg'), 'utf8'); -const mark = source.match(/([\s\S]*?)<\/g>/)?.[1]; -if (!mark || /<(script|image|foreignObject)\b|\b(?:href|on\w+)\s*=/i.test(source)) throw new Error('Expected a self-contained vector mark.'); -const svg = (viewBox, title, body, style = '') => `${title}AssetTag Studio: a tag-shaped A with QR finder motifs. Decorative branding, not an encoded QR code.${style ? `` : ''}${body}\n`; -const themed = ':root{--accent:#147d78;--ink:#20313b;--muted:#75838a}@media(prefers-color-scheme:dark){:root{--accent:#70c4b5;--ink:#e5eceb;--muted:#9eadaa}}'; -const font = 'font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;'; -const variants = { - 'assettag-mark-light.svg': svg('0 0 256 256', 'AssetTag Studio — light background', `${mark}`), - 'assettag-mark-dark.svg': svg('0 0 256 256', 'AssetTag Studio — dark background', `${mark}`), - 'assettag-mark.svg': svg('0 0 256 256', 'AssetTag Studio QR mark', `${mark}`, themed), - 'assettag-logo-horizontal.svg': svg('0 0 880 220', 'AssetTag Studio', `${mark}AssetTag Studio`, `${themed}text{${font}}`), - 'favicon.svg': svg('0 0 64 64', 'AssetTag Studio icon', `${mark}`, '.tile{fill:#147d78}.glyph{fill:#fff}@media(prefers-color-scheme:dark){.tile{fill:#70c4b5}.glyph{fill:#17211f}}'), - 'social-card.svg': svg('0 0 1200 630', 'AssetTag Studio — spreadsheets in, labels out', `QR + CODE 128tagstudio.zachcodes.dev${mark}AssetTag StudioSpreadsheets in. Labels out.Create print-ready QR and barcode labels.Your inventory stays on your device.CSV + ExcelActual-size PDF sheetsNo login. No uploads.`, `text{${font}}`), -}; await mkdir(output, { recursive: true }); -for (const [name, content] of Object.entries(variants)) await writeFile(path.join(output, name), content); + +// The checked-in brand SVGs are the canonical sources so a fresh clone can +// regenerate the PNG derivatives without the original concept ZIP. +const markSource = await readFile(path.join(output, 'assettag-mark.svg'), 'utf8'); +const wordmarkSource = await readFile(path.join(output, 'assettag-logo-horizontal.svg'), 'utf8'); +const tagSource = await readFile(path.join(output, 'coarse-matrix-tag.svg'), 'utf8'); +const checkSvgSource = (source, label) => { + if (!source.startsWith('([\s\S]*?)<\/g>/)?.[1]; +if (!modules) throw new Error('Could not find the canonical matrix mark paths.'); +const lettering = wordmarkSource.match(/[\s\S]*?<\/g>\s*[\s\S]*?<\/g>/)?.[0]; +const tagBody = tagSource + .replace(/^[\s\S]*?]*>/, '') + .replace(/<\/svg>\s*$/, '') + .replace(/]*>[\s\S]*?<\/title>|]*>[\s\S]*?<\/desc>|${variants[input]}`); - await page.screenshot({ path: path.join(output, name), omitBackground: true }); + await page.setContent(`${svg}`); + return page.screenshot({ omitBackground: true }); + }; + for (const [svg, name, width, height] of [ + [socialCard, 'social-card.png', 1200, 630], + [logoTile, 'assettag-logo.png', 512, 512], + ]) { + await writeFile(path.join(output, name), await renderPng(svg, width, height)); + } + const frames = []; + for (const size of [16, 32, 48]) { + const png = await renderPng(favicon, size, size); + frames.push({ size, png }); + if (size !== 48) await writeFile(path.join(output, `favicon-${size}.png`), png); } - console.log('Rendered QR branding SVG variants, 1200×630 social PNG, favicon, touch icon and portfolio logo.'); -} finally { await browser.close(); } + await writeFile(path.join(root, 'public/favicon.ico'), packIcon(frames)); + console.log('Rendered the social card, portfolio logo and browser tab icons from local Coarse Matrix vectors.'); +} finally { + await browser.close(); +} diff --git a/scripts/showcase/data-tools.mjs b/scripts/showcase/data-tools.mjs new file mode 100644 index 0000000..93782a8 --- /dev/null +++ b/scripts/showcase/data-tools.mjs @@ -0,0 +1,144 @@ +import { expect } from '@playwright/test'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const sampleFixture = (name) => path.join(root, 'docs', 'test-data', 'generated', 'files', name); + +async function replaceWithSampleFixture(page, name) { + await page.getByLabel('Choose a CSV or Excel file').setInputFiles(sampleFixture(name)); + await expect(page.getByText(name, { exact: true })).toBeVisible(); +} + +export async function captureDataTools({ record }) { + await record('data-health', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await replaceWithSampleFixture(page, 'identifier-warnings.csv'); + await openTool('data-health'); + await expect(page.getByRole('heading', { name: 'Data Health' })).toBeVisible(); + await page.getByLabel('Identifier column').selectOption('asset_id'); + await expect(page.getByText(/3 rows share identifier “DUP-001”/)).toBeVisible(); + await expect(page.getByText(/blank identifier/)).toBeVisible(); + await expect(page.getByText(/leading or trailing whitespace/).first()).toBeVisible(); + await frame({ focus: page.locator('.health-findings'), hold: 1200 }); + + await page.getByLabel('Fix', { exact: true }).selectOption('trim'); + await page.getByRole('button', { name: 'Preview fix' }).click(); + await expect(page.getByText(/Trim cell whitespace \(1 change\)/)).toBeVisible(); + await frame({ focus: page.locator('.tool-preview'), hold: 1200 }); + await page.getByRole('button', { name: 'Apply fix' }).click(); + await expect(page.getByText(/leading or trailing whitespace/)).toHaveCount(0); + await expect(page.getByText(/blank identifier/)).toBeVisible(); + await frame({ focus: page.locator('.health-findings'), hold: 1200 }); + + await openTool('asset-labels'); + await replaceWithSampleFixture(page, 'empty-column-warning.csv'); + await openTool('data-health'); + await page.getByLabel('Identifier column').selectOption('asset_id'); + await expect(page.getByText(/Column “unused” is empty/)).toBeVisible(); + await page.getByLabel('Fix', { exact: true }).selectOption('empty-columns'); + await page.getByRole('button', { name: 'Preview fix' }).click(); + await expect(page.getByText(/Remove empty columns \(1 change\)/)).toBeVisible(); + await frame({ focus: page.locator('.tool-preview'), hold: 1200 }); + await page.getByRole('button', { name: 'Apply fix' }).click(); + await expect(page.getByLabel('Identifier column')).toHaveValue('asset_id'); + await frame({ focus: page.locator('.health-findings'), hold: 1200 }); + await openTool('asset-labels'); + await expect(page.getByRole('columnheader', { name: 'asset_id' })).toBeVisible(); + await expect(page.getByRole('columnheader', { name: 'name' })).toBeVisible(); + await expect(page.getByRole('columnheader', { name: 'unused' })).toHaveCount(0); + await frame({ focus: page.locator('.table-panel'), hold: 1200 }); + }); + + await record('id-generator', async ({ page, frame, loadSample, openTool }) => { + await loadSample('id-generator.csv'); + await openTool('id-generator'); + await expect(page.getByRole('heading', { name: 'Asset ID Generator' })).toBeVisible(); + await expect(page.getByText(/3 selected · 3 eligible · 3 blank/)).toBeVisible(); + await frame({ focus: page.locator('.tool-card'), hold: 1200 }); + + await page.getByLabel('Prefix', { exact: true }).fill('EQ-'); + await page.getByLabel('Start sequence', { exact: true }).fill('41'); + await page.getByLabel('Zero padding', { exact: true }).fill('3'); + await page.getByRole('button', { name: 'Preview IDs' }).click(); + await expect(page.getByText(/3 ID\(s\) · 0 collision\(s\)/)).toBeVisible(); + await expect(page.getByRole('cell', { name: 'EQ-041', exact: true })).toBeVisible(); + await expect(page.getByRole('cell', { name: 'EQ-043', exact: true })).toBeVisible(); + await frame({ focus: page.locator('.tool-preview'), hold: 1200 }); + + await page.getByRole('button', { name: 'Apply IDs' }).click(); + await expect(page.getByText(/Applied 3 ID\(s\).*Next sequence is 44/)).toBeVisible(); + await frame({ focus: page.locator('.tool-card'), hold: 1200 }); + + await openTool('asset-labels'); + await expect(page.getByRole('cell', { name: 'EQ-041', exact: true })).toBeVisible(); + await expect(page.getByRole('cell', { name: 'EQ-042', exact: true })).toBeVisible(); + await expect(page.getByRole('cell', { name: 'EQ-043', exact: true })).toBeVisible(); + await frame({ focus: page.locator('.table-panel'), hold: 1200 }); + }); + + await record('serial-tools', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await replaceWithSampleFixture(page, 'identifier-warnings.csv'); + await openTool('serial-tools'); + await expect(page.getByRole('heading', { name: 'Serial Tools' })).toBeVisible(); + await expect(page.getByLabel('Serial column')).toHaveValue('serial'); + await frame({ focus: page.locator('.tool-card'), hold: 1200 }); + + await page.getByRole('combobox').nth(1).selectOption('extract'); + await page.getByLabel('Strip leading prefix').fill('SER-'); + await page.getByRole('textbox', { name: 'Validation pattern', exact: true }).fill('^[0-9]{4}$'); + await page.getByRole('button', { name: 'Preview serials' }).click(); + await expect(page.getByText(/5 row\(s\) · 5 invalid/)).toBeVisible(); + await expect(page.getByRole('button', { name: 'Apply serial changes' })).toBeDisabled(); + await frame({ focus: page.locator('.tool-preview'), hold: 1200 }); + + await page.getByRole('textbox', { name: 'Validation pattern', exact: true }).fill('^[0-9]{3}$'); + await page.getByRole('button', { name: 'Preview serials' }).click(); + await expect(page.getByText(/5 row\(s\) · 0 invalid/)).toBeVisible(); + await expect(page.getByRole('cell', { name: '001', exact: true })).toBeVisible(); + await expect(page.getByRole('cell', { name: '005', exact: true })).toBeVisible(); + await frame({ focus: page.locator('.tool-preview'), hold: 1200 }); + + await page.getByRole('button', { name: 'Apply serial changes' }).click(); + await expect(page.getByText(/Applied 5 serial row\(s\)/)).toBeVisible(); + await frame({ focus: page.locator('.tool-card'), hold: 1200 }); + await openTool('asset-labels'); + await expect(page.getByRole('cell', { name: '001', exact: true })).toBeVisible(); + await expect(page.getByRole('cell', { name: '005', exact: true })).toBeVisible(); + await frame({ focus: page.locator('.table-panel'), hold: 1200 }); + }); + + await record('code-inspector', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await openTool('code-inspector'); + await expect(page.getByRole('heading', { name: 'Code inspector' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Inspect current label' })).toBeEnabled(); + await frame({ focus: page.locator('.tool-grid'), hold: 1200 }); + + await page.getByRole('button', { name: 'Inspect current label' }).click(); + await expect(page.locator('pre.tool-preview')).toHaveText('AST-1001', { timeout: 15000 }); + await expect(page.locator('dd').first()).toHaveText('QR CODE'); + await expect(page.locator('dd').nth(3)).toHaveText('1'); + await frame({ focus: page.locator('.tool-grid .tool-card').nth(1), hold: 1200 }); + + await openTool('asset-labels'); + const currentLabel = page.getByRole('img', { name: /Rendered label for/ }); + const qrSource = await currentLabel.getAttribute('src'); + await page.getByRole('button', { name: 'Code 128', exact: true }).click(); + await expect.poll(() => currentLabel.getAttribute('src')).not.toBe(qrSource); + await openTool('code-inspector'); + await page.getByRole('button', { name: 'Inspect current label' }).click(); + await expect(page.locator('pre.tool-preview')).toHaveText('AST-1001', { timeout: 15000 }); + await expect(page.locator('dd').first()).toHaveText('CODE 128'); + await frame({ focus: page.locator('.tool-grid .tool-card').nth(1), hold: 1200 }); + + const url = 'https://inventory.example.invalid/assets/AST-1001'; + await page.getByLabel('Inspector content').fill(url); + await page.getByRole('button', { name: 'Analyze pasted content' }).click(); + await expect(page.locator('pre.tool-preview')).toHaveText(url); + await expect(page.locator('dd').nth(2)).toHaveText('https'); + await expect(page.getByText(/never opened/i)).toBeVisible(); + await frame({ focus: page.locator('.tool-grid .tool-card').nth(1), hold: 1200 }); + }); +} diff --git a/scripts/showcase/encode.py b/scripts/showcase/encode.py new file mode 100644 index 0000000..c38f062 --- /dev/null +++ b/scripts/showcase/encode.py @@ -0,0 +1,54 @@ +"""Encode the browser's lossless frames with reading pauses and a looping APNG.""" +import argparse +import json +import os +from pathlib import Path +import subprocess + +from PIL import Image + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("frames", type=Path) +parser.add_argument("output", type=Path) +parser.add_argument("--video", action="store_true") +args = parser.parse_args() +timeline = json.loads((args.frames / "frames.json").read_text(encoding="utf-8")) +images, delays = [], [] +for item in timeline: + with Image.open(args.frames / item["filename"]) as source: + images.append(source.convert("RGB")) + delays.append(item["hold"]) +if any(img.size != images[0].size for img in images): + raise ValueError("The browser viewport changed during the recording.") +candidate = args.frames / "encoded.apng" +images[0].save(candidate, format="PNG", save_all=True, append_images=images[1:], + duration=delays, loop=0, disposal=0, blend=0, compress_level=7) +with Image.open(candidate) as result: + if not result.is_animated or result.n_frames < 3: + raise ValueError("Expected a multi-frame APNG.") + duration = 0 + for i in range(result.n_frames): + result.seek(i) + result.load() + duration += result.info["duration"] + if abs(duration - sum(delays)) > 2: + raise ValueError("Frame timing changed during encoding.") + print(f"{args.output.name}: {result.n_frames} frames, {duration / 1000:.2f}s, {result.size}") +if args.video: + movie = args.frames / "encoded.mp4" + # The repeated final image lets the concat demuxer honor the last reading pause. + playlist = args.frames / "frames.ffconcat" + entries = ["ffconcat version 1.0"] + for item in timeline: + entries.extend([f"file '{item['filename']}'", f"duration {item['hold'] / 1000:.3f}"]) + entries.append(f"file '{timeline[-1]['filename']}'") + playlist.write_text("\n".join(entries) + "\n", encoding="ascii") + subprocess.run([os.environ.get("FFMPEG", "ffmpeg"), "-hide_banner", "-loglevel", "error", "-y", + "-f", "concat", "-i", playlist.name, "-vf", "fps=20", "-t", f"{duration / 1000:.3f}", + "-c:v", "libx264", "-threads", "2", "-crf", "18", "-pix_fmt", "yuv420p", "-movflags", "+faststart", + movie.name], cwd=args.frames, check=True) + movie.replace(args.output.with_suffix(".mp4")) + # Use the inventory view as the still alternative for reduced-motion readers. + keyframes = [image for image, item in zip(images, timeline) if item["keyframe"]] + keyframes[1].save(args.output.with_name(args.output.stem + "-poster.png")) +candidate.replace(args.output) diff --git a/scripts/showcase/overview.mjs b/scripts/showcase/overview.mjs new file mode 100644 index 0000000..e062968 --- /dev/null +++ b/scripts/showcase/overview.mjs @@ -0,0 +1,119 @@ +import { expect } from '@playwright/test'; +import { PDFDocument } from 'pdf-lib'; +import { readFile } from 'node:fs/promises'; + +async function importToManifest({ page, frame, loadSample, openTool }) { + await frame({ hold: 1300 }); + await loadSample(); + await expect(page.getByText('8 rows · 5 columns')).toBeVisible(); + await frame({ focus: page.locator('.table-heading'), hold: 1750 }); + const preview = page.locator('.single-preview img'); + await expect(preview).toBeVisible(); + const qr = await preview.getAttribute('src'); + const barcode = page.getByRole('button', { name: 'Code 128', exact: true }); + await barcode.click(); + await expect(preview).not.toHaveAttribute('src', qr); + await frame({ focus: barcode }); + await expect(page.locator('.paper-label img')).toHaveCount(8); + await frame({ focus: page.locator('.preview-heading'), hold: 1600 }); + await page.locator('.single-preview').evaluate(el => el.scrollIntoView({ block: 'center', behavior: 'instant' })); + await frame({ focus: page.locator('.single-preview'), hold: 1500 }); + await page.locator('.export-bar').evaluate(el => el.scrollIntoView({ block: 'center', behavior: 'instant' })); + await frame({ focus: page.locator('.export-bar'), hold: 1400 }); + const download = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Download PDF' }).click(); + const pdf = await PDFDocument.load(await readFile(await (await download).path())); + expect(pdf.getPageCount()).toBe(1); + const paper = pdf.getPage(0).getSize(); + expect(paper.width * 25.4 / 72).toBeCloseTo(210, 1); + expect(paper.height * 25.4 / 72).toBeCloseTo(297, 1); + await openTool('manifest'); + await expect(page.getByText(/8 physical labels/)).toBeVisible(); + await frame({ focus: page.getByRole('heading', { name: 'Print manifest' }), hold: 2000 }); +} + +export async function captureOverview({ record }) { + await record('desktop', importToManifest, { walkthrough: true }); + await record('mobile', importToManifest, { walkthrough: true, mobile: true }); + + await record('asset-labels', async ({ page, loadSample, frame }) => { + await loadSample(); + const search = page.getByRole('textbox', { name: 'Search assets' }); + await frame({ focus: page.locator('.table-heading') }); + await page.getByRole('checkbox', { name: 'Select all matching assets' }).uncheck(); + await search.fill('Monitor'); + await expect(page.locator('tbody tr')).toHaveCount(2); + await page.getByRole('checkbox', { name: 'Select all matching assets' }).check(); + await expect(page.getByText('2 selected', { exact: true })).toBeVisible(); + await frame({ focus: search, hold: 1800 }); + await search.fill(''); + await page.getByLabel('Paper size', { exact: true }).selectOption('Letter'); + await expect(page.locator('.paper-label img')).toHaveCount(2); + await frame({ focus: page.getByLabel('Paper size', { exact: true }) }); + await frame({ focus: page.locator('.preview-heading'), hold: 1700 }); + await page.getByRole('button', { name: 'Switch to dark theme' }).click(); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark'); + await frame({ focus: page.locator('.single-preview') }); + }); + + await record('favorites', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await openTool('favorites'); + await expect(page.getByRole('heading', { name: 'No favorite tools yet' })).toBeVisible(); + await frame(); + await openTool('asset-labels'); + const star = page.getByRole('button', { name: 'Favorite Asset labels', exact: true }); + await star.click(); + await expect(star).toHaveAttribute('aria-pressed', 'true'); + await frame({ focus: star }); + await openTool('data-health'); + await page.getByRole('button', { name: 'Favorite Data Health', exact: true }).click(); + await openTool('favorites'); + const hub = page.locator('.favorites-page'); + await expect(hub.getByRole('link', { name: 'Data health' })).toBeVisible(); + await frame({ hold: 1750 }); + await hub.getByRole('link', { name: 'Asset labels' }).click(); + const strip = page.getByRole('navigation', { name: 'Saved tools' }); + await expect(strip).toBeVisible(); + await frame({ focus: strip }); + await strip.getByRole('link', { name: 'Data health' }).click(); + await expect(page).toHaveURL(/#\/favorites\/data-health$/); + await frame({ focus: strip }); + }); + + await record('desktop-navigation', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await page.getByRole('button', { name: 'Switch to dark theme' }).click(); + await frame(); + for (const view of ['cable-labels', 'data-health', 'templates', 'code-inspector']) { + await openTool(view); + await expect(page.getByRole('navigation', { name: 'Studio tools' }).locator('a[aria-current="page"]')) + .toHaveAttribute('href', '#/' + view); + await frame(); + } + }); + + await record('navigation', async ({ page, frame, loadSample }) => { + await loadSample(); + await page.evaluate(() => window.scrollTo(0, 0)); + await frame(); + const dock = page.getByRole('navigation', { name: 'Tool groups' }); + const toggle = page.getByRole('button', { name: 'Show tool dock' }); + if (await toggle.isVisible()) await toggle.click(); + await expect(dock).toBeVisible(); + await frame(); + await dock.getByRole('link', { name: 'Data', exact: true }).click(); + await expect(page.getByRole('heading', { name: 'Data Health', exact: true })).toBeVisible(); + await frame(); + const strip = page.getByRole('navigation', { name: 'Studio tools' }); + await strip.getByRole('link', { name: 'Serial tools', exact: true }).click(); + await expect(page.getByRole('heading', { name: 'Serial Tools', exact: true })).toBeVisible(); + await frame(); + await dock.getByRole('link', { name: 'Tools', exact: true }).click(); + await expect(page.getByRole('heading', { name: 'Code inspector', exact: true })).toBeVisible(); + await frame(); + await page.getByRole('heading', { name: 'Code inspector', exact: true }).click(); + await expect(toggle).toBeVisible(); + await frame(); + }, { mobile: true }); +} diff --git a/scripts/showcase/print-tools.mjs b/scripts/showcase/print-tools.mjs new file mode 100644 index 0000000..3d3fc2d --- /dev/null +++ b/scripts/showcase/print-tools.mjs @@ -0,0 +1,217 @@ +import { expect } from '@playwright/test'; +import { PDFDocument } from 'pdf-lib'; +import Papa from 'papaparse'; +import { readFile } from 'node:fs/promises'; + +async function inspectPdf(download, filename) { + if (filename instanceof RegExp) expect(download.suggestedFilename()).toMatch(filename); + else expect(download.suggestedFilename()).toBe(filename); + const file = await download.path(); + expect(file, `${filename} download path`).toBeTruthy(); + const pdf = await PDFDocument.load(await readFile(file)); + expect(pdf.getPageCount()).toBeGreaterThan(0); + return pdf; +} + +async function downloadText(download) { + const file = await download.path(); + expect(file, `${download.suggestedFilename()} download path`).toBeTruthy(); + return readFile(file, 'utf8'); +} + +async function waitForPreviews(page, count) { + const previews = page.locator('.special-label-previews figure img'); + await expect(previews).toHaveCount(count, { timeout: 15_000 }); + await previews.evaluateAll(images => Promise.all(images.map(image => image.decode()))); +} + +export async function capturePrintTools({ record }) { + await record('cable-labels', async ({ page, frame, loadSample, openTool }) => { + await loadSample('cable-labels.csv'); + await openTool('cable-labels'); + await expect(page.getByRole('heading', { name: 'Cable labels' })).toBeVisible(); + await frame(); + + await page.getByLabel('Source endpoint').selectOption('source'); + await frame({ focus: page.getByLabel('Port') }); + await page.getByLabel('Port').selectOption('port'); + await page.getByLabel('Target endpoint').selectOption('target'); + await page.getByLabel('Label width (mm)').fill('120'); + await waitForPreviews(page, 4); + await expect(page.getByLabel('Mirror for cable wrap')).toBeChecked(); + await frame({ focus: page.locator('.special-label-previews img').first() }); + + await page.getByLabel('Add QR / barcode').check(); + await expect(page.getByLabel('Code type')).toHaveValue('qr'); + await waitForPreviews(page, 4); + await frame({ focus: page.getByLabel('Code type') }); + + await page.getByRole('button', { name: 'Apply layout to workspace' }).click(); + await expect(page.getByRole('status')).toContainText('Template applied'); + await frame({ focus: page.getByRole('button', { name: 'Create PDF' }) }); + + const pdfPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Create PDF' }).click(); + const pdf = await inspectPdf(await pdfPromise, /^asset-labels-\d{4}-\d{2}-\d{2}\.pdf$/); + expect(pdf.getPageCount()).toBeGreaterThan(0); + await expect(page.getByRole('status')).toContainText('4 physical labels exported'); + await frame({ focus: page.getByRole('status') }); + }); + + await record('location-labels', async ({ page, frame, loadSample, openTool }) => { + await loadSample('location-labels.csv'); + await openTool('location-labels'); + await expect(page.getByRole('heading', { name: 'Location labels' })).toBeVisible(); + await frame(); + + await page.getByLabel('Site / warehouse').selectOption('site'); + await page.getByLabel('Building').selectOption('building'); + await page.getByLabel('Floor').selectOption('floor'); + await page.getByLabel('Room').selectOption('room'); + await page.getByLabel('Label width (mm)').fill('120'); + await page.getByLabel('Label height (mm)').fill('100'); + await waitForPreviews(page, 4); + await frame({ focus: page.getByLabel('Room') }); + + await page.getByLabel('Rack').selectOption('rack'); + await page.getByLabel('Shelf').selectOption('shelf'); + await page.getByLabel('Bin').selectOption('bin'); + await waitForPreviews(page, 4); + await expect(page.getByLabel('Add QR / barcode')).toBeChecked(); + await expect(page.locator('.special-label-previews figure img').first()).toHaveAttribute('alt', 'Label preview for 1'); + await frame({ focus: page.locator('.special-label-previews img').first() }); + + await page.getByRole('button', { name: 'Apply layout to workspace' }).click(); + await expect(page.getByRole('status')).toContainText('Template applied'); + await frame({ focus: page.getByRole('button', { name: 'Create PDF' }) }); + + const pdfPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Create PDF' }).click(); + await inspectPdf(await pdfPromise, /^asset-labels-\d{4}-\d{2}-\d{2}\.pdf$/); + await expect(page.getByRole('status')).toContainText('4 physical labels exported'); + await frame({ focus: page.getByRole('status') }); + }); + + await record('calibration', async ({ page, frame, loadSample, openTool }) => { + await loadSample('demo-assets.csv'); + await openTool('calibration'); + await expect(page.getByRole('heading', { name: 'Printer calibration' })).toBeVisible(); + await frame(); + + await page.getByLabel('Horizontal correction (mm)').fill('1.2'); + await page.getByLabel('Vertical correction (mm)').fill('-0.6'); + await expect(page.getByLabel('Horizontal correction (mm)')).toHaveValue('1.2'); + await expect(page.getByLabel('Vertical correction (mm)')).toHaveValue('-0.6'); + await frame({ focus: page.getByRole('button', { name: 'Download calibration PDF' }) }); + + const pdfPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Download calibration PDF' }).click(); + await inspectPdf(await pdfPromise, 'printer-calibration.pdf'); + await frame({ focus: page.getByRole('button', { name: 'Download calibration PDF' }) }); + + await page.getByRole('button', { name: 'Reset offsets' }).click(); + await expect(page.getByLabel('Horizontal correction (mm)')).toHaveValue('0'); + await expect(page.getByLabel('Vertical correction (mm)')).toHaveValue('0'); + await frame({ focus: page.getByRole('button', { name: 'Reset offsets' }) }); + }); + + await record('printer-profiles', async ({ page, frame, loadSample, openTool }) => { + await loadSample('demo-assets.csv'); + await openTool('calibration'); + await expect(page.getByRole('heading', { name: 'Printer calibration' })).toBeVisible(); + await frame(); + + await page.getByLabel('Horizontal correction (mm)').fill('1.2'); + await page.getByLabel('Vertical correction (mm)').fill('-0.6'); + await page.getByLabel('New profile name').fill('Warehouse Zebra'); + await frame({ focus: page.getByRole('button', { name: 'Save new profile' }) }); + + await page.getByRole('button', { name: 'Save new profile' }).click(); + await expect(page.getByLabel('Active profile')).toHaveValue(/.+/); + await expect(page.getByText('1.2 mm X · -0.6 mm Y')).toBeVisible(); + await frame({ focus: page.getByLabel('Active profile') }); + + const profilePromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Export profile' }).click(); + const profileDownload = await profilePromise; + expect(profileDownload.suggestedFilename()).toBe('Warehouse-Zebra.printer.json'); + const profileFile = await profileDownload.path(); + expect(profileFile).toBeTruthy(); + const profile = JSON.parse(await readFile(profileFile, 'utf8')); + expect(profile).toMatchObject({ name: 'Warehouse Zebra', offsetXMm: 1.2, offsetYMm: -0.6 }); + await frame({ focus: page.getByRole('button', { name: 'Export profile' }) }); + + await page.getByLabel('Horizontal correction (mm)').fill('0.8'); + await page.getByLabel('Vertical correction (mm)').fill('0.3'); + await page.getByRole('button', { name: 'Update active profile' }).click(); + await expect(page.getByText('0.8 mm X · 0.3 mm Y')).toBeVisible(); + await frame({ focus: page.getByText('0.8 mm X · 0.3 mm Y') }); + + await page.getByRole('button', { name: 'Delete profile' }).click(); + await expect(page.getByLabel('Active profile')).toHaveValue(''); + await frame({ focus: page.getByRole('button', { name: 'Save new profile' }) }); + }); + + await record('manifest', async ({ page, frame, loadSample, openTool }) => { + await loadSample('demo-assets.csv'); + await openTool('manifest'); + await expect(page.getByRole('heading', { name: 'Print manifest' })).toBeVisible(); + await expect(page.getByText('No successful print job is available yet.')).toBeVisible(); + await frame(); + + await openTool('asset-labels'); + await expect(page.getByRole('img', { name: /Rendered label for/ })).toBeVisible(); + const printPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: /Download PDF/ }).click(); + const printDownload = await printPromise; + expect(printDownload.suggestedFilename()).toMatch(/^asset-labels-\d{4}-\d{2}-\d{2}\.pdf$/); + const printFile = await printDownload.path(); + expect(printFile).toBeTruthy(); + const printPdf = await PDFDocument.load(await readFile(printFile)); + expect(printPdf.getPageCount()).toBeGreaterThan(0); + await frame({ focus: page.getByRole('button', { name: /Download PDF/ }) }); + + await openTool('manifest'); + await expect(page.getByRole('button', { name: 'Download JSON and CSV' })).toBeEnabled(); + await expect(page.locator('.tool-card')).toContainText('8 physical labels'); + await frame({ focus: page.getByRole('button', { name: 'Download JSON and CSV' }) }); + + const jsonPromise = page.waitForEvent('download', { predicate: download => download.suggestedFilename() === 'asset-print-manifest.json' }); + const csvPromise = page.waitForEvent('download', { predicate: download => download.suggestedFilename() === 'asset-print-manifest.csv' }); + await page.getByRole('button', { name: 'Download JSON and CSV' }).click(); + const [jsonDownload, csvDownload] = await Promise.all([jsonPromise, csvPromise]); + const manifest = JSON.parse(await downloadText(jsonDownload)); + const csv = Papa.parse(await downloadText(csvDownload), { header: true, skipEmptyLines: true }).data; + expect(manifest.records).toHaveLength(8); + expect(csv).toHaveLength(8); + expect(manifest.records.map(label => label.assetId)).toEqual(csv.map(row => row.asset_id)); + await expect(page.getByRole('status')).toContainText('Downloaded manifest for 8 labels'); + await frame({ focus: page.getByRole('status') }); + }); + + await record('fieldlens', async ({ page, frame, loadSample, openTool }) => { + await loadSample('demo-assets.csv'); + await openTool('fieldlens'); + await expect(page.getByRole('heading', { name: 'FieldLens export' })).toBeVisible(); + await frame(); + + await page.getByLabel('Asset ID').selectOption('Asset ID'); + await page.getByLabel('Name').selectOption('Name'); + await frame({ focus: page.getByLabel('Asset type') }); + + await page.getByLabel('Asset type').selectOption('Category'); + await page.getByLabel('Location').selectOption('Location'); + await frame({ focus: page.getByRole('button', { name: 'Create FieldLens PDF and CSV' }) }); + + const pdfPromise = page.waitForEvent('download', { predicate: download => download.suggestedFilename() === 'fieldlens-labels.pdf' }); + const csvPromise = page.waitForEvent('download', { predicate: download => download.suggestedFilename() === 'fieldlens-assets.csv' }); + await page.getByRole('button', { name: 'Create FieldLens PDF and CSV' }).click(); + const [pdfDownload, csvDownload] = await Promise.all([pdfPromise, csvPromise]); + await inspectPdf(pdfDownload, 'fieldlens-labels.pdf'); + const csv = Papa.parse(await downloadText(csvDownload), { header: true, skipEmptyLines: true }).data; + expect(csv).toHaveLength(8); + expect(csv[0]).toMatchObject({ asset_id: 'AST-1001', name: 'MacBook Pro 14', asset_type: 'Laptop', location: 'Floor 2 / Desk 18' }); + await expect(page.getByRole('status')).toContainText('Created a PDF and CSV for 8 assets'); + await frame({ focus: page.getByRole('status') }); + }); +} diff --git a/scripts/showcase/workspace-tools.mjs b/scripts/showcase/workspace-tools.mjs new file mode 100644 index 0000000..5645cd8 --- /dev/null +++ b/scripts/showcase/workspace-tools.mjs @@ -0,0 +1,97 @@ +import { expect } from '@playwright/test'; + +const firstLabel = page => page.locator('.special-label-previews img').first(); +const firstPayload = page => page.locator('.tool-preview'); + +export async function captureWorkspaceTools({ record }) { + await record('templates', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await openTool('templates'); + await expect(page.getByRole('heading', { name: 'Templates', exact: true })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'Built-in templates' })).toBeVisible(); + await frame(); + + await page.getByRole('button', { name: 'Standard Asset Tag', exact: true }).click(); + await expect(page.getByRole('status')).toContainText('Needs mapping: Asset Name'); + await frame({ focus: page.getByLabel('Asset Name') }); + + await page.getByLabel('Asset Name').selectOption('Name'); + await expect(page.getByText('All template fields are mapped.', { exact: true })).toBeVisible(); + await frame({ focus: page.getByRole('button', { name: 'Apply template' }) }); + + await page.getByRole('button', { name: 'Apply template' }).click(); + await expect(page.getByRole('status')).toContainText('Standard Asset Tag applied to the current dataset.'); + await frame(); + + await page.getByLabel('Template name').fill('Engineering asset tag'); + await page.getByRole('button', { name: 'Save current settings', exact: true }).click(); + await expect(page.getByRole('status')).toContainText('Template saved to your library.'); + await expect(page.getByRole('button', { name: 'Engineering asset tag', exact: true })).toBeVisible(); + await frame(); + + const savedRow = page.getByRole('row', { name: /Engineering asset tag/ }); + await savedRow.getByRole('button', { name: 'Duplicate' }).click(); + await expect(page.getByRole('status')).toContainText('Engineering asset tag copy added to your library.'); + await expect(page.getByRole('button', { name: 'Engineering asset tag copy', exact: true })).toBeVisible(); + await frame({ focus: page.getByRole('button', { name: 'Engineering asset tag copy', exact: true }) }); + }); + + await record('payload-builder', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await openTool('payload-builder'); + await expect(page.getByRole('heading', { name: /QR payload builder/i })).toBeVisible(); + await expect(firstPayload(page)).toContainText('AST-1001'); + await frame(); + + await page.getByLabel('Payload preset').selectOption('url'); + await expect(firstPayload(page)).toContainText('https://inventory.example/assets/AST-1001'); + await frame({ focus: page.getByLabel('Payload preset') }); + + await page.getByLabel('Payload builder template').fill('https://inventory.example/assets/{Asset ID}?location={Location}'); + await expect(firstPayload(page)).toContainText('https://inventory.example/assets/AST-1001?location=Floor%202%20%2F%20Desk%2018'); + await frame({ focus: firstPayload(page) }); + + await page.getByRole('button', { name: 'Validate selected payloads' }).click(); + await expect(page.getByRole('status')).toContainText(/\d+ valid \/ \d+ selected\. 0 invalid\./, { timeout: 15000 }); + await frame(); + + await page.getByRole('button', { name: 'Apply to label' }).click(); + await expect(page.getByText('Payload applied to the label.', { exact: true })).toBeVisible(); + await frame({ focus: page.getByRole('button', { name: 'Apply to label' }) }); + }); + + await record('codes', async ({ page, frame, loadSample, openTool }) => { + await loadSample(); + await openTool('codes'); + await expect(page.getByRole('heading', { name: 'QR and barcode labels' })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'Label preview' })).toBeVisible(); + await frame(); + + await page.getByLabel('Code value').selectOption('Asset ID'); + await expect(firstLabel(page)).toBeVisible(); + await frame({ focus: page.getByLabel('Code value') }); + + await page.getByLabel('Label width (mm)').fill('75'); + await expect(page.getByLabel('Label width (mm)')).toHaveValue('75'); + await frame({ focus: page.getByLabel('Label width (mm)') }); + + await page.getByLabel('Code type').selectOption('code128'); + await expect(page.getByLabel('Code type')).toHaveValue('code128'); + await expect(firstLabel(page)).toBeVisible(); + await frame({ focus: page.getByLabel('Code type') }); + + await page.getByLabel('Add QR / barcode').uncheck(); + await expect(page.getByLabel('Code type')).toHaveCount(0); + await expect(firstLabel(page)).toBeVisible(); + await frame({ focus: page.getByLabel('Add QR / barcode') }); + + await page.getByLabel('Add QR / barcode').check(); + await expect(page.getByLabel('Code type')).toHaveValue('code128'); + await expect(firstLabel(page)).toBeVisible(); + await frame({ focus: page.getByLabel('Code type') }); + + await page.getByRole('button', { name: 'Apply layout to workspace' }).click(); + await expect(page.getByRole('status')).toContainText('Template applied. Create PDF after the workspace reflects this layout.'); + await frame(); + }); +} diff --git a/scripts/verify-portfolio-showcase.mjs b/scripts/verify-portfolio-showcase.mjs index 42ccc21..5bcf8c6 100644 --- a/scripts/verify-portfolio-showcase.mjs +++ b/scripts/verify-portfolio-showcase.mjs @@ -68,7 +68,8 @@ for (const image of images) { assert((await stat(absolute)).size > 0, `Empty image: ${image.src}`); execFileSync('git', ['-c', `safe.directory=${root.replaceAll('\\', '/')}`, 'ls-files', '--error-unmatch', image.src], { cwd: root, stdio: 'pipe' }); } -assert.equal(resolved.images[0].src, 'https://raw.githubusercontent.com/private-dev-ph/AssetTagStudio/main/docs/media/workspace.png'); +assert.equal(resolved.images[0].src, 'https://raw.githubusercontent.com/private-dev-ph/AssetTagStudio/main/docs/media/walkthroughs/desktop-poster.png'); +assert.equal(resolved.images.find(image => /\.apng$/i.test(image.src))?.src, 'https://raw.githubusercontent.com/private-dev-ph/AssetTagStudio/main/docs/media/walkthroughs/desktop.apng'); if (manifest.logo) assert.equal(resolved.logo.src, `https://raw.githubusercontent.com/private-dev-ph/AssetTagStudio/main/${manifest.logo.src}`); const readme = await readFile(path.join(root, 'README.md'), 'utf8'); assert(readme.includes('portfolio-showcase.json') && readme.includes('private'), 'README must explain metadata and private discovery status.'); diff --git a/src/App.tsx b/src/App.tsx index b394e60..e06ed30 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,12 +1,33 @@ -import { ChangeEvent, DragEvent, useEffect, useMemo, useRef, useState } from 'react'; +import { DragEvent, useEffect, useMemo, useRef, useState } from 'react'; import type { Dataset, LabelField, LabelTemplate, PageSettings } from './types'; import { inspectFile, readSheet } from './features/import/client'; import { validateIdentifiers } from './features/import/normalize'; import { calculateLayout, inchesToMm, mmToInches } from './features/layout/pageLayout'; import { renderLabel, validateTemplate } from './features/labels/renderer'; -import { generatePdf } from './features/export/pdf'; +import { generatePrintJobPdf } from './features/export/pdf'; import { loadPreferences, savePreferences, type Preferences } from './features/preferences/store'; +import { UndoHistory } from './core/dataset'; +import { downloadFile } from './core/download'; +import { createPrintJob, type PrintJob } from './core/printJob'; +import type { StudioPageProps, StudioView } from './studio/contracts'; +import { checkTemplateMapping, estimateSnapshot, favoriteHref, routeFromHash, transformedWorkspace, type WorkspaceSnapshot } from './studio/workspace'; +import { FavoritesContext, useFavorites } from './studio/favorites'; +import { FavoritesPage, FavoriteToolStrip } from './studio/pages/FavoritesPage'; +import { useStudioRoute } from './studio/useStudioRoute'; +import { HelpDetails, PageHeading } from './studio/ui'; +import { ToolNavigation } from './studio/ToolNavigation'; +import { PayloadPage } from './studio/pages/PayloadPage'; +import { TemplatesPage } from './studio/pages/TemplatesPage'; +import { InspectorPage } from './studio/pages/InspectorPage'; +import { DataToolsPage } from './studio/pages/DataToolsPage'; +import { SpecialLabelsPage } from './features/specialized-labels/SpecialLabelsPage'; +import { CalibrationPage } from './features/calibration/CalibrationPage'; +import { ExportToolsPage } from './features/manifest/ExportToolsPage'; +import { FilePicker } from './studio/FilePicker'; +import { SiteFooter } from './studio/SiteFooter'; import './styles.css'; +import './studio/navigation.css'; +import './studio/workspace-shell.css'; const PAGE_PRESETS: Record = { A4: [210, 297], A5: [148, 210], Letter: [215.9, 279.4] }; const PAGE_FIELDS: { key: keyof PageSettings; label: string }[] = [ @@ -15,6 +36,29 @@ const PAGE_FIELDS: { key: keyof PageSettings; label: string }[] = [ ]; function App() { + const route = useStudioRoute(); + const savedTools = useFavorites(); + const missingFavorite = route.inFavorites && !savedTools.favorites.includes(route.view); + const view = missingFavorite ? 'favorites' : route.view; + useEffect(() => { + // Canonicalize invalid saved-tool hashes from the hash event itself. The + // route hook may still be animating the previous view when a stale link is + // re-entered, so waiting for its rendered route can miss that navigation. + function canonicalizeFavoriteHash() { + const current = routeFromHash(window.location.hash); + if (current.inFavorites && !savedTools.favorites.includes(current.view)) { + window.location.replace('#/favorites'); + } + } + canonicalizeFavoriteHash(); + window.addEventListener('hashchange', canonicalizeFavoriteHash); + return () => window.removeEventListener('hashchange', canonicalizeFavoriteHash); + }, [savedTools.favorites]); + const [templateName, setTemplateName] = useState('Current label'); + const [lastJob, setLastJob] = useState(null); + const history = useRef(new UndoHistory(estimateSnapshot)); + const [canUndo, setCanUndo] = useState(false); + const exportLock = useRef(false); const [preferences, setPreferences] = useState(() => loadPreferences()); const [dataset, setDataset] = useState(null); const [file, setFile] = useState(null); @@ -37,11 +81,43 @@ function App() { const [progress, setProgress] = useState(null); const [exportError, setExportError] = useState(''); const [exportController, setExportController] = useState(null); - const fileInput = useRef(null); + const workspace = useRef(null); const previewVersion = useRef(0); const sheetVersion = useRef(0); const importVersion = useRef(0); + function navigate(next: StudioView) { + window.location.hash = route.inFavorites && savedTools.favorites.includes(next) ? favoriteHref(next) : `/${next}`; + setError(''); + } + function clearDatasetHistory() { history.current.clear(); setCanUndo(false); setLastJob(null); } + function restoreWorkspace(snapshot: WorkspaceSnapshot) { + setDataset(snapshot.dataset); setTemplate(snapshot.template); setPage(snapshot.page); setIdField(snapshot.idField); + setSelected(snapshot.selected); setHiddenFields(snapshot.hiddenFields); setPageNumber(0); setTablePage(0); + } + function commitDataset(next: Dataset, description: string, columnMap?: Record) { + if (!dataset || busy || exportLock.current) throw new Error('Wait for the current operation before changing data.'); + const current = { dataset, template, page, idField, selected, hiddenFields }; + try { + const result = transformedWorkspace(current, next, columnMap); + history.current.push(current, description); + restoreWorkspace(result); setCanUndo(history.current.canUndo); setError(''); + } catch (reason) { setError(reason instanceof Error ? reason.message : 'The data change could not be applied.'); throw reason; } + } + function undo() { + if (busy || exportLock.current) return; + const snapshot = history.current.pop(); + if (snapshot) { restoreWorkspace(snapshot); setCanUndo(history.current.canUndo); setError(''); } + } + function applyTemplate(next: LabelTemplate, nextPage?: PageSettings, name?: string) { + if (busy || exportLock.current) throw new Error('Wait for the current operation before changing the label.'); + checkTemplateMapping(next, dataset); validateTemplate(next); + if (nextPage) calculateLayout(next, nextPage, Math.max(1, chosenRecords.length)); + setTemplate(next); setHiddenFields(new Set()); + if (dataset?.columns.includes(next.code.field)) setIdField(next.code.field); + if (nextPage) setPage(nextPage); if (name) setTemplateName(name); setPageNumber(0); + } + const chosenRecords = useMemo(() => dataset?.records.filter((record) => selected.has(record.id)) ?? [], [dataset, selected]); const diagnostics = useMemo(() => dataset && idField ? validateIdentifiers(dataset, idField) : [], [dataset, idField]); @@ -117,7 +193,7 @@ function App() { async function importFile(nextFile: File, replaceBusy = false) { if ((busy || progress !== null) && !replaceBusy) return; const version = ++importVersion.current; - setError(''); setExportError(''); setDataset(null); setFile(nextFile); setSelected(new Set()); setSheets([]); setSheet(''); + clearDatasetHistory(); setError(''); setExportError(''); setDataset(null); setFile(nextFile); setSelected(new Set()); setSheets([]); setSheet(''); setBusy(true); try { const result = await inspectFile(nextFile); @@ -144,7 +220,7 @@ function App() { setSearch(''); setSort({ key: '', dir: 1 }); setPageNumber(0); setTablePage(0); setHiddenFields((current) => new Set([...current].filter((field) => next.columns.includes(field)))); setTemplate((current) => { - const fields = current.fields.filter((field) => next.columns.includes(field.source)).slice(0, 6); + const fields = current.fields.filter((field) => next.columns.includes(field.source)).slice(0, 32); const payloadIsCompatible = [...current.code.payload.matchAll(/\{([^{}]+)\}/g)].every((match) => next.columns.includes(match[1])); return { ...current, code: { ...current.code, field: selectedField, payload: payloadIsCompatible ? current.code.payload : '' }, fields: fields.length ? fields : next.columns.filter((column) => column !== selectedField).slice(0, 2).map((source, index) => ({ source, label: '', fontSize: index === 0 ? 10 : 8, bold: index === 0 })) }; }); @@ -152,7 +228,7 @@ function App() { async function chooseSheet(nextSheet: string) { const version = ++importVersion.current; - setSheet(nextSheet); setError(''); setDataset(null); setSelected(new Set()); setBusy(true); + clearDatasetHistory(); setSheet(nextSheet); setError(''); setDataset(null); setSelected(new Set()); setBusy(true); try { if (file) { const next = await readSheet(file, nextSheet); if (version === importVersion.current) applyDataset(next); } } catch (reason) { if (version === importVersion.current) setError(reason instanceof Error ? reason.message : 'Could not read this worksheet. Select another sheet or file.'); } finally { if (version === importVersion.current) setBusy(false); } @@ -202,32 +278,33 @@ function App() { function removeSelected() { if (!dataset) return; const records = dataset.records.filter((record) => !selected.has(record.id)); - setDataset({ ...dataset, records }); setSelected(new Set()); setPageNumber(0); setTablePage(0); + try { commitDataset({ ...dataset, records }, 'Remove selected rows'); } catch { /* The shared transaction presents the failure. */ } } - function onFileChange(event: ChangeEvent) { const next = event.currentTarget.files?.[0]; if (next) void importFile(next); event.currentTarget.value = ''; } function onDrop(event: DragEvent) { event.preventDefault(); setDragging(false); const next = event.dataTransfer.files[0]; if (next && !busy && progress === null) void importFile(next); } - async function exportPdf() { - if (!dataset || !chosenRecords.length || !idField || noIdCount > 0 || templateError) return; + async function exportPdf(): Promise { + if (exportLock.current || !dataset || !chosenRecords.length || (template.code.type !== 'none' && (!idField || noIdCount > 0)) || templateError || busy) return null; + exportLock.current = true; setExportError(''); setProgress(0); const controller = new AbortController(); setExportController(controller); try { - const bytes = await generatePdf(chosenRecords, effectiveTemplate, page, { signal: controller.signal, onProgress: (complete, total) => setProgress(total ? Math.round((complete / total) * 100) : 100) }); + const job = createPrintJob(chosenRecords, effectiveTemplate, page, { idField, templateName }); + const bytes = await generatePrintJobPdf(job, { signal: controller.signal, onProgress: (complete, total) => setProgress(total ? Math.round((complete / total) * 100) : 100) }); + if (controller.signal.aborted) return null; const sourceBuffer = bytes.buffer; const pdfBuffer = sourceBuffer instanceof ArrayBuffer && bytes.byteOffset === 0 && bytes.byteLength === sourceBuffer.byteLength ? sourceBuffer : bytes.slice().buffer as ArrayBuffer; - const url = URL.createObjectURL(new Blob([pdfBuffer], { type: 'application/pdf' })); - const anchor = document.createElement('a'); const now = new Date(); const localDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`; - anchor.href = url; anchor.download = `asset-labels-${localDate}.pdf`; - document.body.appendChild(anchor); anchor.click(); anchor.remove(); - window.setTimeout(() => URL.revokeObjectURL(url), 1000); + downloadFile(pdfBuffer, 'application/pdf', `asset-labels-${localDate}.pdf`); + setLastJob(job); setProgress(null); + return job; } catch (reason) { if (!controller.signal.aborted) setExportError(reason instanceof Error ? reason.message : 'PDF export failed. Check the page and label settings.'); setProgress(null); - } finally { setExportController(null); } + } finally { exportLock.current = false; setExportController(null); setProgress(null); } + return null; } function setDimension(key: 'widthMm' | 'heightMm' | 'paddingMm' | 'sizeMm' | 'barcodeHeightMm', displayed: number) { @@ -241,33 +318,58 @@ function App() { function setPageDimension(key: 'widthMm' | 'heightMm', displayed: number) { updatePage({ [key]: preferences.unit === 'in' ? inchesToMm(displayed) : displayed, preset: 'Custom' }); } function setMargin(key: keyof PageSettings, displayed: number) { updatePage({ [key]: preferences.unit === 'in' ? inchesToMm(displayed) : displayed }); } + const studioProps: StudioPageProps = { dataset, selectedIds: selected, idField, template: effectiveTemplate, page, busy: busy || progress !== null, previewImage: previewData, lastJob, + onCommitDataset: commitDataset, onApplyTemplate: applyTemplate, onPageChange: next => { if (!exportLock.current) setPage(next); }, + onIdentifierChange: field => { if (!exportLock.current && dataset?.columns.includes(field)) { setIdField(field); updateCode({ field }); } }, + onNavigate: navigate, onUndo: undo, canUndo, onExportJob: exportPdf, onPrintJobCompleted: setLastJob }; + return
+
- + + +
- {dataset && Files stay on this device} - + Get CSV template
-
-
LOCAL-FIRST LABEL WORKSPACE

Turn your asset list into
print-ready labels.

Choose your data, make a label, then export a sheet you can print at actual size.

1 Data2 Design3 Export
+
+
+
+ {route.inFavorites && view !== 'favorites' && } + {savedTools.sessionOnly &&

Browser storage is unavailable. Your favorite changes are available in this tab.

} + {dataset &&
{dataset.records.length.toLocaleString()} rows · selection {selected.size.toLocaleString()} · {templateName}
} + {view !== 'asset-labels' && error &&

{error}

} + {progress !== null && view !== 'asset-labels' &&
Preparing PDF {progress}%
} + {exportError && view !== 'asset-labels' &&

{exportError}

} +
+ {view === 'favorites' ? : + view === 'templates' ? : view === 'code-inspector' ? : view === 'payload-builder' ? : view === 'data-health' || view === 'id-generator' || view === 'serial-tools' ? : view === 'calibration' ? : view === 'manifest' || view === 'fieldlens' ? : view === 'cable-labels' || view === 'location-labels' || view === 'codes' ? : <> + +

Import a spreadsheet, choose the rows to label, then export a printable PDF.

+

Reloading clears imported rows. Preferences, saved templates and printer profiles stay in this browser.

+
{!dataset ?
{ event.preventDefault(); setDragging(true); }} onDragLeave={() => setDragging(false)} onDrop={onDrop}> - -
↥

{busy ? 'Opening your file…' : 'Start with your asset list'}

Drop a CSV or Excel workbook here, or choose a file from your device.

-
-
CSV, XLSX, or XLS · up to 10 MB · processed locally
+

{busy ? 'Opening your file…' : 'Start with your asset list'}

Drop your spreadsheet here to make labels.

+
void importFile(next)} disabled={busy || progress !== null} />
+
CSV, XLSX or XLS · up to 10 MiB
{sheets.length > 0 && } {error &&
{error}
}
: <>
▤
{file?.name ?? 'Asset list'}{dataset.records.length.toLocaleString()} rows · {dataset.columns.length} columns
{sheets.length > 0 && } - - - ● Local only + void importFile(next)} disabled={busy || progress !== null} />
{busy &&
Reading worksheet…
} {error &&
{error}
} @@ -308,7 +410,7 @@ function App() {
YOUR DATA

Choose assets {selected.size} selected

i{noIdCount > 0 ? {noIdCount} selected row{noIdCount === 1 ? '' : 's'} missing an identifier : Selected identifiers are present}{diagnostics.some((message) => /duplicate/i.test(message)) && Duplicate identifiers found}
- {diagnostics.length > 0 &&
Data checks: {diagnostics.length} note{diagnostics.length === 1 ? '' : 's'}
    {diagnostics.slice(0, 5).map((message, index) =>
  • {message}
  • )}
} + {diagnostics.length > 0 &&
    {diagnostics.slice(0, 5).map((message, index) =>
  • {message}
  • )}
}
{dataset.columns.map((column) => )}{displayRows.map((record, rowIndex) => {dataset.columns.map((column) => )})}
0 && visibleRecords.every((record) => selected.has(record.id))} onChange={toggleAll} />
record.values[column]?.trim()).find(Boolean) || `row ${tablePage * 50 + rowIndex + 1}`}`} type="checkbox" checked={selected.has(record.id)} onChange={() => toggleRecord(record.id)} />{record.values[column] || —}
{!displayRows.length &&
No matching assets. Try a different search.
}
Showing {visibleRecords.length ? tablePage * 50 + 1 : 0}–{tablePage * 50 + displayRows.length} of {visibleRecords.length} matching rows · 50 per page{dataset.records.length - selected.size} excluded
{visibleRecords.length > 50 &&
Page {tablePage + 1} of {tablePages}
}
@@ -327,12 +429,15 @@ function App() {
Preview page {Math.min(pageNumber + 1, Math.max(1, pages))} of {Math.max(1, pages)}
}
-
Ready to print?{chosenRecords.length} labels · print at 100% / actual size{progress !== null &&
}{exportError && {exportError}}
{progress !== null && }
+
Ready to print?{chosenRecords.length} labels · print at 100% / actual size{progress !== null &&
}{exportError && {exportError}}
{progress !== null && }
} -
-
AssetTag Studio · Your data stays in this browser session
+ } +
+
+
+ ; } diff --git a/src/core/dataset.ts b/src/core/dataset.ts new file mode 100644 index 0000000..e3d3124 --- /dev/null +++ b/src/core/dataset.ts @@ -0,0 +1,42 @@ +import type { AssetRecord, Dataset } from '../types'; +import { MAX_CELL_CHARACTERS, MAX_COLUMNS, MAX_ROWS } from '../features/import/limits'; + +export function readValue(record: AssetRecord, column: string): string { + return Object.hasOwn(record.values, column) && typeof record.values[column] === 'string' ? record.values[column] : ''; +} +export function cloneValues(values: Record): Record { + return Object.assign(Object.create(null) as Record, values); +} +export function validateDataset(dataset: Dataset): void { + if (!dataset || !Array.isArray(dataset.columns) || !Array.isArray(dataset.records) || !Array.isArray(dataset.warnings)) throw new Error('Choose a valid dataset.'); + if (!dataset.columns.length || dataset.columns.length > MAX_COLUMNS) throw new Error(`A dataset needs 1–${MAX_COLUMNS} columns.`); + if (dataset.columns.some(c => typeof c !== 'string' || !c.trim() || c.length > 200) || new Set(dataset.columns).size !== dataset.columns.length) throw new Error('Column names must be unique, nonempty text up to 200 characters.'); + if (dataset.records.length > MAX_ROWS) throw new Error(`A dataset supports up to ${MAX_ROWS} rows.`); + const ids = new Set(); + for (const record of dataset.records) { + if (!record || typeof record.id !== 'string' || ids.has(record.id) || typeof record.values !== 'object' || record.values === null || Array.isArray(record.values)) throw new Error('Internal row identities must be unique and values must be a record.'); + ids.add(record.id); + for (const column of dataset.columns) { + if (!Object.hasOwn(record.values, column) || typeof record.values[column] !== 'string' || record.values[column].length > MAX_CELL_CHARACTERS) throw new Error(`Invalid or oversized value in column “${column}”.`); + } + } +} +export function estimateDatasetBytes(dataset: Dataset): number { + return 2 * (dataset.columns.join('').length + dataset.records.reduce((sum, record) => sum + record.id.length + dataset.columns.reduce((n, c) => n + c.length + readValue(record, c).length, 0), 0)); +} + +// Store immutable references, never mutate or serialize the user's dataset into storage. +export class UndoHistory { + private items: { value: T; bytes: number; description: string }[] = []; + constructor(private readonly estimate: (value: T) => number, private readonly limitBytes = 24 * 1024 * 1024, private readonly limitEntries = 8) {} + get canUndo(): boolean { return this.items.length > 0; } + get description(): string { return this.items.at(-1)?.description ?? ''; } + push(value: T, description: string): void { + const bytes = this.estimate(value); + if (!Number.isFinite(bytes) || bytes < 0 || bytes > this.limitBytes) throw new Error('This change exceeds the in-memory undo limit. Reduce the dataset before applying it.'); + while (this.items.length >= this.limitEntries || this.items.reduce((sum, i) => sum + i.bytes, 0) + bytes > this.limitBytes) this.items.shift(); + this.items.push({ value, bytes, description }); + } + pop(): T | undefined { return this.items.pop()?.value; } + clear(): void { this.items = []; } +} diff --git a/src/core/download.ts b/src/core/download.ts new file mode 100644 index 0000000..3983854 --- /dev/null +++ b/src/core/download.ts @@ -0,0 +1,12 @@ +export function downloadFile(contents: BlobPart, type: string, name: string): void { + const url = URL.createObjectURL(new Blob([contents], { type })); + const anchor = document.createElement('a'); + anchor.href = url; anchor.download = name; document.body.appendChild(anchor); anchor.click(); anchor.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 1000); +} +export function csvText(rows: string[][]): string { + return rows.map(row => row.map(value => { + const safe = /^[\s]*[=+@-]|^[\t\r\n]/.test(value) ? `'${value}` : value; + return `"${safe.replaceAll('"', '""')}"`; + }).join(',')).join('\r\n') + '\r\n'; +} diff --git a/src/core/fieldlens-contract.test.ts b/src/core/fieldlens-contract.test.ts new file mode 100644 index 0000000..f2227a5 --- /dev/null +++ b/src/core/fieldlens-contract.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from 'vitest'; +import { DEFAULT_TEMPLATE } from '../types'; +import { resolveCodePayload, validatePayloadUri } from './payload'; + +it('matches the existing FieldLens single unescaped case-sensitive identifier contract', () => { + validatePayloadUri('FIELDLENS://ASSET/AST-CTRL-0042', 'fieldlens'); + const code = { ...DEFAULT_TEMPLATE.code, field: 'ID', payload: 'fieldlens://asset/{ID}', payloadMode: 'fieldlens' as const }; + expect(resolveCodePayload({ id: '1', values: { ID: 'PC-001' } }, code)).toBe('fieldlens://asset/PC-001'); + for (const id of ['A/B', 'A B', '%2F', 'A?B', 'A\\B', '..']) expect(() => resolveCodePayload({ id: '1', values: { ID: id } }, code)).toThrow(); +}); diff --git a/src/core/foundation.test.ts b/src/core/foundation.test.ts new file mode 100644 index 0000000..973c246 --- /dev/null +++ b/src/core/foundation.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_TEMPLATE, type Dataset } from '../types'; +import { UndoHistory, cloneValues, readValue, validateDataset } from './dataset'; +import { csvText } from './download'; +import { resolveCodePayload, validatePayloadUri } from './payload'; + +const dataset: Dataset = { columns: ['ID'], records: [{ id: 'row-1', values: { ID: 'A/B ?&' } }], warnings: [] }; +const code = { ...DEFAULT_TEMPLATE.code, field: 'ID' }; +describe('expansion foundation', () => { + it('retains stable identities and rejects invalid working datasets', () => { + validateDataset(dataset); + expect(() => validateDataset({ ...dataset, records: [...dataset.records, dataset.records[0]] })).toThrow(/identities/); + expect(() => validateDataset({ ...dataset, columns: ['ID', 'ID'] })).toThrow(/unique/); + expect(() => validateDataset({ ...dataset, records: [{ id: 'x', values: {} }] })).toThrow(/Invalid/); + }); + it('reads own properties and safely clones special column names', () => { + expect(readValue({ id: 'x', values: {} }, 'toString')).toBe(''); + const values = Object.create(null); values.__proto__ = 'actual'; + expect(readValue({ id: 'x', values: cloneValues(values) }, '__proto__')).toBe('actual'); + }); + it('bounds undo memory/history and restores snapshots in order', () => { + const undo = new UndoHistory(v => v, 10, 2); + undo.push(2, 'first'); undo.push(3, 'second'); undo.push(4, 'third'); + expect(undo.pop()).toBe(4); expect(undo.pop()).toBe(3); expect(undo.canUndo).toBe(false); + expect(() => undo.push(11, 'oversized')).toThrow(/undo limit/); + undo.push(1, 'reset'); undo.clear(); expect(undo.pop()).toBeUndefined(); + }); + it('preserves legacy raw/text payloads but encodes URL token values', () => { + expect(resolveCodePayload(dataset.records[0], code)).toBe('A/B ?&'); + expect(resolveCodePayload(dataset.records[0], { ...code, payload: 'https://example.invalid/assets/{ID}', payloadMode: 'url' })).toBe('https://example.invalid/assets/A%2FB%20%3F%26'); + expect(resolveCodePayload(dataset.records[0], { ...code, payload: 'ID:{ID}' })).toBe('ID:A/B ?&'); + expect(resolveCodePayload(dataset.records[0], { ...code, type: 'none', field: '' })).toBe(''); + }); + it('rejects malformed and unsafe URI modes, absent values and oversized output', () => { + for (const value of ['javascript:alert(1)', 'https://user:pass@example.invalid', 'not a url']) expect(() => validatePayloadUri(value, 'url')).toThrow(); + for (const value of ['fieldlens://other/A', 'fieldlens://asset/A/B', 'fieldlens://asset/%XX', 'fieldlens://asset/A?x=1']) expect(() => validatePayloadUri(value, 'fieldlens')).toThrow(); + expect(() => resolveCodePayload(dataset.records[0], { ...code, payload: '{Missing}' })).toThrow(/not a column/); + expect(() => resolveCodePayload(dataset.records[0], { ...code, payload: '{{ID}}' })).toThrow(/placeholders/); + expect(() => resolveCodePayload(dataset.records[0], { ...code, payload: 'x'.repeat(2001) })).toThrow(/2,000/); + validatePayloadUri('fieldlens://asset/PC-001', 'fieldlens'); + validatePayloadUri('location://warehouse-a/rack-a/bin-07', 'location'); + expect(() => validatePayloadUri('location://warehouse-a//bin-07', 'location')).toThrow(/empty segment/); + }); + it('quotes CSV content and neutralizes spreadsheet formula prefixes', () => { + expect(csvText([['=HYPERLINK("x")', 'a,b', 'A-1']])).toContain('"\'=HYPERLINK(""x"")"'); + expect(csvText([[' a', '+123']])).toBe('" a","\'+123"\r\n'); + }); +}); diff --git a/src/core/payload.ts b/src/core/payload.ts new file mode 100644 index 0000000..9995851 --- /dev/null +++ b/src/core/payload.ts @@ -0,0 +1,54 @@ +import type { AssetRecord, LabelTemplate } from '../types'; +import { readValue } from './dataset'; + +const TOKEN = /\{([^{}]+)\}/g; +const hasControl = (value: string) => Array.from(value).some(character => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127); +export const MAX_PAYLOAD_LENGTH = 2000; +export function payloadReferences(pattern: string): string[] { + if (typeof pattern !== 'string' || pattern.length > MAX_PAYLOAD_LENGTH) throw new Error('Code payload must be text with no more than 2,000 characters.'); + if (/[{}]/.test(pattern.replace(TOKEN, '')) || [...pattern.matchAll(TOKEN)].some(m => !m[1].trim())) throw new Error('Payload placeholders must use the form {columnName}.'); + return [...new Set([...pattern.matchAll(TOKEN)].map(m => m[1]))]; +} +export function validatePayloadUri(payload: string, mode: NonNullable): void { + if (mode === 'text') return; + if (/\s/.test(payload) || hasControl(payload)) throw new Error('URI payloads cannot contain literal whitespace or control characters.'); + try { decodeURI(payload); } catch { throw new Error('URI contains malformed percent encoding.'); } + if (payload.split(/[/?#]/).some(segment => { try { return ['.', '..'].includes(decodeURIComponent(segment)); } catch { return true; } })) throw new Error('URI cannot contain traversal segments.'); + let uri: URL; + try { uri = new URL(payload); } catch { throw new Error('The payload is not a valid absolute URI.'); } + if (mode === 'url') { + if (!['https:', 'http:'].includes(uri.protocol) || !uri.hostname || uri.username || uri.password) throw new Error('Use an HTTP or HTTPS URL without embedded credentials.'); + } else { + const scheme = mode === 'fieldlens' ? 'fieldlens:' : 'location:'; + if (uri.protocol !== scheme || !uri.hostname || uri.port || uri.search || uri.hash || uri.username || uri.password) throw new Error(`Use a valid ${mode} URI without credentials, port, query or fragment.`); + // FieldLens's current mobile resolver explicitly rejects percent-encoded IDs. + if (mode === 'fieldlens' && (uri.hostname.toLowerCase() !== 'asset' || !/^fieldlens:\/\/asset\/[^/\\?#%]+$/i.test(payload))) throw new Error('FieldLens URI needs one unescaped identifier: no %, slash, whitespace, query or fragment.'); + const parts = [uri.hostname, ...uri.pathname.split('/').filter(Boolean)]; + if (mode === 'location' && (uri.pathname.endsWith('/') || uri.pathname.includes('//'))) throw new Error('Location hierarchy cannot contain an empty segment.'); + for (const part of parts) { + let decoded: string; + try { decoded = decodeURIComponent(part); } catch { throw new Error('URI contains malformed percent encoding.'); } + if (!decoded.trim() || hasControl(decoded) || decoded === '.' || decoded === '..') throw new Error('URI segments need nonempty values without control characters or traversal segments.'); + } + } +} +export function resolveCodePayload(record: AssetRecord, code: LabelTemplate['code']): string { + if (code.type === 'none') return ''; + const refs = payloadReferences(code.payload); + let result: string; + if (!code.payload) { + result = readValue(record, code.field); + if (!result.trim()) throw new Error(`Record “${record.id}” has no value in “${code.field}”. Fill that cell or choose another code column.`); + } else { + for (const key of refs) { + if (!Object.hasOwn(record.values, key)) throw new Error(`Payload placeholder “{${key}}” is not a column in the records. Fix the template placeholder.`); + if (!readValue(record, key).trim()) throw new Error(`Record “${record.id}” has no value in “${key}”. Fill that cell or change the payload.`); + } + const encode = code.payloadMode === 'url' || code.payloadMode === 'location'; + result = code.payload.replace(TOKEN, (_, key: string) => encode ? encodeURIComponent(readValue(record, key)) : readValue(record, key)); + } + if (!result.trim()) throw new Error('The code payload is empty.'); + if (result.length > MAX_PAYLOAD_LENGTH) throw new Error(`Record “${record.id}” produces a code value over 2,000 characters.`); + validatePayloadUri(result, code.payloadMode ?? 'text'); + return result; +} diff --git a/src/core/printJob.test.ts b/src/core/printJob.test.ts new file mode 100644 index 0000000..4a32e9e --- /dev/null +++ b/src/core/printJob.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_PAGE, DEFAULT_TEMPLATE, type AssetRecord } from '../types'; +import { createPrintJob } from './printJob'; +import { manifestFromPrintJob } from '../features/manifest/manifest'; + +describe('immutable print jobs', () => { + it('snapshots records, signed calibrated positions, and multipage manifest order', () => { + const records: AssetRecord[] = Array.from({ length: 22 }, (_, index) => ({ id: `row-${index}`, values: { ID: `A-${index}` } })); + const template = { ...DEFAULT_TEMPLATE, code: { ...DEFAULT_TEMPLATE.code, field: 'ID' } }; + const page = { ...DEFAULT_PAGE, widthMm: 123, heightMm: 66, marginLeftMm: 1, marginRightMm: 1, marginTopMm: 1, marginBottomMm: 1, gapXMm: 0, gapYMm: 0, offsetXMm: 0.5, offsetYMm: -0.25 }; + const job = createPrintJob(records, template, page, { idField: 'ID', generatedAt: '2026-10-04T00:00:00.000Z' }); + records[0]!.values.ID = 'edited after export'; + expect(job.records[0]!.values.ID).toBe('A-0'); + expect(Object.isFrozen(job.labels[0]!.position)).toBe(true); + const manifest = manifestFromPrintJob(job); + expect(job.labels.length).toBe(22); + expect(manifest.records.map(row => [row.labelIndex, row.page, row.row, row.column, row.xMm, row.yMm])).toEqual(job.labels.map(label => [label.labelIndex, label.page, label.row, label.column, label.position.xMm, label.position.yMm])); + expect(manifest.calibration).toEqual({ offsetXMm: 0.5, offsetYMm: -0.25 }); + }); + it('does not publish a partial job for invalid payloads or clipping', () => { + const badPayload: AssetRecord[] = [{ id: 'one', values: { ID: '' } }]; + const template = { ...DEFAULT_TEMPLATE, code: { ...DEFAULT_TEMPLATE.code, field: 'ID' } }; + expect(() => createPrintJob(badPayload, template, DEFAULT_PAGE)).toThrow(/no value/); + expect(() => createPrintJob([{ id: 'one', values: { ID: 'A' } }], template, { ...DEFAULT_PAGE, widthMm: 60, marginLeftMm: 0, marginRightMm: 0, offsetXMm: 1 })).toThrow(/off the page/); + }); + it('rejects oversized input before validating or resolving each payload', () => { + const tooMany = Array.from({ length: 20_001 }, (_, i) => ({ id: `r-${i}`, values: {} })); + expect(() => createPrintJob(tooMany, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/supports up to 20,000 records/); + expect(() => createPrintJob([{ id: 'same', values: {} }, { id: 'same', values: {} }], DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/identities must be unique/); + }); +}); diff --git a/src/core/printJob.ts b/src/core/printJob.ts new file mode 100644 index 0000000..aa80d58 --- /dev/null +++ b/src/core/printJob.ts @@ -0,0 +1,85 @@ +import type { AssetRecord, LabelTemplate, PageLayout, PageSettings } from '../types'; +import { calculateLayout } from '../features/layout/pageLayout'; +import { interpolatePayload, validateTemplate } from '../features/labels/renderer'; +import { MAX_CELL_CHARACTERS, MAX_COLUMNS, MAX_ROWS } from '../features/import/limits'; + +export type PrintPlacement = { + recordId: string; assetId: string; labelIndex: number; page: number; row: number; column: number; + payload: string; position: { xMm: number; yMm: number }; widthMm: number; heightMm: number; +}; +export type PrintJob = { + version: 1; generatedAt: string; templateName: string; idField: string; + records: AssetRecord[]; template: LabelTemplate; page: PageSettings; layout: PageLayout; labels: PrintPlacement[]; +}; + +export type CreatePrintJobOptions = { templateName?: string; idField?: string; generatedAt?: string }; +const MAX_PRINT_RECORDS = MAX_ROWS; + +function validateRecords(records: AssetRecord[]): void { + if (records.length > MAX_PRINT_RECORDS) throw new Error(`PDF export supports up to ${MAX_PRINT_RECORDS.toLocaleString()} records.`); + const ids = new Set(); + for (const record of records) { + if (!record || typeof record.id !== 'string' || ids.has(record.id) || typeof record.values !== 'object' || record.values === null || Array.isArray(record.values)) { + throw new Error('Internal row identities must be unique and values must be a record.'); + } + ids.add(record.id); + const entries = Object.entries(record.values); + if (entries.length > MAX_COLUMNS) throw new Error(`A record supports up to ${MAX_COLUMNS} columns.`); + for (const [key, value] of entries) { + if (!key.trim() || key.length > 200 || typeof value !== 'string' || value.length > MAX_CELL_CHARACTERS) throw new Error(`Invalid or oversized value in column “${key.slice(0, 200)}”.`); + } + } +} + +function cloneRecord(record: AssetRecord): AssetRecord { + return { id: record.id, values: Object.fromEntries(Object.entries(record.values)) }; +} + +function deepFreeze(value: T): T { + if (value && typeof value === 'object' && !Object.isFrozen(value)) { + Object.freeze(value); + for (const child of Object.values(value)) deepFreeze(child); + } + return value; +} + +export function createPrintJob(records: AssetRecord[], template: LabelTemplate, page: PageSettings, options: CreatePrintJobOptions = {}): PrintJob { + if (!Array.isArray(records) || records.length === 0) throw new Error('Add at least one record before creating a print job.'); + validateRecords(records); + validateTemplate(template); + const recordSnapshot = records.map(cloneRecord); + const templateSnapshot = structuredClone(template); + const pageSnapshot = structuredClone(page); + const layout = calculateLayout(templateSnapshot, pageSnapshot, recordSnapshot.length); + const idField = options.idField ?? (template.code.field || ''); + const labels = recordSnapshot.map((record, index) => { + const positionIndex = index % layout.labelsPerPage; + const position = layout.positions[positionIndex]!; + const pageIndex = Math.floor(index / layout.labelsPerPage); + const rawId = idField && Object.hasOwn(record.values, idField) ? record.values[idField] : undefined; + return { + recordId: record.id, + assetId: typeof rawId === 'string' && rawId.trim() ? rawId : record.id, + labelIndex: index + 1, + page: pageIndex + 1, + row: Math.floor(positionIndex / layout.columns) + 1, + column: positionIndex % layout.columns + 1, + payload: interpolatePayload(record, templateSnapshot), + position: { ...position }, + widthMm: templateSnapshot.widthMm, + heightMm: templateSnapshot.heightMm, + }; + }); + const job: PrintJob = { + version: 1, + generatedAt: options.generatedAt ?? new Date().toISOString(), + templateName: options.templateName ?? 'Untitled template', + idField, + records: recordSnapshot, + template: templateSnapshot, + page: pageSnapshot, + layout: structuredClone(layout), + labels, + }; + return deepFreeze(job); +} diff --git a/src/features/calibration/CalibrationPage.tsx b/src/features/calibration/CalibrationPage.tsx new file mode 100644 index 0000000..3493672 --- /dev/null +++ b/src/features/calibration/CalibrationPage.tsx @@ -0,0 +1,109 @@ +import { useEffect, useRef, useState } from 'react'; +import type { StudioPageProps } from '../../studio/contracts'; +import { HelpDetails, ToolFrame } from '../../studio/ui'; +import { FilePicker } from '../../studio/FilePicker'; +import { downloadFile } from '../../core/download'; +import { generateCalibrationPdf } from './calibrationPdf'; +import { clearPrinterProfiles, exportPrinterProfile, importPrinterProfile, listPrinterProfiles, putPrinterProfile, readActivePrinterId, readPrinterProfileFile, removePrinterProfile, setActivePrinterId, type PrinterProfile } from './profiles'; + +export function CalibrationPage({ page, onPageChange, busy }: StudioPageProps) { + const [profiles, setProfiles] = useState([]); + const [activeId, setActiveId] = useState(() => readActivePrinterId()); + const [name, setName] = useState('Office printer'); + const [error, setError] = useState(''); + const [working, setWorking] = useState(false); + const [loadingProfiles, setLoadingProfiles] = useState(true); + const [profileLoadFailed, setProfileLoadFailed] = useState(false); + const pageRef = useRef(page); pageRef.current = page; + const pageChangeRef = useRef(onPageChange); pageChangeRef.current = onPageChange; + const disabled = busy || working || loadingProfiles; + useEffect(() => { + let current = true; + void listPrinterProfiles().then(loaded => { + if (!current) return; + setProfiles(loaded); + const savedId = readActivePrinterId(); + const active = loaded.find(item => item.id === savedId); + setActiveId(active?.id ?? ''); + if (active) pageChangeRef.current({ ...pageRef.current, offsetXMm: active.offsetXMm, offsetYMm: active.offsetYMm }); + else setActivePrinterId(''); + }).catch(cause => { if (current) { setError(cause instanceof Error ? cause.message : 'Could not load printer profiles.'); setProfileLoadFailed(true); } }).finally(() => { if (current) setLoadingProfiles(false); }); + return () => { current = false; }; + }, []); + const selectProfile = (id: string) => { + setActiveId(id); setActivePrinterId(id); + const profile = profiles.find(item => item.id === id); + onPageChange({ ...page, offsetXMm: profile?.offsetXMm ?? 0, offsetYMm: profile?.offsetYMm ?? 0 }); + }; + const saveProfile = async (profile: PrinterProfile) => { + setWorking(true); setError(''); + try { + await putPrinterProfile(profile); + setProfiles(await listPrinterProfiles()); + setActiveId(profile.id); setActivePrinterId(profile.id); + onPageChange({ ...page, offsetXMm: profile.offsetXMm, offsetYMm: profile.offsetYMm }); + } + catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not save printer profile.'); } + finally { setWorking(false); } + }; + const saveCurrentProfile = () => { + const existing = profiles.find(item => item.id === activeId); + void saveProfile({ id: existing?.id ?? crypto.randomUUID(), name: existing?.name ?? name, offsetXMm: page.offsetXMm ?? 0, offsetYMm: page.offsetYMm ?? 0 }); + }; + const renameProfile = async (profile: PrinterProfile) => { + const nextName = window.prompt('Printer profile name', profile.name); + if (nextName === null) return; + await saveProfile({ ...profile, name: nextName }); + }; + const reset = async () => { + onPageChange({ ...page, offsetXMm: 0, offsetYMm: 0 }); + const active = profiles.find(item => item.id === activeId); + if (active) await saveProfile({ ...active, offsetXMm: 0, offsetYMm: 0 }); + }; + const printSheet = async () => { + setWorking(true); setError(''); + try { const bytes = await generateCalibrationPdf(page); downloadFile(bytes.slice().buffer as ArrayBuffer, 'application/pdf', 'printer-calibration.pdf'); } + catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not generate the calibration sheet.'); } + finally { setWorking(false); } + }; + const importFile = async (file?: File) => { + if (!file) return; + setWorking(true); setError(''); + try { + const profile = await importPrinterProfile(await readPrinterProfileFile(file)); + setProfiles(current => [...current.filter(item => item.id !== profile.id), profile]); + setActiveId(profile.id); setActivePrinterId(profile.id); + onPageChange({ ...page, offsetXMm: profile.offsetXMm, offsetYMm: profile.offsetYMm }); + } + catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not import printer profile.'); } + finally { setWorking(false); } + }; + const remove = async () => { + if (!activeId) return; + setWorking(true); setError(''); + try { await removePrinterProfile(activeId); setProfiles(current => current.filter(item => item.id !== activeId)); setActivePrinterId(''); setActiveId(''); onPageChange({ ...page, offsetXMm: 0, offsetYMm: 0 }); } + catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not remove printer profile.'); } + finally { setWorking(false); } + }; + const recoverProfiles = async () => { + if (!window.confirm('Clear all saved printer profiles and reset the printer library?')) return; + setWorking(true); setError(''); + try { await clearPrinterProfiles(); setProfiles([]); setActiveId(''); setActivePrinterId(''); setProfileLoadFailed(false); onPageChange({ ...page, offsetXMm: 0, offsetYMm: 0 }); } + catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not clear the printer profile library.'); } + finally { setWorking(false); } + }; + const active = profiles.find(item => item.id === activeId); + return +
+

Measure printer alignment

Print at 100% / Actual Size. Measure the displacement, then enter the correction in millimeters.

+
+
+
+

Printer profiles

{active && }
+ {active &&

{active.offsetXMm} mm X · {active.offsetYMm} mm Y

}
+
void importFile(file)} disabled={disabled} hint="Printer profile JSON · up to 10,000 bytes"/>
+
+
{error &&

{error}

}{(profileLoadFailed || /corrupt/i.test(error)) && } + Profiles store only printer offsets. Imported asset rows are never stored in profiles. +
; +} diff --git a/src/features/calibration/calibrationPdf.test.ts b/src/features/calibration/calibrationPdf.test.ts new file mode 100644 index 0000000..34d8670 --- /dev/null +++ b/src/features/calibration/calibrationPdf.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; +import { PDFDocument } from 'pdf-lib'; +import { DEFAULT_PAGE } from '../../types'; +import { generateCalibrationPdf } from './calibrationPdf'; + +describe('printer calibration sheet', () => { + it('creates a single vector sheet at the selected physical page size', async () => { + const pdf = await PDFDocument.load(await generateCalibrationPdf(DEFAULT_PAGE)); + expect(pdf.getPageCount()).toBe(1); + expect(pdf.getPages()[0]!.getSize()).toEqual({ width: 210 / 25.4 * 72, height: 297 / 25.4 * 72 }); + }); + it.each([Number.NaN, Number.POSITIVE_INFINITY, -1, 2_001])('rejects unsafe page width %s before ruler generation', async widthMm => { + await expect(generateCalibrationPdf({ ...DEFAULT_PAGE, widthMm })).rejects.toThrow(/Page width/); + }); + it.each([Number.NaN, Number.NEGATIVE_INFINITY, 0, 2_001])('rejects unsafe page height %s before ruler generation', async heightMm => { + await expect(generateCalibrationPdf({ ...DEFAULT_PAGE, heightMm })).rejects.toThrow(/Page height/); + }); + it('rejects custom paper too small for readable calibration marks', async () => { + await expect(generateCalibrationPdf({ ...DEFAULT_PAGE, widthMm: 99 })).rejects.toThrow(/at least 100 × 80 mm/); + await expect(generateCalibrationPdf({ ...DEFAULT_PAGE, heightMm: 79 })).rejects.toThrow(/at least 100 × 80 mm/); + }); + it('generates on the smallest supported paper size', async () => { + const bytes = await generateCalibrationPdf({ ...DEFAULT_PAGE, widthMm: 100, heightMm: 80 }); + expect((await PDFDocument.load(bytes)).getPageCount()).toBe(1); + }); +}); diff --git a/src/features/calibration/calibrationPdf.ts b/src/features/calibration/calibrationPdf.ts new file mode 100644 index 0000000..de2c3c2 --- /dev/null +++ b/src/features/calibration/calibrationPdf.ts @@ -0,0 +1,77 @@ +import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; +import type { PageSettings } from '../../types'; +import { mmToInches } from '../layout/pageLayout'; + +const PT_PER_MM = 72 / 25.4; +export function validateCalibrationPage(page: PageSettings): void { + for (const [name, value] of [['Page width', page.widthMm], ['Page height', page.heightMm]] as const) { + if (!Number.isFinite(value) || value <= 0 || value > 2_000) throw new Error(`${name} must be finite and between 0 and 2,000 mm.`); + } + if (page.widthMm < 100 || page.heightMm < 80) throw new Error('Calibration sheets need paper at least 100 × 80 mm so the title, reference box, rulers, and instructions remain readable.'); +} + +function wrapPdfText(text: string, maxWidth: number, font: Awaited>, size: number): string[] { + const lines: string[] = []; + let line = ''; + for (const word of text.split(/\s+/)) { + const candidate = line ? `${line} ${word}` : word; + if (font.widthOfTextAtSize(candidate, size) <= maxWidth) { line = candidate; continue; } + if (line) lines.push(line); + line = word; + } + if (line) lines.push(line); + return lines; +} +export async function generateCalibrationPdf(page: PageSettings): Promise { + validateCalibrationPage(page); + const width = mmToInches(page.widthMm) * 72; + const height = mmToInches(page.heightMm) * 72; + const doc = await PDFDocument.create(); + doc.setTitle('Printer calibration sheet'); + const sheet = doc.addPage([width, height]); + const font = await doc.embedFont(StandardFonts.Helvetica); + const black = rgb(0.05, 0.08, 0.08); + const mm = (value: number) => value * PT_PER_MM; + const cross = (xMm: number, yMm: number, sizeMm = 3) => { + const x = mm(xMm), y = height - mm(yMm), size = mm(sizeMm); + sheet.drawLine({ start: { x: x - size, y }, end: { x: x + size, y }, thickness: 0.7, color: black }); + sheet.drawLine({ start: { x, y: y - size }, end: { x, y: y + size }, thickness: 0.7, color: black }); + sheet.drawCircle({ x, y, size: 1.2, borderColor: black, borderWidth: 0.6 }); + }; + const inset = 10; + cross(inset, inset); cross(page.widthMm - inset, inset); cross(inset, page.heightMm - inset); cross(page.widthMm - inset, page.heightMm - inset); + cross(page.widthMm / 2, page.heightMm / 2, 5); + const rulerY = page.heightMm - 23; + sheet.drawLine({ start: { x: mm(inset), y: height - mm(rulerY) }, end: { x: mm(page.widthMm - inset), y: height - mm(rulerY) }, thickness: 0.7, color: black }); + for (let tick = inset; tick <= page.widthMm - inset; tick += 1) { + const major = tick % 10 === 0; + const y = height - mm(rulerY); + sheet.drawLine({ start: { x: mm(tick), y }, end: { x: mm(tick), y: y + mm(major ? 4 : 1.5) }, thickness: 0.45, color: black }); + if (major) sheet.drawText(String(tick - inset), { x: mm(tick) + 1, y: y + mm(5), size: 7, font, color: black }); + } + const rulerX = page.widthMm - 23; + sheet.drawLine({ start: { x: mm(rulerX), y: height - mm(inset) }, end: { x: mm(rulerX), y: height - mm(page.heightMm - inset) }, thickness: 0.7, color: black }); + for (let tick = inset; tick <= page.heightMm - inset; tick += 1) { + const major = tick % 10 === 0; + const y = height - mm(tick); + sheet.drawLine({ start: { x: mm(rulerX), y }, end: { x: mm(rulerX - (major ? 4 : 1.5)), y }, thickness: 0.45, color: black }); + if (major) sheet.drawText(String(tick - inset), { x: mm(rulerX - 11), y: y - 2, size: 7, font, color: black }); + } + const box = Math.min(100, page.widthMm - 70, page.heightMm - 60); + if (box > 15) { + const x = (page.widthMm - box) / 2; + const y = (page.heightMm - box) / 2; + sheet.drawRectangle({ x: mm(x), y: height - mm(y + box), width: mm(box), height: mm(box), borderColor: black, borderWidth: 0.8 }); + const dimension = `${box.toFixed(1)} mm`; + const dimensionWidth = mm(box - 4); + const dimensionSize = Math.max(5, Math.min(9, dimensionWidth / font.widthOfTextAtSize(dimension, 1))); + sheet.drawText(dimension, { x: mm(x + 2), y: height - mm(y + box / 2), size: dimensionSize, font, color: black, maxWidth: dimensionWidth }); + } + const title = 'PRINTER CALIBRATION — print at 100% / Actual Size'; + const innerWidth = width - mm(inset * 2); + const titleSize = Math.max(7, Math.min(12, innerWidth / font.widthOfTextAtSize(title, 1))); + sheet.drawText(title, { x: mm(inset), y: height - mm(18), size: titleSize, font, color: black, maxWidth: innerWidth }); + const instructions = wrapPdfText('Measure the center cross and corner marks against the printed page. Enter the measured X/Y shift in Printer Calibration. Ruler ticks are 1 mm apart; numbered marks are 10 mm apart.', innerWidth, font, 7); + instructions.forEach((line, index) => sheet.drawText(line, { x: mm(inset), y: mm(7 + (instructions.length - index - 1) * 3.2), size: 7, font, color: black })); + return doc.save(); +} diff --git a/src/features/calibration/profiles.test.ts b/src/features/calibration/profiles.test.ts new file mode 100644 index 0000000..12d78d5 --- /dev/null +++ b/src/features/calibration/profiles.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; +import { parsePrinterProfile, readPrinterProfileFile, serializePrinterProfile } from './profiles'; + +describe('printer profile document', () => { + it('round-trips settings-only profiles with signed offsets', () => { + const profile = { id: 'printer-1', name: 'Warehouse Zebra', offsetXMm: -1.25, offsetYMm: 0.75 }; + expect(parsePrinterProfile(serializePrinterProfile(profile))).toEqual(profile); + }); + it('strictly rejects unknown keys, unsupported versions, and out-of-range offsets', () => { + expect(() => parsePrinterProfile('{"version":1,"id":"p","name":"P","offsetXMm":0,"offsetYMm":0,"rows":[]}')).toThrow(/unsupported or missing/); + expect(() => parsePrinterProfile('{"version":2,"id":"p","name":"P","offsetXMm":0,"offsetYMm":0}')).toThrow(/version/); + expect(() => serializePrinterProfile({ id: 'p', name: 'P', offsetXMm: -100.1, offsetYMm: 0 })).toThrow(/Horizontal calibration/); + expect(() => serializePrinterProfile({ id: 'p', name: 'P'.repeat(101), offsetXMm: 0, offsetYMm: 0 })).toThrow(/1–100 characters/); + expect(() => parsePrinterProfile('{')).toThrow(/valid JSON/); + }); + it('checks file size before reading profile contents', async () => { + const text = async () => { throw new Error('must not read oversized file'); }; + await expect(readPrinterProfileFile({ size: 10_001, text })).rejects.toThrow(/too large/); + await expect(readPrinterProfileFile({ size: 1, text: async () => serializePrinterProfile({ id: 'p', name: 'Printer', offsetXMm: 0, offsetYMm: 0 }) })).resolves.toContain('"version":1'); + }); +}); diff --git a/src/features/calibration/profiles.ts b/src/features/calibration/profiles.ts new file mode 100644 index 0000000..1d442b7 --- /dev/null +++ b/src/features/calibration/profiles.ts @@ -0,0 +1,69 @@ +import { clearEntries, deleteEntry, listEntries, putEntry } from '../storage/library'; + +export const ACTIVE_PRINTER_KEY = 'asset-tag-studio.active-printer.v1'; +export type PrinterProfile = { id: string; name: string; offsetXMm: number; offsetYMm: number }; +export type PrinterLibraryEntry = { id: string; name: string; json: string }; +const MAX_NAME = 100; +export const MAX_PROFILE_BYTES = 10_000; + +function validateName(name: unknown): asserts name is string { + if (typeof name !== 'string' || !name.trim() || name.length > MAX_NAME) throw new Error(`Printer profile name must contain 1–${MAX_NAME} characters.`); +} +function validateOffset(value: unknown, axis: string): asserts value is number { + if (typeof value !== 'number' || !Number.isFinite(value) || Math.abs(value) > 100) throw new Error(`${axis} calibration must be between -100 and 100 mm.`); +} +export function serializePrinterProfile(profile: PrinterProfile): string { + validateName(profile.name); validateOffset(profile.offsetXMm, 'Horizontal'); validateOffset(profile.offsetYMm, 'Vertical'); + if (typeof profile.id !== 'string' || !profile.id || profile.id.length > 200) throw new Error('Printer profile ID is invalid.'); + return JSON.stringify({ version: 1, id: profile.id, name: profile.name.trim(), offsetXMm: profile.offsetXMm, offsetYMm: profile.offsetYMm }); +} +export function parsePrinterProfile(raw: string): PrinterProfile { + if (typeof raw !== 'string' || new TextEncoder().encode(raw).byteLength > MAX_PROFILE_BYTES) throw new Error('Printer profile document is too large.'); + let value: unknown; + try { value = JSON.parse(raw); } catch { throw new Error('Printer profile must be valid JSON.'); } + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Printer profile must be a JSON object.'); + const doc = value as Record; + if (Object.keys(doc).sort().join(',') !== 'id,name,offsetXMm,offsetYMm,version') throw new Error('Printer profile contains unsupported or missing settings.'); + if (doc.version !== 1) throw new Error('Unsupported printer profile version.'); + validateName(doc.name); validateOffset(doc.offsetXMm, 'Horizontal'); validateOffset(doc.offsetYMm, 'Vertical'); + if (typeof doc.id !== 'string' || !doc.id || doc.id.length > 200) throw new Error('Printer profile ID is invalid.'); + return { id: doc.id, name: doc.name.trim(), offsetXMm: doc.offsetXMm, offsetYMm: doc.offsetYMm }; +} +export async function readPrinterProfileFile(file: Pick): Promise { + if (file.size > MAX_PROFILE_BYTES) throw new Error('Printer profile document is too large.'); + const raw = await file.text(); + parsePrinterProfile(raw); + return raw; +} +export async function listPrinterProfiles(): Promise { + const entries = await listEntries('printers') as PrinterLibraryEntry[]; + return entries.map(entry => { + try { + const profile = parsePrinterProfile(entry.json); + if (entry.id !== profile.id || entry.name !== profile.name) throw new Error('Stored profile metadata does not match its settings.'); + return profile; + } catch { + throw new Error('Saved printer profiles are corrupted. Clear the printer profile library to recover.'); + } + }); +} +export async function putPrinterProfile(profile: PrinterProfile): Promise { + const json = serializePrinterProfile(profile); + await putEntry('printers', { id: profile.id, name: profile.name.trim(), json }); +} +export async function removePrinterProfile(id: string): Promise { await deleteEntry('printers', id); } +export async function clearPrinterProfiles(): Promise { await clearEntries('printers'); } +export function readActivePrinterId(storage?: Pick): string { + try { return storage?.getItem(ACTIVE_PRINTER_KEY) ?? (typeof window === 'undefined' ? '' : window.localStorage.getItem(ACTIVE_PRINTER_KEY) ?? ''); } + catch { return ''; } +} +export function setActivePrinterId(id: string, storage?: Pick): void { + try { (storage ?? (typeof window === 'undefined' ? undefined : window.localStorage))?.setItem(ACTIVE_PRINTER_KEY, id); } catch { /* Current session remains usable. */ } +} +export function exportPrinterProfile(profile: PrinterProfile): string { return serializePrinterProfile(profile); } +export async function importPrinterProfile(raw: string, newId = crypto.randomUUID()): Promise { + const parsed = parsePrinterProfile(raw); + const profile = { ...parsed, id: newId }; + await putPrinterProfile(profile); + return profile; +} diff --git a/src/features/code-inspector/analyze.ts b/src/features/code-inspector/analyze.ts new file mode 100644 index 0000000..4cc8865 --- /dev/null +++ b/src/features/code-inspector/analyze.ts @@ -0,0 +1,17 @@ +import { resolveCodePayload, validatePayloadUri } from '../../core/payload'; +import type { Dataset, LabelTemplate } from '../../types'; +export function analyzeContent(text: string, dataset: Dataset | null, template: LabelTemplate) { + if (!text.trim() || text.length > 2000) throw new Error('Enter nonempty content up to 2,000 characters.'); + const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(text)?.[1].toLowerCase() ?? ''; + const issues: string[] = []; + if (Array.from(text).some(character => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) issues.push('Content includes control characters or line breaks. Check the intended scanner behavior.'); + if (scheme) { + if (['http', 'https', 'fieldlens', 'location'].includes(scheme)) { + try { validatePayloadUri(text, scheme === 'fieldlens' ? 'fieldlens' : scheme === 'location' ? 'location' : 'url'); } catch (reason) { issues.push(reason instanceof Error ? reason.message : 'Invalid URI.'); } + } else issues.push(`Unsupported URI scheme: ${scheme}. Content is displayed as text and never opened.`); + } + let matches = 0; + for (const record of dataset?.records ?? []) { try { if (resolveCodePayload(record, template.code) === text) matches += 1; } catch { /* Invalid dataset rows are diagnosed on Data health. */ } } + if (matches > 1) issues.push(`Duplicate payload: ${matches} rows in this dataset generate this code.`); + return { length: text.length, scheme: scheme || 'Plain text', matches, issues }; +} diff --git a/src/features/code-inspector/client.test.ts b/src/features/code-inspector/client.test.ts new file mode 100644 index 0000000..8b7662b --- /dev/null +++ b/src/features/code-inspector/client.test.ts @@ -0,0 +1,60 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { decodeImageData, decodeImageFile } from './client'; +import { MAX_IMAGE_BYTES } from './image'; +class DecoderWorker { + static current: DecoderWorker; + onmessage: ((event: { data: unknown }) => void) | null = null; + onerror: (() => void) | null = null; + terminate = vi.fn(); postMessage = vi.fn(); + constructor() { DecoderWorker.current = this; } +} +const image = { width: 1, height: 1, data: new Uint8ClampedArray(4) } as ImageData; +afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); }); +describe('bounded decoder lifecycle', () => { + it('keeps file preprocessing inside the timed and cancellable worker', async () => { + vi.useFakeTimers(); vi.stubGlobal('Worker', DecoderWorker); + const file = new Blob(['image']); + const read = vi.spyOn(file, 'arrayBuffer'); + const controller = new AbortController(); + const pending = decodeImageFile(file, controller.signal, 100); + expect(DecoderWorker.current.postMessage).toHaveBeenCalledWith({ file }, []); + expect(read).not.toHaveBeenCalled(); + controller.abort(); + await expect(pending).rejects.toThrow(/cancelled/); + expect(DecoderWorker.current.terminate).toHaveBeenCalledOnce(); + const stalled = decodeImageFile(file, new AbortController().signal, 100); + const assertion = expect(stalled).rejects.toThrow(/timed out/); + await vi.advanceTimersByTimeAsync(101); await assertion; + expect(DecoderWorker.current.terminate).toHaveBeenCalledOnce(); + }); + it('rejects oversized or already cancelled files without starting a worker', async () => { + const constructor = vi.fn(); vi.stubGlobal('Worker', constructor); + await expect(decodeImageFile({ size: MAX_IMAGE_BYTES + 1 } as Blob, new AbortController().signal)).rejects.toThrow(/10 MiB/); + const controller = new AbortController(); controller.abort(); + await expect(decodeImageFile(new Blob(['image']), controller.signal)).rejects.toThrow(/cancelled/); + expect(constructor).not.toHaveBeenCalled(); + }); + + it('terminates on completion and returns only valid results', async () => { + vi.stubGlobal('Worker', DecoderWorker); + const result = decodeImageData(image, new AbortController().signal); + DecoderWorker.current.onmessage!({ data: { result: { text: 'A-1', format: 'QR_CODE' } } }); + await expect(result).resolves.toEqual({ text: 'A-1', format: 'QR_CODE' }); + expect(DecoderWorker.current.terminate).toHaveBeenCalledOnce(); + }); + it('terminates stalled workers on timeout and cancelled operations on abort', async () => { + vi.useFakeTimers(); vi.stubGlobal('Worker', DecoderWorker); + const timeout = decodeImageData(image, new AbortController().signal, 100); + const timeoutAssertion = expect(timeout).rejects.toThrow(/timed out/); await vi.advanceTimersByTimeAsync(101); await timeoutAssertion; + expect(DecoderWorker.current.terminate).toHaveBeenCalledOnce(); + const controller = new AbortController(); const cancelled = decodeImageData(image, controller.signal); controller.abort(); + await expect(cancelled).rejects.toThrow(/cancelled/); expect(DecoderWorker.current.terminate).toHaveBeenCalledOnce(); + }); + it('cleans up worker errors and rejects malformed results', async () => { + vi.stubGlobal('Worker', DecoderWorker); + const error = decodeImageData(image, new AbortController().signal); DecoderWorker.current.onerror!(); + await expect(error).rejects.toThrow(/decoder could not start/); + const malformed = decodeImageData(image, new AbortController().signal); DecoderWorker.current.onmessage!({ data: {} }); + await expect(malformed).rejects.toThrow(/invalid result/); expect(DecoderWorker.current.terminate).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/features/code-inspector/client.ts b/src/features/code-inspector/client.ts new file mode 100644 index 0000000..fef8f43 --- /dev/null +++ b/src/features/code-inspector/client.ts @@ -0,0 +1,32 @@ +import type { DecodedCode } from './decode'; +import { MAX_IMAGE_BYTES } from './image'; +export function decodeImageData(image: ImageData, signal: AbortSignal, timeoutMs = 5000): Promise { + const pixels = image.data.slice().buffer; + return decodeRequest({ pixels, width: image.width, height: image.height }, signal, timeoutMs, [pixels]); +} +export function decodeImageFile(file: Blob, signal: AbortSignal, timeoutMs = 5000): Promise { + if (file.size > MAX_IMAGE_BYTES) return Promise.reject(new Error('Image must be 10 MiB or smaller.')); + return decodeRequest({ file }, signal, timeoutMs); +} +function decodeRequest(request: { file: Blob } | { pixels: ArrayBuffer; width: number; height: number }, signal: AbortSignal, timeoutMs: number, transfer: Transferable[] = []): Promise { + if (signal.aborted) return Promise.reject(new Error('Inspection cancelled.')); + return new Promise((resolve, reject) => { + const worker = new Worker(new URL('./decoder.worker.ts', import.meta.url), { type: 'module' }); + let done = false; + const finish = (error?: Error, result?: DecodedCode) => { + if (done) return; done = true; clearTimeout(timeout); worker.terminate(); signal.removeEventListener('abort', aborted); + if (error) reject(error); else resolve(result!); + }; + const aborted = () => finish(new Error('Inspection cancelled.')); + const timeout = setTimeout(() => finish(new Error('Code inspection timed out. Crop the image around one code and retry.')), timeoutMs); + signal.addEventListener('abort', aborted, { once: true }); + worker.onerror = () => finish(new Error('The local decoder could not start. Reload this page and retry.')); + worker.onmessage = (event: MessageEvent<{ result?: DecodedCode; error?: string }>) => { + if (event.data.error) finish(new Error(event.data.error)); + else if (event.data.result && typeof event.data.result.text === 'string' && ['QR_CODE', 'CODE_128'].includes(event.data.result.format)) finish(undefined, event.data.result); + else finish(new Error('The decoder returned an invalid result.')); + }; + try { worker.postMessage(request, transfer); } + catch { finish(new Error('This image could not be sent to the local decoder.')); } + }); +} diff --git a/src/features/code-inspector/decode.test.ts b/src/features/code-inspector/decode.test.ts new file mode 100644 index 0000000..316feed --- /dev/null +++ b/src/features/code-inspector/decode.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import QRCode from 'qrcode'; +import JsBarcode from 'jsbarcode'; +import { decodePixels } from './decode'; +import { analyzeContent } from './analyze'; +import { DEFAULT_TEMPLATE } from '../../types'; +describe('local code inspector', () => { + it('decodes QR content from actual generated pixels', () => { + const qr = QRCode.create('AST-QR-0042', { errorCorrectionLevel: 'M' }); const side = (qr.modules.size + 8) * 5; + const rgba = new Uint8ClampedArray(side * side * 4).fill(255); + for (let y = 0; y < side; y += 1) for (let x = 0; x < side; x += 1) { + const moduleX = Math.floor(x / 5) - 4; const moduleY = Math.floor(y / 5) - 4; + if (moduleX >= 0 && moduleY >= 0 && moduleX < qr.modules.size && moduleY < qr.modules.size && qr.modules.get(moduleY, moduleX)) { const at = (y * side + x) * 4; rgba[at] = rgba[at + 1] = rgba[at + 2] = 0; } + } + expect(decodePixels(rgba, side, side)).toEqual({ text: 'AST-QR-0042', format: 'QR_CODE' }); + }); + it('rejects invalid pixel buffers and images without codes', () => { + expect(() => decodePixels(new Uint8ClampedArray(4), 9_000_000, 1)).toThrow(/megapixels/); + expect(() => decodePixels(new Uint8ClampedArray(100 * 100 * 4).fill(255), 100, 100)).toThrow(); + }); + it('decodes real Code 128 bars produced by the existing encoder', () => { + const encoded = {} as { encodings: { data: string }[] }; + JsBarcode(encoded, 'AST-128-0042', { format: 'CODE128', displayValue: false }); + const bars = encoded.encodings.map(encoding => encoding.data).join(''); + const width = (bars.length + 40) * 3; const height = 100; + const rgba = new Uint8ClampedArray(width * height * 4).fill(255); + for (let y = 10; y < height - 10; y += 1) for (let x = 0; x < width; x += 1) { + if (bars[Math.floor(x / 3) - 20] === '1') { const at = (y * width + x) * 4; rgba[at] = rgba[at + 1] = rgba[at + 2] = 0; } + } + expect(decodePixels(rgba, width, height)).toEqual({ text: 'AST-128-0042', format: 'CODE_128' }); + }); + it('reports duplicates and unsafe/invalid URIs without following them', () => { + const template = { ...DEFAULT_TEMPLATE, code: { ...DEFAULT_TEMPLATE.code, field: 'ID' } }; + const dataset = { columns: ['ID'], records: [1, 2].map(id => ({ id: String(id), values: { ID: 'fieldlens://asset/A-1' } })), warnings: [] }; + expect(analyzeContent('fieldlens://asset/A-1', dataset, template)).toMatchObject({ matches: 2, scheme: 'fieldlens' }); + expect(analyzeContent('javascript:alert(1)', null, template).issues[0]).toMatch(/Unsupported/); + expect(analyzeContent('fieldlens://asset/A%20B', null, template).issues).not.toEqual([]); + expect(() => analyzeContent('x'.repeat(2001), null, template)).toThrow(/2,000/); + }); +}); diff --git a/src/features/code-inspector/decode.ts b/src/features/code-inspector/decode.ts new file mode 100644 index 0000000..df3c04a --- /dev/null +++ b/src/features/code-inspector/decode.ts @@ -0,0 +1,20 @@ +import { BarcodeFormat, BinaryBitmap, DecodeHintType, HybridBinarizer, MultiFormatReader, RGBLuminanceSource } from '@zxing/library'; +import { MAX_IMAGE_PIXELS } from './limits'; +export type DecodedCode = { text: string; format: 'QR_CODE' | 'CODE_128' }; +export function decodePixels(rgba: Uint8ClampedArray, width: number, height: number): DecodedCode { + if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width * height > MAX_IMAGE_PIXELS || rgba.length !== width * height * 4) throw new Error('Image dimensions or pixel data are invalid. Use an image up to 8 megapixels.'); + const luminance = new Uint8ClampedArray(width * height); + for (let i = 0; i < luminance.length; i += 1) { + const offset = i * 4; const alpha = rgba[offset + 3] / 255; + luminance[i] = Math.round(((rgba[offset] + rgba[offset + 1] * 2 + rgba[offset + 2]) / 4) * alpha + 255 * (1 - alpha)); + } + const reader = new MultiFormatReader(); + try { + const result = reader.decode(new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(luminance, width, height))), new Map([ + [DecodeHintType.POSSIBLE_FORMATS, [BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128]], [DecodeHintType.TRY_HARDER, true], + ])); + const text = result.getText(); + if (!text || text.length > 2000) throw new Error('Decoded content is empty or exceeds 2,000 characters.'); + return { text, format: result.getBarcodeFormat() === BarcodeFormat.QR_CODE ? 'QR_CODE' : 'CODE_128' }; + } finally { reader.reset(); } +} diff --git a/src/features/code-inspector/decoder.worker.ts b/src/features/code-inspector/decoder.worker.ts new file mode 100644 index 0000000..15172cb --- /dev/null +++ b/src/features/code-inspector/decoder.worker.ts @@ -0,0 +1,13 @@ +import { decodePixels } from './decode'; +import { workerFilePixels } from './image'; +self.onmessage = async (event: MessageEvent<{ file?: Blob; pixels: ArrayBuffer; width: number; height: number }>) => { + let image: Pick; + try { + image = event.data.file ? await workerFilePixels(event.data.file) : { data: new Uint8ClampedArray(event.data.pixels), width: event.data.width, height: event.data.height }; + } catch (cause) { + self.postMessage({ error: cause instanceof Error ? cause.message : 'Could not prepare this image for inspection.' }); + return; + } + try { self.postMessage({ result: decodePixels(image.data, image.width, image.height) }); } + catch { self.postMessage({ error: 'No readable QR or Code 128 found. Use a sharper, upright image with the full code and its white border visible.' }); } +}; diff --git a/src/features/code-inspector/image.test.ts b/src/features/code-inspector/image.test.ts new file mode 100644 index 0000000..84541a6 --- /dev/null +++ b/src/features/code-inspector/image.test.ts @@ -0,0 +1,29 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { imageDimensions, previewBlob, workerFilePixels } from './image'; +afterEach(() => vi.unstubAllGlobals()); +describe('image preflight resource bounds', () => { + it('closes native bitmaps on canvas failure and checks decoded dimensions again', async () => { + const bytes = new Uint8Array(24); bytes.set([137, 80, 78, 71, 13, 10, 26, 10]); + const view = new DataView(bytes.buffer); view.setUint32(16, 100); view.setUint32(20, 100); + const bitmap = { width: 100, height: 100, close: vi.fn() }; + vi.stubGlobal('createImageBitmap', vi.fn().mockResolvedValue(bitmap)); + vi.stubGlobal('OffscreenCanvas', class { getContext() { return null; } }); + await expect(workerFilePixels(new Blob([bytes]))).rejects.toThrow(/worker image inspection/); + expect(bitmap.close).toHaveBeenCalledOnce(); + bitmap.width = 9000; bitmap.height = 9000; + await expect(workerFilePixels(new Blob([bytes]))).rejects.toThrow(/8 megapixels/); + expect(bitmap.close).toHaveBeenCalledTimes(2); + }); + + it('rejects unsupported/malformed images before browser image decoding', () => { + expect(() => imageDimensions(new TextEncoder().encode(''))).toThrow(/PNG or JPEG/); + expect(() => imageDimensions(new Uint8Array([255, 216, 255, 192, 0, 1]))).toThrow(); + expect(() => previewBlob('https://example.invalid/image.png')).toThrow(/preview/); + }); + it('checks PNG dimensions and pixel limits before allocating a bitmap', () => { + const bytes = new Uint8Array(24); bytes.set([137, 80, 78, 71, 13, 10, 26, 10]); + const view = new DataView(bytes.buffer); view.setUint32(16, 200); view.setUint32(20, 100); + expect(imageDimensions(bytes)).toEqual({ width: 200, height: 100 }); + view.setUint32(16, 8000); view.setUint32(20, 8000); expect(() => imageDimensions(bytes)).toThrow(/8 megapixels/); + }); +}); diff --git a/src/features/code-inspector/image.ts b/src/features/code-inspector/image.ts new file mode 100644 index 0000000..79f38ec --- /dev/null +++ b/src/features/code-inspector/image.ts @@ -0,0 +1,58 @@ +import { MAX_IMAGE_PIXELS } from './limits'; +export const MAX_IMAGE_BYTES = 10 * 1024 * 1024; +export function imageDimensions(bytes: Uint8Array): { width: number; height: number } { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let width = 0; let height = 0; + if (bytes.length >= 24 && [137, 80, 78, 71, 13, 10, 26, 10].every((byte, index) => bytes[index] === byte)) { + width = view.getUint32(16); height = view.getUint32(20); + } else if (bytes.length > 4 && bytes[0] === 255 && bytes[1] === 216) { + let at = 2; + while (at + 4 < bytes.length) { + if (bytes[at++] !== 255) break; + while (bytes[at] === 255 && at < bytes.length) at += 1; + const marker = bytes[at++]; + if (marker === 217 || marker === 218) break; + if (marker === 1 || (marker >= 208 && marker <= 215)) continue; + if (at + 2 > bytes.length) break; + const length = view.getUint16(at); + if (length < 2 || at + length > bytes.length) break; + if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker) && length >= 8) { height = view.getUint16(at + 3); width = view.getUint16(at + 5); break; } + at += length; + } + } + if (!width || !height) throw new Error('Use a valid PNG or JPEG image. SVG and other formats are not supported.'); + if (width * height > MAX_IMAGE_PIXELS || width > 16000 || height > 16000) throw new Error('Image exceeds 8 megapixels. Crop or resize it before inspecting.'); + return { width, height }; +} +// Called only inside the terminable decoder worker. Its client deadline covers +// file reads, native bitmap decoding, canvas allocation/readback and decoding. +export async function workerFilePixels(file: Blob): Promise { + if (file.size > MAX_IMAGE_BYTES) throw new Error('Image must be 10 MiB or smaller.'); + imageDimensions(new Uint8Array(await file.arrayBuffer())); + let bitmap: ImageBitmap; + try { bitmap = await createImageBitmap(file); } + catch { throw new Error('Could not read this PNG or JPEG. Use a valid image and retry.'); } + try { + if (!bitmap.width || !bitmap.height || bitmap.width * bitmap.height > MAX_IMAGE_PIXELS) throw new Error('Image exceeds 8 megapixels. Crop or resize it before inspecting.'); + const scale = Math.min(1, 2048 / Math.max(bitmap.width, bitmap.height)); + const canvas = new OffscreenCanvas(Math.max(1, Math.round(bitmap.width * scale)), Math.max(1, Math.round(bitmap.height * scale))); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (!context) throw new Error('This browser does not support local worker image inspection.'); + context.fillStyle = '#fff'; context.fillRect(0, 0, canvas.width, canvas.height); context.drawImage(bitmap, 0, 0, canvas.width, canvas.height); + return context.getImageData(0, 0, canvas.width, canvas.height); + } finally { bitmap.close(); } +} +export function sourcePixels(source: CanvasImageSource, width: number, height: number): ImageData { + if (!width || !height || width * height > MAX_IMAGE_PIXELS) throw new Error('Image dimensions are unsupported.'); + const scale = Math.min(1, 2048 / Math.max(width, height)); + const canvas = document.createElement('canvas'); canvas.width = Math.max(1, Math.round(width * scale)); canvas.height = Math.max(1, Math.round(height * scale)); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (!context) throw new Error('This browser does not support local image inspection.'); + context.fillStyle = '#fff'; context.fillRect(0, 0, canvas.width, canvas.height); context.drawImage(source, 0, 0, canvas.width, canvas.height); + return context.getImageData(0, 0, canvas.width, canvas.height); +} +export function previewBlob(dataUrl: string): Blob { + if (!dataUrl.startsWith('data:image/png;base64,') || dataUrl.length > 16 * 1024 * 1024) throw new Error('Generate a PNG label preview first.'); + const bytes = Uint8Array.from(atob(dataUrl.slice('data:image/png;base64,'.length)), character => character.charCodeAt(0)); + return new Blob([bytes], { type: 'image/png' }); +} diff --git a/src/features/code-inspector/limits.ts b/src/features/code-inspector/limits.ts new file mode 100644 index 0000000..8e2600c --- /dev/null +++ b/src/features/code-inspector/limits.ts @@ -0,0 +1 @@ +export const MAX_IMAGE_PIXELS = 8_000_000; diff --git a/src/features/data-health/logic.test.ts b/src/features/data-health/logic.test.ts new file mode 100644 index 0000000..eeafe3f --- /dev/null +++ b/src/features/data-health/logic.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import type { Dataset } from '../../types'; +import { auditDataset, previewHealthFix } from './logic'; + +const dataset: Dataset = { columns: ['Asset ID', 'Serial', 'Name', 'Empty'], warnings: [], importAudit: { sourceHeaders: [' Asset ID ', 'Serial', 'Name', 'Empty'], removedEmptyRows: 2 }, records: [ + { id: 'r1', values: { 'Asset ID': ' A-1 ', Serial: 'S1', Name: 'Pump', Empty: '' } }, + { id: 'r2', values: { 'Asset ID': 'A-1', Serial: 'S1', Name: '', Empty: '' } }, +] }; + +describe('data health', () => { + it('returns structured bounded duplicate, blank, empty, whitespace and header findings', () => { + const findings = auditDataset(dataset, 'Asset ID', 'Serial', 'Name'); + expect(findings.some(item => item.code === 'duplicate-id' && item.rowIds?.join(',') === 'r1,r2')).toBe(true); + expect(findings.some(item => item.code === 'duplicate-serial')).toBe(true); + expect(findings.some(item => item.code === 'blank-name' && item.rowIds?.[0] === 'r2')).toBe(true); + expect(findings.some(item => item.code === 'empty-column' && item.column === 'Empty')).toBe(true); + expect(findings.some(item => item.code === 'empty-rows')).toBe(true); + expect(findings.some(item => item.code === 'header-whitespace')).toBe(true); + expect(findings.length).toBeLessThanOrEqual(100); + }); + it('previews trim and header fixes immutably and emits a column map', () => { + const trim = previewHealthFix(dataset, 'trim'); + expect(trim.dataset.records[0]?.values['Asset ID']).toBe('A-1'); + expect(dataset.records[0]?.values['Asset ID']).toBe(' A-1 '); + const headers = previewHealthFix(dataset, 'headers'); + expect(headers.dataset.columns[0]).toBe('Asset ID'); + expect(headers.columnMap?.['Asset ID']).toBe('Asset ID'); + }); + it('blocks fixes that would remove every column or create duplicate names', () => { + expect(() => previewHealthFix({ ...dataset, records: dataset.records.map(row => ({ ...row, values: { 'Asset ID': '', Serial: '', Name: '', Empty: '' } })) }, 'empty-columns')).toThrow(/At least one column/); + expect(() => previewHealthFix({ ...dataset, columns: [' a ', 'a'], records: dataset.records.map(row => ({ ...row, values: { ...row.values, ' a ': '', a: '' } })) }, 'headers')).toThrow(/duplicate names/); + }); + it('counts large duplicate groups while retaining at most twenty row references', () => { + const manyRows: Dataset = { + columns: ['ID'], warnings: [], + records: Array.from({ length: 20_000 }, (_, index) => ({ id: `row-${index + 1}`, values: { ID: 'duplicate' } })), + }; + const finding = auditDataset(manyRows, 'ID').find(item => item.code === 'duplicate-id'); + expect(finding?.message).toContain('20000 rows'); + expect(finding?.rowIds).toEqual(Array.from({ length: 20 }, (_, index) => `row-${index + 1}`)); + }); +}); diff --git a/src/features/data-health/logic.ts b/src/features/data-health/logic.ts new file mode 100644 index 0000000..c6f7d70 --- /dev/null +++ b/src/features/data-health/logic.ts @@ -0,0 +1,90 @@ +import type { Dataset } from '../../types'; +import { cloneValues, readValue } from '../../core/dataset'; +import { MAX_COLUMNS } from '../import/limits'; +import { resolveCodePayload } from '../../core/payload'; + +export type HealthFinding = { code: string; severity: 'warning' | 'error'; message: string; rowIds?: string[]; column?: string }; +export type HealthFix = 'trim' | 'headers' | 'empty-columns' | 'case'; +export type HealthPreview = { dataset: Dataset; columnMap?: Record; changed: number; description: string }; +const FINDING_LIMIT = 100; +const LONG_VALUE = 500; +const addBounded = (items: HealthFinding[], item: HealthFinding) => { if (items.length < FINDING_LIMIT) items.push(item); }; + +export function auditDataset(dataset: Dataset, idField = '', serialField = '', nameField = '', payloadCode?: Parameters[1]): HealthFinding[] { + const findings: HealthFinding[] = []; + const duplicates = (field: string, code: string, label: string) => { + if (!dataset.columns.includes(field)) return; + const groups = new Map(); + for (const row of dataset.records) { + const value = readValue(row, field).trim(); + if (!value) continue; + const group = groups.get(value); + if (group) { group.count += 1; if (group.rowIds.length < 20) group.rowIds.push(row.id); } + else groups.set(value, { count: 1, rowIds: [row.id] }); + } + for (const [value, group] of groups) if (group.count > 1) addBounded(findings, { code, severity: 'error', column: field, rowIds: group.rowIds, message: `${group.count} rows share ${label} “${value}”.` }); + }; + duplicates(idField, 'duplicate-id', 'identifier'); duplicates(serialField, 'duplicate-serial', 'serial number'); + for (const row of dataset.records) { + if (idField && dataset.columns.includes(idField) && !readValue(row, idField).trim()) addBounded(findings, { code: 'blank-id', severity: 'error', rowIds: [row.id], column: idField, message: `Row ${row.id} has a blank identifier.` }); + if (serialField && dataset.columns.includes(serialField) && !readValue(row, serialField).trim()) addBounded(findings, { code: 'blank-serial', severity: 'warning', rowIds: [row.id], column: serialField, message: `Row ${row.id} has a blank serial number.` }); + if (nameField && dataset.columns.includes(nameField) && !readValue(row, nameField).trim()) addBounded(findings, { code: 'blank-name', severity: 'warning', rowIds: [row.id], column: nameField, message: `Row ${row.id} has a blank asset name.` }); + for (const column of dataset.columns) { + const value = readValue(row, column); + if (value.length > LONG_VALUE) addBounded(findings, { code: 'long-value', severity: 'warning', rowIds: [row.id], column, message: `Row ${row.id} has ${value.length} characters in “${column}”.` }); + if (value !== value.trim()) addBounded(findings, { code: 'whitespace', severity: 'warning', rowIds: [row.id], column, message: `Row ${row.id} has leading or trailing whitespace in “${column}”.` }); + if (value && value !== value.toLocaleLowerCase() && value !== value.toLocaleUpperCase()) addBounded(findings, { code: 'inconsistent-case', severity: 'warning', rowIds: [row.id], column, message: `Row ${row.id} uses mixed casing in “${column}”.` }); + } + if (payloadCode) { + try { resolveCodePayload(row, payloadCode); } catch (error) { addBounded(findings, { code: 'invalid-payload', severity: 'error', rowIds: [row.id], message: error instanceof Error ? error.message : 'Payload could not be resolved.' }); } + } + } + for (const column of dataset.columns) if (dataset.records.every(row => !readValue(row, column).trim())) addBounded(findings, { code: 'empty-column', severity: 'warning', column, message: `Column “${column}” is empty.` }); + if (dataset.importAudit?.removedEmptyRows) addBounded(findings, { code: 'empty-rows', severity: 'warning', message: `${dataset.importAudit.removedEmptyRows} fully empty row(s) were skipped during import.` }); + const sourceHeaders = dataset.importAudit?.sourceHeaders ?? dataset.columns; + const headerGroups = new Map(); + for (const [index, source] of sourceHeaders.entries()) { + const normalized = source.trim().replace(/\s+/g, ' '); + const column = dataset.columns[index]; + if (normalized) headerGroups.set(normalized.toLocaleLowerCase(), [...(headerGroups.get(normalized.toLocaleLowerCase()) ?? []), index]); + if (normalized !== source) addBounded(findings, { code: 'header-whitespace', severity: 'warning', column, message: `Imported header “${source}” contains edge or repeated whitespace.` }); + if (normalized && normalized !== normalized.toLocaleLowerCase() && normalized !== normalized.toLocaleUpperCase()) addBounded(findings, { code: 'header-case', severity: 'warning', column, message: `Header “${source}” has mixed casing.` }); + } + for (const indexes of headerGroups.values()) if (indexes.length > 1) addBounded(findings, { code: 'duplicate-header', severity: 'error', message: `Headers ${indexes.map(index => `“${sourceHeaders[index]}”`).join(', ')} match when whitespace and casing are normalized.` }); + return findings; +} + +export function previewHealthFix(dataset: Dataset, fix: HealthFix, column?: string): HealthPreview { + let columns = [...dataset.columns]; + let columnMap: Record | undefined; + let changed = 0; + if (fix === 'empty-columns') { + const keep = columns.filter(name => dataset.records.some(row => readValue(row, name).trim())); + if (!keep.length) throw new Error('At least one column must remain.'); + changed = columns.length - keep.length; columns = keep; + } else if (fix === 'headers') { + columnMap = Object.create(null) as Record; + columns = columns.map(name => { const next = name.trim().replace(/\s+/g, ' '); if (!next) throw new Error('Header fixes cannot create a blank column name.'); columnMap![name] = next; if (next !== name) changed += 1; return next; }); + if (new Set(columns).size !== columns.length) throw new Error('Header fixes would create duplicate names. Resolve those columns before applying.'); + if (columns.some(name => name.length > 200)) throw new Error('A normalized header exceeds 200 characters.'); + if (columns.length > MAX_COLUMNS) throw new Error('Too many columns.'); + } + const records = dataset.records.map(row => { + const values = cloneValues(row.values); + if (fix === 'trim') for (const name of dataset.columns) { const next = readValue(row, name).trim(); if (next !== readValue(row, name)) { values[name] = next; changed += 1; } } + if (fix === 'case') { + if (!column || !dataset.columns.includes(column)) throw new Error('Choose a column to normalize.'); + const next = readValue(row, column).toLocaleUpperCase(); if (next !== readValue(row, column)) { values[column] = next; changed += 1; } + } + if (fix === 'headers') { + const remapped = Object.create(null) as Record; + for (const old of dataset.columns) remapped[columnMap![old]!] = values[old]!; + return { ...row, values: remapped }; + } + return { ...row, values }; + }); + const nextDataset = { ...dataset, columns, records, + ...(fix === 'headers' && dataset.importAudit ? { importAudit: { ...dataset.importAudit, sourceHeaders: columns } } : {}), + }; + return { dataset: nextDataset, columnMap, changed, description: `${fix === 'headers' ? 'Normalize headers' : fix === 'empty-columns' ? 'Remove empty columns' : fix === 'case' ? `Normalize ${column} casing` : 'Trim cell whitespace'} (${changed} change${changed === 1 ? '' : 's'})` }; +} diff --git a/src/features/export/pdf.test.ts b/src/features/export/pdf.test.ts index 054c32d..996027d 100644 --- a/src/features/export/pdf.test.ts +++ b/src/features/export/pdf.test.ts @@ -1,8 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { PDFDocument } from 'pdf-lib'; +import { PDFDocument, PDFPage } from 'pdf-lib'; import type { AssetRecord, LabelTemplate, PageSettings } from '../../types'; import { DEFAULT_TEMPLATE } from '../../types'; -import { generatePdf } from './pdf'; +import { generatePdf, generatePrintJobPdf } from './pdf'; +import { createPrintJob } from '../../core/printJob'; +import { manifestFromPrintJob } from '../manifest/manifest'; const renderLabel = vi.hoisted(() => vi.fn()); vi.mock('../labels/renderer', async () => { @@ -21,6 +23,25 @@ const records: AssetRecord[] = [{ id: 'a', values: { ID: 'A' } }, { id: 'b', val afterEach(() => renderLabel.mockReset()); describe('PDF generation', () => { + it('draws the exact signed-calibrated manifest placements across pages', async () => { + renderLabel.mockResolvedValue(onePixelPng); + const job = createPrintJob(records, template, { ...page, offsetXMm: 0.5, offsetYMm: -0.25 }); + const manifest = manifestFromPrintJob(job); + const draw = vi.spyOn(PDFPage.prototype, 'drawImage'); + try { + const bytes = await generatePrintJobPdf(job); + expect((await PDFDocument.load(bytes)).getPageCount()).toBe(2); + expect(draw).toHaveBeenCalledTimes(manifest.records.length); + manifest.records.forEach((row, index) => { + const placement = draw.mock.calls[index]![1]!; + expect(placement.x).toBeCloseTo(row.xMm * 72 / 25.4, 10); + expect(placement.y).toBeCloseTo(page.heightMm * 72 / 25.4 - (row.yMm + template.heightMm) * (72 / 25.4), 10); + expect(placement.width).toBeCloseTo(template.widthMm * (72 / 25.4), 10); + expect(placement.height).toBeCloseTo(template.heightMm * (72 / 25.4), 10); + }); + } finally { draw.mockRestore(); } + }); + it('keeps physical page dimensions, pagination, and progress ordering', async () => { renderLabel.mockResolvedValue(onePixelPng); const progress: number[] = []; diff --git a/src/features/export/pdf.ts b/src/features/export/pdf.ts index f0b9da3..2f07735 100644 --- a/src/features/export/pdf.ts +++ b/src/features/export/pdf.ts @@ -1,7 +1,8 @@ import { PDFDocument, type PDFImage } from 'pdf-lib'; import type { AssetRecord, LabelTemplate, PageSettings } from '../../types'; -import { calculateLayout, mmToInches } from '../layout/pageLayout'; +import { mmToInches } from '../layout/pageLayout'; import { renderLabel, validateTemplate } from '../labels/renderer'; +import { createPrintJob, type PrintJob } from '../../core/printJob'; export type PdfExportOptions = { onProgress?: (completed: number, total: number) => void; @@ -34,12 +35,18 @@ export async function generatePdf( page: PageSettings, options: PdfExportOptions = {}, ): Promise { + const job = createPrintJob(records, template, page); + return generatePrintJobPdf(job, options); +} + +export async function generatePrintJobPdf(job: PrintJob, options: PdfExportOptions = {}): Promise { + const { records, template, page } = job; if (!Array.isArray(records) || records.length > MAX_RECORDS) { throw new Error(`PDF export supports up to ${MAX_RECORDS.toLocaleString()} records.`); } if (records.length === 0) throw new Error('Add at least one record before creating a PDF.'); validateTemplate(template); - const layout = calculateLayout(template, page, records.length); + if (job.labels.length !== records.length) throw new Error('Print job placements do not match its records.'); checkCancelled(options.signal); const pdf = await PDFDocument.create(); pdf.setTitle('Asset Tag Studio labels'); @@ -50,13 +57,18 @@ export async function generatePdf( let imageCacheBytes = 0; let renderCacheBytes = 0; let completed = 0; + let currentPageNumber = 0; let currentPage = pdf.addPage([pageWidth, pageHeight]); options.onProgress?.(0, records.length); for (let index = 0; index < records.length; index++) { checkCancelled(options.signal); - const positionIndex = index % layout.labelsPerPage; - if (index > 0 && positionIndex === 0) currentPage = pdf.addPage([pageWidth, pageHeight]); + const placement = job.labels[index]!; + if (placement.labelIndex !== index + 1 || placement.page < 1 || placement.page > job.layout.pages) throw new Error('Print job placements are invalid.'); + if (placement.page !== currentPageNumber) { + if (currentPageNumber > 0) currentPage = pdf.addPage([pageWidth, pageHeight]); + currentPageNumber = placement.page; + } const record = records[index]!; const cacheKey = recordKey(record, template); let dataUrl = renderCache.get(cacheKey); @@ -106,7 +118,7 @@ export async function generatePdf( } cachedImage = { image, cost: size }; } - const position = layout.positions[positionIndex]!; + const position = placement.position; currentPage.drawImage(cachedImage.image, { x: position.xMm * MM_TO_POINTS, y: pageHeight - (position.yMm + template.heightMm) * MM_TO_POINTS, diff --git a/src/features/id-generator/logic.test.ts b/src/features/id-generator/logic.test.ts new file mode 100644 index 0000000..39cf9f4 --- /dev/null +++ b/src/features/id-generator/logic.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest'; +import type { Dataset } from '../../types'; +import { applyIdsToColumn, previewIds, type IdGeneratorOptions } from './logic'; + +const dataset: Dataset = { columns: ['Asset ID', 'Type'], warnings: [], records: [ + { id: 'r1', values: { 'Asset ID': '', Type: 'PC' } }, { id: 'r2', values: { 'Asset ID': 'KEEP', Type: 'PC' } }, { id: 'r3', values: { 'Asset ID': 'PC-002', Type: 'PC' } }, +] }; +const options: IdGeneratorOptions = { column: 'Asset ID', pattern: '{Type}-{sequence}', prefix: '', suffix: '', start: 1, padding: 3, year: '2026', date: '2026-10-04', selectedIds: new Set(['r1']), blankOnly: true, overwrite: false }; + +describe('ID generator', () => { + it('previews source tokens and only targets selected blank rows', () => { + expect(previewIds(dataset, options)).toEqual([{ rowId: 'r1', before: '', after: 'PC-001', status: 'ready', message: undefined }]); + }); + it('flags collision with a nonselected row and preserves source immutability', () => { + const preview = previewIds(dataset, { ...options, pattern: 'KEEP' }); + expect(preview[0]?.status).toBe('collision'); + expect(() => applyIdsToColumn(dataset, 'Asset ID', preview)).toThrow(/collisions/); + expect(dataset.records[0]?.values['Asset ID']).toBe(''); + }); + it('requires explicit overwrite and keeps internal identities and unselected values', () => { + const preview = previewIds(dataset, { ...options, selectedIds: new Set(['r2']), blankOnly: false, overwrite: true, pattern: 'NEW-{year}-{sequence}' }); + const changed = applyIdsToColumn(dataset, 'Asset ID', preview); + expect(changed.records.map(row => row.id)).toEqual(['r1', 'r2', 'r3']); + expect(changed.records[1]?.values['Asset ID']).toBe('NEW-2026-001'); + expect(dataset.records[1]?.values['Asset ID']).toBe('KEEP'); + }); + it('does not target populated selected rows with the safe blank-only defaults', () => { + expect(previewIds(dataset, { ...options, selectedIds: new Set(['r2']) })).toEqual([]); + }); + it('rejects missing interpolation columns and unsafe empty token shapes', () => { + expect(() => previewIds(dataset, { ...options, pattern: '{missing}' })).toThrow(/not a dataset column/); + expect(() => previewIds(dataset, { ...options, pattern: '{}' })).toThrow(/Use tokens/); + }); +}); diff --git a/src/features/id-generator/logic.ts b/src/features/id-generator/logic.ts new file mode 100644 index 0000000..6950e8e --- /dev/null +++ b/src/features/id-generator/logic.ts @@ -0,0 +1,54 @@ +import type { Dataset } from '../../types'; +import { cloneValues, readValue } from '../../core/dataset'; + +export type IdGeneratorOptions = { column: string; pattern: string; prefix: string; suffix: string; start: number; padding: number; year: string; date: string; selectedIds: ReadonlySet; blankOnly: boolean; overwrite: boolean }; +export type IdPreviewRow = { rowId: string; before: string; after: string; status: 'ready' | 'collision' | 'unchanged'; message?: string }; +const TOKEN = /\{([^{}]+)\}/g; +const MAX_PREVIEW = 5000; + +export function previewIds(dataset: Dataset, options: IdGeneratorOptions): IdPreviewRow[] { + if (!dataset.columns.includes(options.column)) throw new Error('Choose an existing identifier column.'); + if (!Number.isInteger(options.start) || options.start < 0 || options.start > 999_999_999) throw new Error('Sequence start must be from 0 to 999,999,999.'); + if (!Number.isInteger(options.padding) || options.padding < 1 || options.padding > 12) throw new Error('Zero padding must be from 1 to 12 digits.'); + if (options.pattern.length > 500 || options.prefix.length > 200 || options.suffix.length > 200) throw new Error('Pattern, prefix, or suffix is too long.'); + if (/[{}]/.test(options.pattern.replace(TOKEN, '')) || [...options.pattern.matchAll(TOKEN)].some(match => !match[1]!.trim())) throw new Error('Use tokens like {sequence}, {year}, {date}, or {Column Name}.'); + const selected = options.selectedIds; + const targets = dataset.records.filter(record => selected.has(record.id) && (!options.blankOnly || !readValue(record, options.column).trim()) && (options.overwrite || !readValue(record, options.column).trim())); + if (targets.length > MAX_PREVIEW) throw new Error(`Select no more than ${MAX_PREVIEW} rows for a preview.`); + const targetIds = new Set(targets.map(row => row.id)); + const existing = new Set(); + for (const record of dataset.records) { + if (targetIds.has(record.id)) continue; + const value = readValue(record, options.column).trim(); + if (value) existing.add(value); + } + const generated = new Set(); + return targets.map((record, index) => { + const sequence = String(options.start + index).padStart(options.padding, '0'); + const pattern = options.pattern.replace(TOKEN, (_token, key: string) => { + if (key === 'sequence') return sequence; + if (key === 'year') return options.year; + if (key === 'date') return options.date; + if (!Object.hasOwn(record.values, key)) throw new Error(`Pattern token “{${key}}” is not a dataset column.`); + return readValue(record, key).trim(); + }); + const after = `${options.prefix}${pattern}${options.suffix}`; + if (!after.trim()) throw new Error(`Row ${record.id} would receive an empty identifier.`); + const collision = existing.has(after.trim()) || generated.has(after.trim()); + generated.add(after.trim()); + return { rowId: record.id, before: readValue(record, options.column), after, status: collision ? 'collision' : 'ready', message: collision ? 'Identifier already exists in the dataset or this preview.' : undefined }; + }); +} + +export function applyIdsToColumn(dataset: Dataset, column: string, preview: readonly IdPreviewRow[], allowCollisions = false): Dataset { + if (!dataset.columns.includes(column)) throw new Error('Choose an existing identifier column.'); + if (!allowCollisions && preview.some(row => row.status === 'collision')) throw new Error('Resolve identifier collisions before applying.'); + const byId = new Map(preview.map(row => [row.rowId, row])); + return { ...dataset, records: dataset.records.map(record => { + const row = byId.get(record.id); + if (!row) return record; + const values = cloneValues(record.values); + values[column] = row.after; + return { ...record, values }; + }) }; +} diff --git a/src/features/import/normalize.ts b/src/features/import/normalize.ts index b18f799..352fdec 100644 --- a/src/features/import/normalize.ts +++ b/src/features/import/normalize.ts @@ -36,6 +36,7 @@ export function normalizeRows(rows: unknown[][]): Dataset { if (!header) throw new ImportError(`Header ${index + 1} is empty. Give every column a name.`); return header; }); + const sourceHeaders = headerRow.map((cell, index) => stringifyCell(cell, firstNonEmpty + 1, index + 1)); const seen = new Set(); for (const header of columns) { if (seen.has(header)) throw new ImportError(`Duplicate header "${header}". Column names must be unique.`); @@ -43,13 +44,14 @@ export function normalizeRows(rows: unknown[][]): Dataset { } const records: AssetRecord[] = []; + let removedEmptyRows = 0; const warnings: string[] = []; const emptyColumns = new Set(columns); let longCellCount = 0; const longCellExamples: string[] = []; for (let rowIndex = firstNonEmpty + 1; rowIndex < rows.length; rowIndex += 1) { const row = rows[rowIndex]; - if (!Array.isArray(row) || isBlankRow(row)) continue; + if (!Array.isArray(row) || isBlankRow(row)) { removedEmptyRows += 1; continue; } if (records.length >= MAX_ROWS) throw new ImportError(`The file exceeds the ${MAX_ROWS.toLocaleString()} data row limit.`); if (row.length > MAX_COLUMNS) throw new ImportError(`Row ${rowIndex + 1} exceeds the ${MAX_COLUMNS} column limit.`); if (row.length > columns.length && row.slice(columns.length).some((value) => value != null && String(value).trim() !== '')) { @@ -73,7 +75,7 @@ export function normalizeRows(rows: unknown[][]): Dataset { const remainder = longCellCount - longCellExamples.length; warnings.push(`${longCellCount} cell${longCellCount === 1 ? '' : 's'} exceed ${LONG_CELL_WARNING_CHARACTERS} characters (${longCellExamples.join('; ')}${remainder ? `; and ${remainder} more` : ''}).`); } - return { columns, records, warnings }; + return { columns, records, warnings, importAudit: { sourceHeaders, removedEmptyRows } }; } export function validateIdentifiers(dataset: Dataset, field: string): string[] { diff --git a/src/features/import/parser.test.ts b/src/features/import/parser.test.ts index 7541662..621e3c5 100644 --- a/src/features/import/parser.test.ts +++ b/src/features/import/parser.test.ts @@ -46,6 +46,12 @@ describe('row normalization', () => { expect(dataset.columns).toEqual(['__proto__', 'constructor']); }); + it('records source header whitespace and counts skipped empty rows without changing duplicate rejection', () => { + const data = normalizeRows([[' Asset ID ', 'Name'], ['A-1', 'Pump'], ['', ' '], ['A-2', 'Valve']]); + expect(data.importAudit).toEqual({ sourceHeaders: [' Asset ID ', 'Name'], removedEmptyRows: 1 }); + expect(getMessage(() => normalizeRows([[' ID ', 'ID'], ['a', 'b']]))).toMatch(/Duplicate header/); + }); + it('warns for empty columns and rejects data beyond the header', () => { expect(normalizeRows([['id', 'unused'], ['1', '']]).warnings).toEqual(['Empty columns: unused.']); expect(getMessage(() => normalizeRows([['id'], ['1', '', 'extra']]))).toMatch(/beyond the 1 declared headers/); diff --git a/src/features/integrations/fieldlens/export.test.ts b/src/features/integrations/fieldlens/export.test.ts new file mode 100644 index 0000000..9297fb7 --- /dev/null +++ b/src/features/integrations/fieldlens/export.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_PAGE, DEFAULT_TEMPLATE, type Dataset } from '../../../types'; +import { fieldLensCsv, prepareFieldLensJob, type FieldLensMapping } from './export'; + +const dataset: Dataset = { columns: ['ID', 'Name', 'Kind', 'Serial', 'Location'], warnings: [], records: [ + { id: 'row-a', values: { ID: 'PC-001', Name: 'Laptop', Kind: 'Computer', Serial: 'S-1', Location: 'Room 1' } }, + { id: 'row-b', values: { ID: '=SUM(A1:A2)', Name: 'Desktop', Kind: 'Computer', Serial: '', Location: '' } }, +] }; +const mapping: FieldLensMapping = { idField: 'ID', nameField: 'Name', assetTypeField: 'Kind', serialField: 'Serial', locationField: 'Location' }; + +describe('FieldLens print package', () => { + it('uses one frozen record snapshot for QR payload IDs and CSV asset_id values', () => { + const job = prepareFieldLensJob(dataset, new Set(['row-a']), mapping, DEFAULT_TEMPLATE, DEFAULT_PAGE); + expect(Object.isFrozen(job)).toBe(true); + expect(Object.isFrozen(job.records[0]!.values)).toBe(true); + expect(job.labels[0]!.payload).toBe('fieldlens://asset/PC-001'); + expect(fieldLensCsv(job, mapping)).toContain('"PC-001","Laptop","Computer","S-1","Room 1"'); + expect(() => { job.records[0]!.values.ID = 'changed'; }).toThrow(); + }); + it('rejects duplicates, missing mappings, formula-leading IDs, and incompatible URI values', () => { + expect(() => prepareFieldLensJob(dataset, new Set(), mapping, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/Select at least one/); + expect(() => prepareFieldLensJob(dataset, new Set(['not-current']), mapping, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/no longer in the current dataset/); + expect(() => prepareFieldLensJob({ ...dataset, records: [dataset.records[0]!, { ...dataset.records[0]!, id: 'row-c' }] }, new Set(['row-a', 'row-c']), mapping, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/appears more than once/); + expect(() => prepareFieldLensJob(dataset, new Set(['row-a']), { ...mapping, nameField: '' }, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/Map a valid name/); + expect(() => prepareFieldLensJob(dataset, new Set(['row-b']), mapping, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/formula character/); + const badId = { ...dataset, records: [{ ...dataset.records[0]!, values: { ...dataset.records[0]!.values, ID: 'A/B' } }] }; + expect(() => prepareFieldLensJob(badId, new Set(['row-a']), mapping, DEFAULT_TEMPLATE, DEFAULT_PAGE)).toThrow(/unescaped identifier/); + }); +}); diff --git a/src/features/integrations/fieldlens/export.ts b/src/features/integrations/fieldlens/export.ts new file mode 100644 index 0000000..e173c45 --- /dev/null +++ b/src/features/integrations/fieldlens/export.ts @@ -0,0 +1,41 @@ +import type { Dataset, LabelTemplate, PageSettings } from '../../../types'; +import { createPrintJob, type PrintJob } from '../../../core/printJob'; +import { csvText } from '../../../core/download'; +import { readValue, validateDataset } from '../../../core/dataset'; + +export type FieldLensMapping = { idField: string; nameField: string; assetTypeField: string; serialField?: string; locationField?: string }; +const FORMULA_ID = /^[\s]*[=+@-]/; +export function prepareFieldLensJob(dataset: Dataset, selectedIds: ReadonlySet, mapping: FieldLensMapping, template: LabelTemplate, page: PageSettings): PrintJob { + validateDataset(dataset); + for (const [label, field] of [['Asset ID', mapping.idField], ['Name', mapping.nameField], ['Asset type', mapping.assetTypeField]] as const) { + if (!field || !dataset.columns.includes(field)) throw new Error(`Map a valid ${label.toLowerCase()} column before exporting to FieldLens.`); + } + for (const [label, field] of [['Serial', mapping.serialField], ['Location', mapping.locationField]] as const) { + if (field && !dataset.columns.includes(field)) throw new Error(`Map a valid ${label.toLowerCase()} column or leave it unmapped.`); + } + if (!selectedIds.size) throw new Error('Select at least one asset for FieldLens export.'); + const records = dataset.records.filter(record => selectedIds.has(record.id)); + if (records.length !== selectedIds.size) throw new Error('One or more selected rows are no longer in the current dataset.'); + const seen = new Set(); + for (const record of records) { + const id = readValue(record, mapping.idField); + if (!id.trim()) throw new Error(`Record “${record.id}” has no FieldLens asset ID.`); + if (FORMULA_ID.test(id)) throw new Error(`FieldLens ID “${id}” starts with a spreadsheet formula character. Change the ID before export so the QR and CSV retain the same value safely.`); + if (seen.has(id)) throw new Error(`FieldLens asset ID “${id}” appears more than once in the selected rows.`); + seen.add(id); + } + const fieldlensTemplate: LabelTemplate = { + ...structuredClone(template), mode: 'asset', textLayout: 'standard', + code: { ...template.code, type: 'qr', field: mapping.idField, payload: `fieldlens://asset/{${mapping.idField}}`, payloadMode: 'fieldlens' }, + }; + return createPrintJob(records, fieldlensTemplate, page, { templateName: 'FieldLens Asset Labels', idField: mapping.idField }); +} +export function fieldLensCsv(job: PrintJob, mapping: FieldLensMapping): string { + const byId = new Map(job.records.map(record => [record.id, record])); + const rows = job.labels.map(label => { + const record = byId.get(label.recordId); + if (!record || label.payload !== `fieldlens://asset/${label.assetId}`) throw new Error('Print job FieldLens IDs do not match encoded QR identifiers.'); + return [label.assetId, readValue(record, mapping.nameField), readValue(record, mapping.assetTypeField), mapping.serialField ? readValue(record, mapping.serialField) : '', mapping.locationField ? readValue(record, mapping.locationField) : '']; + }); + return csvText([['asset_id', 'name', 'asset_type', 'serial', 'location'], ...rows]); +} diff --git a/src/features/labels/renderer.test.ts b/src/features/labels/renderer.test.ts index f791ddf..241040e 100644 --- a/src/features/labels/renderer.test.ts +++ b/src/features/labels/renderer.test.ts @@ -1,13 +1,16 @@ -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import type { AssetRecord, LabelTemplate } from '../../types'; import { DEFAULT_TEMPLATE } from '../../types'; -import { interpolatePayload, validateTemplate, wrapText } from './renderer'; +import { interpolatePayload, renderLabel, validateTemplate, wrapText } from './renderer'; + +vi.mock('jsbarcode', () => ({ default: (svg: { setAttribute: (name: string, value: string) => void }) => { svg.setAttribute('width', '120'); svg.setAttribute('height', '64'); } })); const template: LabelTemplate = { ...DEFAULT_TEMPLATE, code: { ...DEFAULT_TEMPLATE.code, field: 'Asset ID' }, }; const record: AssetRecord = { id: 'row-1', values: { 'Asset ID': 'A-104', 'Location Name': 'North room' } }; +afterEach(() => vi.unstubAllGlobals()); describe('label template and payload', () => { it('accepts the default physical size and interpolates headers with spaces', () => { @@ -15,6 +18,88 @@ describe('label template and payload', () => { expect(interpolatePayload(record, { ...template, code: { ...template.code, payload: 'ID={Asset ID}; {Location Name}' } })).toBe('ID=A-104; North room'); }); + it('supports text-only labels and shares payload-mode resolution with the core builder', () => { + const textOnly: LabelTemplate = { ...template, mode: 'cable', textLayout: 'mirrored', fields: [{ source: 'Location Name', label: '', fontSize: 10, bold: true }], code: { ...template.code, type: 'none', field: '' } }; + validateTemplate(textOnly); + expect(interpolatePayload(record, textOnly)).toBe(''); + expect(interpolatePayload(record, { ...template, code: { ...template.code, payload: 'https://inventory.test/{Asset ID}', payloadMode: 'url' } })).toBe('https://inventory.test/A-104'); + expect(() => validateTemplate({ ...textOnly, fields: [] })).toThrow(/text field/); + }); + + it('accepts a text-only cable preset when unused barcode settings are zeroed', () => { + const cablePreset: LabelTemplate = { + ...template, + mode: 'cable', textLayout: 'mirrored', widthMm: 70, heightMm: 18, + fields: [{ source: 'Source endpoint', label: 'From', fontSize: 8, bold: true }], + code: { ...template.code, type: 'none', field: '', barcodeHeightMm: 0, barcodeScale: 0 }, + }; + expect(() => validateTemplate(cablePreset)).not.toThrow(); + }); + + it('renders mirrored labels into disjoint half-width panels, including optional codes', async () => { + const textColors: string[] = []; + const fillText = vi.fn(() => { textColors.push(context.fillStyle as string); }); + const drawImage = vi.fn(); + const translate = vi.fn(); + const rotate = vi.fn(); + const canvases: Array<{ width: number; height: number }> = []; + const context = { fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: 'left', fillRect: vi.fn(), strokeRect: vi.fn(), measureText: (text: string) => ({ width: text.length * 3 }), fillText, drawImage, save: vi.fn(), translate, rotate, restore: vi.fn() } as unknown as CanvasRenderingContext2D; + vi.stubGlobal('document', { + createElement: () => { const canvas = { width: 0, height: 0, getContext: () => context, toDataURL: () => 'data:image/png;base64,AA==' }; canvases.push(canvas); return canvas; }, + createElementNS: () => { const attrs: Record = {}; return { setAttribute: (name: string, value: string) => { attrs[name] = value; }, getAttribute: (name: string) => attrs[name] ?? null }; }, + }); + vi.stubGlobal('XMLSerializer', class { serializeToString() { return ''; } }); + vi.stubGlobal('Image', class { + width = 280; + height = 144; + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + set src(value: string) { if (value.startsWith('data:image/svg')) { this.width = 120; this.height = 64; } this.onload?.(); } + }); + const cable: LabelTemplate = { ...template, mode: 'cable', textLayout: 'mirrored', widthMm: 70, heightMm: 18, paddingMm: 1, fields: [{ source: 'From', label: '', fontSize: 5, bold: true }], code: { ...template.code, type: 'none', field: '' } }; + await renderLabel({ id: 'cable', values: { From: 'SW01 → SERVER01' } }, cable); + expect(fillText).toHaveBeenCalledTimes(1); + expect(textColors).toEqual(['#000']); + expect(canvases.map(({ width, height }) => [width, height])).toEqual([[280, 144], [560, 144]]); + expect(drawImage).toHaveBeenCalledTimes(2); + expect(drawImage.mock.calls[0]?.slice(5)).toEqual([0, 0, 280, 144]); + expect(drawImage.mock.calls[1]?.slice(5)).toEqual([0, 0, 280, 144]); + expect(translate).toHaveBeenCalledWith(560, 144); + expect(rotate).toHaveBeenCalledWith(Math.PI); + + for (const code of [ + { ...template.code, type: 'qr' as const, field: 'Asset ID', sizeMm: 10 }, + { ...template.code, type: 'code128' as const, field: 'Asset ID', barcodeHeightMm: 8 }, + { ...template.code, type: 'code128' as const, field: 'Asset ID', barcodeHeightMm: 8, barcodeText: false }, + ]) { + drawImage.mockClear(); + await renderLabel(record, { ...cable, code }); + expect(drawImage).toHaveBeenCalledTimes(code.type === 'code128' ? 3 : 2); + const panelCalls = drawImage.mock.calls.slice(-2); + expect(panelCalls.map(call => call.slice(5))).toEqual([[0, 0, 280, 144], [0, 0, 280, 144]]); + const leftPanel = [0, 280] as const; + const rightPanel = [280, 560] as const; + expect(leftPanel[1]).toBeLessThanOrEqual(rightPanel[0]); + expect(rightPanel[1]).toBe(560); + } + expect(textColors.every(color => color === '#000')).toBe(true); + }); + + it('renders a seven-level location hierarchy through the label preview renderer', async () => { + const fillText = vi.fn(); + const context = { fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: 'left', fillRect: vi.fn(), strokeRect: vi.fn(), measureText: (text: string) => ({ width: text.length * 5 }), fillText, save: vi.fn(), translate: vi.fn(), rotate: vi.fn(), restore: vi.fn() } as unknown as CanvasRenderingContext2D; + vi.stubGlobal('document', { createElement: () => ({ width: 0, height: 0, getContext: () => context, toDataURL: () => 'data:image/png;base64,AA==' }) }); + const sources = ['Site', 'Building', 'Floor', 'Room', 'Rack', 'Shelf', 'Bin']; + const values = Object.fromEntries(sources.map((source, index) => [source, ['Warehouse A', 'Building 1', 'Floor 2', 'Room 201', 'Rack A', 'Shelf 03', 'Bin 07'][index]!])); + const location: LabelTemplate = { + ...template, mode: 'location', widthMm: 70, heightMm: 60, paddingMm: 2, + fields: sources.map(source => ({ source, label: source, fontSize: 12, bold: true })), + code: { ...template.code, type: 'qr', field: 'Site', sizeMm: 18, payload: `location://site/${sources.map(source => `{${source}}`).join('/')}`, payloadMode: 'location' }, + }; + expect(await renderLabel({ id: 'location', values }, location)).toMatch(/^data:image\/png/); + expect(fillText).toHaveBeenCalledTimes(7); + }); + it('reports a missing raw value and unknown placeholder with repair guidance', () => { expect(() => interpolatePayload({ id: 'empty', values: {} }, template)).toThrow(/no value.*choose another code column/i); expect(() => interpolatePayload(record, { ...template, code: { ...template.code, payload: '{Missing column}' } })).toThrow(/not a column.*Fix the template/i); diff --git a/src/features/labels/renderer.ts b/src/features/labels/renderer.ts index c91ccf7..5b5bb3a 100644 --- a/src/features/labels/renderer.ts +++ b/src/features/labels/renderer.ts @@ -1,6 +1,7 @@ import JsBarcode from 'jsbarcode'; import QRCode from 'qrcode'; import type { AssetRecord, LabelField, LabelTemplate } from '../../types'; +import { resolveCodePayload } from '../../core/payload'; const MAX_LABEL_MM = 200; const MAX_FONT_PT = 48; @@ -24,6 +25,9 @@ export function validateTemplate(template: LabelTemplate): void { throw new Error('Label dimensions are too large to render safely. Reduce the label size.'); } if (!['left', 'center', 'right'].includes(template.alignment)) throw new Error('Choose left, center, or right alignment.'); + if (template.mode !== undefined && !['asset', 'cable', 'location', 'code'].includes(template.mode)) throw new Error('Choose a supported label mode.'); + if (template.textLayout !== undefined && !['standard', 'mirrored'].includes(template.textLayout)) throw new Error('Choose a supported text layout.'); + if (template.textLayout === 'mirrored' && template.widthMm / 2 < 10) throw new Error('Mirrored labels need a physical width of at least 20 mm so each side can render safely.'); if (typeof template.border !== 'boolean') throw new Error('Label border setting must be on or off.'); if (!Array.isArray(template.fields) || template.fields.length > MAX_FIELDS) { throw new Error(`A label can contain at most ${MAX_FIELDS} text fields.`); @@ -37,8 +41,10 @@ export function validateTemplate(template: LabelTemplate): void { if (typeof field.bold !== 'boolean') throw new Error(`Text field ${index + 1} bold setting must be on or off.`); } const code = template.code; - if (!code || !['qr', 'code128'].includes(code.type)) throw new Error('Choose QR or Code 128 as the label code.'); - if (typeof code.field !== 'string' || !code.field.trim() || code.field.length > 200) throw new Error('Choose a code column with a name up to 200 characters.'); + if (!code || !['qr', 'code128', 'none'].includes(code.type)) throw new Error('Choose QR, Code 128, or no code.'); + if (code.type === 'none' && template.fields.length === 0) throw new Error('Add at least one text field to a text-only label.'); + if (code.payloadMode !== undefined && !['text', 'url', 'fieldlens', 'location'].includes(code.payloadMode)) throw new Error('Choose a supported payload mode.'); + if (code.type !== 'none' && (typeof code.field !== 'string' || !code.field.trim() || code.field.length > 200)) throw new Error('Choose a code column with a name up to 200 characters.'); if (typeof code.payload !== 'string' || code.payload.length > 2_000) { throw new Error('Code payload must be text with no more than 2,000 characters.'); } @@ -50,8 +56,8 @@ export function validateTemplate(template: LabelTemplate): void { throw new Error('Payload placeholders need a column name, such as {Asset ID}.'); } if (code.type === 'qr') { - finiteInRange(code.sizeMm, 'QR size', 8, Math.min(template.widthMm, template.heightMm)); - } else { + finiteInRange(code.sizeMm, 'QR size', 8, Math.min(template.textLayout === 'mirrored' ? template.widthMm / 2 : template.widthMm, template.heightMm)); + } else if (code.type === 'code128') { finiteInRange(code.barcodeHeightMm, 'Barcode height', 5, Math.min(40, template.heightMm)); const scale = code.barcodeScale ?? 1; if (!Number.isFinite(scale) || scale < 0.8 || scale > 3) throw new Error('Barcode scale must be between 0.8 and 3.'); @@ -69,25 +75,7 @@ function readStringValue(record: AssetRecord, key: string): string | undefined { export function interpolatePayload(record: AssetRecord, template: LabelTemplate): string { validateTemplate(template); - if (!template.code.payload) { - const value = readStringValue(record, template.code.field); - if (!value?.trim()) throw new Error(`Record “${record.id}” has no value in “${template.code.field}”. Fill that cell or choose another code column.`); - if (value.length > 2_000) throw new Error(`Record “${record.id}” produces a code value over 2,000 characters. Shorten the value or payload.`); - return value; - } - let unknown: string | undefined; - let missingValue: string | undefined; - const result = template.code.payload.replace(PLACEHOLDER, (_match, key: string) => { - const value = readStringValue(record, key); - if (!Object.hasOwn(record.values, key)) unknown = key; - else if (!value?.trim()) missingValue = key; - return value ?? ''; - }); - if (unknown) throw new Error(`Payload placeholder “{${unknown}}” is not a column in the records. Fix the template placeholder.`); - if (missingValue) throw new Error(`Record “${record.id}” has no value in “${missingValue}”. Fill that cell or change the payload.`); - if (!result.trim()) throw new Error(`Record “${record.id}” produces an empty code value. Add a value or change the payload.`); - if (result.length > 2_000) throw new Error(`Record “${record.id}” produces a code value over 2,000 characters. Shorten the value or payload.`); - return result; + return resolveCodePayload(record, template.code); } export function wrapText(text: string, maxWidth: number, measure: (text: string) => number): string[] { @@ -136,12 +124,50 @@ function drawWrappedField(context: CanvasRenderingContext2D, field: LabelField, return y; } +function drawFields(context: CanvasRenderingContext2D, record: AssetRecord, template: LabelTemplate, x: number, y: number, width: number, bottom: number): void { + // Text must not inherit the white background used by text-only labels. + context.fillStyle = '#000'; + let nextY = y; + for (const field of template.fields) { + const value = readStringValue(record, field.source) ?? ''; + if (value.length > 2_000 || field.label.length > 200) throw new Error(`Text for “${field.source}” is too long to render safely. Shorten the cell or label.`); + nextY = drawWrappedField(context, field, value, x, nextY, width, bottom, template.alignment); + } +} + function pngDataUrl(canvas: HTMLCanvasElement): string { return canvas.toDataURL('image/png'); } +async function renderMirroredLabel(record: AssetRecord, template: LabelTemplate): Promise { + const halfWidthMm = template.widthMm / 2; + const halfTemplate = { ...template, widthMm: halfWidthMm, textLayout: 'standard' as const }; + const sideDataUrl = await renderLabel(record, halfTemplate); + const sideImage = await new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => resolve(image); + image.onerror = () => reject(new Error('Could not prepare the mirrored label panels.')); + image.src = sideDataUrl; + }); + const canvas = document.createElement('canvas'); + canvas.width = Math.round(template.widthMm * PIXELS_PER_MM); + canvas.height = Math.round(template.heightMm * PIXELS_PER_MM); + const context = canvasContext(canvas); + context.fillStyle = '#fff'; + context.fillRect(0, 0, canvas.width, canvas.height); + const panelWidth = Math.floor(canvas.width / 2); + context.drawImage(sideImage, 0, 0, sideImage.width, sideImage.height, 0, 0, panelWidth, canvas.height); + context.save(); + context.translate(canvas.width, canvas.height); + context.rotate(Math.PI); + context.drawImage(sideImage, 0, 0, sideImage.width, sideImage.height, 0, 0, panelWidth, canvas.height); + context.restore(); + return pngDataUrl(canvas); +} + export async function renderLabel(record: AssetRecord, template: LabelTemplate): Promise { validateTemplate(template); + if (template.textLayout === 'mirrored') return renderMirroredLabel(record, template); let payload: string; try { payload = interpolatePayload(record, template); @@ -195,13 +221,8 @@ export async function renderLabel(record: AssetRecord, template: LabelTemplate): const textX = x + side + pad; const textWidth = innerRight - textX; if (template.fields.length && textWidth <= 0) throw new Error('There is no room for text beside the QR code. Reduce QR size or padding.'); - let textY = pad; - for (const field of template.fields) { - const fieldValue = readStringValue(record, field.source) ?? ''; - if (fieldValue.length > 2_000 || field.label.length > 200) throw new Error(`Text for “${field.source}” is too long to render safely. Shorten the cell or label.`); - textY = drawWrappedField(context, field, fieldValue, textX, textY, textWidth, innerBottom, template.alignment); - } - } else { + drawFields(context, record, template, textX, pad, textWidth, innerBottom); + } else if (template.code.type === 'code128') { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); try { JsBarcode(svg, payload, { @@ -246,12 +267,10 @@ export async function renderLabel(record: AssetRecord, template: LabelTemplate): context.fillText(payload, canvas.width / 2, textY + PIXELS_PER_MM * 3.5, barcodeWidth); textY += PIXELS_PER_MM * 4.5; } - for (const field of template.fields) { - const fieldValue = readStringValue(record, field.source) ?? ''; - if (fieldValue.length > 2_000 || field.label.length > 200) throw new Error(`Text for “${field.source}” is too long to render safely. Shorten the cell or label.`); - textY = drawWrappedField(context, field, fieldValue, pad, textY, barcodeWidth, innerBottom, template.alignment); - } + drawFields(context, record, template, pad, textY, barcodeWidth, innerBottom); if (textY > innerBottom + 0.5) throw new Error('Barcode and text do not fit. Reduce the barcode height or font sizes, or increase label height.'); + } else { + drawFields(context, record, template, pad, pad, innerRight - pad, innerBottom); } return pngDataUrl(canvas); } diff --git a/src/features/layout/pageLayout.test.ts b/src/features/layout/pageLayout.test.ts index d7cacf0..e2ca657 100644 --- a/src/features/layout/pageLayout.test.ts +++ b/src/features/layout/pageLayout.test.ts @@ -20,6 +20,16 @@ describe('page layout', () => { expect(result.pages).toBe(Math.ceil(25 / result.labelsPerPage)); }); + it('applies signed calibration offsets to shared sheet positions and rejects clipping', () => { + const positive = calculateLayout(template, { ...DEFAULT_PAGE, offsetXMm: 1.5, offsetYMm: 0.8 }, 1); + expect(positive.positions[0]).toEqual({ xMm: 11.5, yMm: 10.8 }); + const negative = calculateLayout(template, { ...DEFAULT_PAGE, offsetXMm: -1, offsetYMm: -2 }, 1); + expect(negative.positions[0]).toEqual({ xMm: 9, yMm: 8 }); + expect(() => calculateLayout(template, { ...DEFAULT_PAGE, marginLeftMm: 0, offsetXMm: -0.1 }, 1)).toThrow(/off the page/); + expect(() => calculateLayout(template, { ...DEFAULT_PAGE, widthMm: 60, marginLeftMm: 0, marginRightMm: 0, offsetXMm: 0.1 }, 1)).toThrow(/off the page/); + expect(() => calculateLayout(template, { ...DEFAULT_PAGE, offsetYMm: Number.NaN }, 1)).toThrow(/Vertical calibration offset/); + }); + it('handles exact fit, uneven margins, empty datasets, and common page dimensions', () => { const exact = calculateLayout(template, { ...DEFAULT_PAGE, widthMm: 60, heightMm: 30, marginLeftMm: 0, marginRightMm: 0, marginTopMm: 0, marginBottomMm: 0, gapXMm: 0, gapYMm: 0 }, 0); expect(exact.pages).toBe(0); diff --git a/src/features/layout/pageLayout.ts b/src/features/layout/pageLayout.ts index 7930442..9c5a11d 100644 --- a/src/features/layout/pageLayout.ts +++ b/src/features/layout/pageLayout.ts @@ -31,6 +31,11 @@ export function calculateLayout(template: LabelTemplate, page: PageSettings, cou throw new Error(`${name} must be a finite number between 0 and ${MAX_PAGE_MM} mm.`); } } + const offsetX = page.offsetXMm ?? 0; + const offsetY = page.offsetYMm ?? 0; + for (const [name, value] of [['Horizontal calibration offset', offsetX], ['Vertical calibration offset', offsetY]] as const) { + if (!Number.isFinite(value) || Math.abs(value) > 100) throw new Error(`${name} must be a finite value between -100 and 100 mm.`); + } if (!Number.isInteger(count) || count < 0 || count > MAX_RECORDS) { throw new Error(`Record count must be a whole number between 0 and ${MAX_RECORDS.toLocaleString()}.`); } @@ -48,8 +53,11 @@ export function calculateLayout(template: LabelTemplate, page: PageSettings, cou } if (labelsPerPage > MAX_POSITIONS) throw new Error(`This page would require ${labelsPerPage.toLocaleString()} label positions. Increase label size or page margins.`); const positions = Array.from({ length: labelsPerPage }, (_, index) => ({ - xMm: page.marginLeftMm + (index % columns) * (template.widthMm + page.gapXMm), - yMm: page.marginTopMm + Math.floor(index / columns) * (template.heightMm + page.gapYMm), + xMm: page.marginLeftMm + (index % columns) * (template.widthMm + page.gapXMm) + offsetX, + yMm: page.marginTopMm + Math.floor(index / columns) * (template.heightMm + page.gapYMm) + offsetY, })); + if (positions.some(({ xMm, yMm }) => xMm < 0 || yMm < 0 || xMm + template.widthMm > page.widthMm || yMm + template.heightMm > page.heightMm)) { + throw new Error('Printer calibration moves a label off the page. Adjust the offset or margins to prevent clipping.'); + } return { columns, rows, labelsPerPage, pages: count === 0 ? 0 : Math.ceil(count / labelsPerPage), positions }; } diff --git a/src/features/manifest/ExportToolsPage.tsx b/src/features/manifest/ExportToolsPage.tsx new file mode 100644 index 0000000..380cbce --- /dev/null +++ b/src/features/manifest/ExportToolsPage.tsx @@ -0,0 +1,64 @@ +import { useEffect, useRef, useState } from 'react'; +import type { StudioPageProps } from '../../studio/contracts'; +import { ColumnSelect, HelpDetails, NoDataset, ToolFrame } from '../../studio/ui'; +import { downloadFile } from '../../core/download'; +import { generatePrintJobPdf } from '../export/pdf'; +import { manifestCsv, manifestJson } from './manifest'; +import { fieldLensCsv, prepareFieldLensJob, type FieldLensMapping } from '../integrations/fieldlens/export'; +import type { PrintJob } from '../../core/printJob'; + +type Props = StudioPageProps & { mode: 'manifest' | 'fieldlens'; onPrintJobCompleted?: (job: PrintJob) => void }; +export function ExportToolsPage(props: Props) { + const { mode, lastJob, dataset, selectedIds, idField, template, page, busy } = props; + const [mapping, setMapping] = useState({ idField, nameField: '', assetTypeField: '', serialField: '', locationField: '' }); + const [working, setWorking] = useState(false); + const [error, setError] = useState(''); + const [notice, setNotice] = useState(''); + const controller = useRef(null); + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { mounted.current = false; controller.current?.abort(); }; + }, []); + const disabled = busy || working; + const manifestMode = mode === 'manifest'; + const downloadManifest = () => { + if (!lastJob) return; + setError(''); setNotice(''); + try { + downloadFile(manifestJson(lastJob), 'application/json', 'asset-print-manifest.json'); + downloadFile(manifestCsv(lastJob), 'text/csv;charset=utf-8', 'asset-print-manifest.csv'); + setNotice(`Downloaded manifest for ${lastJob.labels.length} labels from the last successful print job.`); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not export the print manifest.'); } + }; + const runFieldLens = async () => { + if (!dataset) return; + if (selectedIds.size === 0) { setError('Select at least one asset in Asset Labels before creating the FieldLens package.'); return; } + setWorking(true); setError(''); setNotice(''); + const aborter = new AbortController(); controller.current = aborter; + try { + const job = prepareFieldLensJob(dataset, selectedIds, mapping, template, page); + const pdf = await generatePrintJobPdf(job, { signal: aborter.signal }); + if (aborter.signal.aborted || !mounted.current) return; + const csv = fieldLensCsv(job, mapping); + await Promise.resolve(); + if (aborter.signal.aborted || !mounted.current) return; + downloadFile(pdf.slice().buffer as ArrayBuffer, 'application/pdf', 'fieldlens-labels.pdf'); + downloadFile(csv, 'text/csv;charset=utf-8', 'fieldlens-assets.csv'); + props.onPrintJobCompleted?.(job); + setNotice(`Created a PDF and CSV for ${job.labels.length} assets from one frozen print snapshot. FieldLens exchange uses the asset_id column and fieldlens://asset/ID QR payload; this build does not claim a verified CSV importer.`); + } catch (cause) { + if (!mounted.current) return; + if (cause instanceof Error && cause.name === 'AbortError') setNotice('FieldLens export canceled.'); + else setError(cause instanceof Error ? cause.message : 'Could not create the FieldLens export.'); + } finally { if (controller.current === aborter) controller.current = null; if (mounted.current) setWorking(false); } + }; + const cancel = () => controller.current?.abort(); + if (!manifestMode && !dataset) return props.onNavigate('asset-labels')}/>; + const choose = (key: keyof FieldLensMapping, label: string, optional = false) => setMapping(old => ({ ...old, [key]: value }))}/>; + return + {manifestMode ?

Last successful print job

{lastJob ? <>

{lastJob.templateName} · {lastJob.labels.length} physical labels · {new Date(lastJob.generatedAt).toLocaleString()}

:

No successful print job is available yet. Create a PDF from Asset Labels or a specialized label page first.

}
:

Map FieldLens asset data

{choose('idField', 'Asset ID')}{choose('nameField', 'Name')}{choose('assetTypeField', 'Asset type')}
{choose('serialField', 'Serial', true)}{choose('locationField', 'Location', true)}
{working && }
} + {notice &&

{notice}

}{error &&

{error}

} + {manifestMode ? 'The manifest records label placements from the most recent successful print job and can support audit or recreation.' : 'Asset IDs are checked against FieldLens mobile URI rules, and the PDF and CSV use the same print snapshot.'} +
; +} diff --git a/src/features/manifest/manifest.ts b/src/features/manifest/manifest.ts new file mode 100644 index 0000000..9387344 --- /dev/null +++ b/src/features/manifest/manifest.ts @@ -0,0 +1,23 @@ +import type { PrintJob } from '../../core/printJob'; +import { csvText } from '../../core/download'; + +export type PrintManifest = { + version: 1; generatedAt: string; template: string; codeType: PrintJob['template']['code']['type']; + encodedField: string; calibration: { offsetXMm: number; offsetYMm: number }; + records: Array<{ recordId: string; assetId: string; labelIndex: number; page: number; row: number; column: number; xMm: number; yMm: number; payload: string }>; +}; +export function manifestFromPrintJob(job: PrintJob): PrintManifest { + return { + version: 1, generatedAt: job.generatedAt, template: job.templateName, codeType: job.template.code.type, + encodedField: job.idField, calibration: { offsetXMm: job.page.offsetXMm ?? 0, offsetYMm: job.page.offsetYMm ?? 0 }, + records: job.labels.map(label => ({ recordId: label.recordId, assetId: label.assetId, labelIndex: label.labelIndex, page: label.page, row: label.row, column: label.column, xMm: label.position.xMm, yMm: label.position.yMm, payload: label.payload })), + }; +} +export function manifestJson(job: PrintJob): string { return JSON.stringify(manifestFromPrintJob(job), null, 2); } +export function manifestCsv(job: PrintJob): string { + const manifest = manifestFromPrintJob(job); + return csvText([ + ['record_id', 'asset_id', 'label_index', 'page', 'row', 'column', 'x_mm', 'y_mm', 'payload'], + ...manifest.records.map(row => [row.recordId, row.assetId, String(row.labelIndex), String(row.page), String(row.row), String(row.column), String(row.xMm), String(row.yMm), row.payload]), + ]); +} diff --git a/src/features/payload-builder/model.test.ts b/src/features/payload-builder/model.test.ts new file mode 100644 index 0000000..eb087c7 --- /dev/null +++ b/src/features/payload-builder/model.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_TEMPLATE } from '../../types'; +import { checkPayload, payloadPreset } from './model'; +const record = { id: 'r1', values: { ID: 'A/B ?&' } }; +const code = { ...DEFAULT_TEMPLATE.code, field: 'ID', sizeMm: 30 }; +describe('payload builder', () => { + it('uses the same safe encoding and raw contract as print jobs', () => { + expect(checkPayload(record, { ...code, ...payloadPreset('url', 'ID') }).payload).toBe('https://inventory.example/assets/A%2FB%20%3F%26'); + expect(checkPayload(record, { ...code, ...payloadPreset('raw', 'ID') }).payload).toBe('A/B ?&'); + expect(checkPayload(record, { ...code, ...payloadPreset('structured', 'ID') }).payload).toBe('asset_id=A/B ?&\ntype=asset'); + }); + it('rejects unsafe schemes, absent tokens, dense codes and incompatible FieldLens identifiers', () => { + expect(() => checkPayload(record, { ...code, payload: 'javascript:alert(1)', payloadMode: 'url' })).toThrow(/HTTP/); + expect(() => checkPayload(record, { ...code, payload: '{Absent}' })).toThrow(/not a column/); + expect(() => checkPayload(record, { ...code, ...payloadPreset('fieldlens', 'ID') })).toThrow(); + expect(() => checkPayload({ id: 'r', values: { ID: 'x'.repeat(1500) } }, { ...code, sizeMm: 8 })).toThrow(/dense/); + }); +}); diff --git a/src/features/payload-builder/model.ts b/src/features/payload-builder/model.ts new file mode 100644 index 0000000..75937f9 --- /dev/null +++ b/src/features/payload-builder/model.ts @@ -0,0 +1,19 @@ +import QRCode from 'qrcode'; +import type { AssetRecord, LabelTemplate } from '../../types'; +import { resolveCodePayload } from '../../core/payload'; + +export type PayloadCheck = { payload: string; length: number; modules: number; moduleMm: number; warning: string }; +export function checkPayload(record: AssetRecord, code: LabelTemplate['code']): PayloadCheck { + const payload = resolveCodePayload(record, { ...code, type: 'qr' }); + const qr = QRCode.create(payload, { errorCorrectionLevel: 'M' }); + const modules = qr.modules.size + 8; + const moduleMm = code.sizeMm / modules; + if (!Number.isFinite(moduleMm) || moduleMm < 0.2) throw new Error('The QR payload is too dense for this code size. Increase the QR size or shorten the payload.'); + return { payload, length: payload.length, modules, moduleMm, warning: moduleMm < 0.3 ? 'Small modules: test a printed label with the actual scanner before printing the batch.' : '' }; +} +export function payloadPreset(kind: 'raw' | 'text' | 'url' | 'fieldlens' | 'structured', column: string): Pick { + if (kind === 'raw') return { payload: '', payloadMode: 'text' }; + if (kind === 'url') return { payload: `https://inventory.example/assets/{${column}}`, payloadMode: 'url' }; + if (kind === 'fieldlens') return { payload: `fieldlens://asset/{${column}}`, payloadMode: 'fieldlens' }; + return { payload: kind === 'structured' ? `asset_id={${column}}\ntype=asset` : `Asset: {${column}}`, payloadMode: 'text' }; +} diff --git a/src/features/preferences/store.test.ts b/src/features/preferences/store.test.ts index 22f52b4..7c8fd1b 100644 --- a/src/features/preferences/store.test.ts +++ b/src/features/preferences/store.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import { DEFAULT_PAGE } from '../../types'; import { DEFAULT_PREFERENCES, loadPreferences, parsePreferences, PREFERENCES_KEY, savePreferences } from './store'; describe('local preferences', () => { @@ -22,6 +23,15 @@ describe('local preferences', () => { expect(parsePreferences(JSON.stringify(value))).toEqual(value); }); + it('preserves optional specialized label settings and signed sheet offsets', () => { + const value = { ...DEFAULT_PREFERENCES, + template: { ...DEFAULT_PREFERENCES.template, mode: 'cable' as const, textLayout: 'mirrored' as const, fields: [{ source: 'Name', label: '', fontSize: 10, bold: true }], code: { ...DEFAULT_PREFERENCES.template.code, type: 'none' as const, field: '', payloadMode: 'text' as const } }, + page: { ...DEFAULT_PREFERENCES.page, offsetXMm: -1.25, offsetYMm: 0.8 }, + }; + expect(parsePreferences(JSON.stringify(value))).toEqual(value); + expect(parsePreferences(JSON.stringify({ ...value, page: { ...value.page, offsetXMm: 500, offsetYMm: Number.NaN } })).page).toEqual(DEFAULT_PAGE); + }); + it('replaces out-of-range saved dimensions and code settings with safe defaults', () => { const value = parsePreferences(JSON.stringify({ template: { ...DEFAULT_PREFERENCES.template, widthMm: 999, heightMm: -1, paddingMm: 99, code: { ...DEFAULT_PREFERENCES.template.code, sizeMm: 999, barcodeHeightMm: 100, barcodeScale: 9 } }, page: { ...DEFAULT_PREFERENCES.page, widthMm: 0, heightMm: -10 } })); expect(value.template.widthMm).toBe(DEFAULT_PREFERENCES.template.widthMm); diff --git a/src/features/preferences/store.ts b/src/features/preferences/store.ts index 1e982e3..46945ff 100644 --- a/src/features/preferences/store.ts +++ b/src/features/preferences/store.ts @@ -11,7 +11,7 @@ function readTemplate(value: unknown): LabelTemplate { if (typeof value !== 'object' || value === null) return DEFAULT_TEMPLATE; const candidate = value as Record; const code = typeof candidate.code === 'object' && candidate.code !== null ? candidate.code as Record : {}; - const fields = Array.isArray(candidate.fields) ? candidate.fields.slice(0, 6).flatMap((item): LabelTemplate['fields'] => { + const fields = Array.isArray(candidate.fields) ? candidate.fields.slice(0, 32).flatMap((item): LabelTemplate['fields'] => { if (typeof item !== 'object' || item === null) return []; const field = item as Record; if (typeof field.source !== 'string' || typeof field.label !== 'string' || !finite(field.fontSize, 5, 30) || typeof field.bold !== 'boolean') return []; @@ -23,13 +23,16 @@ function readTemplate(value: unknown): LabelTemplate { paddingMm: finite(candidate.paddingMm, 0, 30) ? candidate.paddingMm : DEFAULT_TEMPLATE.paddingMm, border: typeof candidate.border === 'boolean' ? candidate.border : DEFAULT_TEMPLATE.border, alignment: candidate.alignment === 'center' || candidate.alignment === 'right' ? candidate.alignment : 'left', + ...(candidate.mode === 'cable' || candidate.mode === 'location' || candidate.mode === 'code' || candidate.mode === 'asset' ? { mode: candidate.mode } : {}), + ...(candidate.textLayout === 'mirrored' ? { textLayout: 'mirrored' as const } : {}), fields, code: { - type: code.type === 'code128' ? 'code128' : 'qr', + type: code.type === 'code128' ? 'code128' : code.type === 'none' ? 'none' : 'qr', field: typeof code.field === 'string' ? code.field.slice(0, 200) : '', sizeMm: finite(code.sizeMm, 8, 60) ? code.sizeMm : DEFAULT_TEMPLATE.code.sizeMm, barcodeScale: finite(code.barcodeScale, 0.8, 3) ? code.barcodeScale : 1, payload: typeof code.payload === 'string' && code.payload.length <= 2000 ? code.payload : '', + ...(code.payloadMode === 'url' || code.payloadMode === 'fieldlens' || code.payloadMode === 'location' || code.payloadMode === 'text' ? { payloadMode: code.payloadMode } : {}), barcodeHeightMm: finite(code.barcodeHeightMm, 5, 40) ? code.barcodeHeightMm : DEFAULT_TEMPLATE.code.barcodeHeightMm, barcodeText: typeof code.barcodeText === 'boolean' ? code.barcodeText : true, barcodeTextPosition: code.barcodeTextPosition === 'top' ? 'top' : 'bottom', @@ -41,7 +44,7 @@ function readPage(value: unknown): PageSettings { const candidate = value as Record; const dimension = (key: string, fallback: number, max: number, min = 0) => finite(candidate[key], min, max) ? candidate[key] as number : fallback; const preset = candidate.preset === 'A5' || candidate.preset === 'Letter' || candidate.preset === 'Custom' ? candidate.preset : 'A4'; - return { preset, widthMm: dimension('widthMm', DEFAULT_PAGE.widthMm, 500, 1), heightMm: dimension('heightMm', DEFAULT_PAGE.heightMm, 700, 1), marginTopMm: dimension('marginTopMm', 10, 100), marginBottomMm: dimension('marginBottomMm', 10, 100), marginLeftMm: dimension('marginLeftMm', 10, 100), marginRightMm: dimension('marginRightMm', 10, 100), gapXMm: dimension('gapXMm', 3, 50), gapYMm: dimension('gapYMm', 3, 50) }; + return { preset, widthMm: dimension('widthMm', DEFAULT_PAGE.widthMm, 500, 1), heightMm: dimension('heightMm', DEFAULT_PAGE.heightMm, 700, 1), marginTopMm: dimension('marginTopMm', 10, 100), marginBottomMm: dimension('marginBottomMm', 10, 100), marginLeftMm: dimension('marginLeftMm', 10, 100), marginRightMm: dimension('marginRightMm', 10, 100), gapXMm: dimension('gapXMm', 3, 50), gapYMm: dimension('gapYMm', 3, 50), ...(finite(candidate.offsetXMm, -100, 100) ? { offsetXMm: candidate.offsetXMm } : {}), ...(finite(candidate.offsetYMm, -100, 100) ? { offsetYMm: candidate.offsetYMm } : {}) }; } export function parsePreferences(raw: string | null): Preferences { diff --git a/src/features/serial-tools/logic.test.ts b/src/features/serial-tools/logic.test.ts new file mode 100644 index 0000000..e005c96 --- /dev/null +++ b/src/features/serial-tools/logic.test.ts @@ -0,0 +1,89 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { Dataset } from '../../types'; +import { applySerialPreview, PreviewGeneration, previewSerials, testSerialPattern } from './logic'; + +const dataset: Dataset = { columns: ['Serial'], warnings: [], records: [ + { id: 'a', values: { Serial: ' sn: czc-91237 ' } }, { id: 'b', values: { Serial: 'CZC91237' } }, { id: 'c', values: { Serial: 'CC10042' } }, +] }; +const selectedIds = new Set(['a', 'b']); + +describe('serial tools', () => { + it('normalizes with preview, detects duplicates, and applies only on request', async () => { + const preview = await previewSerials(dataset, { column: 'Serial', selectedIds, mode: 'normalize', casing: 'upper', stripPrefix: 'SN:', removeSeparators: true, minLength: 1, maxLength: 30, knownPrefixes: 'CZC', pattern: '' }); + expect(preview.map(row => row.after)).toEqual(['CZC91237', 'CZC91237']); + expect(preview[1]?.status).toBe('duplicate'); + const changed = applySerialPreview(dataset, 'Serial', preview); + expect(changed.records[0]?.values.Serial).toBe('CZC91237'); + expect(dataset.records[0]?.values.Serial).toContain(' sn:'); + }); + it('deduplicates deterministically and keeps the first dataset row', async () => { + const preview = await previewSerials(dataset, { column: 'Serial', selectedIds: new Set(['a', 'b', 'c']), mode: 'deduplicate', casing: 'upper', stripPrefix: 'SN:', removeSeparators: true, minLength: 1, maxLength: 30, knownPrefixes: '', pattern: '' }); + const changed = applySerialPreview(dataset, 'Serial', preview, true); + expect(changed.records.map(row => row.id)).toEqual(['a', 'c']); + }); + it('validates extracted values on a bounded checker and rejects risky patterns', async () => { + const preview = await previewSerials(dataset, { column: 'Serial', selectedIds: new Set(['a']), mode: 'extract', casing: 'upper', stripPrefix: '', removeSeparators: true, minLength: 1, maxLength: 30, knownPrefixes: 'CZC', pattern: '^(CZC|CC)[A-Z0-9]+$' }, async (_pattern, values) => values.map(() => true)); + expect(preview[0]?.after).toBe('CZC91237'); + await expect(previewSerials(dataset, { column: 'Serial', selectedIds, mode: 'validate', casing: 'preserve', stripPrefix: '', removeSeparators: false, minLength: 1, maxLength: 30, knownPrefixes: '', pattern: '(a+)+$' })).rejects.toThrow(/too long/); + }); + it('rejects invalid length rules before work', async () => { + await expect(previewSerials(dataset, { column: 'Serial', selectedIds, mode: 'validate', casing: 'preserve', stripPrefix: '', removeSeparators: false, minLength: 40, maxLength: 2, knownPrefixes: '', pattern: '' })).rejects.toThrow(/Length rules/); + }); +}); + +describe('serial pattern worker', () => { + afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); }); + it('terminates a worker that exceeds its time limit', async () => { + vi.useFakeTimers(); + const terminate = vi.fn(); + class StalledWorker { static current: StalledWorker; constructor() { StalledWorker.current = this; } onmessage: ((event: MessageEvent) => void) | null = null; onerror: (() => void) | null = null; postMessage() {} terminate = terminate; } + vi.stubGlobal('Worker', StalledWorker); + const result = testSerialPattern('^A+$', ['AAAA']); + const rejected = expect(result).rejects.toThrow(/time limit/); + StalledWorker.current.onmessage!({ data: { ready: true } } as MessageEvent); + await vi.advanceTimersByTimeAsync(101); + await rejected; + expect(terminate).toHaveBeenCalledOnce(); + }); + it('allows bounded slow startup without spending the execution budget', async () => { + vi.useFakeTimers(); + class ReadyWorker { + static current: ReadyWorker; + constructor() { ReadyWorker.current = this; } + onmessage: ((event: MessageEvent) => void) | null = null; + onerror: (() => void) | null = null; + terminate = vi.fn(); + postMessage = vi.fn((request: { id: number }) => this.onmessage!({ data: { id: request.id, ok: true, matches: [true] } } as MessageEvent)); + } + vi.stubGlobal('Worker', ReadyWorker); + const result = testSerialPattern('^A+$', ['AAAA']); + await vi.advanceTimersByTimeAsync(1000); + expect(ReadyWorker.current.postMessage).not.toHaveBeenCalled(); + ReadyWorker.current.onmessage!({ data: { ready: true } } as MessageEvent); + await expect(result).resolves.toEqual([true]); + expect(ReadyWorker.current.terminate).toHaveBeenCalledOnce(); + }); + it('terminates workers that never finish starting', async () => { + vi.useFakeTimers(); + const terminate = vi.fn(); + class NeverReadyWorker { static current: NeverReadyWorker; constructor() { NeverReadyWorker.current = this; } onmessage: ((event: MessageEvent) => void) | null = null; onerror = null; postMessage() {} terminate = terminate; } + vi.stubGlobal('Worker', NeverReadyWorker); + const result = testSerialPattern('^A+$', ['AAAA']); + const rejected = expect(result).rejects.toThrow(/startup/); + await vi.advanceTimersByTimeAsync(5001); await rejected; + expect(terminate).toHaveBeenCalledOnce(); + NeverReadyWorker.current.onmessage!({ data: { ready: true } } as MessageEvent); + expect(vi.getTimerCount()).toBe(0); + }); +}); + +describe('serial preview request generation', () => { + it('invalidates results after settings or selection changes', () => { + const requests = new PreviewGeneration(); + const stale = requests.begin(); + requests.invalidate(); + expect(requests.isCurrent(stale)).toBe(false); + const current = requests.begin(); + expect(requests.isCurrent(current)).toBe(true); + }); +}); diff --git a/src/features/serial-tools/logic.ts b/src/features/serial-tools/logic.ts new file mode 100644 index 0000000..2649b93 --- /dev/null +++ b/src/features/serial-tools/logic.ts @@ -0,0 +1,121 @@ +import type { Dataset } from '../../types'; +import { cloneValues, readValue } from '../../core/dataset'; + +export type SerialOptions = { column: string; selectedIds: ReadonlySet; mode: 'normalize' | 'extract' | 'validate' | 'deduplicate'; casing: 'upper' | 'lower' | 'preserve'; stripPrefix: string; removeSeparators: boolean; minLength: number; maxLength: number; knownPrefixes: string; pattern: string }; +export type SerialPreviewRow = { rowId: string; before: string; after: string; status: 'ready' | 'invalid' | 'duplicate' | 'unchanged'; message?: string; drop?: boolean }; +const MAX_ROWS = 2000; +const MAX_SERIAL_CHARS = 500; + +export class PreviewGeneration { + private generation = 0; + begin(): number { this.generation += 1; return this.generation; } + invalidate(): void { this.generation += 1; } + isCurrent(generation: number): boolean { return generation === this.generation; } +} + +function validatePattern(source: string): void { + if (source.length > 120) throw new Error('Validation pattern must be 120 characters or fewer.'); + if (/\\[1-9]|\(\?[=!<]|\([^)]*[+*][^)]*\)[+*{]|(?:\*|\+|\{\d+,?\d*\})\s*(?:\*|\+|\{)/.test(source)) throw new Error('Pattern uses a construct that can take too long to validate. Simplify it before applying.'); +} +export function testSerialPattern(source: string, values: string[]): Promise { + if (typeof Worker === 'undefined') return Promise.reject(new Error('Pattern validation requires a browser worker.')); + return new Promise((resolve, reject) => { + const worker = new Worker(new URL('./regex.worker.ts', import.meta.url), { type: 'module' }); + const id = Date.now() + Math.floor(Math.random() * 1_000_000); + let timeout = setTimeout(() => finish(new Error('Pattern worker startup exceeded its time limit. Reload and retry.')), 5000); + let started = false; + let settled = false; + const finish = (error?: Error, matches?: boolean[]) => { + if (settled) return; + settled = true; clearTimeout(timeout); worker.terminate(); + if (error) reject(error); else resolve(matches ?? []); + }; + worker.onmessage = event => { + if (settled) return; + if (event.data?.ready && !started) { + started = true; clearTimeout(timeout); + timeout = setTimeout(() => finish(new Error('Pattern validation exceeded its time limit. Simplify the pattern.')), 100); + try { worker.postMessage({ id, source, values }); } catch { finish(new Error('Could not send serial values for validation.')); } + return; + } + if (!started) return; + if (event.data?.id !== id) return; + if (event.data.ok) finish(undefined, event.data.matches); + else finish(new Error('Enter a valid regular expression.')); + }; + worker.onerror = () => finish(new Error('Pattern worker failed. Simplify the pattern and try again.')); + }); +} +function transform(value: string, options: SerialOptions): string { + let result = value; + if (options.mode === 'extract') { + const match = result.match(/(?:\bSN\s*[:#-]?\s*)?([A-Za-z0-9][A-Za-z0-9._/-]*)/i); + result = match?.[1] ?? ''; + } + result = result.trim(); + if (options.stripPrefix && result.toLocaleLowerCase().startsWith(options.stripPrefix.toLocaleLowerCase())) result = result.slice(options.stripPrefix.length); + result = result.replace(/\s+/g, ''); + if (options.removeSeparators) result = result.replace(/[._/-]+/g, ''); + if (options.casing === 'upper') result = result.toLocaleUpperCase(); + if (options.casing === 'lower') result = result.toLocaleLowerCase(); + return result; +} + +export async function previewSerials(dataset: Dataset, options: SerialOptions, patternTester = testSerialPattern): Promise { + if (!dataset.columns.includes(options.column)) throw new Error('Choose an existing serial column.'); + if (options.minLength < 0 || options.maxLength < options.minLength || options.maxLength > MAX_SERIAL_CHARS) throw new Error(`Length rules must be within 0–${MAX_SERIAL_CHARS} characters.`); + if (options.stripPrefix.length > 80) throw new Error('Prefix rule must be 80 characters or fewer.'); + if (options.pattern) validatePattern(options.pattern); + const known = options.knownPrefixes.split(/[\n,;]/).map(item => item.trim().toLocaleUpperCase()).filter(Boolean).slice(0, 50); + if (known.some(item => item.length > 40)) throw new Error('Known prefixes must be 40 characters or fewer.'); + const selected = dataset.records.filter(row => options.selectedIds.has(row.id)); + if (selected.length > MAX_ROWS) throw new Error(`Select no more than ${MAX_ROWS} rows for preview.`); + const counts = new Map(); + const rows: SerialPreviewRow[] = selected.map(row => { + const before = readValue(row, options.column); + const after = options.mode === 'validate' ? before : transform(before, options); + const problems: string[] = []; + if (options.mode !== 'validate' && options.mode !== 'deduplicate' && !after.trim()) problems.push('Result is blank.'); + if (after.length < options.minLength || after.length > options.maxLength) problems.push(`Length must be ${options.minLength}–${options.maxLength}.`); + if (known.length && after && !known.some(prefix => after.toLocaleUpperCase().startsWith(prefix))) problems.push('Value does not start with a known prefix.'); + const key = after.toLocaleUpperCase(); + if (key) counts.set(key, (counts.get(key) ?? 0) + 1); + return { rowId: row.id, before, after, status: problems.length ? 'invalid' as const : before === after ? 'unchanged' as const : 'ready' as const, message: problems.join(' ') || undefined }; + }); + if (options.pattern) { + const matches = await patternTester(options.pattern, rows.map(row => row.after).filter(Boolean)); + let index = 0; + for (const row of rows) if (row.after) { if (!matches[index++]) { row.status = 'invalid'; row.message = [row.message, 'Value does not match the pattern.'].filter(Boolean).join(' '); } } + } + const duplicateIds = new Set(); + const firstSeen = new Set(); + for (const record of dataset.records) { + const value = options.mode === 'validate' ? readValue(record, options.column) : transform(readValue(record, options.column), options); + const key = value.toLocaleUpperCase(); + if (!key) continue; + if (firstSeen.has(key)) duplicateIds.add(record.id); + else firstSeen.add(key); + } + for (const row of rows) { + if (duplicateIds.has(row.rowId)) { + const duplicateMessage = `${counts.get(row.after.toLocaleUpperCase()) ?? 2} rows normalize to the same serial.`; + row.status = row.status === 'invalid' ? 'invalid' : 'duplicate'; + row.message = row.message ? `${row.message} ${duplicateMessage}` : duplicateMessage; + row.drop = options.mode === 'deduplicate'; + } + } + return rows; +} + +export function applySerialPreview(dataset: Dataset, column: string, preview: readonly SerialPreviewRow[], dropDuplicates = false): Dataset { + if (!dataset.columns.includes(column)) throw new Error('Choose an existing serial column.'); + if (preview.some(row => row.status === 'invalid')) throw new Error('Resolve invalid serial values before applying.'); + const byId = new Map(preview.map(row => [row.rowId, row])); + const records = dataset.records.filter(row => !(dropDuplicates && byId.get(row.id)?.drop)).map(row => { + const change = byId.get(row.id); + if (!change) return row; + const values = cloneValues(row.values); values[column] = change.after; + return { ...row, values }; + }); + return { ...dataset, records }; +} diff --git a/src/features/serial-tools/regex.worker.ts b/src/features/serial-tools/regex.worker.ts new file mode 100644 index 0000000..958407b --- /dev/null +++ b/src/features/serial-tools/regex.worker.ts @@ -0,0 +1,15 @@ +export {}; +type Request = { id: number; source: string; values: string[] }; +const scope = self as unknown as { onmessage: ((event: MessageEvent) => void) | null; postMessage: (message: unknown) => void }; +scope.onmessage = (event: MessageEvent) => { + const { id, source, values } = event.data; + try { + const regex = new RegExp(source); + const matches = values.map(value => { regex.lastIndex = 0; return regex.test(value); }); + scope.postMessage({ id, ok: true, matches }); + } catch (error) { + scope.postMessage({ id, ok: false, error: error instanceof Error ? error.message : 'Invalid pattern.' }); + } +}; +// Native worker loading has a separate deadline from regex execution. +scope.postMessage({ ready: true }); diff --git a/src/features/specialized-labels/SpecialLabelsPage.tsx b/src/features/specialized-labels/SpecialLabelsPage.tsx new file mode 100644 index 0000000..258a5d5 --- /dev/null +++ b/src/features/specialized-labels/SpecialLabelsPage.tsx @@ -0,0 +1,109 @@ +import { useEffect, useMemo, useState } from 'react'; +import type { LabelField, LabelTemplate } from '../../types'; +import { DEFAULT_TEMPLATE } from '../../types'; +import type { StudioPageProps } from '../../studio/contracts'; +import { ColumnSelect, HelpDetails, NoDataset, ToolFrame } from '../../studio/ui'; +import { renderLabel, validateTemplate } from '../labels/renderer'; + +type Props = StudioPageProps & { mode: 'cable' | 'location' | 'code' }; +const makeField = (source: string, label: string, fontSize: number, bold = true): LabelField => ({ source, label, fontSize, bold }); + +export function SpecialLabelsPage(props: Props) { + const { dataset, selectedIds, template, page, busy, mode, onApplyTemplate, onExportJob, onNavigate } = props; + const [columns, setColumns] = useState>({}); + const [useCode, setUseCode] = useState(mode !== 'cable'); + const [codeKind, setCodeKind] = useState<'qr' | 'code128'>('qr'); + const [mirrored, setMirrored] = useState(mode === 'cable'); + const [widthInput, setWidthInput] = useState(String(mode === 'code' ? 50 : 70)); + const [heightInput, setHeightInput] = useState(String(mode === 'cable' ? 18 : mode === 'location' ? 60 : 25)); + const [notice, setNotice] = useState(''); + const [error, setError] = useState(''); + const [previews, setPreviews] = useState>([]); + const [previewError, setPreviewError] = useState(''); + + useEffect(() => { + setUseCode(mode !== 'cable'); setCodeKind('qr'); setMirrored(mode === 'cable'); + setWidthInput(String(mode === 'code' ? 50 : 70)); setHeightInput(String(mode === 'cable' ? 18 : mode === 'location' ? 60 : 25)); + }, [mode]); + + const current = useMemo(() => { + if (!dataset) return DEFAULT_TEMPLATE; + const fields: LabelField[] = []; + const append = (...items: Array<[string, string, number, boolean?]>) => items.forEach(([key, label, size, bold]) => { + const source = columns[key]; if (source) fields.push(makeField(source, label, size, bold)); + }); + if (mode === 'cable') append(['source', 'From', 8], ['port', 'Port', 7, false], ['target', 'To', 8]); + else if (mode === 'location') append(['site', 'Site', 12], ['building', 'Building', 10], ['floor', 'Floor', 9], ['room', 'Room', 12], ['rack', 'Rack', 11], ['shelf', 'Shelf', 10], ['bin', 'Bin', 10]); + else append(['value', 'Code value', 14]); + const hierarchy = ['site', 'building', 'floor', 'room', 'rack', 'shelf', 'bin'].map(key => columns[key]).filter((value): value is string => Boolean(value)); + const codeType: LabelTemplate['code']['type'] = useCode ? (mode !== 'location' ? codeKind : 'qr') : 'none'; + const locationPayload = mode === 'location' && useCode && hierarchy.length ? `location://site/${hierarchy.map(key => `{${key}}`).join('/')}` : ''; + const codeField = mode === 'code' ? columns.value ?? '' : mode === 'location' ? hierarchy[0] ?? '' : columns.source ?? ''; + return { + ...DEFAULT_TEMPLATE, + widthMm: Number(widthInput), + heightMm: Number(heightInput), + paddingMm: 2, border: true, alignment: 'center' as const, mode, + textLayout: mirrored ? 'mirrored' as const : 'standard' as const, + fields, + code: { + ...DEFAULT_TEMPLATE.code, type: codeType, field: codeField, + sizeMm: mode === 'location' ? 18 : mode === 'cable' ? 10 : 16, + barcodeHeightMm: 8, barcodeText: true, payload: locationPayload, + ...(mode === 'location' && useCode ? { payloadMode: 'location' as const } : {}), + }, + } satisfies LabelTemplate; + }, [dataset, columns, mode, useCode, codeKind, mirrored, widthInput, heightInput]); + + const selectedRecords = useMemo(() => dataset ? dataset.records.filter(record => selectedIds.has(record.id)) : [], [dataset, selectedIds]); + useEffect(() => { + let live = true; + setPreviews([]); setPreviewError(''); + if (!dataset) return () => { live = false; }; + void (async () => { + try { + const result: Array<{ id: string; src: string }> = []; + for (const record of selectedRecords.slice(0, 36)) { + const src = await renderLabel(record, current); + if (!live) return; + result.push({ id: record.id, src }); setPreviews([...result]); + } + } catch (cause) { + if (live) setPreviewError(cause instanceof Error ? cause.message : 'Could not render the label preview.'); + } + })(); + return () => { live = false; }; + }, [dataset, mode, selectedRecords, current]); + + const templateReady = JSON.stringify(template) === JSON.stringify(current); + const apply = () => { + setError(''); + try { + if (!selectedRecords.length) throw new Error('Select at least one row before preparing specialized labels.'); + validateTemplate(current); + onApplyTemplate(current, page, mode === 'cable' ? 'Cable wrap label' : mode === 'location' ? 'Location label' : 'Code label'); + setNotice('Template applied. Create PDF after the workspace reflects this layout.'); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not apply this label layout.'); } + }; + const print = async () => { + setError(''); + try { + if (!templateReady) throw new Error('Apply this layout to the workspace first.'); + if (!selectedRecords.length) throw new Error('Select at least one row before creating labels.'); + const job = await onExportJob(); + if (!job) throw new Error('The print job did not complete. Review its settings and try again.'); + setNotice(`${job.labels.length} physical labels exported from an immutable print snapshot.`); + } catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not create this print job.'); } + }; + const choose = (key: string, label: string, optional = false) => setColumns(old => ({ ...old, [key]: value }))}/>; + if (!dataset) return onNavigate('asset-labels')}/>; + const description = mode === 'cable' ? 'Create cable wrap labels.' : mode === 'location' ? 'Create labels from location fields.' : 'Create QR, barcode, or text labels.'; + return +
{selectedRecords.length} selected labels{mode === 'cable' ? 'The mirrored pair is one physical label.' : 'Choose rows in Asset Labels to preview or export.'}
+ {mode === 'cable' ? <>{choose('source', 'Source endpoint')}{choose('port', 'Port', true)}{choose('target', 'Target endpoint')} : mode === 'location' ? <>{choose('site', 'Site / warehouse')}{choose('building', 'Building', true)}{choose('floor', 'Floor', true)}{choose('room', 'Room', true)}{choose('rack', 'Rack', true)}{choose('shelf', 'Shelf', true)}{choose('bin', 'Bin', true)} : choose('value', 'Code value')} +
{useCode && }{mode === 'cable' && }
+

Label preview

Previewing up to 36 selected labels.{mode === 'cable' && mirrored ? ' Each wrap repeats the endpoints on opposite-facing panels.' : ''}

{previewError &&

{previewError}

}
{previews.map(item =>
{`Label
{item.id}
)}{!previews.length && !previewError &&

Select rows to preview their labels.

}
+ {notice &&

{notice}

}{error &&

{error}

} + {mode === 'location' && Map the hierarchy levels present in your data. QR codes use the mapped location path.} +
; +} diff --git a/src/features/storage/library.ts b/src/features/storage/library.ts new file mode 100644 index 0000000..40f5f53 --- /dev/null +++ b/src/features/storage/library.ts @@ -0,0 +1,132 @@ +export type LibraryStore = 'templates' | 'printers'; +export type LibraryEntry = { id: string; name: string; json: string }; + +const DATABASE_NAME = 'assettag-studio-library'; +const DATABASE_VERSION = 1; +const MAX_ENTRIES = 100; +const MAX_DOCUMENT_BYTES = 128 * 1024; + +function validateStore(store: LibraryStore): LibraryStore { + if (store !== 'templates' && store !== 'printers') throw new Error('Choose a supported library.'); + return store; +} + +function validateEntry(entry: LibraryEntry) { + if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string' || !entry.id.trim() || entry.id.length > 200) throw new Error('Library entry has an invalid id.'); + if (typeof entry.name !== 'string' || !entry.name.trim() || entry.name.length > 100) throw new Error('Library entry name must contain 1 to 100 characters.'); + if (typeof entry.json !== 'string' || new TextEncoder().encode(entry.json).byteLength > MAX_DOCUMENT_BYTES) throw new Error('Library document must be 128 KiB or smaller.'); +} + +function openDatabase(): Promise { + if (typeof indexedDB === 'undefined') return Promise.reject(new Error('Browser storage is unavailable in this environment.')); + return new Promise((resolve, reject) => { + let request!: IDBOpenDBRequest; + try { request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION); } + catch { reject(new Error('Browser storage could not be opened. Check this browser’s storage settings.')); return; } + let settled = false; + request.onupgradeneeded = () => { + const database = request.result; + if (!database.objectStoreNames.contains('templates')) database.createObjectStore('templates', { keyPath: 'id' }); + if (!database.objectStoreNames.contains('printers')) database.createObjectStore('printers', { keyPath: 'id' }); + }; + request.onblocked = () => { + if (!settled) { settled = true; reject(new Error('Browser storage upgrade is blocked. Close another AssetTag Studio tab and retry.')); } + }; + request.onerror = () => { + if (!settled) { settled = true; reject(new Error('Browser storage could not be opened. Check this browser’s storage settings.')); } + }; + request.onsuccess = () => { + const database = request.result; + database.onversionchange = () => database.close(); + if (!settled) { settled = true; resolve(database); } + else database.close(); + }; + }); +} + +function transactionError(error: unknown, fallback: string): Error { + if (error instanceof DOMException && error.name === 'QuotaExceededError') return new Error('Browser storage is full. Delete saved items or free space, then retry.'); + if (error instanceof DOMException && error.name === 'ConstraintError') return new Error('An item with this id already exists. Refresh the library and retry.'); + if (error instanceof Error && error.message) return new Error(error.message); + return new Error(fallback); +} + +function runTransaction(store: LibraryStore, mode: IDBTransactionMode, operation: (objectStore: IDBObjectStore, transaction: IDBTransaction) => IDBRequest | void, fallback: string): Promise { + return openDatabase().then((database) => new Promise((resolve, reject) => { + let transaction: IDBTransaction; + try { transaction = database.transaction(validateStore(store), mode); } + catch (error) { database.close(); reject(transactionError(error, fallback)); return; } + let result: T | undefined; + let requestError: unknown; + let finished = false; + let request: IDBRequest | void = undefined; + try { request = operation(transaction.objectStore(store), transaction); } + catch (error) { transaction.abort(); requestError = error; } + if (request) { + request.onsuccess = () => { result = request.result; }; + request.onerror = () => { requestError = request?.error; }; + } + transaction.oncomplete = () => { + if (finished) return; + finished = true; database.close(); resolve(result); + }; + transaction.onabort = () => { + if (finished) return; + finished = true; database.close(); reject(transactionError(requestError ?? transaction.error, fallback)); + }; + transaction.onerror = () => { requestError = requestError ?? transaction.error; }; + })); +} + +export async function listEntries(store: LibraryStore): Promise { + // Fetch only enough rows to distinguish an allowed library from an over-capacity one. + const result = await runTransaction(store, 'readonly', (objectStore) => objectStore.getAll(undefined, MAX_ENTRIES + 1), 'Saved items could not be read from browser storage.'); + if (!Array.isArray(result)) throw new Error('Saved library data is corrupted. Remove the damaged item and retry.'); + if (result.length > MAX_ENTRIES) throw new Error('Saved library contains more than 100 items. Delete extras before continuing.'); + return result.map((candidate) => { + if (!candidate || typeof candidate !== 'object') throw new Error('Saved library data is corrupted. Remove the damaged item and retry.'); + const entry = candidate as Partial; + try { validateEntry(entry as LibraryEntry); } catch { throw new Error('Saved library data is corrupted. Remove the damaged item and retry.'); } + return { id: entry.id!, name: entry.name!, json: entry.json! }; + }); +} + +export async function putEntry(store: LibraryStore, entry: LibraryEntry): Promise { + validateStore(store); validateEntry(entry); + let capacityError: Error | undefined; + let operationError: unknown; + const fallback = 'Saved item could not be written to browser storage.'; + await runTransaction(store, 'readwrite', (objectStore, transaction) => { + const countRequest = objectStore.count(); + countRequest.onsuccess = () => { + let existing: IDBRequest; + try { existing = objectStore.get(entry.id); } + catch (error) { operationError = error; try { transaction.abort(); } catch { /* Already aborting. */ } return; } + existing.onsuccess = () => { + if (!existing.result && countRequest.result >= MAX_ENTRIES) { + capacityError = new Error('This library already contains 100 items. Delete an item before saving another.'); + try { transaction.abort(); } catch { /* Already aborting. */ } + return; + } + try { objectStore.put({ ...entry }); } + catch (error) { operationError = error; try { transaction.abort(); } catch { /* Already aborting. */ } } + }; + existing.onerror = () => { operationError = existing.error; }; + }; + return; + }, fallback).catch((error: unknown) => { + if (capacityError) throw capacityError; + throw transactionError(operationError ?? error, fallback); + }); +} + +export async function deleteEntry(store: LibraryStore, id: string): Promise { + validateStore(store); + if (typeof id !== 'string' || !id) throw new Error('Choose a saved item to delete.'); + await runTransaction(store, 'readwrite', (objectStore) => objectStore.delete(id), 'Saved item could not be deleted from browser storage.'); +} + +export async function clearEntries(store: LibraryStore): Promise { + validateStore(store); + await runTransaction(store, 'readwrite', (objectStore) => objectStore.clear(), 'Saved library could not be cleared from browser storage.'); +} diff --git a/src/features/templates/documents.test.ts b/src/features/templates/documents.test.ts new file mode 100644 index 0000000..b905e1f --- /dev/null +++ b/src/features/templates/documents.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_PAGE, DEFAULT_TEMPLATE } from '../../types'; +import { mapTemplateFields, parseTemplateDocument, serializeTemplateDocument } from './documents'; +import { BUILT_IN_TEMPLATES } from '../../studio/pages/TemplatesPage'; + +const VALID_TEMPLATE = { ...DEFAULT_TEMPLATE, code: { ...DEFAULT_TEMPLATE.code, field: 'Asset ID' } }; + +describe('template documents', () => { + it('preserves all seven hierarchy fields within the renderer bounds', () => { + const fields = ['Site', 'Building', 'Floor', 'Room', 'Rack', 'Shelf', 'Bin'].map(source => ({ source, label: source, fontSize: 14, bold: true })); + const template = { ...VALID_TEMPLATE, heightMm: 80, fields }; + expect(parseTemplateDocument(serializeTemplateDocument('Hierarchy', template)).template.fields).toEqual(fields); + expect(() => serializeTemplateDocument('Too many', { ...template, fields: Array.from({ length: 33 }, () => fields[0]) })).toThrow(/32 fields/); + }); + it('round trips a settings-only version 1 document without changing its input', () => { + const source = structuredClone(VALID_TEMPLATE); + const json = serializeTemplateDocument('Receiving', source, DEFAULT_PAGE); + expect(parseTemplateDocument(json)).toEqual({ version: 1, kind: 'template', name: 'Receiving', template: source, page: DEFAULT_PAGE }); + expect(source).toEqual(VALID_TEMPLATE); + }); + + it('accepts supported optional print contracts without inserting defaults', () => { + const document = { version: 1, kind: 'template', name: 'Cable', template: { ...VALID_TEMPLATE, mode: 'cable', textLayout: 'mirrored', code: { ...VALID_TEMPLATE.code, type: 'none' } } }; + expect(parseTemplateDocument(JSON.stringify(document)).template).toEqual(document.template); + const legacy = JSON.parse(serializeTemplateDocument('Legacy', VALID_TEMPLATE)) as Record; + const template = legacy.template as Record; + delete template.mode; + delete template.textLayout; + const code = template.code as Record; + delete code.payloadMode; + delete code.barcodeScale; + expect(parseTemplateDocument(JSON.stringify(legacy)).template).not.toHaveProperty('mode'); + }); + + it('rejects unknown, row-bearing, malformed, future-version, and oversized documents', () => { + const base = JSON.parse(serializeTemplateDocument('Valid', VALID_TEMPLATE)) as Record; + expect(() => parseTemplateDocument(JSON.stringify({ ...base, extra: true }))).toThrow(/unsupported property/i); + expect(() => parseTemplateDocument(JSON.stringify({ ...base, records: [{ id: '1', values: { asset: 'x' } }] }))).toThrow(/unsupported property/i); + expect(() => parseTemplateDocument(JSON.stringify({ ...base, version: 2 }))).toThrow(/version/i); + expect(() => parseTemplateDocument(JSON.stringify({ ...base, template: { ...(base.template as object), unsafe: 'value' } }))).toThrow(/unsupported property/i); + expect(() => parseTemplateDocument('{')).toThrow(/valid json/i); + expect(() => parseTemplateDocument(' '.repeat(128 * 1024 + 1))).toThrow(/128 kib/i); + }); + + it('rejects out-of-range numeric settings, impossible dimensions, and malformed payload tokens', () => { + const makeDocument = (templatePatch: Record, pagePatch?: Record) => { + const template = { ...VALID_TEMPLATE, ...templatePatch }; + const page = { ...DEFAULT_PAGE, ...pagePatch }; + return JSON.stringify({ version: 1, kind: 'template', name: 'Invalid', template, page }); + }; + expect(() => parseTemplateDocument(makeDocument({ paddingMm: 11 }))).toThrow(/paddingmm/i); + expect(() => parseTemplateDocument(makeDocument({ code: { ...VALID_TEMPLATE.code, sizeMm: 31 } }))).toThrow(/sizeMm/i); + expect(() => parseTemplateDocument(makeDocument({ code: { ...VALID_TEMPLATE.code, field: ' ' } }))).toThrow(/field/i); + expect(() => parseTemplateDocument(makeDocument({ code: { ...VALID_TEMPLATE.code, payload: 'tag:{Asset ID' } }))).toThrow(/placeholders/i); + expect(() => parseTemplateDocument(makeDocument({}, { widthMm: 100, marginLeftMm: 60, marginRightMm: 50 }))).toThrow(/margins/i); + }); + + it('maps each source explicitly and preserves unmapped references and source objects', () => { + const source = { ...VALID_TEMPLATE, code: { ...VALID_TEMPLATE.code, field: 'Serial', payload: 'asset:{Asset ID}' }, fields: [{ source: 'Name', label: 'Device', fontSize: 8, bold: false }] }; + const mapping = { Serial: 'S/N', 'Asset ID': 'Tag', Name: 'Device Name' }; + const result = mapTemplateFields(source, ['S/N', 'Tag', 'Device Name'], mapping); + expect(result.missing).toEqual([]); + expect(result.template.code).toMatchObject({ field: 'S/N', payload: 'asset:{Tag}' }); + expect(result.template.fields[0].source).toBe('Device Name'); + expect(source.code.field).toBe('Serial'); + const incomplete = mapTemplateFields(source, ['S/N'], { Serial: 'S/N' }); + expect(incomplete.missing).toEqual(['Name', 'Asset ID']); + expect(incomplete.template.fields[0].source).toBe('Name'); + }); + + it('maps hostile property names as ordinary dataset column names', () => { + const source = { + ...VALID_TEMPLATE, + code: { ...VALID_TEMPLATE.code, field: '__proto__', payload: '{constructor}:{toString}' }, + fields: [{ source: 'toString', label: '', fontSize: 8, bold: false }], + }; + const mapping = Object.create(null) as Record; + mapping.__proto__ = 'Asset Key'; + mapping['constructor'] = 'Serial'; + mapping['toString'] = 'Display Name'; + const result = mapTemplateFields(source, ['Asset Key', 'Serial', 'Display Name'], mapping); + expect(result.missing).toEqual([]); + expect(result.template.code.field).toBe('Asset Key'); + expect(result.template.code.payload).toBe('{Serial}:{Display Name}'); + expect(result.template.fields[0].source).toBe('Display Name'); + }); + + it('serializes and maps every built-in preset, omitting the unused code field for no-code labels', () => { + for (const item of BUILT_IN_TEMPLATES) { + const json = serializeTemplateDocument(item.name, item.template, item.page); + expect(parseTemplateDocument(json).template).toEqual(item.template); + const refs = [...new Set([...(item.template.code.type === 'none' ? [] : [item.template.code.field]), ...item.template.fields.map((field) => field.source), ...[...item.template.code.payload.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1])].filter(Boolean))]; + expect(mapTemplateFields(item.template, refs, {}).missing).toEqual([]); + if (item.template.code.type === 'none') expect(refs).not.toContain(item.template.code.field); + } + }); +}); diff --git a/src/features/templates/documents.ts b/src/features/templates/documents.ts new file mode 100644 index 0000000..7dc97da --- /dev/null +++ b/src/features/templates/documents.ts @@ -0,0 +1,175 @@ +import type { LabelTemplate, PageSettings } from '../../types'; + +export const TEMPLATE_DOCUMENT_VERSION = 1; +export const MAX_TEMPLATE_DOCUMENT_BYTES = 128 * 1024; +export const MAX_TEMPLATE_NAME_LENGTH = 100; + +export type TemplateDocument = { + version: 1; + kind: 'template'; + name: string; + template: LabelTemplate; + page?: PageSettings; +}; + +const TEMPLATE_KEYS = ['widthMm', 'heightMm', 'paddingMm', 'border', 'alignment', 'code', 'fields', 'mode', 'textLayout'] as const; +const CODE_KEYS = ['type', 'field', 'sizeMm', 'payload', 'barcodeHeightMm', 'barcodeScale', 'barcodeText', 'barcodeTextPosition', 'payloadMode'] as const; +const FIELD_KEYS = ['source', 'label', 'fontSize', 'bold'] as const; +const PAGE_KEYS = ['preset', 'widthMm', 'heightMm', 'marginTopMm', 'marginBottomMm', 'marginLeftMm', 'marginRightMm', 'gapXMm', 'gapYMm', 'offsetXMm', 'offsetYMm'] as const; + +function record(value: unknown, label: string): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object.`); + return value as Record; +} + +function exactKeys(value: Record, allowed: readonly string[], label: string, required: readonly string[] = allowed) { + for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error(`${label} has an unsupported property: ${key}.`); + for (const key of required) if (!Object.hasOwn(value, key)) throw new Error(`${label} is missing ${key}.`); +} + +function boundedNumber(value: unknown, label: string, min: number, max: number): number { + if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) throw new Error(`${label} must be a number from ${min} to ${max}.`); + return value; +} + +function boundedString(value: unknown, label: string, max: number, allowEmpty = true): string { + if (typeof value !== 'string' || value.length > max || (!allowEmpty && !value.trim())) throw new Error(`${label} must be ${allowEmpty ? 'a' : 'a non-empty'} string up to ${max} characters.`); + return value; +} + +function boolean(value: unknown, label: string): boolean { + if (typeof value !== 'boolean') throw new Error(`${label} must be true or false.`); + return value; +} + +function parseTemplate(value: unknown): LabelTemplate { + const input = record(value, 'template'); + exactKeys(input, TEMPLATE_KEYS, 'template', ['widthMm', 'heightMm', 'paddingMm', 'border', 'alignment', 'code', 'fields']); + const alignment = input.alignment; + if (!['left', 'center', 'right'].includes(String(alignment))) throw new Error('template.alignment is unsupported.'); + if (input.mode !== undefined && !['asset', 'cable', 'location', 'code'].includes(String(input.mode))) throw new Error('template.mode is unsupported.'); + if (input.textLayout !== undefined && !['standard', 'mirrored'].includes(String(input.textLayout))) throw new Error('template.textLayout is unsupported.'); + const codeInput = record(input.code, 'template.code'); + exactKeys(codeInput, CODE_KEYS, 'template.code', ['type', 'field', 'sizeMm', 'payload', 'barcodeHeightMm', 'barcodeText', 'barcodeTextPosition']); + if (!['qr', 'code128', 'none'].includes(String(codeInput.type))) throw new Error('template.code.type is unsupported.'); + if (!['top', 'bottom'].includes(String(codeInput.barcodeTextPosition))) throw new Error('template.code.barcodeTextPosition is unsupported.'); + if (codeInput.payloadMode !== undefined && !['text', 'url', 'fieldlens', 'location'].includes(String(codeInput.payloadMode))) throw new Error('template.code.payloadMode is unsupported.'); + const widthMm = boundedNumber(input.widthMm, 'template.widthMm', 10, 200); + const heightMm = boundedNumber(input.heightMm, 'template.heightMm', 10, 200); + const paddingMm = boundedNumber(input.paddingMm, 'template.paddingMm', 0, Math.min(widthMm, heightMm) / 3); + const fieldsInput = input.fields; + if (!Array.isArray(fieldsInput) || fieldsInput.length > 32) throw new Error('template.fields must contain at most 32 fields.'); + const fields = fieldsInput.map((candidate, index) => { + const field = record(candidate, `template.fields[${index}]`); + exactKeys(field, FIELD_KEYS, `template.fields[${index}]`); + return { + source: boundedString(field.source, `template.fields[${index}].source`, 200, false), + label: boundedString(field.label, `template.fields[${index}].label`, 200), + fontSize: boundedNumber(field.fontSize, `template.fields[${index}].fontSize`, 5, 48), + bold: boolean(field.bold, `template.fields[${index}].bold`), + }; + }); + const codeType = codeInput.type as LabelTemplate['code']['type']; + const codeField = boundedString(codeInput.field, 'template.code.field', 200); + if (codeType !== 'none' && !codeField.trim()) throw new Error('template.code.field must name a column when a code is enabled.'); + const sizeMm = boundedNumber(codeInput.sizeMm, 'template.code.sizeMm', 0, 100); + const barcodeHeightMm = boundedNumber(codeInput.barcodeHeightMm, 'template.code.barcodeHeightMm', 0, 100); + if (codeType === 'qr' && (sizeMm < 8 || sizeMm > Math.min(widthMm, heightMm))) throw new Error(`template.code.sizeMm must be from 8 to ${Math.min(widthMm, heightMm)} for a QR code.`); + if (codeType === 'code128' && (barcodeHeightMm < 5 || barcodeHeightMm > Math.min(40, heightMm))) throw new Error(`template.code.barcodeHeightMm must be from 5 to ${Math.min(40, heightMm)} for Code 128.`); + const payload = boundedString(codeInput.payload, 'template.code.payload', 2000); + if (/[{}]/.test(payload.replace(/\{([^{}]+)\}/g, '')) || [...payload.matchAll(/\{([^{}]+)\}/g)].some((match) => !match[1]?.trim())) { + throw new Error('template.code.payload must use complete, non-empty {columnName} placeholders.'); + } + const result: LabelTemplate = { + widthMm, + heightMm, + paddingMm, + border: boolean(input.border, 'template.border'), + alignment: alignment as LabelTemplate['alignment'], + code: { + type: codeType, + field: codeField, + sizeMm, + payload, + barcodeHeightMm, + barcodeText: boolean(codeInput.barcodeText, 'template.code.barcodeText'), + barcodeTextPosition: codeInput.barcodeTextPosition as 'top' | 'bottom', + ...(codeInput.barcodeScale === undefined ? {} : { barcodeScale: boundedNumber(codeInput.barcodeScale, 'template.code.barcodeScale', 0.8, 3) }), + ...(codeInput.payloadMode === undefined ? {} : { payloadMode: codeInput.payloadMode as NonNullable }), + }, + fields, + ...(input.mode === undefined ? {} : { mode: input.mode as NonNullable }), + ...(input.textLayout === undefined ? {} : { textLayout: input.textLayout as NonNullable }), + }; + return result; +} + +function parsePage(value: unknown): PageSettings { + const input = record(value, 'page'); + exactKeys(input, PAGE_KEYS, 'page', ['preset', 'widthMm', 'heightMm', 'marginTopMm', 'marginBottomMm', 'marginLeftMm', 'marginRightMm', 'gapXMm', 'gapYMm']); + if (!['A4', 'Letter', 'A5', 'Custom'].includes(String(input.preset))) throw new Error('page.preset is unsupported.'); + const result: PageSettings = { + preset: input.preset as PageSettings['preset'], + widthMm: boundedNumber(input.widthMm, 'page.widthMm', 50, 500), + heightMm: boundedNumber(input.heightMm, 'page.heightMm', 50, 700), + marginTopMm: boundedNumber(input.marginTopMm, 'page.marginTopMm', 0, 100), + marginBottomMm: boundedNumber(input.marginBottomMm, 'page.marginBottomMm', 0, 100), + marginLeftMm: boundedNumber(input.marginLeftMm, 'page.marginLeftMm', 0, 100), + marginRightMm: boundedNumber(input.marginRightMm, 'page.marginRightMm', 0, 100), + gapXMm: boundedNumber(input.gapXMm, 'page.gapXMm', 0, 50), + gapYMm: boundedNumber(input.gapYMm, 'page.gapYMm', 0, 50), + ...(input.offsetXMm === undefined ? {} : { offsetXMm: boundedNumber(input.offsetXMm, 'page.offsetXMm', -50, 50) }), + ...(input.offsetYMm === undefined ? {} : { offsetYMm: boundedNumber(input.offsetYMm, 'page.offsetYMm', -50, 50) }), + }; + if (result.marginLeftMm + result.marginRightMm >= result.widthMm) throw new Error('page left and right margins must leave room for labels.'); + if (result.marginTopMm + result.marginBottomMm >= result.heightMm) throw new Error('page top and bottom margins must leave room for labels.'); + return result; +} + +function documentBytes(json: string) { + return new TextEncoder().encode(json).byteLength; +} + +export function parseTemplateDocument(json: string): TemplateDocument { + if (typeof json !== 'string' || documentBytes(json) > MAX_TEMPLATE_DOCUMENT_BYTES) throw new Error('Template document must be 128 KiB or smaller.'); + let parsed: unknown; + try { parsed = JSON.parse(json) as unknown; } catch { throw new Error('Template file is not valid JSON.'); } + const input = record(parsed, 'document'); + exactKeys(input, ['version', 'kind', 'name', 'template', 'page'], 'document', ['version', 'kind', 'name', 'template']); + if (input.version !== TEMPLATE_DOCUMENT_VERSION) throw new Error(`Unsupported template document version: ${String(input.version)}.`); + if (input.kind !== 'template') throw new Error('This file is not a template document.'); + const name = boundedString(input.name, 'name', MAX_TEMPLATE_NAME_LENGTH, false).trim(); + if (!name) throw new Error('Template name cannot be blank.'); + return { version: 1, kind: 'template', name, template: parseTemplate(input.template), ...(input.page === undefined ? {} : { page: parsePage(input.page) }) }; +} + +export function serializeTemplateDocument(name: string, template: LabelTemplate, page?: PageSettings): string { + const document: TemplateDocument = { version: 1, kind: 'template', name: name.trim(), template, ...(page ? { page } : {}) }; + const json = JSON.stringify(document, null, 2); + if (documentBytes(json) > MAX_TEMPLATE_DOCUMENT_BYTES) throw new Error('Template document must be 128 KiB or smaller.'); + // Run generated documents through the same whitelist and bounds as imported files. + parseTemplateDocument(json); + return json; +} + +export type TemplateFieldMapping = { template: LabelTemplate; missing: string[] }; + +/** Maps every imported field reference explicitly; unknown references remain visible as missing. */ +export function mapTemplateFields(template: LabelTemplate, columns: readonly string[], mapping: Record): TemplateFieldMapping { + const references = new Set([...(template.code.type === 'none' ? [] : [template.code.field]), ...template.fields.map((field) => field.source), ...[...template.code.payload.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1])].filter(Boolean)); + const mappedReference = (reference: string) => { + const value = Object.hasOwn(mapping, reference) ? mapping[reference] : undefined; + return typeof value === 'string' && value ? value : reference; + }; + const missing = [...references].filter((reference) => !columns.includes(mappedReference(reference))); + const mapped: LabelTemplate = { + ...template, + code: { + ...template.code, + field: template.code.field ? mappedReference(template.code.field) : '', + payload: template.code.payload.replace(/\{([^{}]+)\}/g, (_token, field: string) => `{${mappedReference(field)}}`), + }, + fields: template.fields.map((field) => ({ ...field, source: mappedReference(field.source) })), + }; + return { template: mapped, missing }; +} diff --git a/src/studio/FilePicker.css b/src/studio/FilePicker.css new file mode 100644 index 0000000..3329028 --- /dev/null +++ b/src/studio/FilePicker.css @@ -0,0 +1,169 @@ +.file-picker { + display: inline-flex; + flex-direction: column; + align-items: flex-start; + gap: 6px; + min-width: 0; + max-width: 100%; +} + +.file-picker__actions { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 6px; + min-width: 0; +} + +.file-picker__button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + min-width: 44px; + min-height: 44px; + max-width: 100%; + white-space: normal; + text-align: center; +} + +.file-picker__icon { + flex: none; +} + +.file-picker__hint { + display: block; + max-width: 100%; + color: var(--nav-muted, var(--muted)); + font-size: 0.75rem; + line-height: 1.45; + overflow-wrap: anywhere; +} + +.file-picker__button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; +} + +.file-picker__button:disabled { + cursor: not-allowed; +} + +.welcome-actions .file-picker { + align-items: stretch; +} + +.welcome-actions .file-picker__button { + width: 100%; + height: 100%; +} + +.tool-row .file-picker { + flex: 0 1 auto; +} + +.tool-row .file-picker__button { + max-width: 100%; +} + +.tool-control .file-picker { + align-items: flex-start; + width: 100%; +} + +.file-picker--drop { + display: flex; + width: 100%; + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 14px; + border: 1px dashed var(--line); + border-radius: 10px; + background: var(--wash); + transition: border-color 140ms ease, background 140ms ease, box-shadow 140ms ease; +} + +.file-picker--drop:hover, +.file-picker--drop.is-dragging { + border-color: var(--accent); + background: var(--accent-soft); +} + +.file-picker--drop.is-dragging { + border-style: solid; + box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 20%, transparent); +} + +.file-picker__drop-copy { + display: flex; + min-width: 0; + align-items: center; + gap: 12px; + color: var(--ink); +} + +.file-picker__tile { + display: grid; + width: 46px; + height: 46px; + flex: 0 0 46px; + place-items: center; + border: 1px solid color-mix(in srgb, var(--accent) 22%, var(--line)); + border-radius: 10px; + background: var(--surface); + color: var(--accent-dark); +} + +.file-picker__drop-label { + font-size: 12px; + font-weight: 600; + line-height: 1.4; +} + +.file-picker--drop .file-picker__actions { + align-items: flex-end; +} + +.file-picker--drop .file-picker__hint { + text-align: right; +} + +.tool-row .file-picker--drop { + flex: 1 1 100%; +} + +.tool-control .file-picker--drop { + align-items: center; +} + +@media (max-width: 640px) { + .tool-row .file-picker { + max-width: 100%; + } + + .tool-row .file-picker__button { + white-space: normal; + } + + .file-picker--drop { + align-items: flex-start; + flex-direction: column; + } + + .file-picker--drop .file-picker__actions, + .file-picker--drop .file-picker__button { + width: 100%; + } + + .file-picker--drop .file-picker__hint { + text-align: left; + } +} + +@media (prefers-reduced-motion: reduce) { + .file-picker--drop { + transition: none; + } +} diff --git a/src/studio/FilePicker.tsx b/src/studio/FilePicker.tsx new file mode 100644 index 0000000..1827ce1 --- /dev/null +++ b/src/studio/FilePicker.tsx @@ -0,0 +1,81 @@ +import { useId, useRef, useState, type DragEvent } from 'react'; +import './FilePicker.css'; + +type FilePickerProps = { + accept: string; + inputLabel: string; + buttonText: string; + onFile: (file: File) => void; + disabled?: boolean; + hint?: string; + buttonClassName?: string; + dropTarget?: boolean; +}; + +export function FilePicker({ accept, inputLabel, buttonText, onFile, disabled = false, hint, buttonClassName = 'secondary-button', dropTarget = false }: FilePickerProps) { + const input = useRef(null); + const hintId = useId(); + const [dragging, setDragging] = useState(false); + + function openPicker() { + if (!input.current || disabled) return; + // Clear before opening so selecting the same file fires change again, even after cancel. + input.current.value = ''; + input.current.click(); + } + + function onDragOver(event: DragEvent) { + if (!dropTarget || !event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + if (disabled) { + event.dataTransfer.dropEffect = 'none'; + setDragging(false); + return; + } + event.dataTransfer.dropEffect = 'copy'; + setDragging(true); + } + + function onDragLeave(event: DragEvent) { + if (dropTarget && !event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false); + } + + function onDrop(event: DragEvent) { + if (!dropTarget) return; + event.preventDefault(); + setDragging(false); + const file = event.dataTransfer.files[0]; + if (file && !disabled) onFile(file); + } + + return
+ {dropTarget && } +
+ + {hint && {hint}} +
+ { + const file = event.currentTarget.files?.[0]; + event.currentTarget.value = ''; + if (file) onFile(file); + }} + /> +
; +} diff --git a/src/studio/FloatingToolDock.tsx b/src/studio/FloatingToolDock.tsx new file mode 100644 index 0000000..91a9f0b --- /dev/null +++ b/src/studio/FloatingToolDock.tsx @@ -0,0 +1,101 @@ +import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; +import { NAVIGATION, type ToolGroup } from './workspace'; + +const revealDistance = 24; + +export function FloatingToolDock({ group, children }: { group: ToolGroup; children: ReactNode }) { + const [open, setOpen] = useState(false); + const panelId = useId(); + const dock = useRef(null); + const tab = useRef(null); + const dot = useRef(null); + const focusGroupOnOpen = useRef(false); + const focusTabOnClose = useRef(false); + const index = NAVIGATION.findIndex(item => item.group === group); + const lastIndex = useRef(index); + + useLayoutEffect(() => { + const distance = Math.abs(index - lastIndex.current); + lastIndex.current = index; + if (!open || !distance || !dot.current || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; + // The crest travels with CSS. Only the teal dot stretches, more on longer jumps. + const animation = dot.current.animate([ + { transform: 'scale(1)' }, + { transform: `scale(${1.18 + distance * .1}, .77)`, offset: .35 }, + { transform: 'scale(.94, 1.04)', offset: .77 }, + { transform: 'scale(1)' }, + ], { duration: 460, easing: 'ease-in-out' }); + return () => animation.cancel(); + }, [index, open]); + + useLayoutEffect(() => { + if (open && focusGroupOnOpen.current) { + focusGroupOnOpen.current = false; + dock.current?.querySelector('.group-dock a[aria-current]')?.focus({ preventScroll: true }); + } else if (!open && focusTabOnClose.current) { + focusTabOnClose.current = false; + tab.current?.focus({ preventScroll: true }); + } + }, [open]); + + useEffect(() => { + if (!open) { + // Ignore rubber-band overscroll at either end of the document. + const scrollPosition = () => Math.max(0, Math.min(window.scrollY, + document.documentElement.scrollHeight - document.documentElement.clientHeight)); + let start = scrollPosition(); + const revealOnScroll = () => { + const current = scrollPosition(); + start = Math.min(start, current); + if (current - start >= revealDistance) setOpen(true); + }; + window.addEventListener('scroll', revealOnScroll, { passive: true }); + return () => window.removeEventListener('scroll', revealOnScroll); + } + + const dismiss = () => { + if (dock.current?.contains(document.activeElement)) focusTabOnClose.current = true; + setOpen(false); + }; + const outsideClick = (event: MouseEvent) => { + const target = event.target; + if (!(target instanceof Element) || dock.current?.contains(target)) return; + if (target.closest('a[href^="#/"], .brand[href="#top"], [data-tool-navigation]')) return; + dismiss(); + }; + const escape = (event: KeyboardEvent) => { + if (event.key === 'Escape' && !event.defaultPrevented) dismiss(); + }; + document.addEventListener('click', outsideClick, true); + document.addEventListener('keydown', escape); + return () => { + document.removeEventListener('click', outsideClick, true); + document.removeEventListener('keydown', escape); + }; + }, [open]); + + const revealDock = () => { + focusGroupOnOpen.current = true; + setOpen(true); + }; + + return
+ + +
; +} diff --git a/src/studio/SiteFooter.tsx b/src/studio/SiteFooter.tsx new file mode 100644 index 0000000..b41892b --- /dev/null +++ b/src/studio/SiteFooter.tsx @@ -0,0 +1,61 @@ +import { useLayoutEffect, useRef } from 'react'; + +export function SiteFooter() { + const privacyRef = useRef(null); + + useLayoutEffect(() => { + const paragraph = privacyRef.current; + const footer = paragraph?.parentElement; + if (!paragraph || !footer) return; + const sentences = Array.from(paragraph.children); + + const fitSentences = () => { + const available = paragraph.getBoundingClientRect().width; + if (!available) return; + const rem = parseFloat(getComputedStyle(document.documentElement).fontSize); + let low = rem * 0.625; + let high = rem * 0.75; + const setSize = (size: number) => footer.style.setProperty('--footer-privacy-size', size + 'px'); + const fits = () => sentences.every(span => span.getBoundingClientRect().width <= available); + + // Measure both sentences on single lines, then restore wrapping before the next paint. + paragraph.setAttribute('data-measuring', ''); + setSize(high); + if (!fits()) { + while (high - low > 0.05) { + const size = (low + high) / 2; + setSize(size); + if (fits()) low = size; + else high = size; + } + setSize(low); + } + paragraph.removeAttribute('data-measuring'); + }; + + const resize = new ResizeObserver(fitSentences); + resize.observe(paragraph); + const typography = new MutationObserver(fitSentences); + const changes = { attributes: true, attributeFilter: ['style', 'class'] }; + typography.observe(document.documentElement, changes); + typography.observe(paragraph, changes); + document.fonts.addEventListener('loadingdone', fitSentences); + fitSentences(); + + return () => { + resize.disconnect(); + typography.disconnect(); + document.fonts.removeEventListener('loadingdone', fitSentences); + }; + }, []); + + return ; +} diff --git a/src/studio/ToolIcon.tsx b/src/studio/ToolIcon.tsx new file mode 100644 index 0000000..d0c370a --- /dev/null +++ b/src/studio/ToolIcon.tsx @@ -0,0 +1,23 @@ +import type { ReactNode } from 'react'; +import type { StudioView } from './contracts'; + +const icons: Record = { + favorites: , + 'asset-labels': <>, + 'cable-labels': <>, + 'location-labels': <>, + codes: <>, + 'data-health': <>, + 'id-generator': <>, + 'serial-tools': <>, + templates: <>, + 'payload-builder': <>, + calibration: <>, + 'code-inspector': <>, + manifest: <>, + fieldlens: <>, +}; + +export function ToolIcon({ view }: { view: StudioView }) { + return ; +} diff --git a/src/studio/ToolNavigation.tsx b/src/studio/ToolNavigation.tsx new file mode 100644 index 0000000..e3065e6 --- /dev/null +++ b/src/studio/ToolNavigation.tsx @@ -0,0 +1,105 @@ +import { useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type MouseEvent, type ReactNode } from 'react'; +import type { StudioView } from './contracts'; +import { favoriteHref, NAVIGATION, type ToolGroup } from './workspace'; +import { ToolIcon } from './ToolIcon'; +import { FloatingToolDock } from './FloatingToolDock'; + +const itemByView = new Map(NAVIGATION.flatMap(group => group.items).map(item => [item.view, item])); +const dockQuery = '(max-width: 1099px)'; +const usesToolDock = () => window.matchMedia(dockQuery).matches; + +function subscribeToDockWidth(notify: () => void) { + const media = window.matchMedia(dockQuery); + media.addEventListener('change', notify); + return () => media.removeEventListener('change', notify); +} + +const groupIcons: Record = { + Favorites: <>, + Create: <>, + Data: <>, + Design: <>, + Tools: <>, +}; + +function revealToolStrip(event: MouseEvent) { + if (event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey + && usesToolDock()) { + window.scrollTo({ top: 0, behavior: 'instant' }); + } +} + +export function ToolNavigation({ view, favorites, inFavorites }: { view: StudioView; favorites: readonly StudioView[]; inFavorites: boolean }) { + const activeGroup = inFavorites ? 'Favorites' : NAVIGATION.find(group => group.items.some(item => item.view === view))!.group; + const shortcuts = favorites.slice(0, 3); + const narrow = useSyncExternalStore(subscribeToDockWidth, usesToolDock); + const [recent, setRecent] = useState>>({}); + if (activeGroup !== 'Favorites' && recent[activeGroup] !== view) setRecent({ ...recent, [activeGroup]: view }); + + const directoryRef = useRef(null); + const [sidebarMarker, setSidebarMarker] = useState({ top: 0, height: 0 }); + useLayoutEffect(() => { + const directory = directoryRef.current; + const currentLink = directory?.querySelector("a[aria-current='page']"); + if (!directory) return; + if (!currentLink) { + setSidebarMarker({ top: 0, height: 0 }); + return; + } + + const update = () => { + const directoryRect = directory.getBoundingClientRect(); + const linkRect = currentLink.getBoundingClientRect(); + setSidebarMarker({ top: linkRect.top - directoryRect.top + directory.scrollTop, height: linkRect.height }); + }; + update(); + const observer = new ResizeObserver(update); + observer.observe(directory); + observer.observe(currentLink); + window.addEventListener('resize', update); + return () => { + observer.disconnect(); + window.removeEventListener('resize', update); + }; + }, [view, favorites.length, inFavorites]); + + const directoryStyle = { + '--sidebar-marker-top': `${sidebarMarker.top}px`, + '--sidebar-marker-height': `${sidebarMarker.height}px`, + } as CSSProperties; + + return
+ {narrow && + {NAVIGATION.map(({ group, items }) => { + const target = group === 'Favorites' ? 'favorites' : recent[group] ?? items[0].view; + return + + {group} + ; + })} + } + {favorites.length > 0 && } + +
; +} diff --git a/src/studio/contracts.ts b/src/studio/contracts.ts new file mode 100644 index 0000000..a9f501b --- /dev/null +++ b/src/studio/contracts.ts @@ -0,0 +1,14 @@ +import type { Dataset, LabelTemplate, PageSettings } from '../types'; +import type { PrintJob } from '../core/printJob'; + +export type StudioView = 'favorites' | 'asset-labels' | 'cable-labels' | 'location-labels' | 'codes' | 'data-health' | 'id-generator' | 'serial-tools' | 'templates' | 'payload-builder' | 'calibration' | 'code-inspector' | 'manifest' | 'fieldlens'; +export type StudioPageProps = { + dataset: Dataset | null; selectedIds: ReadonlySet; idField: string; + template: LabelTemplate; page: PageSettings; busy: boolean; previewImage: string; lastJob: PrintJob | null; + onCommitDataset: (next: Dataset, description: string, columnMap?: Record) => void; + onApplyTemplate: (template: LabelTemplate, page?: PageSettings, name?: string) => void; + onPageChange: (page: PageSettings) => void; onIdentifierChange: (field: string) => void; + onNavigate: (view: StudioView) => void; onUndo: () => void; canUndo: boolean; + onExportJob: () => Promise; + onPrintJobCompleted?: (job: PrintJob) => void; +}; diff --git a/src/studio/favorites.tsx b/src/studio/favorites.tsx new file mode 100644 index 0000000..9a430f6 --- /dev/null +++ b/src/studio/favorites.tsx @@ -0,0 +1,70 @@ +import { createContext, useContext, useEffect, useState } from 'react'; +import type { StudioView } from './contracts'; +import { NAVIGATION } from './workspace'; +import { ToolIcon } from './ToolIcon'; + +const prefix = 'asset-tag-studio.favorite.v1.'; +const tools = NAVIGATION.flatMap(group => group.items).map(item => item.view).filter(view => view !== 'favorites'); +type Tool = typeof tools[number]; + +function readFavorites(): StudioView[] { + try { + return tools.filter(tool => localStorage.getItem(prefix + tool) === '1'); + } catch { + return []; + } +} + +function withFavorite(current: StudioView[], tool: Tool, selected: boolean) { + return tools.filter(item => item === tool ? selected : current.includes(item)); +} + +export function useFavorites() { + const [favorites, setFavorites] = useState(readFavorites); + const [unsaved, setUnsaved] = useState([]); + + useEffect(() => { + function changed(event: StorageEvent) { + if (event.storageArea !== window.localStorage) return; + if (event.key === null) { + setFavorites(readFavorites()); + setUnsaved([]); + return; + } + const tool = tools.find(item => event.key === prefix + item); + if (tool) { + // Another tab may have changed this flag again before this event was delivered. + const selected = event.storageArea.getItem(prefix + tool) === '1'; + setFavorites(current => withFavorite(current, tool, selected)); + setUnsaved(current => current.filter(item => item !== tool)); + } + } + window.addEventListener('storage', changed); + return () => window.removeEventListener('storage', changed); + }, []); + + function toggle(tool: StudioView) { + if (tool === 'favorites') return; + const selected = !favorites.includes(tool); + setFavorites(current => withFavorite(current, tool, selected)); + try { + if (selected) localStorage.setItem(prefix + tool, '1'); + else localStorage.removeItem(prefix + tool); + setUnsaved(current => current.filter(item => item !== tool)); + } catch { + setUnsaved(current => withFavorite(current, tool, true)); + } + } + return { favorites, toggle, sessionOnly: unsaved.length > 0 }; +} + +export const FavoritesContext = createContext<(ReturnType & { view: StudioView }) | null>(null); + +export function FavoriteButton({ title }: { title: string }) { + const state = useContext(FavoritesContext); + if (!state || state.view === 'favorites') return null; + const selected = state.favorites.includes(state.view); + return ; +} diff --git a/src/studio/hints.css b/src/studio/hints.css new file mode 100644 index 0000000..a6fb4db --- /dev/null +++ b/src/studio/hints.css @@ -0,0 +1,69 @@ +.hint-panel { + --hint-duration: 220ms; + --hint-ease: cubic-bezier(.2, .7, .2, 1); + position: fixed; + z-index: 1000; + box-sizing: border-box; + max-width: calc(100vw - 24px); + max-height: calc(100vh - 24px); + overflow: auto; + overscroll-behavior: contain; + border: 1px solid var(--line); + border-radius: 8px; + box-shadow: 0 8px 28px rgb(20 40 32 / 18%); + opacity: 0; + visibility: hidden; + pointer-events: none; + transition: opacity var(--hint-duration) var(--hint-ease), + visibility 0s linear var(--hint-duration); +} + +.hint-panel.is-open { + opacity: 1; + visibility: visible; + pointer-events: auto; + transition-delay: 0s; +} + +.hint-panel-inner { min-width: 0; } + +.hint-panel .hint-panel-copy { + padding: 10px 14px; + color: var(--ink); + background: var(--surface); + overflow-wrap: anywhere; + font-family: inherit; + font-size: .8125rem; + font-weight: 400; + line-height: 1.6; +} + +.hint-panel .hint-panel-copy p { color: inherit; font-size: inherit; line-height: inherit; margin: 0; } +.hint-panel .hint-panel-copy p + p { margin-top: 5px; } + +.help-details .help-summary { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 44px; + padding: 0 5px; + border: 0; + border-radius: 5px; + background: transparent; + color: var(--accent-dark); + cursor: pointer; + font: inherit; + font-size: .8125rem; + font-weight: 600; + text-align: left; +} + +.help-summary svg { flex-shrink: 0; } +.help-summary:hover { background: var(--wash); } +.help-summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.help-summary:active { background: var(--accent-soft); } +.help-summary[aria-expanded='true'] { text-decoration: underline; text-underline-offset: 3px; } + +@media (prefers-reduced-motion: reduce) { + .hint-panel, .hint-panel.is-open { transition: none; } +} diff --git a/src/studio/navigation.css b/src/studio/navigation.css new file mode 100644 index 0000000..03ef15d --- /dev/null +++ b/src/studio/navigation.css @@ -0,0 +1,379 @@ +.studio-layout { + --nav-muted: #516861; + --nav-rule: #d5e1db; + display: grid; + grid-template-columns: 13rem minmax(0, 1fr); + align-items: start; + gap: clamp(1.5rem, 3vw, 3rem); + max-width: 1540px; + margin-inline: auto; + padding: 24px clamp(16px, 2.5vw, 40px) 36px; +} + +:root[data-theme='dark'] .studio-layout { + --nav-muted: #adc2b9; + --nav-rule: #3d514a; +} + +.studio-layout .workspace { min-width: 0; width: 100%; max-width: none; padding: 0; } +.skip-tools { + position: fixed; top: 8px; left: 8px; z-index: 10; + transform: translateY(calc(-100% - 12px)); + border: 1px solid var(--accent); border-radius: 6px; padding: 10px; + background: var(--surface); color: var(--ink); +} +.skip-tools:focus { transform: none; } +.topbar .icon-button { min-width: 44px; min-height: 44px; } +.topbar .quiet-link { display: inline-flex; align-items: center; min-height: 44px; } +.welcome-actions button { min-height: 44px; } +.welcome-card .file-hint { font-size: 12px; color: var(--nav-muted); } +.welcome-card p { color: var(--nav-muted); } +.tool-nav { min-width: 0; } +@media (min-width: 1100px) { + .tool-nav { + position: sticky; + top: 12px; + max-height: calc(100vh - 24px); + overflow-y: auto; + scroll-padding-block: 6px; + padding: 3px; + } +} +.floating-tool-dock { display: none; } +.dock-tab[hidden] { display: none !important; } +.tool-directory { position: relative; display: grid; gap: 16px; padding-right: 12px; border-right: 1px solid var(--nav-rule); } +.tool-directory::before { + content: ''; + position: absolute; + z-index: 0; + top: 0; + left: 0; + right: 12px; + height: var(--sidebar-marker-height, 0px); + border-radius: 8px; + background: var(--accent-soft); + box-shadow: inset 3px 0 var(--accent); + transform: translateY(var(--sidebar-marker-top, 0px)); + pointer-events: none; +} +.tool-nav-group { display: grid; align-content: start; } +.tool-nav-group > p { + margin: 0 0 5px; + padding: 0 12px; + font-size: .6875rem; + color: var(--nav-muted); + letter-spacing: .08em; + font-weight: 700; + text-transform: uppercase; +} +.tool-nav-group a { + color: var(--ink); + text-decoration: none; + min-height: 44px; + border-radius: 8px; + align-items: center; + gap: 10px; + padding: 7px 12px; + font-size: .875rem; + line-height: 1.35; +} +.tool-nav-group a { display: flex; } +.tool-nav-group a { position: relative; z-index: 1; } +.tool-nav-group a > span { min-width: 0; overflow-wrap: break-word; } +.tool-nav-group a > svg { width: 20px; height: 20px; flex: 0 0 20px; color: var(--nav-muted); } +.tool-nav-group a:hover, .page-help:hover { background: var(--wash); } +.tool-nav-group a[aria-current='page'] { + color: var(--accent-dark); + font-weight: 700; + background: transparent; + box-shadow: none; +} +.tool-nav-group a[aria-current='page'] > svg { color: currentColor; } +.favorite-shortcuts { display: grid; gap: 2px; margin-bottom: 14px; padding: 0 12px 10px 0; border-right: 1px solid var(--nav-rule); border-bottom: 1px solid var(--nav-rule); } +.favorite-shortcuts a { display: flex; align-items: center; gap: 10px; min-height: 38px; padding: 6px 12px; border-radius: 8px; color: var(--ink); text-decoration: none; font-size: .8125rem; } +.favorite-shortcuts a:hover { background: var(--wash); } +.favorite-shortcuts a[aria-current] { color: var(--accent-dark); font-weight: 700; background: var(--accent-soft); } +.favorite-shortcuts a > svg { width: 18px; height: 18px; flex: 0 0 18px; color: var(--nav-muted); } +.favorite-shortcuts .favorite-shortcuts-all { min-height: 34px; padding-left: 12px; color: var(--accent-dark); font-weight: 700; } +.tool-nav a:focus-visible, .page-help:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +.tool-nav a:active, .page-help:active { background: var(--accent-soft); } +.tool-heading { margin: 0 0 20px; } +.heading-row { display: flex; align-items: center; gap: 10px; } +.heading-row h1 { margin: 0; color: var(--ink); font-size: clamp(1.625rem, 3vw, 2.375rem); line-height: 1.2; overflow-wrap: anywhere; } +.page-help { + display: grid; + place-items: center; + flex: 0 0 44px; + min-height: 44px; + color: var(--nav-muted); + background: transparent; + border: 0; + border-radius: 50%; +} +.page-help[aria-expanded='true'] { color: var(--accent-dark); background: var(--accent-soft); } +.import-art { color: var(--accent-dark); margin-bottom: 10px; line-height: 0; } +.site-footer .footer-brand { margin: 10px 0 0; max-width: none; font-weight: 700; color: var(--ink); } +.site-footer nav { margin-top: 2px; column-gap: 20px; row-gap: 0; } +.site-footer nav a { display: inline-flex; min-height: 44px; align-items: center; font-size: 12px; } + +@media (max-width: 1099px) { + :root { --dock-clearance: calc(64px + env(safe-area-inset-bottom, 0px)); scroll-padding-bottom: var(--dock-clearance); } + .studio-layout { display: block; } + .tool-nav { margin-bottom: 20px; } + .tool-directory { padding: 0; border: 0; } + .tool-directory::before, .favorite-shortcuts { display: none; } + .tool-nav-group { display: none; } + .tool-nav-group[data-current='true']:not(.tool-nav-favorites) { position: relative; display: grid; grid-template-columns: repeat(var(--tool-count), minmax(0, 1fr)); grid-auto-flow: column; gap: 0; } + .tool-nav-group[data-current='true']:not(.tool-nav-favorites)::before { + content: ''; + position: absolute; + z-index: 0; + inset-block: 1px; + left: 0; + width: calc(100% / var(--tool-count)); + border: 1px solid var(--accent); + border-radius: 8px; + background: var(--accent-soft); + transform: translateX(var(--tool-offset, 0%)); + pointer-events: none; + } + .tool-nav-group > p { display: none; } + .tool-nav-group a { + justify-content: center; + text-align: center; + background: var(--surface); + border: 1px solid var(--nav-rule); + } + .tool-nav-group a[aria-current='page'] { + border-color: var(--accent); + box-shadow: inset 0 -2px var(--accent); + } + .floating-tool-dock { + position: fixed; + z-index: 20; + display: block; + left: 50%; + bottom: calc(8px + env(safe-area-inset-bottom, 0px)); + width: min(calc(100vw - 24px), 26rem); + height: 0; + transform: translateX(-50%); + pointer-events: none; + } + .dock-tab { + position: absolute; + z-index: 1; + inset-inline: 0; + bottom: 0; + display: grid; + place-items: center; + width: 48px; + min-width: 48px; + height: 48px; + min-height: 48px; + margin-inline: auto; + padding: 0; + border: 1px solid var(--nav-rule); + border-radius: 50%; + color: var(--ink); + background: var(--surface); + box-shadow: 0 5px 22px rgb(13 40 34 / 20%); + pointer-events: auto; + -webkit-tap-highlight-color: transparent; + } + @media (prefers-reduced-motion: no-preference) { + .app-shell .floating-tool-dock .dock-tab { transition: opacity 140ms ease 180ms; } + @starting-style { + .app-shell .floating-tool-dock .dock-tab:not([hidden]) { opacity: 0; } + } + .app-shell .floating-tool-dock .dock-tab:focus-visible { transition: none; } + } + .dock-tab > svg { + width: 16px; + height: 16px; + color: var(--accent-dark); + } + .dock-tab:hover { border-color: var(--accent); background: var(--wash); } + .dock-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } + .group-dock { + --dock-icon-lift: 8px; + position: absolute; + inset-inline: 0; + bottom: 0; + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + padding: 14px 6px 6px; + border: 1px solid var(--nav-rule); + border-radius: 22px; + background: var(--surface); + box-shadow: 0 8px 28px rgb(13 40 34 / 20%); + isolation: isolate; + overflow: visible; + opacity: 0; + visibility: hidden; + transform: translateY(8px) scale(.98); + transform-origin: bottom center; + pointer-events: none; + transition: opacity 180ms ease, transform 220ms cubic-bezier(.22, .85, .25, 1), visibility 0s linear 220ms; + } + .floating-tool-dock[data-open='true'] .group-dock { + opacity: 1; + visibility: visible; + transform: translateY(0) scale(1); + pointer-events: auto; + transition-delay: 0s; + } + .floating-tool-dock:has(.dock-tab:focus-visible) .group-dock[inert] { transition: none; } + .dock-indicator { + position: absolute; + z-index: 0; + top: calc(31px - var(--dock-icon-lift)); + left: calc(6px + (100% - 12px) * var(--dock-cell-center, .1)); + transform: translate(-50%, -50%); + width: 34px; + height: 34px; + overflow: visible; + pointer-events: none; + transition: left 420ms var(--settle, cubic-bezier(.22, .85, .25, 1)); + } + .dock-crest { + position: absolute; + z-index: 0; + top: -.5px; + left: calc(6px + (100% - 12px) * var(--dock-cell-center, .1)); + width: min(calc((100% - 14px) / 5 - 10px), 70px); + height: auto; + overflow: visible; + transform: translate(-50%, -25%); + transform-origin: center top; + pointer-events: none; + transition: left 420ms var(--settle, cubic-bezier(.22, .85, .25, 1)), + width 420ms var(--settle, cubic-bezier(.22, .85, .25, 1)); + } + .group-dock[data-active='Create'] { --dock-cell-center: .3; } + .group-dock[data-active='Data'] { --dock-cell-center: .5; } + .group-dock[data-active='Design'] { --dock-cell-center: .7; } + .group-dock[data-active='Tools'] { --dock-cell-center: .9; } + .group-dock[data-active='Favorites'] .dock-crest, + .group-dock[data-active='Tools'] .dock-crest { + width: calc((100% - 14px) / 5 - 30px); + } + .dock-crest-shape { fill: var(--surface); } + .dock-crest-edge { + fill: none; + stroke: var(--nav-rule); + stroke-width: 1px; + vector-effect: non-scaling-stroke; + stroke-linecap: butt; + } + .dock-dot { + fill: var(--accent); + transform-box: fill-box; + transform-origin: center; + } + .group-dock a { + position: relative; + z-index: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 3px; + min-height: 52px; + padding: 4px 2px; + border-radius: 14px; + color: var(--nav-muted); + font-size: .75rem; + line-height: 1.3; + font-weight: 600; + text-decoration: none; + } + .group-dock a[aria-current] { + color: var(--accent-dark); + font-weight: 750; + -webkit-tap-highlight-color: transparent; + } + /* The raised icon and its badge live on separate layers. Keep them aligned during a press. */ + .group-dock a[aria-current]:active { background: transparent; transform: none; } + .group-dock a:focus-visible { outline-offset: -2px; } + .group-dock a[aria-current]:focus-visible { outline: none; } + .group-dock:has(a[aria-current]:focus-visible) .dock-indicator { + outline: 2px solid var(--accent); + outline-offset: 2px; + border-radius: 50%; + } + .group-dock a > span { white-space: nowrap; } + .group-dock a > svg { + position: relative; + z-index: 1; + transition: transform 420ms var(--settle, cubic-bezier(.22, .85, .25, 1)), color 90ms ease-out; + } + .group-dock a[aria-current] > svg { + color: var(--surface); + transform: translateY(calc(0px - var(--dock-icon-lift))); + transition-delay: 0ms, 180ms; + } + .tool-nav-group[data-current='true']:not(.tool-nav-favorites) a { position: relative; z-index: 1; border-color: transparent; background: transparent; box-shadow: none; } + .tool-nav-group[data-current='true']:not(.tool-nav-favorites) a[aria-current='page'] { color: var(--accent-dark); } +} +@media (max-width: 680px) { + .studio-layout { padding: 16px 12px 24px; } + .tool-nav-group a { flex-direction: column; justify-content: flex-start; gap: 4px; padding: 8px 3px; font-size: .8125rem; line-height: 1.2; } + .tool-nav-group a > span { text-wrap: balance; } +} +@media (max-width: 1099px) and (max-height: 460px) { + .group-dock a { min-height: 48px; gap: 1px; font-size: .625rem; } + .group-dock a > svg { width: 18px; height: 18px; } + .group-dock a > span { transform: translateY(4px); } +} +@media (forced-colors: active) { + .tool-nav a[aria-current] { border: 2px solid Highlight; } + .dock-tab { border: 1px solid ButtonText; color: ButtonText; } + .group-dock { border-color: ButtonText; } + .dock-crest-shape { fill: Canvas; } + .dock-crest-edge { stroke: ButtonText; } + .dock-dot { fill: Highlight; } +} + +@media (prefers-reduced-motion: no-preference) { + .app-shell { --settle: cubic-bezier(.22, .85, .25, 1); } + .app-shell button:not(.skip-tools), .tool-nav a { + transition: transform 260ms var(--settle), background-color 220ms ease-out, + color 200ms ease-out, border-color 220ms ease-out, box-shadow 260ms var(--settle); + } + @media (hover: hover) and (pointer: fine) { + .app-shell :is(.primary-button, .secondary-button):enabled:hover { + transform: translateY(-2px); + box-shadow: 0 4px 10px rgb(13 55 49 / 18%); + } + .app-shell :is(.page-help, .icon-button):enabled:hover { transform: translateY(-2px) scale(1.06); } + .tool-nav-group a:hover > svg { translate: 2px 0; } + } + .app-shell button:not(.skip-tools):enabled:active, .tool-nav a:active { + transform: translateY(1px) scale(.96); + transition-duration: 80ms; + } + .tool-nav-group a > svg { transition: translate 230ms var(--settle); } + .tool-directory::before { transition: transform 320ms var(--settle), height 220ms ease-out; } + .tool-nav-group a[aria-current='page'] > svg { animation: tool-settle 320ms var(--settle); } + .tool-heading { animation: heading-arrive 280ms var(--settle); } + @media (max-width: 1099px) { + .tool-nav-group[data-current='true']:not(.tool-nav-favorites)::before { transition: transform 320ms var(--settle); } + .tool-nav-group[data-current='true'] { animation: heading-arrive 260ms var(--settle); } + } +} +@keyframes tool-settle { + 0% { transform: translateY(3px) scale(.84); } + 65% { transform: translateY(-2px) scale(1.08); } + 100% { transform: none; } +} +@keyframes heading-arrive { + from { transform: translateY(6px); opacity: .55; } + to { transform: translateY(0); opacity: 1; } +} +@media (prefers-reduced-motion: reduce) { + .app-shell .primary-button:hover:not(:disabled) { transform: none; } + .group-dock, .dock-indicator, .dock-crest, .group-dock a > svg, .dock-tab > svg, .dock-tab { transition: none; animation: none !important; } +} diff --git a/src/studio/pages/DataToolsPage.tsx b/src/studio/pages/DataToolsPage.tsx new file mode 100644 index 0000000..3cb00f2 --- /dev/null +++ b/src/studio/pages/DataToolsPage.tsx @@ -0,0 +1,218 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import type { Dataset } from '../../types'; +import { readValue } from '../../core/dataset'; +import type { StudioPageProps } from '../contracts'; +import { ColumnSelect, HelpDetails, NoDataset, ToolFrame } from '../ui'; +import { auditDataset, previewHealthFix, type HealthFix, type HealthPreview } from '../../features/data-health/logic'; +import { applyIdsToColumn, previewIds, type IdGeneratorOptions, type IdPreviewRow } from '../../features/id-generator/logic'; +import { applySerialPreview, PreviewGeneration, previewSerials, type SerialOptions, type SerialPreviewRow } from '../../features/serial-tools/logic'; +import { selectBoundedRows } from './boundedSelection'; + +export type DataToolsPageProps = StudioPageProps & { view: 'data-health' | 'id-generator' | 'serial-tools' }; +const emptyIds: IdGeneratorOptions = { column: '', pattern: '{sequence}', prefix: '', suffix: '', start: 1, padding: 3, year: String(new Date().getFullYear()), date: new Date().toISOString().slice(0, 10), selectedIds: new Set(), blankOnly: true, overwrite: false }; +const emptySerial: SerialOptions = { column: '', selectedIds: new Set(), mode: 'normalize', casing: 'upper', stripPrefix: '', removeSeparators: true, minLength: 1, maxLength: 100, knownPrefixes: '', pattern: '' }; + +export function DataToolsPage(props: DataToolsPageProps) { + const { view, dataset, onNavigate } = props; + if (!dataset) return onNavigate('asset-labels')} />; + if (view === 'data-health') return ; + if (view === 'id-generator') return ; + return ; +} + +function viewTitle(view: DataToolsPageProps['view']) { return view === 'data-health' ? 'Data Health' : view === 'id-generator' ? 'Asset ID Generator' : 'Serial Tools'; } +function viewDescription(view: DataToolsPageProps['view']) { return view === 'data-health' ? 'Review data quality and preview cleanup.' : view === 'id-generator' ? 'Generate identifiers for selected rows.' : 'Normalize or validate serial values.'; } +function useFreshPreview(dataset: Dataset) { + const [entry, setEntry] = useState<{ source: Dataset; value: T } | null>(null); + useEffect(() => { setEntry(null); }, [dataset]); + const setValue = useCallback((value: T | null) => setEntry(value === null ? null : { source: dataset, value }), [dataset]); + return [entry?.source === dataset ? entry.value : null, setValue] as const; +} +function fieldDefault(dataset: Dataset, expression: RegExp) { return dataset.columns.find(column => expression.test(column)) ?? ''; } +function ErrorText({ message }: { message: string }) { return message ?

{message}

: null; } + +function HealthPage(props: DataToolsPageProps & { dataset: Dataset }) { + const { dataset } = props; + const [id, setId] = useState(() => props.idField && dataset.columns.includes(props.idField) ? props.idField : fieldDefault(dataset, /asset\s*id|identifier|\bid\b/i)); + const [serial, setSerial] = useState(() => fieldDefault(dataset, /serial|s\/n/i)); + const [name, setName] = useState(() => fieldDefault(dataset, /name|description/i)); + const [fix, setFix] = useState('trim'); + const [fixColumn, setFixColumn] = useState(''); + const [preview, setPreview] = useFreshPreview(dataset); + const [error, setError] = useState(''); + const findings = useMemo(() => auditDataset(dataset, id, serial, name, props.template.code.type === 'none' ? undefined : props.template.code), [dataset, id, serial, name, props.template.code]); + const runPreview = () => { try { setError(''); setPreview(previewHealthFix(dataset, fix, fixColumn || undefined)); } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not preview this cleanup.'); setPreview(null); } }; + const apply = () => { + if (!preview || preview.dataset === dataset || props.busy) return; + try { props.onCommitDataset(preview.dataset, preview.description, preview.columnMap); setPreview(null); setError(''); } + catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not apply this data fix.'); } + }; + return +

{dataset.records.length} records · {dataset.columns.length} columns

+ + + +

{findings.length ? `${findings.length} finding${findings.length === 1 ? '' : 's'}${findings.length === 100 ? ' (showing first 100)' : ''}` : 'No issues found for the selected fields.'}

+
{findings.map((item, index) => )}
SeverityIssue
{item.severity}{item.message}
+ {dataset.importAudit?.removedEmptyRows ?

Import skipped {dataset.importAudit.removedEmptyRows} empty data row(s); the original rows are not retained.

: null} +

Preview a safe fix

{fix === 'case' && { setFixColumn(value); setPreview(null); }} />}
+ + {preview &&

{preview.description}

} + +
+
; +} + +function IdPage(props: DataToolsPageProps & { dataset: Dataset }) { + const { dataset } = props; + const [options, setOptions] = useState(() => ({ ...emptyIds, column: props.idField && dataset.columns.includes(props.idField) ? props.idField : fieldDefault(dataset, /asset\s*id|identifier|\bid\b/i), selectedIds: props.selectedIds })); + const [preview, setPreview] = useFreshPreview(dataset); + const [batchStart, setBatchStart] = useState(1); + const [batchCount, setBatchCount] = useState(() => Math.min(2_000, props.selectedIds.size)); + const [error, setError] = useState(''); + const [continuationNotice, setContinuationNotice] = useState(''); + const ownCommit = useRef<{ dataset: Dataset; batchStart: number; batchCount: number; nextSequence: number; appliedCount: number; sequenceLimitReached: boolean } | null>(null); + const selectedCount = dataset.records.filter(record => props.selectedIds.has(record.id)).length; + const populatedCount = dataset.records.filter(record => props.selectedIds.has(record.id) && Boolean(options.column && readValue(record, options.column).trim())).length; + const blankCount = options.column ? selectedCount - populatedCount : 0; + const eligibleCount = options.overwrite ? selectedCount : blankCount; + useLayoutEffect(() => { + const continuation = ownCommit.current?.dataset === dataset ? ownCommit.current : null; + ownCommit.current = null; + setOptions(current => ({ ...current, selectedIds: props.selectedIds, column: dataset.columns.includes(current.column) ? current.column : '', ...(continuation ? { start: continuation.nextSequence } : {}) })); + if (continuation) { + setBatchStart(continuation.batchStart); setBatchCount(continuation.batchCount); + setContinuationNotice(continuation.sequenceLimitReached + ? `Applied ${continuation.appliedCount} ID(s). The sequence limit was reached; choose a new sequence before continuing.` + : `Applied ${continuation.appliedCount} ID(s). Next sequence is ${continuation.nextSequence}. Use Next batch, then Preview IDs to continue.`); + } else { + setBatchStart(1); setBatchCount(Math.min(2_000, dataset.records.filter(record => props.selectedIds.has(record.id)).length)); + setContinuationNotice(''); + } + setPreview(null); setError(''); + }, [dataset, props.selectedIds, selectedCount, setPreview]); + const update = (key: K, value: IdGeneratorOptions[K]) => { setOptions(current => ({ ...current, [key]: value })); if (key === 'start') setContinuationNotice(''); setPreview(null); }; + const updateBatch = (start: number, count: number) => { setBatchStart(start); setBatchCount(count); setPreview(null); setError(''); }; + const run = () => { try { setError(''); const batch = selectBoundedRows(dataset, props.selectedIds, batchStart, batchCount, 5_000); setPreview(previewIds(dataset, { ...options, selectedIds: batch.selectedIds })); } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not create an ID preview.'); setPreview(null); } }; + const apply = () => { + if (!preview || props.busy) return; + try { + const next = applyIdsToColumn(dataset, options.column, preview); + const requestedNextSequence = options.start + preview.length; + const nextSequence = Math.min(requestedNextSequence, 999_999_999); + ownCommit.current = { dataset: next, batchStart, batchCount, nextSequence, appliedCount: preview.length, sequenceLimitReached: requestedNextSequence > 999_999_999 }; + try { props.onCommitDataset(next, 'Generate asset identifiers'); } + catch (reason) { ownCommit.current = null; throw reason; } + setPreview(null); + } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not apply generated IDs.'); } + }; + return +

Pattern

+ update('column', value)} /> + + + + +
+

{selectedCount} selected · {eligibleCount} eligible · {blankCount} blank · {populatedCount} populated. Blank-only is the safe default. Enable “Allow overwriting existing IDs” to include populated rows.

+ {continuationNotice &&

{continuationNotice}

} + {selectedCount === 0 ?

Select rows to preview IDs.

: options.column && eligibleCount === 0 ?

All selected IDs are populated. Enable overwriting to generate replacements.

: null} + + + {preview &&

{preview.length} ID(s) · {preview.filter(row => row.status === 'collision').length} collision(s)

Previewing {preview.length} of {selectedCount} selected row(s), starting at selected row {batchStart}.

{preview.length === 0 && eligibleCount > 0 ?

This batch has no blank IDs. Move to another batch or enable overwriting.

: null}
{preview.slice(0, 200).map(row => )}
RowBeforeGeneratedStatus
{row.rowId}{row.before || '—'}{row.after}{row.message ?? row.status}

Apply affects only the {preview.length} rows in this preview.

} +
+
; +} + +function SerialPage(props: DataToolsPageProps & { dataset: Dataset }) { + const { dataset } = props; + const [options, setOptions] = useState(() => ({ ...emptySerial, column: fieldDefault(dataset, /serial|s\/n/i), selectedIds: props.selectedIds })); + const [preview, setPreview] = useFreshPreview(dataset); + const [batchStart, setBatchStart] = useState(1); + const [batchCount, setBatchCount] = useState(() => Math.min(2_000, props.selectedIds.size)); + const [error, setError] = useState(''); + const [pending, setPending] = useState(false); + const [continuationNotice, setContinuationNotice] = useState(''); + const ownCommit = useRef<{ dataset: Dataset; batchStart: number; batchCount: number; mode: SerialOptions['mode']; appliedCount: number } | null>(null); + const requestGeneration = useRef(new PreviewGeneration()); + useLayoutEffect(() => { + requestGeneration.current.invalidate(); setPending(false); + const continuation = ownCommit.current?.dataset === dataset ? ownCommit.current : null; + ownCommit.current = null; + setOptions(current => ({ ...current, selectedIds: props.selectedIds, column: dataset.columns.includes(current.column) ? current.column : '' })); + if (continuation?.mode !== 'deduplicate' && continuation) { + setBatchStart(continuation.batchStart); setBatchCount(continuation.batchCount); + setContinuationNotice(`Applied ${continuation.appliedCount} serial row(s). Use Next batch, then Preview serials to continue.`); + } else { + setBatchStart(1); setBatchCount(Math.min(2_000, dataset.records.filter(record => props.selectedIds.has(record.id)).length)); + setContinuationNotice(''); + } + setPreview(null); setError(''); + return () => requestGeneration.current.invalidate(); + }, [dataset, props.selectedIds, setPreview]); + const update = (key: K, value: SerialOptions[K]) => { requestGeneration.current.invalidate(); setPending(false); setOptions(current => ({ ...current, [key]: value })); setContinuationNotice(''); setPreview(null); }; + const updateBatch = (start: number, count: number) => { requestGeneration.current.invalidate(); setPending(false); setBatchStart(start); setBatchCount(count); setPreview(null); setError(''); setContinuationNotice(''); }; + const selectedCount = dataset.records.filter(record => props.selectedIds.has(record.id)).length; + const run = async () => { + if (pending) return; + let batch: ReturnType; + try { batch = selectBoundedRows(dataset, props.selectedIds, batchStart, batchCount, 2_000); } + catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not create a serial preview.'); setPreview(null); return; } + const generation = requestGeneration.current.begin(); + setPending(true); setError(''); setPreview(null); + try { + const result = await previewSerials(dataset, { ...options, selectedIds: batch.selectedIds }); + if (requestGeneration.current.isCurrent(generation)) setPreview(result); + } catch (reason) { + if (requestGeneration.current.isCurrent(generation)) setError(reason instanceof Error ? reason.message : 'Could not create a serial preview.'); + } finally { + if (requestGeneration.current.isCurrent(generation)) setPending(false); + } + }; + const apply = () => { + if (!preview || props.busy) return; + try { + const next = applySerialPreview(dataset, options.column, preview, options.mode === 'deduplicate'); + ownCommit.current = { dataset: next, batchStart, batchCount, mode: options.mode, appliedCount: preview.length }; + try { props.onCommitDataset(next, options.mode === 'deduplicate' ? 'Deduplicate serial numbers' : 'Normalize serial numbers'); } + catch (reason) { ownCommit.current = null; throw reason; } + setPreview(null); + } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not apply serial changes.'); } + }; + const drops = preview?.filter(row => row.drop).length ?? 0; + return +
update('column', value)} /> + + + + + +
+

{selectedCount} selected row(s). Previews are limited to 2,000 selected rows per batch.

+ {continuationNotice &&

{continuationNotice}

} + + + {preview &&

{preview.length} row(s) · {preview.filter(row => row.status === 'invalid').length} invalid · {preview.filter(row => row.status === 'duplicate').length} duplicates{drops ? ` · ${drops} row(s) will be removed` : ''}

Previewing {preview.length} of {selectedCount} selected row(s), starting at selected row {batchStart}.

{preview.slice(0, 200).map(row => )}
RowOriginalResultStatus
{row.rowId}{row.before || '—'}{row.after || '—'}{row.message ?? row.status}
{options.mode !== 'validate' && <>

Apply affects only the {preview.length} rows in this preview.

}{drops > 0 &&

For each repeated normalized serial, the first dataset row is retained. Review the preview before applying.

}
} + Patterns are length limited and reject known high-risk constructs.
+
; +} + +function BatchControls({ disabled, selectedCount, start, count, maxCount, onChange }: { disabled: boolean; selectedCount: number; start: number; count: number; maxCount: number; onChange: (start: number, count: number) => void }) { + const previousBatches = useRef>([]); + useEffect(() => { previousBatches.current = []; }, [selectedCount]); + const validStart = Number.isInteger(start) && start >= 1 && start <= selectedCount; + const maxForStart = validStart ? Math.min(maxCount, selectedCount - start + 1) : maxCount; + const validCount = Number.isInteger(count) && count >= 1 && count <= maxForStart; + const previous = () => { const prior = previousBatches.current.pop(); onChange(prior?.start ?? Math.max(1, start - count), prior?.count ?? count); }; + const next = () => { + const nextStart = start + count; + previousBatches.current.push({ start, count }); + onChange(nextStart, Math.min(count, selectedCount - nextStart + 1)); + }; + return
+ + + + +
; +} diff --git a/src/studio/pages/FavoritesPage.tsx b/src/studio/pages/FavoritesPage.tsx new file mode 100644 index 0000000..f7033c4 --- /dev/null +++ b/src/studio/pages/FavoritesPage.tsx @@ -0,0 +1,67 @@ +import { useLayoutEffect, useRef } from 'react'; +import type { StudioView } from '../contracts'; +import { ToolIcon } from '../ToolIcon'; +import { PageHeading } from '../ui'; +import { favoriteHref, NAVIGATION } from '../workspace'; +import './favorites-workspace.css'; + +export function FavoriteToolStrip({ view, favorites }: { view: StudioView; favorites: readonly StudioView[] }) { + const list = useRef(null); + useLayoutEffect(() => { + const row = list.current; + const current = row?.querySelector('[aria-current="page"]'); + if (!row || !current) return; + const item = current.getBoundingClientRect(); + const bounds = row.getBoundingClientRect(); + if (item.left < bounds.left) row.scrollLeft += item.left - bounds.left; + else if (item.right > bounds.right) row.scrollLeft += item.right - bounds.right; + }, [view, favorites]); + + return ; +} + +export function FavoritesPage({ favorites, onRemove }: { + favorites: readonly StudioView[]; + onRemove: (view: StudioView) => void; +}) { + const list = useRef(null); + const nextFocus = useRef(null); + useLayoutEffect(() => { + if (nextFocus.current === null || !list.current) return; + const links = list.current.querySelectorAll('a'); + links[Math.min(nextFocus.current, links.length - 1)]?.focus(); + nextFocus.current = null; + }, [favorites]); + + return
+ Use the star beside a tool’s title to add or remove it here. + {favorites.length === 0 ?
+ +

No favorite tools yet

+

Select the star beside any tool’s title to save it here.

+ Open Asset labels +
: NAVIGATION.map(({ group, items }) => { + const saved = items.filter(item => favorites.includes(item.view)); + if (!saved.length) return null; + return
+

{group}

+
    {saved.map(({ view, title }) =>
  • + {title} + +
  • )}
+
; + })} +
; +} diff --git a/src/studio/pages/InspectorPage.tsx b/src/studio/pages/InspectorPage.tsx new file mode 100644 index 0000000..0cd7bdd --- /dev/null +++ b/src/studio/pages/InspectorPage.tsx @@ -0,0 +1,60 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import type { StudioPageProps } from '../contracts'; +import { HelpDetails, ToolFrame } from '../ui'; +import type { DecodedCode } from '../../features/code-inspector/decode'; +import { decodeImageData, decodeImageFile } from '../../features/code-inspector/client'; +import { analyzeContent } from '../../features/code-inspector/analyze'; +import { previewBlob, sourcePixels } from '../../features/code-inspector/image'; +import { FilePicker } from '../FilePicker'; + +export function InspectorPage(props: StudioPageProps) { + const [text, setText] = useState(''); const [result, setResult] = useState(null); + const [error, setError] = useState(''); const [inspecting, setInspecting] = useState(false); const [camera, setCamera] = useState(false); const [requesting, setRequesting] = useState(false); + const decodeController = useRef(null); const stream = useRef(null); const video = useRef(null); const cameraVersion = useRef(0); + function stopCamera() { cameraVersion.current += 1; stream.current?.getTracks().forEach(track => track.stop()); stream.current = null; if (video.current) video.current.srcObject = null; setCamera(false); setRequesting(false); } + useEffect(() => { + const hidden = () => { if (document.hidden) { stopCamera(); decodeController.current?.abort(); } }; + document.addEventListener('visibilitychange', hidden); + return () => { document.removeEventListener('visibilitychange', hidden); cameraVersion.current += 1; stream.current?.getTracks().forEach(track => track.stop()); stream.current = null; decodeController.current?.abort(); }; + }, []); + useEffect(() => { + if (!camera || !video.current || !stream.current) return; + video.current.srcObject = stream.current; + void video.current.play().catch(() => { setError('Camera preview could not start. Stop the camera and retry.'); stopCamera(); }); + }, [camera]); + const analysis = useMemo(() => { + if (!result) return null; + try { return analyzeContent(result.text, props.dataset, props.template); } catch { return null; } + }, [result, props.dataset, props.template]); + async function inspect(source: () => Blob | ImageData) { + decodeController.current?.abort(); const controller = new AbortController(); decodeController.current = controller; + setInspecting(true); setError(''); setResult(null); + try { const image = source(); if (controller.signal.aborted) return; const decoded = await (image instanceof Blob ? decodeImageFile(image, controller.signal) : decodeImageData(image, controller.signal)); if (!controller.signal.aborted) { setResult(decoded); setText(decoded.text); } } + catch (reason) { if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : 'Inspection failed. Use another image.'); } + finally { if (decodeController.current === controller) setInspecting(false); } + } + async function startCamera() { + if (!navigator.mediaDevices?.getUserMedia) { setError('Camera access requires a supported browser on HTTPS or localhost. You can inspect an uploaded image instead.'); return; } + stopCamera(); const version = ++cameraVersion.current; setRequesting(true); setError(''); + try { + const media = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false }); + if (version !== cameraVersion.current) { media.getTracks().forEach(track => track.stop()); return; } + stream.current = media; setCamera(true); + } catch { if (version === cameraVersion.current) setError('Camera access was denied or no camera is available. Check browser permissions, or upload an image.'); } + finally { if (version === cameraVersion.current) setRequesting(false); } + } + return +

Inspect a code

+
Image void inspect(() => file)} disabled={inspecting} hint="PNG or JPEG · up to 10 MiB and 8 megapixels" dropTarget />
+
{inspecting && }
+