24 KiB
Learnings Registry
Format: LRN-XXX | Date | Pattern | Context | Future application
LRN-001 | 2026-05-18 | Zod discriminatedUnion for nextAppointment
Report.nextAppointment uses discriminatedUnion('kind', [...]). Gives precise TS narrowing on .kind; avoids optional union type ambiguity. Apply: any polymorphic field with a literal discriminant.
LRN-002 | 2026-05-18 | SVG hitbox+visible twin pattern
Two SVG elements share same data-anno-id: hitbox (pointer-events:all, fill:transparent) + visible (pointer-events:none, colored). Parser groups by data-anno-id → Bone.hitboxEls[], Bone.visibleEls[]. Apply: any SVG-based interactive map needing precise click areas.
LRN-003 | 2026-05-18 | pnpm via corepack shim breaks on older Node 20
corepack shim on Node 20.20.0 throws ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. Fix: install pnpm directly via get.pnpm.io/install.sh. Binary lands at ~/.local/share/pnpm/bin/pnpm. Apply: CI/dev envs without system pnpm.
LRN-004 | 2026-05-19 | SVG behavior hints via free-form data-anno-special
Branch click handling on data-anno-special (free-form string), not on data-anno-category.
Why: category is free-form metadata (LRN follow-up to refactor BDR/cad94a4 chain); coupling logic to category re-introduces a closed enum and silently breaks when SVG author renames a slug. Hints stay opaque to parser, consumed only at use site.
Apply: any SVG-driven UI where authors add new annotation types regularly — use data-anno-special for behavior triggers, keep category for grouping/filters only.
LRN-005 | 2026-05-19 | Detail-popup needs its own bones map
When a popup loads a separate SVG, its annotation ids are not in the parent's bones map.
Parse detail SVG on popup open and keep a detailBones map; fall back lookup bones.get(id) ?? detailBones.get(id) in shared click handler.
Apply: any nested/zoom-popup pattern where the child SVG has independent ids.
LRN-006 | 2026-05-19 | Strip authoring annotations before rasterizing for print
Source SVGs carry interaction-only artifacts (data-anno-, transparent hitboxes, faint default fills) that are invisible in-app via CSS but leak into PDF rasterization.
Before raster: walk [data-anno-id], hide non-selected via display="none", strip data-anno- attributes, recolor selected.
Apply: any "screen → print" pipeline where the screen SVG has interaction layers.
LRN-007 | 2026-05-19 | pdf-lib maxWidth wraps glyphs, not your cursor
pdf-lib's drawText({ maxWidth }) wraps the visible glyph run but the returned y is unchanged — caller must measure with widthOfTextAtSize and advance the cursor per wrapped line. Otherwise subsequent text blocks overlap the wrapped tail. Apply: any pdf-lib layout with variable-length user text. Always wrap explicitly + advance per line.
LRN-008 | 2026-05-19 | pdf-lib eyebrow + title vertical spacing
Times-22 ascender ≈ 17pt. Eyebrow size-9 baseline above title baseline needs ≥22pt gap to clear the ascender + leave ≥6pt visual breathing. Header rule needs ≥30pt cushion below for a size-22 title (title baseline at height-120ish on A4). Apply: any pdf-lib heading stack (eyebrow + title or chained headings). Compute from font.heightAtSize/widthOfTextAtSize, never eyeball pixel offsets.
LRN-009 | 2026-05-19 | pdf-lib variable-count image layout — pre-rasterize, reserve text, then grid
Variable-count image blocks (N SVGs per observation) overflow page when stacked top-down because each item's height depends on its rasterized aspect ratio, unknown until after embedPng. Order: (1) pre-rasterize every image in parallel via Promise.all, capture aspect = img.height/img.width; (2) build text sections + estimate their height with wrapLines on real font metrics; (3) reserve bottom area = MARGIN_BOTTOM + textHeight + gap, derive availH for images; (4) pick cols (1 if single image, else 2), rows = ceil(n/cols); (5) rowBudget = (availH - rows*labelGap - (rows-1)rowGap)/rows with a min-cell floor; (6) cellH per item = min(cellWaspect, rowBudget) — preserves aspect, capped by budget. Apply: any pdf-lib page where image count is data-driven and text must remain visible. Never lay out images before measuring text; never embed-then-skip — embed all, then place. Min-cell floor prevents zero-height when content is dense.
LRN-010 | 2026-05-19 | React effect that mutates async-appended DOM needs a "loaded" gate
Symptom: highlight effect (querySelectorAll + setAttribute) silently no-ops when sibling effect appends DOM async via loadSvg().then(append). First render: mutate-effect runs against empty container, then DOM arrives, then nothing re-paints because deps didn't change. Symptom is intermittent ("sometimes highlighted, sometimes not") — actually depends on which effect resolves first on a given mount.
Fix pattern: hold a loadedSrc state, set it to null at src-change, set it to src right after appendChild, and depend the mutate-effect on [data, loadedSrc, src] with guard if (loadedSrc !== src) return. Now the mutate-effect re-runs both on data change AND when DOM finishes mounting.
Apply: any React component that mounts external DOM async and applies attribute/style mutations in a separate effect. Includes inline SVG injection, MapLibre overlays, Lottie players. Never rely on effect ordering across an async boundary.
LRN-011 | 2026-05-20 | Zod recursive schema via z.lazy + explicit ZodType
Recursive shapes (FindingNode with optional children: FindingNode[]) need TS interface declared first, then const FindingNodeSchema: z.ZodType<FindingNode> = z.lazy(() => z.object({...})). Without the explicit ZodType annotation, TS infers any for the recursive arm and the entire downstream type chain collapses. Without z.lazy, the schema references itself before initialization → runtime ReferenceError.
Apply: any tree/AST-style schema in Zod 3.x. Declare interface first, type the schema explicitly, wrap recursive shape in z.lazy. Same trick works for ZodType<U[]> when the recursion is via children: U[].
LRN-012 | 2026-05-20 | Once-per-session UX modal via sessionStorage flag
Pattern: state disclaimer: string | null, useEffect on the data dep that reads sessionStorage.getItem(FLAG); if absent, set state to the message. Acknowledge handler writes the flag and clears state. Survives reloads within tab, resets on new tab. Cheaper than persisting per-user (no backend) and respects practitioner intent — they see the legal scope reminder once per work session.
Apply: any single-praticien tool needing one-shot acknowledgment per session (legal disclaimers, version-change notices, GDPR banners scoped to a session). Use a stable string key prefixed with osteo: to avoid collision.
LRN-013 | 2026-05-20 | Vite import.meta.glob + default-export = plugin discovery
import.meta.glob<{ default: T }>('./*/index.ts', { eager: true }) scans the folder at build time and returns a Record<path, module>. Combined with a "each module must default-export a T" convention, you get drop-folder plugin discovery: drop a conforming folder → it shows up in Object.values(modules).map(m => m.default). Eager mode resolves synchronously so the registry is a plain object literal in the bundled output.
Pitfalls: a missing default export silently disappears (warn explicitly on !mod.default), and duplicate ids need a tie-break policy (first-wins + warn). Glob ordering is filesystem-dependent — sort the output by a stable key (e.g. labelFr) before exposing it to UI.
Apply: any registry-style module set where you want zero-touch onboarding — species, integrations, plugins, theme packs.
LRN-014 | 2026-05-20 | Cross-walk human strings via normalize + Levenshtein
When bridging two sources of the same human label (SVG data-anno-name-fr ↔ JSON zone.name_fr), strict equality is too brittle (casse, accents, "(ATM)" abbreviations, typos). Robust strategy: aggressive normalize (lowercase + NFD-strip combining marks + drop non-alphanumerics), then score by 0=exact, 1=substring, 2+d=Levenshtein within max(2, floor(maxLen*0.25)), ∞=no match. EN-first if both languages available — no accent normalization edge cases.
Apply: any cross-system label match where one side is authored, the other generated or hand-typed. The 25% character tolerance is a sweet spot — catches single typos on labels 8+ chars, refuses cross-zone collisions (Sphenoid ↛ Spheno-Basilar Synchondrosis even though both share "spheno").
LRN-015 | 2026-05-20 | Per-source try/catch beats loop-wrapping try/catch
Original buildZoneLabels wrapped main + every detail SVG fetch in one outer try/catch. First failing source (e.g. 404 on a detail asset) aborted the whole loop, leaving callers a partially-filled map with no signal — the rest of the labels never made it in. Lesson: when each iteration is independent, the try/catch belongs INSIDE the iteration (or inside the Promise.all callback). Outer catch only makes sense when iterations are sequentially dependent and the work is moot after a failure.
Apply: any fan-out fetch / parse / transform over heterogeneous sources — config loaders, plugin enumerators, asset preloaders. Bonus: log on failure (console.warn) so the silent skip is observable in dev.
LRN-016 | 2026-05-20 | PDF custom-font text is glyph-subset — bytes-grep won't find it
pdf-lib with embedded TTF fonts (Inter, Fraunces) subsets glyphs and stores text streams as glyph indices, not codepoints. A latin1 / utf-8 grep over the raw PDF bytes will not match user-visible strings ("Temporo" never appears literally in the dump). Standard PDF text show ops (Tj, TJ) carry the glyph IDs inside content streams that are typically Flate-encoded too.
Testing implication: don't assert PDF text via byte grep — either re-extract the embedded JSON attachment (already plain text) or refactor the offending logic into an exported helper and unit-test that. Same pattern when smoke-testing PDF output in CI.
LRN-017 | 2026-05-20 | i18n dict parity via Object.keys.sort equality
Cheapest drift guard between fr/en dicts: one test asserts Object.keys(fr).sort() deep-equals Object.keys(en).sort() + every value non-empty. Catches any forgotten translation at CI time without enumerating keys. Pairs with a flat <area>.<key> convention so adding a key in fr.ts forces matching update in en.ts at the next test run.
Apply: any project with N parallel translation dicts (i18n, locale strings, error-code maps). Beats type-level enforcement (TS can't easily require Record<K, ...> shapes to match across two as const literals without ceremony).
LRN-018 | 2026-05-20 | useT hook: selector subscribe + closure-per-render
export function useT() {
const locale = useLocaleStore((s) => s.locale)
const dict = getDict(locale)
return (key) => dict[key] ?? (warn(key), key)
}
Selector subscribe re-renders consumer only on locale change. Dict resolved once per render, the returned closure does a single hash lookup per call. No prop drilling, no context provider, no React useMemo needed. Missing-key path warns in DEV (import.meta.env?.DEV) and falls back to the key literal so the UI never crashes on a typo.
Apply: any Zustand-state-driven derived computation that needs to re-render N components without prop chains. Same pattern works for theme tokens, feature flags, current user.
LRN-019 | 2026-05-20 | exhaustive-deps trap with closures over store values
Defining a helper like const nameOf = (z) => locale === 'en' ? z.name_en : z.name_fr inside a component and using it inside useMemo([deps]) triggers react-hooks/exhaustive-deps: nameOf is a fresh function each render, listing it in deps invalidates the memo every render; omitting it makes the linter complain. Two fixes:
- Inline the locale-conditional inside the memo body (no closure).
- Wrap the helper in
useCallback([locale])so it's referentially stable. Inline is simpler when the helper is one expression. Apply: any closure that bridges a memoized computation to an outer hook value (store selector, prop, context). Same trap withuseEffectdeps.
LRN-021 | 2026-05-21 | pdf-lib StandardFonts use WinAnsi — Latin-1 only, throws on any non-WinAnsi char
PDFDocument.embedFont(StandardFonts.Helvetica) (and the 13 other Adobe built-ins) returns a font whose encoding is WinAnsi (cp1252). Any text op (widthOfTextAtSize, drawText) on a string carrying a non-WinAnsi codepoint throws synchronously: WinAnsi cannot encode "<glyph>" (0x<hex>). Common offenders: ⚠ U+26A0, → U+2192, ✓ U+2713, ★, em-dash variants outside cp1252, all CJK. The error surfaces at the FIRST measurement pass (text-height estimator) — well before any draw call — so even a try/catch around drawing won't save you.
Fix paths:
- Quick: replace the offending glyph with a WinAnsi-safe ASCII surrogate (
(!)instead of⚠,->instead of→). - Right: embed a TTF (Inter, NotoSans, Fraunces…) via
pdfDoc.embedFont(ttfBytes). pdf-lib then subsets the actually-used glyphs into the PDF; arbitrary Unicode works. Per CLAUDE.md spec our PDF should already use TTFs — current StandardFonts shipment is a drift. Why: Slipped past CI because the existing PDF roundtrip tests exercised observations without vet-referral findings; the WinAnsi error only fires when the offending glyph is present in a measured string. How to apply: When a new visual cue (icon, badge, arrow) is added to PDF output, either restrict to ASCII or audit the font path. Add a regression test that exercises the measurement path with a representative string. The cheap canary:font.widthOfTextAtSize(candidateGlyph, 10)in a test.
LRN-020 | 2026-05-21 | Forward-compat Zod schema absorbs catalog version bump zero-code
Catalog JSON went v1.2→v2.0 (semantic breaking change per author doc), but findings.ts Zod schema declared requires_vet_referral boolean + description_fr optional from B0 day-one. Result: v2.0 file dropped in, parses clean, 154/154 tests stay green, no schema edit, no consumer rewrite. Picker + PDF already keyed on boolean (no textual description_fr.includes('vétérinaire') fallback ever existed in our code), so the v2.0 "removed redundant text" change is a no-op at consumption site. Lesson: when authoring a Zod schema for external content, mark anything that "might or might not" appear as .optional() + make booleans authoritative early. The schema then forms a stable contract that absorbs author-side simplifications without code churn.
Apply: any data contract sourced from non-engineering authors (clinical, legal, marketing). Decouple presence-of-field from semantic-of-field; let the boolean drive logic, let text be display-only ornamentation.
LRN-023 | 2026-05-22 | DOMParser for safe SVG loading in React-wrapped vanilla editors
When wrapping vanilla JS editor in React, avoid innerHTML = svgText for user-uploaded SVG. Use new DOMParser().parseFromString(svgText, 'image/svg+xml') + document.importNode(parsedSvg, true) to safely parse and import SVG into DOM. Parser rejects malformed XML, returns parseerror element on failure — gives clean error path. importNode deep-clones into current document context so all DOM APIs (createSVGPoint, getScreenCTM) work correctly.
Apply: any user-uploaded SVG injection into a React-hosted vanilla canvas. Also avoids security hook warnings about innerHTML with untrusted content.
LRN-022 | 2026-05-21 | pnpm 11.x requires Node 22.13 — pin pnpm to ≤10.x when staying on Node 20, never use @latest
pnpm 11.x imports node:sqlite for its store-index module — loaded at pnpm startup for any command that touches the store (install, fetch, add, prune). node:sqlite is a Node 22.13+ built-in. Result: ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite on every fresh Docker build using node:20-alpine + pnpm 11.x. The crash is deterministic for cold installs and invisible for warm dev hosts that already have node_modules resolved (pnpm 11 on Node 20 can still spawn child scripts because the store module isn't required for pnpm run).
Initial hypothesis ("pnpm@latest pulls a newer 11.x with a new Node floor") was wrong — the whole pnpm 11.0+ line carries the sqlite dependency.
Fix paths:
- Stay on Node 20 → pin Dockerfile to
pnpm@10.x(e.g.corepack prepare pnpm@10.13.1 --activate). pnpm 10 reads lockfile v9 unchanged. - Move to Node 22 → bump
FROM node:22-alpine,.nvmrc, and CLAUDE.md stack table together. Required if pnpm 11+ features needed. - Mirror exact version in
package.json:"packageManager": "pnpm@X.Y.Z"so host + Docker stay synced via corepack. - Never
corepack prepare pnpm@latest— re-resolves at every cold build, silently bumps toolchain across deploys with no commit. Why: Floating tag = drift bomb between cached dev + fresh prod resolve. Same risk for unpinnednode:lts,:alpine, GitHub Actionsuses: foo@v1(prefer SHA). Lockfile pins app deps; Dockerfile must pin toolchain. How to apply: Before first prod deploy, audit every Dockerfile, docker-compose, and CI workflow for floating upstream refs. For pnpm specifically, check Node version against pnpm minimum (pnpm 11 ↔ Node 22.13, pnpm 10 ↔ Node 18+, pnpm 9 ↔ Node 18+).
LRN-025 | 2026-05-22 | SVG importNode executes inline scripts — sanitize before append
DOMParser.parseFromString(text, 'image/svg+xml') is safe — doesn't execute scripts during parse. But document.importNode(svg, true) into a live document DOES allow <script>, on* event handlers, and <foreignObject> to execute. Must strip these after importNode, before appending to DOM.
Why: discovered during pathology editor code review — file upload path accepts arbitrary SVG.
How to apply: any tool accepting user-uploaded SVG: strip script, foreignObject, and all on* attributes after importNode. Or use DOMPurify. Applies to both standalone HTML tools and React-wrapped vanilla editors.
LRN-026 | 2026-05-22 | Standalone HTML tools: port logic inline, don't share modules
When standalone .html tools (no build step) need logic from TS modules (zoneMatch, ID generation), port algorithm inline as vanilla JS. Cannot import .ts files. Keep algorithms identical to source for consistency. Document which .ts file was ported so future changes can sync. Why: pathology-editor.html ports normalizeLabel/levenshtein/scorePair/matchZone from src/lib/zoneMatch.ts. How to apply: if zoneMatch.ts changes, pathology-editor.html matching must be updated manually. Consider a test that compares outputs of both implementations on a shared fixture set.
LRN-027 | 2026-05-22 | CSS h-full fails in nested flex — use flex-1
height: 100% (Tailwind h-full) resolves to auto when parent has flex-1 but no explicit height. Caused 3 failed centering attempts on route containers inside App.tsx flex layout. Fix: use flex-1 (flex-grow) on child instead — works because parent IS a flex container, no explicit height needed.
Why: nested flex layout: App wrapper (min-h-screen flex-col) → main (flex-1) → route (h-full broke here) → section (flex-1 grid place-items-center). The section's place-items-center needs actual height to center within.
How to apply: any flex-nested layout where child needs to fill parent — use flex-1, not h-full, unless parent has explicit height or is viewport-sized (h-screen).
LRN-028 | 2026-05-27 | Drive derived UI by spawning the source-of-truth row, not patching each consumer
SVG highlight (boneStates) AND findings picker both derive from observation.zones. So making a cross-region vertebra pick "highlight + add zone + add findings" = ONE lever: spawn the spine zone in observation.zones. No separate highlight call, no separate findings wiring — both consumers already react to zones. Keep distribution logic pure (distributeVertebraeToZones(zones, targetIndex, verts, bones) → new zones[]) so it unit-tests without React; component handler stays a one-liner.
Inverse-map region→zone via reusing the same label heuristic (regionFromLabel) that maps zone→region — store the function once, scan bones for special==='vertebral-precision' whose label matches.
Apply: any feature where "select X in modal → reflect in N places". Find the single derived-from state; mutate that; let existing selectors fan out. Avoids drift between the highlight path and the data path.
LRN-029 | 2026-06-13 | Vite bundles only index.html — standalone HTML must live in public/
Extra .html at repo root never reaches dist/ — Vite build entry = index.html only. Prod 404: nginx try_files falls through to SPA index.html, React shows "Page introuvable". Fix: put standalone HTML in public/ (copied verbatim to dist/). Links resolve from web root, so href stays /file.html.
Why: pathology-editor.html shipped at root (BDR-020 standalone-HTML pattern), worked in pnpm dev (Vite serves root files in dev) but 404'd in prod (only public/ + bundled entries land in dist/). Dev-vs-prod gap hid it.
How to apply: standalone HTML tool / extra entry → public/, OR add to vite build.rollupOptions.input for hashed-asset processing. Verify via vite preview (serves real dist/), not just pnpm dev. Ties to BDR-020.
LRN-030 | 2026-07-12 | Dockerized SPA on port >=1024 — full non-root nginx works
nginx:alpine default = master root, workers nginx. Listen port >=1024 → USER nginx viable: chown /var/cache/nginx + pre-created /var/run/nginx.pid + /etc/nginx/conf.d (entrypoint envsubst rewrite) + html dir (env.js write). Official image log symlinks (/dev/stdout|stderr) work non-root. Why: tour 2026-07-12 semgrep HIGH (no USER before ENTRYPOINT, Dockerfile:34). Fixed d8e478a; verified docker run: HTTP 200, SPA fallback, env override, ps = uid 101 master+workers. How to apply: any nginx-served SPA container: keep listen >=1024, chown the 4 paths above, USER nginx. Contract change: PORT <1024 now fails to bind — flag BREAKING. Alt base: nginxinc/nginx-unprivileged.
LRN-031 | 2026-07-12 | Build toolchain in dependencies inflates prod CVE audit surface
vite + @vitejs/plugin-react-swc + @tailwindcss/vite sat in dependencies → pnpm audit --prod reported their CVEs as prod findings. Build-time-only packages belong in devDependencies; SPA runtime imports none of them.
Why: tour 2026-07-12 cso posture audit — all 3 "prod" advisories were build-toolchain. Moved 187dfb5; build+tests green, prod audit clean.
How to apply: scaffold check: anything imported only by vite.config / build pipeline → devDependencies. Then pnpm audit --prod reflects real runtime surface. Docker multi-stage unaffected (builder installs all).
LRN-032 | 2026-10-08 | pnpm via corepack prepare, not ~/.local/bin
Dev host: no pnpm on PATH, no node_modules, Node 24.21 (CLAUDE.md said Node 20 + ~/.local/bin/pnpm, both stale). corepack prepare pnpm@10.13.1 --activate + corepack pnpm <cmd> works, zero global install, same pin as Dockerfile (BLK-005). Suite 271/271 on Node 24.
Apply: never export PATH=… in Bash tool (denied); call corepack pnpm. Pin packageManager in package.json so corepack picks version alone.
LRN-033 | 2026-10-08 | Characterise legacy via DOM + prototype spies, no refactor
Untestable seams (click chain inside route, PDF text) pinned without touching src: render route in MemoryRouter + mock @/anatomy/svgLoader to parse real files, dispatch bubbling click on [data-anno-id]; vi.spyOn(PDFPage.prototype,'drawText') captures every drawn string (pdf-lib has no extractor); attachment dicts via doc.context.enumerateIndirectObjects() + String(obj) (object streams hide names from raw bytes). Standalone HTML tool: slice functions by text markers, new Function(src) → parity test.
Trap: store set outside React then click = stale closure; drive state through UI (collapse card) and waitFor.
Apply: any "tests before migration" step on untested legacy code.
LRN-034 | 2026-10-08 | pnpm 10.13 reads onlyBuiltDependencies, not allowBuilds
allowBuilds key in pnpm-workspace.yaml = pnpm ≥10.14 syntax; 10.13.1 ignores it silently → "Ignored build scripts: @swc/core, esbuild" on every install. Fix: onlyBuiltDependencies list. Warning persists until pnpm rebuild (state cached in node_modules/.modules.yaml), then disappears.
Also: root scripts calling pnpm -r fail under corepack pnpm (shim not on child PATH) → pin pnpm as root devDependency.
Apply: any pnpm 10.x workspace; check pnpm --version vs key syntax before trusting a silent config.