From 39507709d6322521bbbbcd89d9c461273223bdcc Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 22 Nov 2026 22:06:07 +0100 Subject: [PATCH] =?UTF-8?q?chore(memory):=20plan=20=E2=80=94=20detail=20vi?= =?UTF-8?q?ews=20drawn=20on=20the=20drawing,=20rev=201=20for=20challenge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-11-22-detail-views-graphic-crop.md | 3588 +++++++++++++++++ 1 file changed, 3588 insertions(+) create mode 100644 .claude/tasks/plans/2026-11-22-detail-views-graphic-crop.md diff --git a/.claude/tasks/plans/2026-11-22-detail-views-graphic-crop.md b/.claude/tasks/plans/2026-11-22-detail-views-graphic-crop.md new file mode 100644 index 00000000..88472010 --- /dev/null +++ b/.claude/tasks/plans/2026-11-22-detail-views-graphic-crop.md @@ -0,0 +1,3588 @@ +# U2/U4 Detail Views Drawn on the Drawing: Implementation Plan (V1-2.6), rev 1 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use subagent-driven-development to implement this plan task-by-task. +> Steps use checkbox (`- [ ]`) syntax for tracking. + +**Status:** DRAFT for the owner's technical validation (owner, 2026-11-22: « Cette validation concerne le design. Elle +n'autorise pas encore l'implémentation. Je validerai le plan technique avant le début du code. »). No product code +before that validation. Contract: `.claude/tasks/contracts/2026-11-22-detail-views-graphic-crop-0134.md`. + +**Goal:** a detail view is created by drawing its frame on the parent drawing, opened from its access (rectangle, +polygon or circle) and from the access's label on the editor, the catalogue and the bilan, recropped graphically, shown +whole between neutral bands with nothing outside the frame, and printed in the PDF at its exact proportions (full width +from 3:1), with no overlap and no loss on long notes. + +**Architecture:** four layers, each argued from the validated board. + +1. **Core (Rust).** Detail-view accesses get a reserved internal category, `cat-access`: schema v2, no new key, no SQL + migration. The editor commands (`edit.rs`) create it when an access enters it and refuse every other write of it. + Validation (`validate.rs`) does not change, so every N-1 document stays valid. One additive preview value gives the + smallest side an access may have in each view. The PDF writer gets an exact-ratio raster beyond today's clamps and a + three-mode image layout: fit, proportional shrink, and text flowing onto continuation pages. +2. **Editor (TypeScript).** A frame work item in the work store, with the press machine's draw and handle drags. A + « Nouvelle vue de détail » dialog commits the view, its access and the category as one undo step, through + `commitBatch`. A recrop work item reuses the same frame. Access shapes come with a radius handle. The strip gets its + view commands. +3. **The three surfaces.** One shared pick gives the annotation priority. One pure D25 placement drives the label + buttons and « Autres vues (N) ». One band clip hides everything outside a detail view's frame. The bilan's detail + window gets a back stack. +4. **Proofs.** An N-1 characterisation test is written first. The plan also proves non-collision, pgTAP behaviour, + fingerprint and oracle non-regression, and wasm budget measures. New PDF references are shown to the owner before + they are frozen. The trial happens on `db:trial` by the owner. + +**Tech Stack:** Rust core (`crates/core`, edition 2024, wasm facade `packages/core-wasm`), React 19, TypeScript strict, +Zustand 5, Tailwind 4, vitest + happy-dom, Playwright Chromium + axe (`pnpm db:sandbox e2e-shell`, `pnpm e2e:ui`), +pgTAP on PGlite. + +**Spec (binding, in this order):** + +- The validated board `docs/design/v1-2-6-u2-detail-views/` (README.md D1 to D25, « Conséquences » 1 to 3, panels 00 + to 19; revision 4 validated graphically 2026-11-22). +- The contract's CLARIFICATIONS (five owner messages, all `[gated 2026-11-22]`). +- `docs/development/V1-2-6_UX_PLAN.md` §U4 (616-631) and §U6 (655-695) for what stays at U6. +- `docs/development/V1-2-6_UX_COMPATIBILITY.md` §0, §7, §8. + +Plan form, as in the U2 plan: Rust and pure TypeScript functions are given in full. React tasks give the files, the +behaviour, the test cases and how to verify. The executor writes the JSX under TDD against the board panels named in +each task. + +## Owner requirements carried verbatim into tasks + +| # | Owner wording (2026-11-22) | Task | +|---|---|---| +| R1 | « Une vue peut temporairement ne pas posséder d'accès pendant la préparation d'un brouillon. En revanche, une vue de détail dépourvue d'accès depuis sa parente doit conserver une erreur bloquant sa soumission. » | 1, 10, 29 | +| R2 | « La correction PDF doit couvrir les notes longues, le plancher actuel de 60 pt, les changements de page et l'absence de chevauchement avec les autres éléments. La correction ne doit jamais déformer les images ni afficher du contenu situé hors du cadre. » | 24 to 28 | +| R3 | Verify: no collision, creation by the core, uniqueness and behaviour on removal or edit, read and rewrite by an N-1 application, existing sheets, the U6 transition. | 1, 2, 4, 5, 13 | +| R4 | Non-regression tests on historical documents and existing PDF references; new references shown visually before being frozen. | 5, 24, 28 | +| R5 | Keep: no change to pre-existing sandbox data, never `editor-equine` on the persistent sandbox, never DEV, no `db:trial` without an authorised checkpoint, no merge, no deploy. | Global Constraints, 29, 30 | +| R6 | The plan separates: Rust core; document compatibility and the N-1 reader; frame creation and editing; accesses and their shapes; annotation priority on the three surfaces; label placement and accessibility; parent/child navigation; PDF engine fixes; automated tests and manual trials on db:trial. | Parts 1 to 9 | + +## Arbitrations for the owner (visible choices this plan settles; recommendation first) + +These are the choices that neither the board nor the five owner messages settle. Each is applied as recommended +unless the owner says otherwise. A changed answer is listed with the task it changes. + +- **A1. Generated access too small to be read on the parent** (found while writing this plan). + - The core already refuses any access whose short side is under 4 px on the parent's smallest preview: + - `TooSmall` and the interior rule apply to triggers, `crates/core/src/anatomy/frame.rs:162-166, 210-230`; + - on the main view, that minimum is about 29 drawing units, about 1.4 % of the drawing's width; + - on the head view it is about 8 units. + - So a small frame drawn while zoomed, or a very thin strip, would make « Créer la vue » fail on its default access + option. + - Recommended: the generated access is the frame's rectangle, grown around its centre to that minimum when needed, + and kept inside the parent. The dialog then says « L'accès est agrandi autour du cadre pour rester lisible sur la + vue parente. » + - This needs one additive core value, `PreviewState.min_access_span` (Task 3), so that the page never copies the rule. + - Alternative: refuse the default option for such frames and ask the person to pick « Je le tracerai ensuite » or + « Aucun pour l'instant ». That drops Task 3. +- **A2. Strip commands of a selected access.** + - Panel 05 shows « Ouvrir la vue », « Recadrer la vue », « Propriétés », « Supprimer ». + - Today a selected polygon also offers « Déplacer la zone », which is the path that needs no dragging (A11, + WCAG 2.5.7). Panel 05 would drop it for accesses. + - Recommended: « Ouvrir la vue », « Recadrer la vue », « Déplacer l'accès », « Propriétés ». + - « Supprimer » stays in the properties dialog, as for every annotation (`AnnotationDialog.tsx:181`). + - The strip keeps four buttons, so its width budget does not move. + - Alternative: panel 05 exactly, with no non-drag move of a whole access. +- **A3. PDF continuation pages.** + - Today a note that is long enough runs over the footer and, beyond that, off the page. There is one page per + observation and no overflow check (`layout/observation.rs:633-657`). + - Recommended: the images shrink in proportion down to the 60 pt floor. If the text still does not fit, the images + keep their size and the text continues on a following page. That page carries the same header and the same + observation title (number and severity), with no new wording and no new label key; a new key would break the N-1 + reading of archived labels. + - « One page per observation » then holds except for those cases. +- **A4. Order of full-width views on the page.** + - Recommended: the first view keeps the top of the page, so a 3:1 or wider main view comes first, alone on its row. + - The other views follow the two-column grid in their order. The other full-width views come after the grid, one + per row. + - Alternative: strict view order, which leaves half-empty rows between full-width ones. +- **A5. Raster tolerance.** + - Beyond today's clamps (taller than 1:2, wider than 5:1), the new size rule gives the raster the frame's ratio to + within half a pixel. At most 0.25 px of drawing beyond the frame can show at an edge, which antialiasing makes + invisible. + - Frames between 1:2 and 5:1 keep today's size (« rien ne change », validated). Their rounding can show up to about + 1.25 px beyond the frame at the sides of a 5:1 frame. That is pre-existing and was never seen. + - Recommended: keep the validated « rien ne change ». + - Alternative: the exact rule everywhere. This changes, by one pixel, some frozen raster-size expectations of + `crates/core/tests/oracles/r4/text.json`, and no existing PDF or reference. +- **A6. Where the internal category is created** (wording, no behaviour change). The core creates `cat-access` when the + first access enters it, inside the same undo step as the view when « Créer la vue » makes the access. This also + covers « Je le tracerai ensuite » and a new access to an existing view. The README's « seul le lot vue, catégorie et + accès la crée » becomes « seul le cœur la crée, quand un accès y entre ». +- **A7. Bands on detail views only.** The neutral bands and the clip apply to detail views. The main view keeps today's + look on the three surfaces. + +## Audit findings (2026-11-22, read-only, at 84ce1955) + +### Core + +- Edit commands are one generic enum, `crates/core/src/domain/sheet/edit.rs:96`: insert, update, remove, move, + set_status, mark_reviewed over element keys. There is no batch in Rust: `commitBatch` + (`apps/app/src/editor/state/editorEdit.ts:275-291`) applies a command list on a scratch text and records one undo + entry. +- Ids come from the page (`apps/app/src/editor/ids.ts`, `-<10 chars a-z2-7>`). The equine draft's category + ids are words (`articulations`, `os`, `charnieres-vertebrales`, `zone-colonne`, `cadrans-du-crane`). `cat-access` is + a valid `stable_id` (`domain/js.rs:157-166`). +- `EditError` (`edit.rs:236-262`) has seven kinds; the app phrases them by `editor.refusal.core.` + (`apps/app/src/editor/refusal.ts:12`). +- Removing a category that annotations use is refused (`edit.rs:570-577`, `HasDependents`). +- Category update replaces name and colour freely (`edit.rs:465-467`). +- `view.unreachable` (`validate.rs:~205-225`) is an Error. + - It fails the server verdict and publication (`is_publishable`, `validate.rs:560`; `verdict.rs:~279-300`). + - It never blocks a save (`sheet.edit` does not run the rules). +- No validation rule reads an unused category or a null colour (the 21 codes of `validate.rs`). An empty `cat-access` + is therefore harmless. +- Triggers are measured like zones (`frame.rs:162-166`): the short side times the parent's preview scale must reach + 4 px. Main preview 286 × 310 px, detail preview 254 × 191 px (`frame.rs:65-66`). +- `PreviewState.min_point_radius` (`preview.rs:375`) is the precedent of an additive per-view value. It cost 3 188 B of + wasm (`RUST.md:3956`). +- Wasm: 595 331 B of the 600 000 B budget at `5ca2b7e3`, the last core commit. That leaves a 4 669 B margin, measured + by `packages/core-wasm/tests/size.test.ts` (LRN-118). + +### Compatibility + +- The frozen N-1 reader (`packages/core-wasm/tests/n-1`) can parse sheet documents and read archives. It cannot edit + (Zod schemas from `1a7ee7d`, strict `AnnotationCategorySchema {id, name, color}`). +- No test applies an earlier core to a sheet document. The "N-1 application" for editing is therefore the core at the + commit before this change (Task 1). +- Fingerprints: equine canonical `12d78872…`, alias `27c7383c…` (`fingerprint.rs:44`, tests in `sheet_fingerprint.rs`). +- Review digests: `general` covers `categories` (`review.rs:~215`). A first access therefore changes the `general` + digest of a document. That is expected, and it is listed in the README. +- SQL refuses duplicate category ids (`20261010100000_sheet_document_schema_v2.sql:32-62`, + `category.id.duplicate`). + +### PDF + +- Raster: width 1 200 px, height `round(1200 × clamp(h/w, 0.2, 2.0))` (`pdf/write/views.rs:80-85`). + - Composed roots carry no `preserveAspectRatio`, so `meet` applies. + - Outside the clamp, the drawing beyond the frame shows. + - 57 cases are pinned in `crates/core/tests/oracles/r4/text.json` `rasterSizeOf` (`pdf_session.rs:88-103`). +- Layout: one page per observation, with no page break (`layout/observation.rs:633-657`, `PDF-FORMAT.md:16`). + - The text is reserved below the images with `MARGIN_BOTTOM 48`. + - A row budget floored at 60 pt squashes images (`draw_image_row`, `:361-401`), and the text can run past the footer + rule (y 70, `footer.rs:19-31`) once the text estimate exceeds about 553 pt. + - Pages accumulate in the draw log until `Layout::end` (`layout/mod.rs:228-251`), so a continuation page needs no + session change. +- Goldens use stub PNGs (1 × 1 nologos, 2 × 1 logos), so no golden exercises the clamp or a squash. + - O1 draw logs are compared at full precision and in call order (`pdf_layout.rs`). + - R4 digests pin the writer's bytes (`pdf_serialize.rs`). +- `measure` and `wrap_lines` are public (`pdf/write/text.rs:166, 198`), and `PageLog.footer_start` marks the footer + calls. A test can therefore build text boxes and the footer region from the log alone. +- Raster for review images: no resvg in the repo. `pdftoppm` 25 and ImageMagick are installed. The browser rasterizer is + Chromium (`apps/app/src/pdf/browserRasterizer.ts`). + +### Editor and surfaces + +- The press machine (`editor/annotations/press.ts`) has no drag-to-create. + - Hits come from `elementsFromPoint` (`usePressGesture.ts:59-76`). + - `pressTarget` takes the top annotation, whatever its kind. +- The work store is `editor/annotations/workStore.ts` (`Creation`, `ModeWork`, `GuardWork`, stamps). + - The R-12 guard is `drawingGuard.ts`. + - Escape uses `escape.ts` and `deselect.ts`. + - The history hold is `HistoryButtons.tsx` `holdOf`. +- Strip: `EditStrip.tsx` (fixed height `--edit-strip-height`), content from `SceneStrip.tsx` `commandsKeyOf` and + `SceneCommands`. +- Tool id of the access tool: `'link'`. `linkDisabled = model.children.length === 0`, with the reason in the strip + (`no_child_view`). +- Categories are read at: `creation.ts:56`, `CreationFields.tsx:135-138`, `AnnotationEditForm.tsx:34,72`, + `OverviewPanel.tsx:147-199`, `CategoriesSection.tsx:39`, `EditableAnnotations.tsx:307,415,485,544`, + `SceneStrip.tsx:240`, `overview.ts:54-61`, `AnnotationReadBody.tsx:29`, `catalogue/ZonePanel.tsx:46`, + `sheetDocument.ts:110`. +- Views today: + - `DetailViewForm` (four numeric fields) and `CropEditor`/`CropCanvas` (preview only), under « Gérer les vues » + (`sections/ViewsSection.tsx`); + - `updateView` (`editor/viewUpdate.ts:25`) with a guarded accept; + - the chip row `ViewSwitcher.tsx`. +- Canvas: `AnnotationCanvas.tsx` holds a 4:3 viewport, a transformed `DrawingLayer` (drawing svg + `AnnotationOverlay` + + `HandleLayer`, same `viewBox` with `meet`), and the `Loupe`. + - `clientToDrawing` is the inverse of `getScreenCTM` (`gesture.ts:57`). + - There is no HTML overlay positioned on the drawing today. +- Catalogue: `CatalogueCanvas.tsx` (4:3, 3:2 from `sm`). A click on a trigger switches the tab + (`SheetRoute.tsx:104-112`). Clicks are read from `event.target.closest` (`:134`). +- Bilan: `EditorRoute.tsx` with `AnatomyCanvas.tsx` reads clicks the same way (`:30-33, 93`). `DetailModal.tsx` holds + one `detailViewId` and has no back control (`EditorRoute.tsx:181-182, 386-395`). Its canvas wrapper sizes the svg + with `max-w-full max-h-full mx-auto`, unlike the other two surfaces. +- Core layer: triggers paint in the Shape pass, above point hitbox rings and under point twins (`layer.rs:112-157`). On + a ring, the top element is therefore the trigger. +- D25 reference: the board's `placeTabsStrict` (`maquettes.html`, revision 4). Run in the pinned Chromium on panel + 15's inputs (343 × 257 px, five accesses, 13 points), it gives « Tête » inside top-left, « Boulet antérieur » + stacked with a leader, and Épaule, Coude and Genou antérieur in « Autres vues ». Those numbers are the fixture of + Task 18. + +## Global Constraints + +- Repo `/home/bchanot/Documents/faunosteo-v1-2`, branch `feature/v1-2-anatomical-sheets`. Commit in place; the hooks + push. Never merge, never `gitflow finish`, never deploy. +- Never DEV. Never `pnpm db:trial` or any command on the trial stack: the trial is the owner's to run (Task 30). Never + `db:sandbox reset`, never `up fresh`. +- e2e only as `pnpm db:sandbox e2e-shell e2e/shell/.spec.ts --workers=2`, one or more full spec paths. Never + `editor-equine.spec.ts`. Specs create their own sheets (`seedDraft`) and archive them by captured id with a name + read-back (LRN-143). No pre-existing sandbox row may change: data guard before and after. +- `pnpm lint` alone (never combined in one command). `pnpm typecheck` before each commit with TypeScript changes. +- Rust: after any change under `crates/core` or `crates/wasm`, run `pnpm wasm:build` before the TypeScript suites + (BUILD_STAMP). Before each Rust commit, `pnpm rust:check` must be green. ts-rs types under `packages/core-wasm/types` + are regenerated and committed, with `types/index.ts` updated. +- Wasm budget (LRN-118): after every Rust task, measure with + `pnpm --filter @faunosteo/core-wasm exec vitest run tests/size.test.ts` (Node `gzipSync` level 9 on `pkg`). Record + the figure in the task's commit body. + - Never raise `COMPRESSED_BUDGET_BYTES`. + - If a measure exceeds 600 000 B, STOP and report to the owner (decision T1, `V1-2-6_UX_DECISIONS.md:17`) with the + figure per task. The first candidate to cut is Task 3, whose fallback is arbitration A1's alternative. +- Frozen files are never regenerated to make a test pass: + - `apps/app/tests/fixtures/goldens/step6`, `goldens/r4`, `crates/core/tests/oracles/**`; + - the N-1 copies `packages/core-wasm/tests/n-1/**` and the equine seed; + - `MAKE_GOLDEN` and `MAKE_R4_ORACLES` are never set. + - A difference is reported to the owner with its justification and before/after renders. +- Validation rules (`validate.rs`) do not change. Editor refusals live in `edit.rs` (sheet-model rule). +- `docs/ANNOTATION-RENDERING.md` is updated before any change to how a surface hit-tests or overlays the drawing. +- UI text goes through `useT()`, FR and EN (keys listed in each task). French typography: « » with non-breaking spaces, + a non-breaking space before : ; ? !, no em-dash. +- No new dependency. No change to `apps/app/src/core/*` contracts beyond the generated types. +- Commit messages: Conventional Commits, scopes from CLAUDE.md, subject ≤ 72 characters. + +## Review Focus + +The five failure modes this spec implies that no single task's happy path exercises. Each has its test in the task +named. + +1. **An N-1 application writes the internal category in a state the new version must survive.** + - The states: renamed, recoloured, holding a point, removed while empty. + - The new version must still open the sheet, list the point under « Accès aux vues détaillées », recreate the + category at the next access, and never block a save. + - Tests: Task 2 (core) and Task 13 (UI). +2. **A frame drawn while zoomed, or a thin strip, whose generated access the core refuses.** + - Expected: the access is grown (A1), the commit is accepted, and nothing is lost. + - Tests: Task 3 (core value proven against `annotation_placement`) and Task 10 (dialog). +3. **The text of a long observation note reaching the footer or the page bottom.** + - Covers a note of 5 000 characters with 0, 1, 4 and 8 views, wide and tall ones mixed. + - Expected: no op under the footer region, no image overlapping anything, no squashed image, continuation pages in + order. + - Tests: Task 27. +4. **Five accesses crowded on a phone-width drawing.** + - Expected: no label on a point, a label or a handle; no crossing leaders; every access either labelled or in + « Autres vues », never lost; the board's panel 15 result exactly. + - Tests: Task 18 (fixture + property test) and Task 29 (e2e at 375 px). +5. **An access covered by a point on the bilan and the catalogue.** + - Expected: a click on the point's ring selects or adds the point, not the access. The access stays reachable by its + label, including by keyboard. + - Tests: Task 17 (unit) and Task 29 (e2e on both surfaces). + +## File Structure + +| File | Responsibility | Task | +|---|---|---| +| `crates/core/tests/fixtures/n1/access-category.json` | NEW. The horse slice plus a crop view, its access in `cat-access` and the category: what the new core writes | 1 | +| `crates/core/tests/n1_access_category.rs` | NEW. N-1 characterisation: permanent read/validate/rewrite tests, and the N-1 edits that flip to refusals at Task 2 | 1, 2 | +| `crates/core/src/domain/sheet/access.rs` | NEW. `ACCESS_CATEGORY_ID`, the category's fixed content, the "enters" and "reserved" predicates | 2 | +| `crates/core/src/domain/sheet/edit.rs` | `EditError::ReservedCategory`, guards in `insert_top`, `update`, `update_annotation`, `remove`; category appended when an access enters it | 2 | +| `crates/core/tests/sheet_access_category.rs` | NEW. Guards, creation, fixture equality, R1 (`view.unreachable`), census of `cat-access` in the repo | 2, 4 | +| `crates/core/src/anatomy/frame.rs`, `domain/sheet/preview.rs` | `min_access_span`, `min_access_spans`, `PreviewState.min_access_span` | 3 | +| `supabase/tests/024_sheet_access_category.sql` | NEW. pgTAP: one `cat-access` saves, two are refused | 4 | +| `packages/core-wasm/tests/n-1.access-category.test.ts` | NEW. Frozen N-1 Zod reader on the fixture; N-1 scanner and readers on a PDF of that sheet | 4 | +| `crates/core/src/pdf/write/views.rs` | `raster_size_of` exact beyond the clamps | 25 | +| `crates/core/src/pdf/write/layout/observation.rs` | Rows (grid + full width), proportional scale, text flow onto continuation pages, text floor | 26, 27 | +| `crates/core/tests/common/page_boxes.rs` | NEW. Boxes of a draw log page, the footer region, the overlap census | 24 | +| `crates/core/tests/pdf_proportions.rs` | NEW. Raster sizes, layout modes, flow and stress cases, new references | 25 to 28 | +| `crates/core/tests/oracles/proportions/*.json` | NEW, frozen after the owner's checkpoint. Draw logs of the new reference cases | 28 | +| `apps/app/src/editor/accessCategory.ts` | NEW. `ACCESS_CATEGORY_ID`, `isAccessCategory`, `ordinaryCategories` | 13 | +| `apps/app/src/editor/annotations/frameBox.ts` | NEW. Frame geometry: corners, default, resize by part, move, clamp, ratio label, handle visibility | 6 | +| `apps/app/src/editor/annotations/accessShape.ts` | NEW. Rectangle polygon, circle from a drag, defaults, grown access box | 10, 14 | +| `apps/app/src/editor/annotations/frameWork.ts` | NEW. Frame work mutations (create, recrop) on the work store | 7 | +| `apps/app/src/editor/annotations/viewCreation.ts`, `recrop.ts` | NEW. Commands and accept of « Créer la vue » and of « Appliquer » | 10, 11 | +| `apps/app/src/anatomy/annotationPick.ts` | NEW. D11 pick among the elements under the pointer | 17 | +| `apps/app/src/anatomy/accessLabels.ts` | NEW. D25 placement, the board's `placeTabsStrict` ported, plus cut accesses and the « Autres vues » reservation | 18 | +| `apps/app/src/anatomy/frameBands.ts` | NEW. D7 band insets and the clip | 22 | +| `apps/app/src/components/canvas/AccessLabels.tsx`, `useAccessLabels.ts` | NEW. Label buttons, « Autres vues (N) » and its list, measuring | 19, 20 | +| `apps/app/src/components/editor/annotations/*` | Frame handles, frame and recrop strip commands, view creation dialog, shape choice, radius handle, view commands | 8 to 12, 14 to 16, 21 | +| `apps/app/src/components/canvas/{AnatomyCanvas,DetailModal}.tsx`, `app/routes/EditorRoute.tsx`, `components/ui/Dialog.tsx` | Bilan pick, labels, bands, back stack, header slot | 17, 20, 22, 23 | +| `apps/app/src/components/catalogue/CatalogueCanvas.tsx`, `app/routes/app/anatomy/SheetRoute.tsx` | Catalogue pick, labels, bands | 17, 20, 22 | +| `apps/app/e2e/shell/editor-detail-views.spec.ts`, `e2e/ui/access-labels.spec.ts` (+ harness page) | NEW. Browser proofs | 29 | +| Docs | `ANNOTATION-RENDERING.md` (first), `PDF-FORMAT.md`, `RUST.md` §10 and §12, `ANATOMICAL_SHEET_MODEL.md`, `V1-2-6_UX_COMPATIBILITY.md` §1, `V1-2-6_UX_TESTS.md` U4, `V1-2-6_UX_PLAN.md` U4, `V1-2-6_OWNER_TRIAL.md` §4.18, board README | 5, 17, 28, 30 | + +Execution order: +- 0, 1, 2, 3, 4, 5; +- the PDF: 24, 25, 26, 27, 28 (its freeze waits for the owner; the rest goes on meanwhile); +- 13, 17, 18, 19, then 6, 7, 8, 9, 10, 11, 12, 21, 14, 15, 16, 22, 23, 20; +- 29, 30, 31. + +Each task's own interfaces block names what it needs from earlier ones. + +--- + +## Part 0 · Baselines + +### Task 0: Record the baselines (no code) + +**Files:** none changed. The figures go into the SDD ledger. + +- [ ] **Step 1: State of the branch.** `git -C /home/bchanot/Documents/faunosteo-v1-2 status --short` shows only the + untracked `faunosteo-v1-2-6-revue-ux-chatgpt.md`. Record `git rev-parse HEAD` as `PLAN_BASE`. +- [ ] **Step 2: Wasm figure.** + - Run `pnpm wasm:build`. + - Then run `pnpm --filter @faunosteo/core-wasm exec vitest run tests/size.test.ts`. + - Record the gzip figure. Expected 595 331 B; if it differs, record the real one, which becomes the reference. +- [ ] **Step 3: Frozen suites green before any change.** Each must pass. A failure here stops the plan and is reported + to the owner. + - `cargo test -p faunosteo-core --features pdf-write --test pdf_layout --test pdf_serialize --test pdf_session --test pdf_content` + - `cargo test -p faunosteo-core --test sheet_fingerprint --test sheet_review --test r5_6_switch --test characterisation_serde_tolerance --test sheet_edit --test sheet_rules --test sheet_frame --test sheet_preview` +- [ ] **Step 4: Sandbox census (read-only, R3 « aucune collision »).** The sandbox must already be up; never start or + reset it for this. Run: + +```bash +pnpm db:sandbox sql <<'SQL' +begin transaction read only; +select count(*) as versions_with_access_category +from public.anatomical_sheet_versions v, + jsonb_array_elements(coalesce(v.content -> 'categories', '[]'::jsonb)) c +where c ->> 'id' = 'cat-access'; +rollback; +SQL +``` + + Expected: `0`. Any other figure stops the plan, reported to the owner with the rows' sheet ids (one more read-only + query). The same query on DEV is run only if the owner asks for it; it is never part of this plan. + +## Part 1 · Rust core changes + +### Task 1: N-1 characterisation of a sheet carrying `cat-access` (BEFORE any core change) + +The owner asked for this first (R3): « un test de caractérisation, écrit et rendu vert sur le cœur actuel avant tout +changement, lit une fiche portant `cat-access` et des accès, la modifie, la réécrit et la relit ». The commit of this +task is the **N-1 baseline**. Record its sha in the ledger as `N1_BASE`. + +**Files:** +- Create: `crates/core/tests/fixtures/n1/access-category.json` +- Create: `crates/core/tests/n1_access_category.rs` + +**Interfaces:** +- Produces: + - the fixture path `crates/core/tests/fixtures/n1/access-category.json`, read by Tasks 2, 4 and 5; + - the helpers `access_category()`, `forelimb_view()`, `forelimb_access()` (JSON values), copied by Task 2's test file. + +- [ ] **Step 1: Write the fixture.** It is the horse slice (`crates/core/tests/fixtures/horse-slice.json` `input`) + with three elements appended: what « Créer la vue » with the frame access writes. The tests compare documents + through the core's own serialization (parse, then `to_value`), so defaults the slice omits never make a false + difference: + +```bash +cd /home/bchanot/Documents/faunosteo-v1-2 && mkdir -p crates/core/tests/fixtures/n1 && python3 - <<'PY' +import json, pathlib +doc = json.loads(pathlib.Path('crates/core/tests/fixtures/horse-slice.json').read_text(encoding='utf-8'))['input'] +doc['categories'].append({"id": "cat-access", + "name": {"fr": "Accès aux vues détaillées", "en": "Detail view access"}, "color": None}) +doc['views'].append({"id": "view-forelimbaa", "kind": "detail", + "name": {"fr": "Membre antérieur", "en": "Forelimb"}, "parent_view_id": "view-main", + "svg_asset_id": None, "view_box": {"min_x": 625, "min_y": 969, "width": 220, "height": 660}}) +doc['annotations'].append({"id": "anno-forelimbaa", "kind": "detail_trigger", "view_id": "view-main", + "category_id": "cat-access", "laterality": "left", + "geometry": {"type": "polygon", "points": [[625, 969], [845, 969], [845, 1629], [625, 1629]]}, + "review_status": "to_confirm", "color": None, "name": None, "opens_view_id": "view-forelimbaa"}) +pathlib.Path('crates/core/tests/fixtures/n1/access-category.json').write_text( + json.dumps(doc, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') +PY +``` + +- [ ] **Step 2: Write the test file.** + +```rust +//! N-1 characterisation of the internal access category (owner 2026-11-22, board +//! `docs/design/v1-2-6-u2-detail-views/README.md`, « Conséquences » 1). Written and green on the +//! core BEFORE the change: what that core does with a sheet carrying `cat-access` is what every +//! N-1 application does. `permanent` stays green for ever. `baseline_edits` records the N-1 +//! edits; at Task 2 they flip to refusals, and Task 5 replays this file at the baseline commit +//! on the current fixture (read by path: the replay copies that one file). +#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use faunosteo_core::domain::js::parse_json; +use faunosteo_core::domain::sheet::edit::{EditCommand, EditError, apply_edit}; +use faunosteo_core::domain::sheet::{ + AnatomicalSheetDocument, is_publishable, validate_sheet_document, +}; +use serde_json::{Value, json}; + +const FIXTURE: &str = "crates/core/tests/fixtures/n1/access-category.json"; +const SLICE: &str = "crates/core/tests/fixtures/horse-slice.json"; + +fn value_of(path: &str) -> Value { + parse_json(&common::repo_file(path)).unwrap() +} + +fn fixture() -> AnatomicalSheetDocument { + serde_json::from_value(value_of(FIXTURE)).unwrap() +} + +fn slice() -> AnatomicalSheetDocument { + serde_json::from_value(value_of(SLICE)["input"].clone()).unwrap() +} + +fn command(value: Value) -> EditCommand { + serde_json::from_value(value).unwrap() +} + +fn insert(kind: &str, value: Value) -> EditCommand { + command(json!({ "op": "insert", "element": { "kind": kind, "value": value } })) +} + +fn apply_all( + doc: &AnatomicalSheetDocument, + commands: Vec, +) -> Result { + commands + .into_iter() + .try_fold(doc.clone(), |next, c| apply_edit(&next, c)) +} + +fn issues(doc: &AnatomicalSheetDocument) -> Vec<(String, String)> { + let mut list: Vec<(String, String)> = validate_sheet_document(doc) + .into_iter() + .map(|issue| (issue.code, issue.path)) + .collect(); + list.sort(); + list +} + +fn access_category() -> Value { + json!({ "id": "cat-access", + "name": { "fr": "Accès aux vues détaillées", "en": "Detail view access" }, "color": null }) +} + +fn forelimb_view() -> Value { + json!({ "id": "view-forelimbaa", "kind": "detail", + "name": { "fr": "Membre antérieur", "en": "Forelimb" }, "parent_view_id": "view-main", + "svg_asset_id": null, + "view_box": { "min_x": 625, "min_y": 969, "width": 220, "height": 660 } }) +} + +fn forelimb_access() -> Value { + json!({ "id": "anno-forelimbaa", "kind": "detail_trigger", "view_id": "view-main", + "category_id": "cat-access", "laterality": "left", + "geometry": { "type": "polygon", + "points": [[625, 969], [845, 969], [845, 1629], [625, 1629]] }, + "review_status": "to_confirm", "color": null, "name": null, + "opens_view_id": "view-forelimbaa" }) +} + +fn a_point_in_the_access_category() -> Value { + json!({ "id": "anno-n1pointaa", "kind": "point", "view_id": "view-main", + "category_id": "cat-access", "laterality": "unpaired", + "geometry": { "type": "circle", "cx": 700, "cy": 1000, "r": 14 }, + "review_status": "to_confirm", "color": null, "name": { "fr": "P", "en": "P" }, + "finding_zone_id": null, "vertebral_region_code": null }) +} + +mod permanent { + use super::*; + + #[test] + fn the_fixture_reads_strictly_and_rewrites_to_itself() { + let written = serde_json::to_value(fixture()).unwrap(); + let reread: AnatomicalSheetDocument = serde_json::from_value(written.clone()).unwrap(); + assert_eq!(serde_json::to_value(reread).unwrap(), written); + } + + #[test] + fn the_fixture_raises_no_issue_the_slice_does_not() { + assert_eq!(issues(&fixture()), issues(&slice())); + } + + /// Owner R1: a detail view without its access saves, but keeps the error that blocks + /// submission and publication. + #[test] + fn a_view_without_its_access_saves_and_blocks_submission() { + let doc = apply_all(&slice(), vec![insert("view", forelimb_view())]).unwrap(); + let unreachable = validate_sheet_document(&doc) + .into_iter() + .find(|issue| issue.code == "view.unreachable") + .expect("view.unreachable"); + assert_eq!(unreachable.path, "views[2]"); + assert!(!is_publishable(&validate_sheet_document(&doc))); + } +} + +mod baseline_edits { + use super::*; + + /// At the N-1 baseline, the page could write the category itself: the fixture is the slice + /// plus three plain inserts. + #[test] + fn the_fixture_is_the_slice_plus_three_inserts() { + let built = apply_all(&slice(), vec![ + insert("category", access_category()), + insert("view", forelimb_view()), + insert("annotation", forelimb_access()), + ]) + .unwrap(); + assert_eq!(serde_json::to_value(&built).unwrap(), serde_json::to_value(fixture()).unwrap()); + } + + #[test] + fn an_n1_application_renames_and_recolours_it() { + let renamed = json!({ "id": "cat-access", "name": { "fr": "Navigation", "en": "Navigation" }, + "color": "#123456" }); + let done = apply_edit(&fixture(), command(json!({ "op": "update", + "key": { "kind": "category", "id": "cat-access" }, + "element": { "kind": "category", "value": renamed } }))); + let doc = done.unwrap(); + let reread: AnatomicalSheetDocument = + serde_json::from_value(serde_json::to_value(&doc).unwrap()).unwrap(); + assert_eq!(issues(&reread), issues(&slice())); + } + + #[test] + fn an_n1_application_puts_a_point_in_it() { + let doc = apply_edit(&fixture(), insert("annotation", a_point_in_the_access_category())); + assert!(doc.is_ok()); + } + + #[test] + fn an_n1_application_cannot_remove_it_while_an_access_uses_it() { + let done = apply_edit(&fixture(), command(json!({ "op": "remove", + "key": { "kind": "category", "id": "cat-access" } }))); + assert_eq!(done.unwrap_err(), EditError::HasDependents); + } + + #[test] + fn an_n1_application_removes_it_once_empty() { + let done = apply_all(&fixture(), vec![ + command(json!({ "op": "remove", "key": { "kind": "annotation", "id": "anno-forelimbaa" } })), + command(json!({ "op": "remove", "key": { "kind": "category", "id": "cat-access" } })), + ]); + assert!(done.is_ok()); + } +} +``` + +- [ ] **Step 3: Run it on the unchanged core.** + - Run `cargo test -p faunosteo-core --test n1_access_category`. + - Expected: 8 passed. A failure means the fixture is not what the N-1 core writes. Fix the fixture's construction, + never the assertions, and rerun. +- [ ] **Step 4: Commit.** + - `git add crates/core/tests/fixtures/n1/access-category.json crates/core/tests/n1_access_category.rs` + - `git commit -m "test(domain): characterise the N-1 core on a sheet carrying cat-access"` + - Record the sha as `N1_BASE`. + +### Task 2: The internal category in the editor commands + +**Files:** +- Create: `crates/core/src/domain/sheet/access.rs` +- Modify: `crates/core/src/domain/sheet/mod.rs` (add `pub mod access;`) +- Modify: `crates/core/src/domain/sheet/edit.rs`: + - `EditError` and `kind()` (`:236-262`); + - `insert_top` (`:349-375`); + - `update` (`:465-467`); + - `update_annotation` (`:495-509`); + - `remove` (`:570`). +- Create: `crates/core/tests/sheet_access_category.rs` +- Modify: `crates/core/tests/n1_access_category.rs` (module `baseline_edits` flips, see Step 5) +- Modify: `apps/app/src/editor/refusal.ts` (`:12` list), `apps/app/src/i18n/fr.ts`, `en.ts` (one key) + +**Interfaces:** +- Produces: + - `faunosteo_core::domain::sheet::access::{ACCESS_CATEGORY_ID, is_access_category, access_category, enters_access_category, ensure_access_category}`; + - `EditError::ReservedCategory`, kind `"reserved_category"`. + - The page relies on it: an `insert` of a `detail_trigger` whose `category_id` is `"cat-access"` creates the category + when absent, in the same command. + +- [ ] **Step 1: Write the failing tests** in `crates/core/tests/sheet_access_category.rs`: + +```rust +//! The internal access category (owner 2026-11-22, README « Conséquences » 1): created by the +//! core when an access enters it, never written by a person, N-1 states kept usable. +#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use faunosteo_core::domain::js::parse_json; +use faunosteo_core::domain::sheet::AnatomicalSheetDocument; +use faunosteo_core::domain::sheet::access::ACCESS_CATEGORY_ID; +use faunosteo_core::domain::sheet::edit::{EditCommand, EditError, apply_edit}; +use faunosteo_core::facade::call; +use serde_json::{Value, json}; + +const FIXTURE: &str = "crates/core/tests/fixtures/n1/access-category.json"; +const SLICE: &str = "crates/core/tests/fixtures/horse-slice.json"; + +fn value_of(path: &str) -> Value { + parse_json(&common::repo_file(path)).unwrap() +} + +fn doc_of(value: Value) -> AnatomicalSheetDocument { + serde_json::from_value(value).unwrap() +} + +fn slice() -> AnatomicalSheetDocument { + doc_of(value_of(SLICE)["input"].clone()) +} + +fn fixture_value() -> Value { + value_of(FIXTURE) +} + +fn command(value: Value) -> EditCommand { + serde_json::from_value(value).unwrap() +} + +fn insert(kind: &str, value: Value) -> EditCommand { + command(json!({ "op": "insert", "element": { "kind": kind, "value": value } })) +} + +fn update(kind: &str, id: &str, value: Value) -> EditCommand { + command(json!({ "op": "update", "key": { "kind": kind, "id": id }, + "element": { "kind": kind, "value": value } })) +} + +fn remove(kind: &str, id: &str) -> EditCommand { + command(json!({ "op": "remove", "key": { "kind": kind, "id": id } })) +} + +fn element(list: &str, id: &str) -> Value { + let doc = fixture_value(); + let found = doc[list].as_array().unwrap().iter().find(|e| e["id"] == id); + found.unwrap().clone() +} + +fn access_count(doc: &AnatomicalSheetDocument) -> usize { + doc.categories.iter().filter(|c| c.id == ACCESS_CATEGORY_ID).count() +} + +fn refused(doc: &AnatomicalSheetDocument, c: EditCommand) -> EditError { + apply_edit(doc, c).unwrap_err() +} + +#[test] +fn the_fixture_is_the_slice_plus_the_view_and_its_access() { + let with_view = apply_edit(&slice(), insert("view", element("views", "view-forelimbaa"))); + let built = apply_edit(&with_view.unwrap(), + insert("annotation", element("annotations", "anno-forelimbaa"))); + let fixture = serde_json::to_value(doc_of(fixture_value())).unwrap(); + assert_eq!(serde_json::to_value(built.unwrap()).unwrap(), fixture); +} + +#[test] +fn a_second_access_never_duplicates_the_category() { + let mut second = element("annotations", "anno-forelimbaa"); + second["id"] = json!("anno-forelimbbb"); + let doc = apply_edit(&doc_of(fixture_value()), insert("annotation", second)).unwrap(); + assert_eq!(access_count(&doc), 1); +} + +#[test] +fn a_category_renamed_by_an_n1_application_is_kept() { + let mut value = fixture_value(); + value["categories"][4]["name"] = json!({ "fr": "Navigation", "en": "Navigation" }); + let mut second = element("annotations", "anno-forelimbaa"); + second["id"] = json!("anno-forelimbbb"); + let doc = apply_edit(&doc_of(value), insert("annotation", second)).unwrap(); + assert_eq!(doc.categories[4].name.fr, "Navigation"); + assert_eq!(access_count(&doc), 1); +} + +#[test] +fn a_category_removed_by_an_n1_application_comes_back_with_the_next_access() { + let mut value = fixture_value(); + value["annotations"].as_array_mut().unwrap().pop(); + value["categories"].as_array_mut().unwrap().pop(); + let doc = apply_edit(&doc_of(value), + insert("annotation", element("annotations", "anno-forelimbaa"))).unwrap(); + let fixture = serde_json::to_value(doc_of(fixture_value())).unwrap(); + assert_eq!(serde_json::to_value(&doc).unwrap(), fixture); +} + +#[test] +fn the_page_never_inserts_renames_recolours_or_removes_it() { + let doc = doc_of(fixture_value()); + let category = element("categories", ACCESS_CATEGORY_ID); + let mut renamed = category.clone(); + renamed["name"]["fr"] = json!("Autre"); + let mut recoloured = category; + recoloured["color"] = json!("#123456"); + let reserved = EditError::ReservedCategory; + assert_eq!(refused(&slice(), insert("category", element("categories", ACCESS_CATEGORY_ID))), reserved); + assert_eq!(refused(&doc, update("category", ACCESS_CATEGORY_ID, renamed)), reserved); + assert_eq!(refused(&doc, update("category", ACCESS_CATEGORY_ID, recoloured)), reserved); + assert_eq!(refused(&doc, remove("category", ACCESS_CATEGORY_ID)), reserved); + let empty = apply_edit(&doc, remove("annotation", "anno-forelimbaa")).unwrap(); + assert_eq!(refused(&empty, remove("category", ACCESS_CATEGORY_ID)), reserved); +} + +#[test] +fn moving_it_in_the_list_stays_allowed() { + let moved = apply_edit(&doc_of(fixture_value()), command(json!({ "op": "move", + "key": { "kind": "category", "id": ACCESS_CATEGORY_ID }, "position": 0 }))); + assert_eq!(moved.unwrap().categories[0].id, ACCESS_CATEGORY_ID); +} + +#[test] +fn a_point_a_zone_or_another_access_never_enters_it() { + let doc = doc_of(fixture_value()); + let mut point = element("annotations", "hip"); + point["id"] = json!("anno-newpointa"); + point["category_id"] = json!(ACCESS_CATEGORY_ID); + assert_eq!(refused(&doc, insert("annotation", point)), EditError::ReservedCategory); + let mut hip = element("annotations", "hip"); + hip["category_id"] = json!(ACCESS_CATEGORY_ID); + assert_eq!(refused(&doc, update("annotation", "hip", hip)), EditError::ReservedCategory); + let mut head = element("annotations", "head-trigger"); + head["category_id"] = json!(ACCESS_CATEGORY_ID); + assert_eq!(refused(&doc, update("annotation", "head-trigger", head)), EditError::ReservedCategory); +} + +#[test] +fn an_access_in_it_is_reshaped_and_an_n1_point_in_it_stays_editable() { + let mut access = element("annotations", "anno-forelimbaa"); + access["geometry"]["points"][0] = json!([630, 970]); + let doc = apply_edit(&doc_of(fixture_value()), + update("annotation", "anno-forelimbaa", access)).unwrap(); + let mut value = serde_json::to_value(&doc).unwrap(); + let point = json!({ "id": "anno-n1pointaa", "kind": "point", "view_id": "view-main", + "category_id": ACCESS_CATEGORY_ID, "laterality": "unpaired", + "geometry": { "type": "circle", "cx": 700, "cy": 1000, "r": 14 }, + "review_status": "to_confirm", "color": null, "name": { "fr": "P", "en": "P" }, + "finding_zone_id": null, "vertebral_region_code": null }); + value["annotations"].as_array_mut().unwrap().push(point.clone()); + let with_point = doc_of(value); + let mut moved = point.clone(); + moved["geometry"]["cx"] = json!(710); + assert!(apply_edit(&with_point, update("annotation", "anno-n1pointaa", moved)).is_ok()); + let mut ordinary = point; + ordinary["category_id"] = json!("articulations"); + assert!(apply_edit(&with_point, update("annotation", "anno-n1pointaa", ordinary)).is_ok()); +} + +#[test] +fn the_facade_names_the_refusal() { + let input = json!({ "document": value_of(SLICE)["input"], + "command": { "op": "insert", "element": { "kind": "category", + "value": element("categories", ACCESS_CATEGORY_ID) } } }); + let answer: Value = serde_json::from_str(&call("sheet.edit", &input.to_string())).unwrap(); + assert_eq!(answer["ok"], json!(false)); + assert_eq!(answer["kind"], json!("reserved_category")); +} +``` + +- [ ] **Step 2: Run them, expect compile failure** (`access` module and `ReservedCategory` missing): + `cargo test -p faunosteo-core --test sheet_access_category`. +- [ ] **Step 3: Write `access.rs`.** + +```rust +//! The internal category of the detail-view accesses (owner 2026-11-22, board +//! `docs/design/v1-2-6-u2-detail-views/README.md`, « Conséquences » 1; V1-2.6 T10 option B +//! without the `role` key): an ordinary `{id, name, color}` category marked by its reserved id, +//! so every reader of schema v2 reads it. The editor commands create it when an access enters +//! it and never let a person insert, rename, recolour or remove it, nor give it to a point, a +//! zone or another access. Validation does not know it: N-1 documents stay valid. + +use super::schema::{AnatomicalSheetDocument, Annotation, AnnotationCategory, LocalizedText}; + +/// The reserved id: page ids are `cat-` and ten letters (`apps/app/src/editor/ids.ts`), the +/// curated ones are words, so neither can take it. +pub const ACCESS_CATEGORY_ID: &str = "cat-access"; + +pub fn is_access_category(id: &str) -> bool { + id == ACCESS_CATEGORY_ID +} + +/// What the core writes the first time an access enters the category (T10 names, no colour: +/// the layer draws it in `FALLBACK_COLOR`). +pub fn access_category() -> AnnotationCategory { + AnnotationCategory { + id: ACCESS_CATEGORY_ID.to_owned(), + name: LocalizedText { + fr: "Accès aux vues détaillées".to_owned(), + en: "Detail view access".to_owned(), + }, + color: None, + } +} + +/// Whether `annotation` is an access placed in the internal category. +pub fn enters_access_category(annotation: &Annotation) -> bool { + annotation.trigger().is_some() && is_access_category(annotation.category_id()) +} + +/// Appends the internal category when the document lacks it; an existing one (renamed or +/// recoloured by an earlier application) is kept as it is. +pub fn ensure_access_category(document: &mut AnatomicalSheetDocument) { + if !document.categories.iter().any(|c| is_access_category(&c.id)) { + document.categories.push(access_category()); + } +} +``` + +- [ ] **Step 4: Guard the commands in `edit.rs`.** Add `use super::access::{enters_access_category, + ensure_access_category, is_access_category};` and: + +```rust +// EditError: one more variant, documented + /// A write of the internal access category other than an access entering it (`access.rs`). + ReservedCategory, +// EditError::kind + Self::ReservedCategory => "reserved_category", + +// insert_top: replace the Category and Annotation arms + NewElement::Category(c) if is_access_category(&c.id) => Err(EditError::ReservedCategory), + NewElement::Category(c) => insert_new(&mut doc.categories, c, |c| &c.id, position), + NewElement::Annotation(a) => insert_annotation(doc, a, position), + +// new, under insert_top +/// A new annotation, `to_confirm`; an access entering the internal category brings the +/// category with it, and nothing else may enter it. +fn insert_annotation( + doc: &mut AnatomicalSheetDocument, + mut annotation: Annotation, + position: Option, +) -> Edit { + if is_access_category(annotation.category_id()) && annotation.trigger().is_none() { + return Err(EditError::ReservedCategory); + } + let enters = enters_access_category(&annotation); + set_annotation_status(&mut annotation, ReviewStatus::ToConfirm); + insert_new(&mut doc.annotations, annotation, Annotation::id, position)?; + if enters { + ensure_access_category(doc); + } + Ok(()) +} + +// update: before the generic Category arm + (ElementKey::Category { id }, NewElement::Category(_)) if is_access_category(id) => { + Err(EditError::ReservedCategory) + } + +// update_annotation: right after `let current = &doc.annotations[at];` + if is_access_category(next.category_id()) && !is_access_category(current.category_id()) { + return Err(EditError::ReservedCategory); + } + +// remove: right after `let at = locate(doc, key)?;` + if matches!(key, ElementKey::Category { id } if is_access_category(id)) { + return Err(EditError::ReservedCategory); + } +``` + +- [ ] **Step 5: Flip `baseline_edits` in `n1_access_category.rs`.** + - Keep the module name and its tests' names. Above the module, add the doc comment: « At the N-1 baseline (`N1_BASE`, + ledger) these edits were accepted; Task 5 replays them there. The current core refuses them. » + - Change the bodies as follows: + - `the_fixture_is_the_slice_plus_three_inserts`: the category insert is now refused with `ReservedCategory`. The + assertion becomes: inserting `access_category()` into the slice gives `Err(EditError::ReservedCategory)`. + - `an_n1_application_renames_and_recolours_it`: `Err(EditError::ReservedCategory)`. + - `an_n1_application_puts_a_point_in_it`: `Err(EditError::ReservedCategory)`. + - `an_n1_application_cannot_remove_it_while_an_access_uses_it`: `Err(EditError::ReservedCategory)`. + - `an_n1_application_removes_it_once_empty`: the second command is refused with `ReservedCategory`. +- [ ] **Step 6: The page phrases the refusal.** + - Append `'reserved_category'` to the kinds list of `apps/app/src/editor/refusal.ts:12`. + - Add the key `editor.refusal.core.reserved_category`: + - fr « Cette catégorie est réservée aux accès des vues détaillées. » + - en "This category is reserved for detail-view accesses." +- [ ] **Step 7: Run.** + - `cargo test -p faunosteo-core --test sheet_access_category --test n1_access_category --test sheet_edit --test sheet_rules`. + Expected: all pass. + - `sheet_edit`'s property test still holds: no generated command uses `cat-access`. + - Then `pnpm rust:check`. +- [ ] **Step 8: Wasm measure.** `pnpm wasm:build`, then the size test. Record the figure. +- [ ] **Step 9: Commit.** + - Files: `crates/core/src/domain/sheet/{access,edit,mod}.rs`, both test files, `refusal.ts`, `fr.ts`, `en.ts`, and + `packages/core-wasm/types` if changed. + - Message: `feat(domain): reserved cat-access category created by the core with an access`. Put the wasm figure in + the body. + +### Task 3: The smallest side of an access in each view (arbitration A1) + +Dropped if the owner picks A1's alternative. Task 10 then takes its « A1 alternative » bullet. + +**Files:** +- Modify: `crates/core/src/anatomy/frame.rs` (after `min_point_radii`, `:242-255`) +- Modify: `crates/core/src/domain/sheet/preview.rs` (`PreviewState`, `:362-378`; `state()` `:280-293`) +- Modify: `crates/core/tests/sheet_frame.rs`, `crates/core/tests/sheet_preview.rs` +- Regenerate: `packages/core-wasm/types/PreviewState.ts` + +**Interfaces:** +- Produces: + - `faunosteo_core::anatomy::frame::{min_access_span, min_access_spans}`; + - `PreviewState.min_access_span: BTreeMap` (TS `min_access_span: { [key in string]?: number }`), with + one entry for every view that has a usable frame and drawing. + +- [ ] **Step 1: Failing tests** in `sheet_frame.rs`. Build the slice's frames the way the file already builds them for + `frame_faults`, then: + +```rust +/// A rectangle access of side `min_access_span` passes on the main view and on the head view; +/// one of 0.95 times that side is `TooSmall` (owner A1: the generated access is grown to it). +#[test] +fn an_access_of_the_minimum_side_passes_and_a_smaller_one_does_not() { + for (view_id, main) in [("view-main", true), ("view-head", false)] { + let frame = slice_frame(view_id); // the file's existing way to get a view's Frame + let span = min_access_span(&frame, main); + assert!(frame_faults_of_access(view_id, &frame, span).is_empty(), "{view_id}"); + let faults = frame_faults_of_access(view_id, &frame, span * 0.95); + assert!(matches!(faults.as_slice(), [FrameFault::Annotation { + placement: Placement::TooSmall | Placement::InteriorTooSmall, .. }]), "{view_id}"); + } +} +``` + + `frame_faults_of_access(view_id, frame, side)` is a local helper. It adds to the slice a `detail_trigger` drawn in + `view_id`: a square of `side` centred on the frame, opening a new child view of `view_id`. It returns the faults of + that annotation only. Write it from the file's existing doc-building helpers. In `sheet_preview.rs`, assert that + `PreviewState.min_access_span` holds `view-main` and `view-head`, and that each value equals `min_access_span` of its + frame. +- [ ] **Step 2: Run, expect failure** (unknown function): `cargo test -p faunosteo-core --test sheet_frame --test sheet_preview`. +- [ ] **Step 3: Implement.** + +```rust +/// The smallest side an access (a detail trigger) drawn in a view with this frame may have: +/// `TooSmall` measures its short side at the preview scale, and the interior rule needs a disc +/// of `MIN_VISIBLE_PX` (with `INTERIOR_TOLERANCE_PX` of slack); rounded up to 0.01 unit. +pub fn min_access_span(frame: &Frame, main_view: bool) -> f64 { + let span = (MIN_VISIBLE_PX + INTERIOR_TOLERANCE_PX) / frame.preview_scale(main_view); + (span * 100.0).ceil() / 100.0 +} + +/// `min_access_span` of every view with a usable frame and drawing, by view id. +pub fn min_access_spans<'a>( + document: &AnatomicalSheetDocument, + drawing_of: impl Fn(&str) -> Option<&'a Element>, +) -> BTreeMap { + document + .views + .iter() + .filter_map(|view| { + let drawing = first_view_drawing(document, view, &drawing_of)?; + let span = min_access_span(&view_frame(view, drawing)?, view.is_main()); + Some((view.id().to_owned(), span)) + }) + .collect() +} +``` + + In `preview.rs`, add the field after `min_point_radius`, with this documentation: « The smallest side of an access + drawn in each view, by view id (`min_access_span`): the page grows a generated access to it. Absent for a view + without a usable frame or drawing. » Fill it in `state()` exactly like `min_point_radius`. +- [ ] **Step 4: Run.** + - `cargo test -p faunosteo-core --test sheet_frame --test sheet_preview`: pass. + - Then `pnpm rust:check`, which exports the type, and `pnpm wasm:build`. + - Then `pnpm --filter @faunosteo/core-wasm exec vitest run`. Fix any TS fixture that builds a `PreviewState` by adding + `min_access_span: {}`. +- [ ] **Step 5: Wasm measure**, recorded. Over 600 000 B → STOP (Global Constraints). +- [ ] **Step 6: Commit.** + - Files: `frame.rs`, `preview.rs`, the two tests, `packages/core-wasm/types/PreviewState.ts`, TS fixtures if touched. + - Message: `feat(anatomy): smallest access side per view in preview state`, wasm figure in the body. + +## Part 2 · Document compatibility and the N-1 reader + +### Task 4: No collision, SQL uniqueness, the frozen N-1 readers + +**Files:** +- Create: `crates/core/tests/access_category_census.rs`, and its `[[test]]` entry in `crates/core/Cargo.toml` with + `required-features = ["pdf-read"]` +- Create: `supabase/tests/024_sheet_access_category.sql` +- Create: `packages/core-wasm/tests/n-1.access-category.test.ts` +- Modify: `apps/app/tests/unit/n-1.reader.test.ts` (one case) + +- [ ] **Step 1: Census test (R3 « aucune collision »).** + - The test walks these trees: `supabase/seed`, `crates/core/tests/fixtures`, `crates/core/tests/oracles`, + `apps/app/tests/fixtures`, `packages/core-wasm/tests`. + - For every `.json`, `.sql`, `.svg` and `.md` file, it asserts the bytes do not contain `cat-access`. The only + exception is `crates/core/tests/fixtures/n1/access-category.json`. + - For every `.pdf` under `apps/app/tests/fixtures`, it locates the attachment with + `faunosteo_core::pdf::read::read_attached_document(&bytes, ProbeLimits::UNBOUNDED)` (the call + `pdf_layout.rs:39-52` uses), and asserts the attachment text does not contain `cat-access`. + - Expected: green. +- [ ] **Step 2: pgTAP (R3 « unicité »).** In `supabase/tests/024_sheet_access_category.sql`: + - Follow `016_sheet_review_workflow.sql:40-60` for the setup: an editor account, a draft sheet, a version content + built with `jsonb_build_object`. + - Assert a draft whose `content.categories` holds one `cat-access` category saves (`lives_ok`). + - Assert one holding two is refused with the `category.id.duplicate` issue (`throws_ok`, the message the existing + duplicate tests expect). + - Run `pnpm --filter @faunosteo/supabase test:run`: green. +- [ ] **Step 3: Frozen N-1 readers (R3 « lecture par l'application N-1 »).** + - In `packages/core-wasm/tests/n-1.access-category.test.ts`, read the fixture JSON by path. Then: + - `AnatomicalSheetDocumentSchema.parse` from `@faunosteo/core-wasm/n-1` succeeds; + - the N-1 `validate` twin (`tests/n-1/domain/anatomical-sheet/validate.ts`) returns the same issue codes for the + fixture as for the horse slice's input. + - In `apps/app/tests/unit/n-1.reader.test.ts`, add one case beside the existing « drafts and archives written + through the core » cases (`:178-196`): + - apply to the bundled reference document, through the core's `sheet.edit`, the insert of a detail view + (`view_box` 625, 969, 220 × 660 on the main view) and of its access in `cat-access`; + - build the archive snapshot and the PDF attachment of a report touching that sheet, the way the neighbouring case + does; + - assert the frozen N-1 scanner and `readArchiveDocument` and `assertSnapshot` accept it; + - record in the test whether the lean snapshot carries `cat-access` (assert the observed fact, either way, with a + comment). +- [ ] **Step 4: Run.** + - `cargo test -p faunosteo-core --features pdf-read --test access_category_census` + - `pnpm --filter @faunosteo/core-wasm exec vitest run tests/n-1.access-category.test.ts` + - `pnpm --filter @faunosteo/app exec vitest run tests/unit/n-1.reader.test.ts` + - Expected: all pass. +- [ ] **Step 5: Commit.** + - Files: the four test files, `crates/core/Cargo.toml`, the SQL test. + - Message: `test(supabase): cat-access census, SQL uniqueness and N-1 readers`. + +### Task 5: N-1 replay, existing sheets and references unchanged, the U6 transition written down + +**Files:** +- Modify: `docs/development/V1-2-6_UX_COMPATIBILITY.md` (§1 and §7) +- Modify: `docs/development/ANATOMICAL_SHEET_MODEL.md` (categories and editor refusals) +- Modify: `docs/development/RUST.md` (§12, the editor commands; the wasm figure row) + +- [ ] **Step 1: Replay the N-1 characterisation at its baseline (R3).** One command block, run from the repo root. The + worktree path is a fresh `mktemp -d`, written in the same command. `N1_BASE` is the sha recorded at Task 1. + +```bash +cd /home/bchanot/Documents/faunosteo-v1-2 && WT=$(mktemp -d) && \ +git worktree add --detach "$WT/core" "$N1_BASE" && \ +cp crates/core/tests/fixtures/n1/access-category.json "$WT/core/crates/core/tests/fixtures/n1/access-category.json" && \ +(cd "$WT/core" && cargo test -p faunosteo-core --test n1_access_category) ; \ +git worktree remove --force "$WT/core" +``` + + Expected: `test result: ok. 8 passed`. This is the baseline core reading, editing and rewriting the current fixture. + Record the output in the ledger. +- [ ] **Step 2: Existing sheets unchanged (R3 « fiches existantes »).** + - `git diff --stat "$PLAN_BASE"..HEAD -- supabase/seed crates/core/tests/oracles apps/app/tests/fixtures/goldens packages/core-wasm/tests/n-1` + prints nothing. + - `pnpm import:equine --check` reports no drift. + - `cargo test -p faunosteo-core --test sheet_fingerprint --test r5_6_switch --test characterisation_serde_tolerance --test sheet_review --test anatomy_canvas_op --test anatomy_compose --test anatomy_layer` + is green. + - `cargo test -p faunosteo-core --features curation --test curation_review --test curation_draft` is green. +- [ ] **Step 3: Write the compatibility record.** + - `V1-2-6_UX_COMPATIBILITY.md` §1, a dated paragraph under the route A text: + - the internal category of detail-view accesses is marked by its reserved id `cat-access` (owner 2026-11-22), with + no key and schema v2; + - the core creates it when an access enters it, and the editor commands refuse every other write + (`reserved_category`); + - N-1 applications read it as an ordinary category, and their possible states are listed with what the new version + does (README « Conséquences » 1); + - U6 still brings the `role` key for the fixed categories with its write lock, and decides whether `navigation` + stays in the role list. + - `V1-2-6_UX_COMPATIBILITY.md` §7: add « U2 with `cat-access`: revertible, documents stay plain v2 ». + - `ANATOMICAL_SHEET_MODEL.md`: the reserved id and the refusal kind. + - `RUST.md` §12: `EditError::ReservedCategory`, `min_access_span`, and the wasm figures of Tasks 2 and 3. +- [ ] **Step 4: Commit.** Message: `docs(docs): cat-access compatibility record and N-1 replay`. Put the replay output + in the body. + + +## Part 3 · Creating and editing frames + +### Task 6: Frame geometry (pure) + +**Files:** +- Create: `apps/app/src/editor/annotations/frameBox.ts` +- Create: `apps/app/tests/unit/annotations.frameBox.test.ts` + +**Interfaces:** +- Consumes: `Frame` `{x, y, w, h}` from `editor/annotations/frame.ts`, and `round2` from `editor/annotations/gesture.ts` + (export it there if it is file-local). +- Produces, used by Tasks 8, 10, 11, 14: + - the types `XY`, `FrameHandle`, `FramePart`; + - the constants `FRAME_HANDLES`, `MIN_FRAME_PX`, `SIDE_HANDLES_MIN_PX`; + - the functions `boxFromCorners`, `intersection`, `clampInto`, `defaultBox`, `drawnBox`, `moveBox`, `resizeBox`, + `ratioLabel`, `shownHandles`, `toViewBox`. + +- [ ] **Step 1: Write the failing tests.** One `it` per line: + - `boxFromCorners({x:10,y:40},{x:4,y:2})` is `{x:4,y:2,w:6,h:38}`. + - `defaultBox({x:500,y:400}, {x:0,y:0,w:900,h:675}, 4/3, {x:0,y:0,w:2073.4,h:1629.4})`: width 300, height 225, + centred on (500, 400). + - Near the drawing's corner, `defaultBox` stays inside both the visible part and the bounds. + - `drawnBox` with a 10-unit drag and `min` 20 returns the fallback. + - `drawnBox` with a 100 × 80 drag partly outside the bounds returns the part inside the bounds. + - `resizeBox` on `'e'` moves only the right edge, and stops at the bounds and at `min`. + - `resizeBox` on `'nw'` keeps the bottom-right corner. + - `resizeBox` with `keepRatio` on `'se'` keeps the start ratio, and on `'e'` keeps the vertical centre. + - `resizeBox` with `keepRatio` stays inside the bounds and keeps the ratio when it has to shrink. + - `moveBox` clamps into the bounds and never resizes. + - `ratioLabel` gives: + - `(300,400,'fr')` « 3:4 », `(7,1)` « 7:1 », `(220,660)` « 1:3 », `(500,380)` « 4:3 », `(980,140)` « 7:1 »; + - `(100,1)` « 100:1 », `(1,100)` « 1:100 »; + - `(2.718,1,'fr')` « 8:3 » (within 2 %); + - `(2.45,1,'fr')` « 2,5:1 », and in English `'en'` « 2.5:1 ». + - `shownHandles(40, 200)` hides `n` and `s` and keeps `e`, `w` and the four corners. + - `toViewBox` rounds to 0.01. +- [ ] **Step 2: Run, expect failure:** `pnpm --filter @faunosteo/app exec vitest run tests/unit/annotations.frameBox.test.ts`. +- [ ] **Step 3: Implement.** + +```ts +import type { ViewBox } from '@faunosteo/core-wasm/types' + +import type { Frame } from './frame' +import { round2 } from './gesture' + +/** A point in drawing units. */ +export interface XY { + x: number + y: number +} + +/** The eight handles of a frame (D8), clockwise from the top-left corner: their tab order. */ +export type FrameHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' +export type FramePart = FrameHandle | 'body' +export const FRAME_HANDLES: readonly FrameHandle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] + +/** D6: the smallest side on screen while drawing and adjusting (44 px: a finger target). */ +export const MIN_FRAME_PX = { mouse: 16, pen: 16, touch: 44 } as const +/** D6: a side shorter than this on screen hides its middle handle; the corners suffice. */ +export const SIDE_HANDLES_MIN_PX = 48 + +interface Edges { + l: number + t: number + r: number + b: number +} + +const edgesOf = (f: Frame): Edges => ({ l: f.x, t: f.y, r: f.x + f.w, b: f.y + f.h }) +const frameOf = (e: Edges): Frame => ({ x: e.l, y: e.t, w: e.r - e.l, h: e.b - e.t }) + +export function boxFromCorners(a: XY, b: XY): Frame { + return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(b.x - a.x), h: Math.abs(b.y - a.y) } +} + +export function intersection(a: Frame, b: Frame): Frame | null { + const l = Math.max(a.x, b.x) + const t = Math.max(a.y, b.y) + const r = Math.min(a.x + a.w, b.x + b.w) + const bottom = Math.min(a.y + a.h, b.y + b.h) + return r > l && bottom > t ? { x: l, y: t, w: r - l, h: bottom - t } : null +} + +/** `box` moved inside `bounds`; it shrinks only when larger than them. */ +export function clampInto(box: Frame, bounds: Frame): Frame { + const w = Math.min(box.w, bounds.w) + const h = Math.min(box.h, bounds.h) + const x = Math.min(Math.max(box.x, bounds.x), bounds.x + bounds.w - w) + const y = Math.min(Math.max(box.y, bounds.y), bounds.y + bounds.h - h) + return { x, y, w, h } +} + +/** D4: a third of the visible width at the drawing area's ratio (w / h), centred on `at`. */ +export function defaultBox(at: XY, visible: Frame, areaRatio: number, bounds: Frame): Frame { + const w = visible.w / 3 + const h = w / areaRatio + const room = intersection(visible, bounds) ?? bounds + return clampInto({ x: at.x - w / 2, y: at.y - h / 2, w, h }, room) +} + +/** D4, D6: the frame a drag draws, cut to `bounds`; one narrower or shorter than `min` + * (drawing units) counts as a click: `fallback()`, the default frame there. */ +export function drawnBox(from: XY, to: XY, min: number, bounds: Frame, fallback: () => Frame): Frame { + const inside = intersection(boxFromCorners(from, to), bounds) + return inside === null || inside.w < min || inside.h < min ? fallback() : inside +} + +export function moveBox(box: Frame, delta: XY, bounds: Frame): Frame { + return clampInto({ ...box, x: box.x + delta.x, y: box.y + delta.y }, bounds) +} + +export interface Resize { + start: Frame + handle: FrameHandle + delta: XY + /** The smallest side, in drawing units (`MIN_FRAME_PX` times the units per px). */ + min: number + keepRatio: boolean + bounds: Frame +} + +/** D8: `start` after dragging `handle` by `delta`: the opposite side or corner stays put, each + * side keeps `min`, the box stays in `bounds`; `keepRatio` (Maj, « Garder les proportions ») + * keeps the ratio of `start`. */ +export function resizeBox(input: Resize): Frame { + const moved = moveEdges(input) + return input.keepRatio ? frameOf(withRatio(moved, input)) : frameOf(moved) +} + +function moveEdges({ start, handle, delta, min, bounds }: Resize): Edges { + const e = edgesOf(start) + const lim = edgesOf(bounds) + const next = { ...e } + if (handle.includes('w')) next.l = Math.min(Math.max(e.l + delta.x, lim.l), e.r - min) + if (handle.includes('e')) next.r = Math.max(Math.min(e.r + delta.x, lim.r), e.l + min) + if (handle.includes('n')) next.t = Math.min(Math.max(e.t + delta.y, lim.t), e.b - min) + if (handle.includes('s')) next.b = Math.max(Math.min(e.b + delta.y, lim.b), e.t + min) + return next +} + +interface Size { + w: number + h: number +} + +function withRatio(moved: Edges, { start, handle, min, bounds }: Resize): Edges { + const ratio = start.w / start.h + const w = moved.r - moved.l + const h = moved.b - moved.t + const byWidth = handle === 'e' || handle === 'w' || (handle.length === 2 && w / start.w >= h / start.h) + let size: Size = byWidth ? { w, h: w / ratio } : { w: h * ratio, h } + const grow = Math.max(1, min / size.w, min / size.h) + size = { w: size.w * grow, h: size.h * grow } + const fit = fitScale(handle, edgesOf(start), size, edgesOf(bounds)) + return anchored(handle, edgesOf(start), { w: size.w * fit, h: size.h * fit }) +} + +/** Scale (at most 1) that keeps the anchored box inside `lim`. */ +function fitScale(handle: FrameHandle, s: Edges, size: Size, lim: Edges): number { + const cx = (s.l + s.r) / 2 + const cy = (s.t + s.b) / 2 + const centredW = 2 * Math.min(cx - lim.l, lim.r - cx) + const centredH = 2 * Math.min(cy - lim.t, lim.b - cy) + const roomW = handle.includes('w') ? s.r - lim.l : handle.includes('e') ? lim.r - s.l : centredW + const roomH = handle.includes('n') ? s.b - lim.t : handle.includes('s') ? lim.b - s.t : centredH + return Math.min(1, roomW / size.w, roomH / size.h) +} + +/** The box of `size` held by the side or corner opposite `handle`, centred on the other axis. */ +function anchored(handle: FrameHandle, s: Edges, size: Size): Edges { + const cx = (s.l + s.r) / 2 + const cy = (s.t + s.b) / 2 + const l = handle.includes('w') ? s.r - size.w : handle.includes('e') ? s.l : cx - size.w / 2 + const t = handle.includes('n') ? s.b - size.h : handle.includes('s') ? s.t : cy - size.h / 2 + return { l, t, r: l + size.w, b: t + size.h } +} + +/** D6: « 3:4 », « 7:1 »: the simplest p:q within 2 % of w / h with p or q from 1 to 4, else + * one decimal against 1 (« 2,5:1 » in French). */ +export function ratioLabel(w: number, h: number, locale: 'fr' | 'en'): string { + const r = w / h + const near = (p: number, q: number) => p >= 1 && q >= 1 && Math.abs(p / q - r) / r <= 0.02 + let best: [number, number] | null = null + for (let k = 1; k <= 4; k++) { + const pairs: [number, number][] = [[Math.round(r * k), k], [k, Math.round(k / r)]] + for (const [p, q] of pairs) { + if (near(p, q) && (best === null || Math.max(p, q) < Math.max(best[0], best[1]))) best = [p, q] + } + } + if (best !== null) return `${best[0]}:${best[1]}` + const decimal = (n: number) => n.toFixed(1).replace('.', locale === 'fr' ? ',' : '.') + return r >= 1 ? `${decimal(r)}:1` : `1:${decimal(1 / r)}` +} + +/** D6: the handles shown for a frame of this size on screen. */ +export function shownHandles(widthPx: number, heightPx: number): FrameHandle[] { + return FRAME_HANDLES.filter((handle) => { + if (handle.length === 2) return true + return handle === 'n' || handle === 's' ? widthPx >= SIDE_HANDLES_MIN_PX : heightPx >= SIDE_HANDLES_MIN_PX + }) +} + +export function toViewBox(box: Frame): ViewBox { + return { min_x: round2(box.x), min_y: round2(box.y), width: round2(box.w), height: round2(box.h) } +} +``` + +- [ ] **Step 4: Run, expect pass.** Then `pnpm typecheck`. +- [ ] **Step 5: Commit.** Message: `feat(editor): frame geometry for detail views drawn on the drawing`. + +### Task 7: The frame work item (create and recrop), its guards, Escape and the history hold + +**Files:** +- Create: `apps/app/src/editor/annotations/frameWork.ts` +- Modify: `apps/app/src/editor/annotations/workStore.ts`: + - `Work` gets `frame: FrameWork | null`; + - `GuardWork` adds `'frame'`; + - `guardWork`, `dropStale` and `resetWork` handle it; + - `HistoryHold` adds `'frame'`. +- Modify: `apps/app/src/editor/annotations/escape.ts` (input `framing`, action `'ask_frame'`, at the rank of `'ask_creation'`) +- Modify: `apps/app/src/editor/annotations/drawingGuard.ts` (the question for `'frame'`) +- Modify: `apps/app/src/components/editor/DrawingGuardDialog.tsx` (two titles) +- Modify: `apps/app/src/components/editor/HistoryButtons.tsx` (`holdOf`), `apps/app/src/editor/useUndoShortcuts.ts` +- Modify: `apps/app/src/i18n/fr.ts`, `en.ts` +- Tests: `apps/app/tests/unit/annotations.workStore.test.ts`, `editor-escape.test.tsx`, `editor-history-buttons.test.tsx`, + `editor-undo-shortcuts.test.tsx` + +**Interfaces:** +- Produces: + - `FrameWork`: + ```ts + { + purpose: 'create' | 'recrop' + viewId: string // create: the parent; recrop: the view recropped + drawnOn: string // the view whose drawing shows the frame + box: Frame | null + keepRatio: boolean + moveAccess: boolean + moving: boolean + dialog: boolean + started: boolean + base: string + returnTo: string // the view shown before the work began + } + ``` + - The mutations `startFrame(start)`, `setFrameBox(box)`, `setKeepRatio(on)`, `setMoveAccess(on)`, + `setFrameMoving(on)`, `openViewDialog()`, `backToFrame()`, `dropFrame()`. + +- [ ] **Step 1: Failing tests.** + - `startFrame` refuses while a creation or a mode is open: it returns false and leaves the store unchanged. + - `setFrameBox` marks `started`. + - `dropStale` drops a frame whose `base` differs. + - `guardWork` returns `'frame'` only once a box is drawn (create) or changed (recrop). + - `escapeAction({ ..., framing: true })` returns `'ask_frame'`. + - `holdOf` returns `'frame'` for undo and redo while a frame is open. + - Ctrl+Z does nothing while a frame is open. + - The guard dialog title is « Abandonner la création ? » for create and « Abandonner le recadrage ? » for recrop. +- [ ] **Step 2: Run, expect failure.** +- [ ] **Step 3: Implement.** `frameWork.ts` follows `creationWork.ts`: each mutation is one `useAnnotationWork.setState`. + - `startFrame` takes `{ purpose, viewId, drawnOn, box, returnTo }` and stamps `base` with the current document text. + - The R-12 guard (BDR-123) asks only when `started`. The guard texts use the existing `ConfirmDialog` keys pattern + (`editor.annotations.guard.*`). +- [ ] **Step 4: i18n.** + +| Key | fr | en | +|---|---|---| +| `editor.annotations.guard.frame_create` | Abandonner la création ? | Abandon the creation? | +| `editor.annotations.guard.frame_recrop` | Abandonner le recadrage ? | Abandon the recrop? | +| `editor.history.hold_frame` | Terminez ou abandonnez le cadre en cours. | Finish or abandon the frame in progress. | + +- [ ] **Step 5: Run.** + - Run the four test files above, then `pnpm typecheck`. + - Run `pnpm --filter @faunosteo/app exec vitest run tests/unit/editor-history-guards.test.tsx tests/unit/editor-leave-cascade.test.tsx`. + - Expected: pass. +- [ ] **Step 6: Commit.** Message: `feat(editor): frame work item with its guard, Escape and history hold`. + +### Task 8: Drawing and adjusting the frame on the drawing (mouse, touch, keyboard) + +Board panels 02, 03, 12, 13, 18. Decisions D4, D6, D8, D10, D21. + +**Files:** +- Modify: `apps/app/src/editor/annotations/press.ts` +- Modify: `apps/app/src/editor/annotations/usePressGesture.ts`, `useCanvasGestures.ts` +- Create: `apps/app/src/components/editor/annotations/FrameHandles.tsx` +- Modify: `apps/app/src/components/editor/annotations/HandleLayer.tsx` (mount `FrameHandles`) +- Modify: `apps/app/src/components/editor/annotations/AnnotationOverlay.tsx` (frame outline, veil, drag preview) +- Modify: `apps/app/src/components/editor/annotations/AnnotationCanvas.tsx`: + - `data-creating` while a frame is open (existing CSS dims annotations, D10); + - Enter while drawing places the default frame at the centre. +- Tests: `apps/app/tests/unit/annotations.press.test.ts`, new `apps/app/tests/unit/editor-frame-draw.test.tsx` + +**Interfaces:** +- Consumes: `frameBox.ts` (Task 6), `frameWork.ts` (Task 7). +- Produces: + - `HandleRef` gains `{ kind: 'frame'; part: FramePart }`; + - `DragAction` gains `{ type: 'draw' }` and `{ type: 'drag_frame'; part: FramePart }`; + - `ClickAction` gains `{ type: 'place_default' }`; + - `DragContext` gains `drawing: boolean`: a frame without a box, or the access tool with the rectangle or circle shape + (Task 14). + +Behaviour (the pure decisions in `press.ts`, tested first): + +1. **Drawing phase** (frame open, `box` null, or `ctx.drawing`). With any pointer kind, a press past the slop is + `{type:'draw'}`. This includes one finger: D4 says a one-finger drag draws in this mode only. A release within the + slop is `{type:'place_default'}`. Annotation hits are ignored. A second pointer cancels (`multi`) and zooms or pans, + as today. +2. **Adjust phase** (frame open, `box` set): + - a press on a `{kind:'frame', part}` handle is `drag_frame` with that part; `body` moves the whole box; + - a press elsewhere starts no drag and selects nothing: `{type:'none', futile:false}`, and with the mouse the + framing pans; + - a click elsewhere does nothing. +3. **Glue** (`usePressGesture`). + - `draw` keeps a local preview box (`boxFromCorners` of the start and the current point, in drawing units through + `clientToDrawing`). + - On release, `drawnBox(from, to, min, bounds, fallback)` with: + - `min = MIN_FRAME_PX[kind] × drawingPerClientPx(svg)`; + - `bounds` = the parent's frame (root `viewBox`); + - `fallback` = `defaultBox(at, visibleBounds(...), 4/3, bounds)`. + - That result goes through `setFrameBox`. + - `drag_frame` previews `resizeBox` (or `moveBox` for `body`) from the box at press time, with `keepRatio` = the work + item's flag OR Shift held. Release goes through `setFrameBox`. + - Nothing reaches the core during the gesture (BDR-050). +4. **`FrameHandles`**, in the handle layer's coordinates: + - a focusable body `` named « Cadre »; + - then the handles of `shownHandles(widthPx, heightPx)` in `FRAME_HANDLES` order, each `role="button"` and named + (« Coin haut gauche », « Côté haut », « Coin haut droit », « Côté droit », « Coin bas droit », « Côté bas », + « Coin bas gauche », « Côté gauche »); + - hit radius `sizes.hit` (22 px coarse), constant on screen like the vertex handles; + - keyboard: + - arrows move the body (`moveBox`) or the focused handle (`resizeBox`) by `moveStep(frame, shift)`; + - Enter validates (Task 9's « Valider le cadre », or « Appliquer » in recrop); + - Escape asks (Task 7). + - The loupe follows a touch drag of a handle, as for vertices (board 12). +5. **Overlay** (`aria-hidden`): + - the box is a solid accent stroke, 2 px non-scaling; + - the veil is an even-odd path over the parent frame minus the box, `fill` ink at 0.35; + - the drag preview draws the same, in place. +6. **Keyboard placement.** Enter on the focused drawing while drawing, or the start from the strip by keyboard (Task 9), + places `defaultBox` at the visible centre and announces « Cadre posé au centre. » in the existing polite status of + `KeyboardAdd`. + +- [ ] **Step 1: Failing press tests.** + - Drawing phase: + - a mouse drag gives `draw`, and so does a one-finger drag; + - a click gives `place_default`; + - a second pointer cancels. + - Adjust phase: + - a press on `{frame, se}` gives `drag_frame se`, and on `{frame, body}` gives `drag_frame body`; + - a press on an annotation does nothing. +- [ ] **Step 2: Failing component tests** (`editor-frame-draw.test.tsx`, happy-dom, with the store set directly): + - eight named handle buttons plus « Cadre » render for a 300 × 200 px box, and six for a 40 px wide box; + - ArrowRight on « Côté droit » widens the box by one step, and by ten with Shift; + - Enter on the drawing with an empty frame sets the default box and announces it. +- [ ] **Step 3: Implement** until both pass. +- [ ] **Step 4: Run.** + - `pnpm --filter @faunosteo/app exec vitest run tests/unit/annotations.press.test.ts tests/unit/editor-frame-draw.test.tsx tests/unit/editor-zone-edit.test.tsx tests/unit/editor-point-edit.test.tsx` + - `pnpm typecheck` +- [ ] **Step 5: Commit.** Message: `feat(editor): draw and adjust a detail view frame with mouse, touch and keys`. + +### Task 9: The strip's view commands and frame commands + +Board panels 01, 03, 09, 18, 19. Decisions D3, D6, D15, D16. + +**Files:** +- Create: `apps/app/src/components/editor/annotations/ViewCommands.tsx` (idle commands) +- Create: `apps/app/src/components/editor/annotations/FrameCommands.tsx` (create and recrop phases) +- Modify: `apps/app/src/components/editor/annotations/SceneStrip.tsx`: + - `commandsKeyOf`: keys `frame-draw`, `frame-adjust`, `frame-recrop`, `view-idle`; + - `SceneCommands`; + - the strip lead while a frame is open. +- Modify: `apps/app/src/editor/annotations/stripLead.ts` +- Modify: `apps/app/src/i18n/fr.ts`, `en.ts` +- Test: new `apps/app/tests/unit/editor-view-commands.test.tsx` + +Behaviour: + +1. **Idle** (tool `select`, nothing selected, no creation, no frame): + - on the main view, the strip shows « Nouvelle vue de détail »; + - on a detail view, it shows « Vue parente » (Task 21 wires it), « Recadrer la vue » (crop views only, i.e. + `svg_asset_id` null) and « Nouvelle vue de détail ». + - The commands box keeps its fixed height (A6). `commandsKey` remounts the box instead of resizing it (LRN-131). +2. **« Nouvelle vue de détail »** calls `startFrame({ purpose: 'create', viewId: scene.viewId, drawnOn: scene.viewId, + box: null, returnTo: scene.viewId })` under `guardedPress`. + - A keyboard press (`event.detail === 0`) also places the default box at the centre (Task 8, point 6). + - The read-only editor and widths under 1 024 px never show it (editing is read-only there). +3. **Drawing phase**: lead « Nouvelle vue de détail », detail « Glissez sur le dessin pour tracer le cadre, ou cliquez + pour poser un cadre par défaut. », commands « Abandonner ». +4. **Adjust phase** (board 03, 18): + - lead detail « Glissez un coin ou un côté pour ajuster, l'intérieur pour déplacer. »; + - commands: the chip « Format {ratio} » (`ratioLabel`), the checkbox « Garder les proportions », then « Déplacer », + « Retracer », « Abandonner », and « Valider le cadre » (primary); + - « Déplacer » enters the move bar (`MoveModeBar`), whose arrows call `moveBox` and whose « Valider la position » + leaves it (A11); + - « Retracer » sets `box` back to null; + - « Valider le cadre » calls `openViewDialog()` (Task 10). +5. **Recrop phase** (Task 11 fills the actions): lead « Recadrer · {name} », detail + « Les {count} annotations de cette vue repasseront « à confirmer » » (plural keys), commands « Format », « Garder + les proportions », « Déplacer l'accès avec le cadre », « Abandonner », « Appliquer » (primary). +6. **Width.** At 1 024 px and at 1 280 px, no command is clipped. Task 29 measures this in the browser. If the adjust + phase does not fit at 1 024 px, the chip « Format » moves into the lead's detail line, never onto a second line. + +| Key | fr | en | +|---|---|---| +| `editor.annotations.view.new` | Nouvelle vue de détail | New detail view | +| `editor.annotations.view.recrop` | Recadrer la vue | Recrop the view | +| `editor.annotations.frame.draw_hint` | Glissez sur le dessin pour tracer le cadre, ou cliquez pour poser un cadre par défaut. | Drag on the drawing to draw the frame, or click to place a default frame. | +| `editor.annotations.frame.adjust_hint` | Glissez un coin ou un côté pour ajuster, l'intérieur pour déplacer. | Drag a corner or a side to adjust, the inside to move. | +| `editor.annotations.frame.format` | Format {ratio} | Ratio {ratio} | +| `editor.annotations.frame.keep_ratio` | Garder les proportions | Keep the proportions | +| `editor.annotations.frame.move` | Déplacer | Move | +| `editor.annotations.frame.redraw` | Retracer | Draw again | +| `editor.annotations.frame.abandon` | Abandonner | Abandon | +| `editor.annotations.frame.validate` | Valider le cadre | Confirm the frame | +| `editor.annotations.frame.apply` | Appliquer | Apply | +| `editor.annotations.frame.recrop_title` | Recadrer · {name} | Recrop · {name} | +| `editor.annotations.frame.recrop_warning_one` | L'annotation de cette vue repassera « à confirmer ». | The annotation of this view will go back to “to confirm”. | +| `editor.annotations.frame.recrop_warning_other` | Les {count} annotations de cette vue repasseront « à confirmer ». | The {count} annotations of this view will go back to “to confirm”. | +| `editor.annotations.frame.move_access` | Déplacer l'accès avec le cadre | Move the access with the frame | +| `editor.annotations.frame.placed` | Cadre posé au centre. | Frame placed at the centre. | +| `editor.annotations.frame.part.body` | Cadre | Frame | +| `editor.annotations.frame.part.nw` … `part.w` | Coin haut gauche · Côté haut · Coin haut droit · Côté droit · Coin bas droit · Côté bas · Coin bas gauche · Côté gauche | Top-left corner · Top side · Top-right corner · Right side · Bottom-right corner · Bottom side · Bottom-left corner · Left side | + +- [ ] **Step 1: Failing tests:** + - idle commands on the main view and on a crop detail view; none on an own-drawing view's « Recadrer »; + - the commands key changes between phases; + - « Retracer » clears the box; + - the « Format » chip follows the box; + - Shift or the checkbox keeps the ratio while a handle moves. +- [ ] **Step 2: Implement** until they pass. +- [ ] **Step 3: Run.** `pnpm --filter @faunosteo/app exec vitest run tests/unit/editor-view-commands.test.tsx tests/unit/editor-annotations-tab.test.tsx tests/unit/editor-add-buttons.test.tsx`, then `pnpm typecheck`. +- [ ] **Step 4: Commit.** Message: `feat(editor): strip commands to create and adjust a detail view frame`. + +### Task 10: « Nouvelle vue de détail »: the dialog and the one-step commit + +Board panels 04, 05, 11. Decisions D7, D13, D14, D18, D19. Arbitration A1. Owner requirement R1. + +**Files:** +- Create: `apps/app/src/editor/annotations/viewCreation.ts` +- Create: `apps/app/src/editor/annotations/accessShape.ts` (only `rectanglePolygon` and `accessBox` here; Task 14 adds + the rest) +- Create: `apps/app/src/components/editor/annotations/ViewCreationDialog.tsx` +- Create: `apps/app/src/components/editor/annotations/CropPreviews.tsx` (« Fenêtre du bilan » and « Page du PDF ») +- Modify: `apps/app/src/components/editor/tabs/AnnotationsTab.tsx` (mount the dialog beside `CreationDialog`) +- Modify: `apps/app/src/editor/annotations/useCreationFollow.ts` (follow-up after a view creation) +- Modify: `apps/app/src/i18n/fr.ts`, `en.ts` +- Tests: new `apps/app/tests/unit/annotations.viewCreation.test.ts`, new `apps/app/tests/unit/editor-view-creation.test.tsx` + +**Interfaces:** +- Consumes: + - `ACCESS_CATEGORY_ID` (Task 13: write that file first if Task 13 has not run; the execution order puts Task 13 + first); + - `toViewBox` and `clampInto` (Task 6); + - `PreviewState.min_access_span` (Task 3); + - `commitBatch` (`editorEdit.ts:275-291`), `geometryAccept` (`issues.ts:169`), `newElementId`. +- Produces: + ```ts + export type AccessChoice = 'frame' | 'later' | 'none' + export interface NewViewForm { fr: string; en: string; access: AccessChoice; laterality: Laterality | '' } + export interface NewViewPlace { parentViewId: string; box: Frame; parentBounds: Frame; minAccessSpan: number | null } + export function newViewCommands(form: NewViewForm, place: NewViewPlace, ids: { view: string; access: string }): EditCommand[] + export function frameKnown(viewId: string): (state: PreviewState) => boolean + ``` + `accessShape.ts` gains `rectanglePolygon(box)` and `accessBox(frame, minSpan, bounds): { box: Frame; grown: boolean }`. + +- [ ] **Step 1: Failing pure tests** (`annotations.viewCreation.test.ts`): + - `newViewCommands` with `access: 'frame'` gives exactly two commands: + - an insert of a detail view `{ kind: 'detail', id, name: {fr, en}, svg_asset_id: null, view_box: toViewBox(box), parent_view_id }`; + - an insert of a `detail_trigger`: + ```ts + { + id, view_id: parentViewId, category_id: 'cat-access', laterality, + geometry: rectanglePolygon(accessBox(box, minAccessSpan, parentBounds).box), + review_status: 'to_confirm', color: null, name: null, opens_view_id: id, + } + ``` + - With `'later'` and `'none'`, only the view insert. + - `accessBox` grows a 10 × 10 frame to a 29 × 29 square around the same centre when `minSpan` is 29, keeps it inside + the bounds near an edge, reports `grown`, and leaves a large frame unchanged (`grown: false`). + - `rectanglePolygon` returns four vertices clockwise from the top-left, rounded to 0.01. + - `frameKnown` refuses a state whose report holds `view.frame.unknown` at the new view's path, and accepts otherwise. +- [ ] **Step 2: Implement `viewCreation.ts` and the two `accessShape.ts` functions.** + +```ts +// accessShape.ts (this task's part) +import type { Polygon } from '@faunosteo/core-wasm/types' + +import type { Frame } from './frame' +import { clampInto } from './frameBox' +import { round2 } from './gesture' + +/** D5, D9: a rectangle access, stored as a polygon of four vertices clockwise from the + * top-left, so it reshapes by its vertices like a zone. */ +export function rectanglePolygon(box: Frame): Polygon { + const l = round2(box.x) + const t = round2(box.y) + const r = round2(box.x + box.w) + const b = round2(box.y + box.h) + return { type: 'polygon', points: [[l, t], [r, t], [r, b], [l, b]] } +} + +/** A1: the generated access, the frame's rectangle grown around its centre to `minSpan` on + * each side when needed (the core's smallest readable access on the parent), kept in `bounds`. */ +export function accessBox(frame: Frame, minSpan: number | null, bounds: Frame): { box: Frame; grown: boolean } { + const span = minSpan ?? 0 + const w = Math.max(frame.w, span) + const h = Math.max(frame.h, span) + const grown = w > frame.w || h > frame.h + const box = clampInto({ x: frame.x + (frame.w - w) / 2, y: frame.y + (frame.h - h) / 2, w, h }, bounds) + return { box, grown } +} +``` + +```ts +// viewCreation.ts +import type { EditCommand, Laterality, PreviewState } from '@faunosteo/core-wasm/types' + +import { ACCESS_CATEGORY_ID } from '../accessCategory' +import { accessBox, rectanglePolygon } from './accessShape' +import type { Frame } from './frame' +import { toViewBox } from './frameBox' + +export type AccessChoice = 'frame' | 'later' | 'none' + +export interface NewViewForm { + fr: string + en: string + access: AccessChoice + laterality: Laterality | '' +} + +export interface NewViewPlace { + parentViewId: string + box: Frame + parentBounds: Frame + minAccessSpan: number | null +} + +/** D13, D14: the view, then its access in the internal category (the core adds the category + * with it, A6); one `commitBatch`, one undo step. */ +export function newViewCommands( + form: NewViewForm, + place: NewViewPlace, + ids: { view: string; access: string }, +): EditCommand[] { + const view: EditCommand = { + op: 'insert', + element: { + kind: 'view', + value: { + kind: 'detail', + id: ids.view, + name: { fr: form.fr.trim(), en: form.en.trim() }, + svg_asset_id: null, + view_box: toViewBox(place.box), + parent_view_id: place.parentViewId, + }, + }, + } + if (form.access !== 'frame' || form.laterality === '') return [view] + const geometry = rectanglePolygon(accessBox(place.box, place.minAccessSpan, place.parentBounds).box) + const access: EditCommand = { + op: 'insert', + element: { + kind: 'annotation', + value: { + kind: 'detail_trigger', + id: ids.access, + view_id: place.parentViewId, + category_id: ACCESS_CATEGORY_ID, + laterality: form.laterality, + geometry, + review_status: 'to_confirm', + color: null, + name: null, + opens_view_id: ids.view, + }, + }, + } + return [view, access] +} + +/** The core could not frame the new view (`view.frame.unknown`: a side under one unit, beyond + * 100:1, or too far for its size): refuse the commit. */ +export function frameKnown(viewId: string): (state: PreviewState) => boolean { + return (state) => { + const index = state.document.views.findIndex((view) => view.id === viewId) + const path = `views[${index}]` + return !state.report.issues.some((issue) => issue.code === 'view.frame.unknown' && issue.path === path) + } +} +``` + + Adapt the field order and literal types to the generated `EditCommand` type. The test pins the values, not the key + order. Wrap `frameKnown` into the accept shape `commitBatch` takes, the way `geometryAccept` is wrapped. +- [ ] **Step 3: Failing dialog tests** (`editor-view-creation.test.tsx`, with the core runtime of + `tests/helpers/annotationsCore.ts`): + - **Mount.** « Valider le cadre » opens the dialog over the right column (`anchor`, `veilCloses={false}`) with: + - the parent reminder « Vue parente : {nom} »; + - FR and EN names, both required; + - the access radio group with « Le rectangle du cadre (remodelable ensuite) » checked; + - the laterality select, shown with that choice, required and without default (A4); + - the note « Rangé dans « Accès aux vues détaillées » »; + - the two previews; + - « Créer la vue » (primary), « Ajuster le cadre », « Abandonner ». + - **Grown access.** When `accessBox(...).grown`, the note « L'accès est agrandi autour du cadre pour rester lisible + sur la vue parente. » shows under the access group. + - **Create with the frame access.** + - « Créer la vue » makes exactly one undo entry. The document then has the view, the access and `cat-access`, and + one Undo removes all three. + - The parent stays shown, and the new access is selected with its vertex handles (D14). + - The chip joins the row, and the message « Vue « {fr} » créée » with « Défaire » shows under the drawing. + - **« Aucun pour l'instant »** (R1). The view is created without an access. The Vérification tab lists + `view.unreachable` for it, as an error that blocks submission. Saving still works (`saveDraft` path unchanged). + - **« Je le tracerai ensuite ».** The view is created. The access tool is then armed on the parent, with the new view + preset as the access dialog's « Vue ouverte » (Task 14 reads the preset). + - **Core refusal.** The dialog stays open, and the error shows in the dialog's single error slot (LRN-134) with + focus. `frameRefusalMessage` phrases `view.frame.unknown`. + - **Leaving.** « Abandonner », Escape or leaving the tab asks « Abandonner la création ? » through the dialog's own + `DiscardConfirm`, as `CreationDialog` does. « Ajuster le cadre » closes the dialog and keeps the box. + - **Previews.** « Fenêtre du bilan » is a 4:3 box showing the parent drawing cropped to the box between neutral + bands (Task 22's `bandInsets`). « Page du PDF » is a page sketch with the image at the box's ratio, half width, or + full width when `w ≥ 3h`. The constant is `PDF_FULL_WIDTH_RATIO = 3`. +- [ ] **Step 4: Implement until they pass.** + - Ids come from `newElementId('view')` and `newElementId('anno')`, built again once on `duplicate_key` (the `runBatch` + pattern). + - Accept: `geometryAccept({ before, changedIds: [accessId] })` combined with `frameKnown(viewId)`. + - `minAccessSpan` is `previewState.min_access_span[parentViewId] ?? null`. + - A1 alternative, only if the owner picks it: `accessBox` is not called (`minAccessSpan` null, no grown note). + - A frame too small for a readable access is refused by the core (`TooSmall`, `geometryAccept`). + - The dialog shows in its error slot « Ce cadre est trop petit pour servir d'accès lisible sur la vue parente : + choisissez « Je le tracerai ensuite » ou « Aucun pour l'instant », ou agrandissez le cadre. » + - Focus goes to the access group. +- [ ] **Step 5: The PDF constant stays in step with the core.** Add a test that reads + `crates/core/src/pdf/write/layout/observation.rs` and asserts it declares `const FULL_WIDTH_MIN_RATIO: u32 = 3;` + (Task 26 adds that constant). Before Task 26 runs, mark the test `it.todo`; Task 26 turns it into a real test. + +| Key | fr | en | +|---|---|---| +| `editor.views.create.title` | Nouvelle vue de détail | New detail view | +| `editor.views.create.parent` | Vue parente : {name} | Parent view: {name} | +| `editor.views.create.access_legend` | Accès sur la vue parente | Access on the parent view | +| `editor.views.create.access_frame` | Le rectangle du cadre (remodelable ensuite) | The frame's rectangle (reshape it later) | +| `editor.views.create.access_later` | Je le tracerai ensuite | I will draw it next | +| `editor.views.create.access_none` | Aucun pour l'instant | None for now | +| `editor.views.create.access_note` | Rangé dans « Accès aux vues détaillées » | Filed under “Detail view access” | +| `editor.views.create.access_grown` | L'accès est agrandi autour du cadre pour rester lisible sur la vue parente. | The access is enlarged around the frame so it stays readable on the parent view. | +| `editor.views.create.preview_bilan` | Fenêtre du bilan | Report window | +| `editor.views.create.preview_pdf` | Page du PDF | PDF page | +| `editor.views.create.submit` | Créer la vue | Create the view | +| `editor.views.create.adjust` | Ajuster le cadre | Adjust the frame | +| `editor.views.create.created` | Vue « {name} » créée | View “{name}” created | + +- [ ] **Step 6: Run** both test files, `editor-creation-dialog.test.tsx` and `editor-batch.test.ts`, then + `pnpm typecheck`. +- [ ] **Step 7: Commit.** Message: `feat(editor): create a detail view and its access in one step`. + +### Task 11: Recropping a view on its parent + +Board panel 10. Decision D16. + +**Files:** +- Create: `apps/app/src/editor/annotations/recrop.ts` +- Modify: `apps/app/src/editor/viewUpdate.ts` (export the guarded accept builder as `viewBoxAccept(before, viewId, + changedIds)`; `updateView` keeps calling it) +- Modify: `FrameCommands.tsx` (recrop actions), `AnnotationOverlay.tsx` (ghosts), `EditableAnnotations.tsx` (display the + parent while recropping; labels hidden, see Task 20) +- Test: new `apps/app/tests/unit/editor-recrop.test.tsx`, `apps/app/tests/unit/annotations.recrop.test.ts` + +**Interfaces:** +- Produces: + ```ts + export function startRecrop(viewId: string): boolean // only for a crop view (svg_asset_id null, view_box set) + export function accessFollows(doc: AnatomicalSheetDocument, viewId: string): DetailTriggerAnnotation | null + export function recropCommands(view: DetailView, box: Frame, follower: DetailTriggerAnnotation | null): EditCommand[] + ``` + `accessFollows` returns the one access on the parent opening the view whose polygon equals + `rectanglePolygon(oldBox)`, within 0.01 per coordinate. Otherwise it returns null. + +Behaviour: + +1. **Entry points.** + - « Recadrer la vue », on an idle detail view (Task 9) or on a selected access (Task 16, the view it opens). + - « Recadrer sur le dessin » in « Gérer les vues » (Task 12). + - Each calls `startFrame({ purpose: 'recrop', viewId, drawnOn: parentId, box: viewBox, returnTo })`. The drawing + switches to the parent, under the R-12 guard. +2. **Display.** The parent shows whole with the frame (accent, eight handles) and the access (its own dashed look, no + change). The view's annotations are ghosts inside the frame: `AnnotationOverlay` draws their geometries at 0.35 + opacity with no `data-anno-id`. Access labels are hidden (D16). +3. **« Déplacer l'accès avec le cadre ».** Enabled and checked only when `accessFollows` finds the access. Otherwise it + is disabled and unchecked, with the reason as its description: « L'accès n'a plus la forme du cadre. » +4. **« Appliquer ».** + - It runs `commitBatch(recropCommands(view, box, followerIfChecked), { accept: viewBoxAccept(before, viewId, + followerId ? [followerId] : []) })`: one undo step, with the view's annotations going back to `to_confirm` + (`reconfirm_redrawn_views`). + - On success, the drawing returns to `returnTo`, with the message « Vue « {name} » recadrée » and « Défaire ». + - On refusal, the message is written under the drawing (`frameRefusalMessage`), and the frame stays in place, still + adjustable (D16). Nothing else changes. +5. **« Abandonner » and Escape** ask « Abandonner le recadrage ? » once the box moved (Task 7). A yes returns to + `returnTo`. + +| Key | fr | en | +|---|---|---| +| `editor.annotations.frame.access_shape_lost` | L'accès n'a plus la forme du cadre. | The access no longer has the frame's shape. | +| `editor.views.recropped` | Vue « {name} » recadrée | View “{name}” recropped | + +- [ ] **Step 1: Failing tests.** + - Pure: + - `recropCommands` gives one view update, plus one access update to `rectanglePolygon(newBox)` when a follower is + given; + - `accessFollows` finds the frame-shaped access and ignores a reshaped one. + - Component: + - recrop shows ghosts and no labels; + - the checkbox is disabled for a reshaped access; + - « Appliquer » makes one undo entry; + - a box that leaves an annotation outside is refused, the message shows, and the box stays. +- [ ] **Step 2: Implement until they pass.** +- [ ] **Step 3: Run** both test files, `editor-repair.test.tsx` and `editor-tabs-views.test.tsx`, then `pnpm typecheck`. +- [ ] **Step 4: Commit.** Message: `feat(editor): recrop a detail view on its parent drawing`. + +### Task 12: « Gérer les vues » follows the new journey + +Board panel 14. Decisions D2, D17. README « Hors périmètre » (own-drawing views). + +**Files:** +- Modify: `apps/app/src/components/editor/annotations/sections/ViewsSection.tsx` +- Modify: `apps/app/src/components/editor/views/DetailViewRow.tsx`, `CropEditor.tsx` (folded), `DetailViewForm.tsx` + (reached from the link) +- Modify: `apps/app/src/i18n/fr.ts`, `en.ts` +- Test: `apps/app/tests/unit/editor-tabs-views.test.tsx` + +Behaviour (board 14): + +1. **Top card « Nouvelle vue de détail ».** + - « Tracer sur le dessin » (primary) closes the section, shows the drawing on the current view and starts the frame + creation (Task 9, point 2). + - The link « Vue avec sa propre illustration… » opens the existing `DetailViewForm` unchanged. +2. **Main view row.** « Créer une vue de détail » starts the creation with that view as the parent (D2). +3. **Detail view rows.** + - « Recadrer sur le dessin » (crop views only) starts Task 11. + - The disclosure « Valeurs précises » holds the existing four `CropEditor` fields, folded by default (D17). + - « Supprimer » is unchanged. +4. **Missing access.** A view without an access on its parent shows the notice « Aucun accès sur « {parent} » » with + « Ajouter l'accès ». That button switches to the parent and arms the access tool with the rectangle shape, then + places the default rectangle at the parent's centre (`placeAtCentre`, Task 14). The access dialog then asks the + laterality, with the view preset as « Vue ouverte ». Own-drawing views get the same. +5. **Where the categories stand.** Nothing in this section asks for a category. +6. **The « Vues » card of the right column** (`OverviewPanel.tsx` `ViewsCard`, D3) gets « Nouvelle vue de détail », + which starts the creation on the view shown. That is the second entry point D3 names; the tool column and the add + row stay unchanged (BDR-124). + +| Key | fr | en | +|---|---|---| +| `editor.views.draw_new` | Tracer sur le dessin | Draw on the drawing | +| `editor.views.own_drawing` | Vue avec sa propre illustration… | View with its own drawing… | +| `editor.views.create_here` | Créer une vue de détail | Create a detail view | +| `editor.views.recrop_on_drawing` | Recadrer sur le dessin | Recrop on the drawing | +| `editor.views.precise` | Valeurs précises | Precise values | +| `editor.views.no_access` | Aucun accès sur « {name} » | No access on “{name}” | +| `editor.views.add_access` | Ajouter l'accès | Add the access | + +- [ ] **Step 1: Failing tests** for points 1 to 4 and 6. + - The existing numeric paths keep their tests green. + - « Valeurs précises » stays folded until opened, and its fields still apply on Enter or blur. +- [ ] **Step 2: Implement.** Run `editor-tabs-views.test.tsx` and `editor-keep-alive.test.tsx`, then + `pnpm typecheck`. +- [ ] **Step 3: Commit.** Message: `feat(editor): views section draws, recrops and adds accesses on the drawing`. + +## Part 4 · Accesses and their shapes + +### Task 13: The internal category in the interface + +Decisions D22, D23. Owner R3 (« la nouvelle version refuse de la renommer, la recolorer ou la supprimer »). Review +Focus 1. + +**Files:** +- Create: `apps/app/src/editor/accessCategory.ts` +- Modify every read listed in the audit: + - `editor/annotations/creation.ts:56` (`emptyForm`: the first ordinary category; `ACCESS_CATEGORY_ID` for a + `detail_trigger`); + - `components/editor/annotations/CreationFields.tsx:135-156`: + - no category select for a new access; + - for an existing access in `cat-access`, the fixed label instead of the select; + - for the head access and every point or zone, the ordinary categories, plus the current one when it is + `cat-access` (an N-1 state) so it can be changed; + - `AnnotationEditForm.tsx:34,72`; + - `OverviewPanel.tsx:147-199` (card and count: ordinary only); + - `general/CategoriesSection.tsx:39`: ordinary only. A move's position is mapped back to the document index, so a + `cat-access` placed in the middle by an N-1 application never shifts the others; + - `EditableAnnotations.tsx:307,415,485` (`noCategory` and the blocked flags use the ordinary categories; the access + tool and « Nouvelle vue de détail » no longer need any category); + - `SceneStrip.tsx:240`; + - `editor/annotations/missingFields.ts:118` (no category check for a new access); + - `editor/annotations/overview.ts:54-61`: the `cat-access` group is labelled `editor.annotations.access_group` and + placed last, whatever name the document stores; + - `AnnotationReadBody.tsx:29` and `editor/sheetDocument.ts:110` (fixed label). +- Test: new `apps/app/tests/unit/editor-access-category.test.tsx` + +**Interfaces:** + +```ts +// apps/app/src/editor/accessCategory.ts +/** The internal category of detail-view accesses (owner 2026-11-22, README « Conséquences » 1): + * the core alone creates it, when an access enters it; the page never lists it among the + * anatomical categories and shows it under a fixed label, whatever the document stores. */ +export const ACCESS_CATEGORY_ID = 'cat-access' + +export function isAccessCategory(id: string): boolean { + return id === ACCESS_CATEGORY_ID +} + +/** The categories a person picks from: every category but the internal one. */ +export function ordinaryCategories(categories: readonly T[]): T[] { + return categories.filter((category) => !isAccessCategory(category.id)) +} +``` + +- [ ] **Step 1: Failing tests** (`editor-access-category.test.tsx`, real core through `tests/helpers/annotationsCore.ts`): + - **Core agreement.** Inserting through `sheet.edit` a `detail_trigger` with `category_id: ACCESS_CATEGORY_ID` + creates a category of that id named « Accès aux vues détaillées ». + - **Hidden as a category.** The overview card and its count, the creation pickers and the Categories section never + show `cat-access`. + - **Its own group.** The annotations list shows « Accès aux vues détaillées », last, holding the new access and, + for an N-1 state, a point stored in it. Its label stays the same when the stored name is « Navigation ». + - **N-1 point.** The point's properties dialog shows « Accès aux vues détaillées » as its current category and lets + the person move it to « Articulations ». The update is accepted by the core. + - **Category no longer required.** A sheet whose only category is `cat-access` blocks Point and Zone with the + no-category reason, and leaves Access and « Nouvelle vue de détail » available. + - **Head access.** Its properties dialog keeps the category select with the ordinary categories (D22). +- [ ] **Step 2: Implement until they pass.** Run `editor-overview.test.tsx`, `editor-creation-dialog.test.tsx` and + `annotations.missingFields.test.ts`, then `pnpm typecheck`. + +| Key | fr | en | +|---|---|---| +| `editor.annotations.access_group` | Accès aux vues détaillées | Detail view access | + +- [ ] **Step 3: Commit.** Message: `feat(editor): internal access category kept out of the anatomical categories`. + +### Task 14: Access shapes: rectangle, polygon, circle + +Board panel 07. Decisions D5, D23. + +**Files:** +- Modify: `apps/app/src/editor/annotations/accessShape.ts` (add `circleFromDrag`, `defaultCircle`, `circleInside`) +- Modify: + - `apps/app/src/editor/annotations/uiState.ts`: `accessShape: 'rectangle' | 'polygon' | 'circle'`, default + `'rectangle'`, kept when the `'view'` action resets the rest (the last choice lasts the session); also + `accessTarget: string | null`, the preset « Vue ouverte » of Tasks 10 and 12; + - `usePlacement.ts` (`keyboardPending` and `placeAtCentre` by shape), `creation.ts` (`keyboardPending`); + - `press.ts`: `ctx.drawing` for the link tool with rectangle or circle; + - `usePressGesture.ts`: on release, the pending element goes through `placePending`, and the creation dialog opens + as today; + - `CreationFields.tsx`: `OpensSelect` preset from `accessTarget`. +- Create: `apps/app/src/components/editor/annotations/AccessShapeChoice.tsx` (strip, link tool armed, no creation) +- Modify: `SceneStrip.tsx`, `KeyboardAdd.tsx` (announcement with the shape) +- Modify: `apps/app/src/i18n/fr.ts`, `en.ts` (and `editor.annotations.no_child_view` reworded, D23) +- Tests: `apps/app/tests/unit/annotations.accessShape.test.ts` (new), `editor-add-buttons.test.tsx`, + `editor-creation-dialog.test.tsx` + +```ts +// accessShape.ts, added by this task +import type { Circle } from '@faunosteo/core-wasm/types' +import type { XY } from './frameBox' + +/** D5: a circle dragged from its centre to its edge, kept inside `bounds`; a radius under + * `minR` counts as a click: `fallback()`. */ +export function circleFromDrag(centre: XY, edge: XY, minR: number, bounds: Frame, fallback: () => Circle): Circle { + const r = Math.hypot(edge.x - centre.x, edge.y - centre.y) + if (r < minR) return fallback() + return circleInside({ type: 'circle', cx: centre.x, cy: centre.y, r }, bounds) +} + +/** D5: the default circle, a twelfth of the visible width in radius, centred on `at`. */ +export function defaultCircle(at: XY, visible: Frame, bounds: Frame): Circle { + return circleInside({ type: 'circle', cx: at.x, cy: at.y, r: visible.w / 12 }, bounds) +} + +/** The circle moved (and shrunk only if larger) so it lies inside `bounds`, rounded to 0.01. */ +export function circleInside(circle: Circle, bounds: Frame): Circle { + const r = Math.min(circle.r, bounds.w / 2, bounds.h / 2) + const cx = Math.min(Math.max(circle.cx, bounds.x + r), bounds.x + bounds.w - r) + const cy = Math.min(Math.max(circle.cy, bounds.y + r), bounds.y + bounds.h - r) + return { type: 'circle', cx: round2(cx), cy: round2(cy), r: round2(r) } +} +``` + +Behaviour: + +1. **Shape choice.** With the access tool armed and no creation open, the strip shows a radio group « Forme de + l'accès »: Rectangle, Polygone, Cercle. Arrow keys move inside the group. +2. **Rectangle.** Drag like the frame (`drawnBox`, min `MIN_FRAME_PX`), or click for `defaultBox`. The pending element + is `rectanglePolygon(box)`. +3. **Circle.** Drag from the centre (`circleFromDrag`, min radius `MIN_FRAME_PX[kind] / 2` in units), or click for + `defaultCircle`. +4. **Polygon.** As today, vertex by vertex. +5. **« Placer au centre »** places the chosen shape at the visible centre: `defaultBox` → polygon, `defaultCircle`, or + the existing triangle for Polygone. +6. **Announcement:** « Outil Accès armé, forme {shape}. » +7. **The access dialog** asks « Vue ouverte » (preset from `accessTarget` when set) and the laterality. There is no + category: `ACCESS_CATEGORY_ID` (Task 13). On commit the core creates the category if it is missing (A6). +8. **The access tool's disabled reason** becomes « Créez d'abord une vue de détail. » (D23). + +| Key | fr | en | +|---|---|---| +| `editor.annotations.shape.legend` | Forme de l'accès | Access shape | +| `editor.annotations.shape.rectangle` | Rectangle | Rectangle | +| `editor.annotations.shape.polygon` | Polygone | Polygon | +| `editor.annotations.shape.circle` | Cercle | Circle | +| `editor.annotations.armed.detail_trigger_shape` | Outil Accès armé, forme {shape}. | Access tool armed, {shape} shape. | +| `editor.annotations.no_child_view` | Créez d'abord une vue de détail. | Create a detail view first. | + +- [ ] **Step 1: Failing tests:** + - pure tests of the three circle functions (minimum radius, clamping at an edge, rounding); + - the shape choice keeps across a view change and defaults to Rectangle; + - a rectangle drag opens the access dialog with a four-vertex polygon pending; + - a circle drag opens it with a circle pending; + - « Placer au centre » places each shape; + - the dialog has no category field; + - the committed access lands in `cat-access`. +- [ ] **Step 2: Implement until they pass.** Run `annotations.accessShape.test.ts`, `editor-add-buttons.test.tsx`, + `editor-creation-dialog.test.tsx` and `annotations.press.test.ts`, then `pnpm typecheck`. +- [ ] **Step 3: Commit.** Message: `feat(editor): rectangle, polygon and circle accesses`. + +### Task 15: The radius handle of a circle access + +Board panel 07. Decisions D5, D21. + +**Files:** +- Modify: `press.ts` (`HandleRef` `{ kind: 'radius' }`; `dragAction` gives `drag_radius` when movable), + `usePressGesture.ts`, `useBlockDrag.ts` (radius preview) +- Modify: `HandleLayer.tsx` (a radius handle on the circle's edge, at angle 0, for a selected `detail_trigger` with a + circle geometry; points keep their size slider) +- Modify: `editor/annotations/usePointEdit.ts` (keys of the radius handle) +- Test: `apps/app/tests/unit/editor-point-edit.test.tsx` (new describe « radius handle ») + +Behaviour: + +- **The handle.** A `role="button"` named « Rayon de {nom} », with the coarse hit radius of 22 px. +- **Dragging** sets `r` to the distance from the centre, at least `MIN_FRAME_PX[kind] / 2` in units, with the circle + kept inside the view's frame (`circleInside`). Release commits through `updateGeometry`, the same path as the other + drags (one undo entry, core judgement, refusal message with the old place). +- **Keyboard.** ArrowRight or ArrowUp grows by `moveStep(frame)`, ArrowLeft or ArrowDown shrinks; Shift multiplies by + ten. Enter or blur commits the series: one commit path (LRN-134), the same as the point handle keys. + +| Key | fr | en | +|---|---|---| +| `editor.annotations.handle.radius` | Rayon de {name} | Radius of {name} | + +- [ ] **Step 1: Failing tests:** + - the radius handle renders only for a selected circle access; + - a drag commits a new radius; + - keys grow and shrink, with Shift multiplying by ten; + - a radius that takes the circle out of the frame is clamped; + - a too-small radius refused by the core shows the refusal and keeps the old circle. +- [ ] **Step 2: Implement.** Run `editor-point-edit.test.tsx` and `annotations.press.test.ts`, then `pnpm typecheck`. +- [ ] **Step 3: Commit.** Message: `feat(editor): radius handle for circle accesses`. + +### Task 16: What a selected access offers (arbitration A2) and its second click + +Board panels 05, 06. Decisions D14, D16. Arbitration A2. + +**Files:** +- Create: `apps/app/src/components/editor/annotations/AccessCommands.tsx` +- Modify: `SceneStrip.tsx` (`selected-detail_trigger` uses `AccessCommands`, unless a vertex is chosen, where the vertex + commands show as today) +- Modify: `usePressGesture.ts` / `EditableAnnotations.tsx` (`onOpen` for a `detail_trigger` opens its view instead of + the properties dialog, through Task 21's `openView`) +- Test: new `apps/app/tests/unit/editor-access-commands.test.tsx` + +Behaviour: + +1. **Commands** of a selected access (A2, recommended): + - « Ouvrir la vue » (primary), wired by Task 21; + - « Recadrer la vue » (Task 11, shown only when the opened view is a crop view); + - « Déplacer l'accès » (the existing move mode, A11: arrows, « Valider la position », « Annuler »); + - « Propriétés ». + - « Supprimer » stays in the properties dialog. If the owner picks panel 05 exactly, « Déplacer l'accès » is + replaced by « Supprimer » (the `DeleteDialog` path). +2. **Clicks.** A second click on the selected access, or a double click, opens the view (D14). On a point or a zone, it + still opens the properties dialog. +3. **Vertices.** A chosen vertex of a polygon access shows the vertex commands, as for a zone (« Déplacer le sommet », + « + », « − » on the drawing). + +| Key | fr | en | +|---|---|---| +| `editor.annotations.view.open` | Ouvrir la vue | Open the view | +| `editor.annotations.move.access` | Déplacer l'accès | Move the access | + +- [ ] **Step 1: Failing tests** for points 1 to 3. The selected head access, a polygon in Articulations, gets the same + commands. +- [ ] **Step 2: Implement.** Run the new test, `editor-zone-edit.test.tsx` and `editor-annotation-dialog.test.tsx`, then + `pnpm typecheck`. +- [ ] **Step 3: Commit.** Message: `feat(editor): selected access commands and opening on a second click`. + + +## Part 5 · Annotation priority on the three surfaces + +### Task 17: An annotation under the pointer wins over an access, everywhere (D11) + +Board panel 08. Decisions D11, D24. README « Conséquences » 3: the core layer is not reordered, and the page picks. +Review Focus 5. + +**Files:** +- Modify FIRST: `docs/ANNOTATION-RENDERING.md`, § hit handling (`:63-71`). New rule: on the editor, the catalogue and + the bilan, the page reads every element under the pointer (`elementsFromPoint`) and takes the first annotation that + is not an access; an access answers only where no other annotation lies. The paint order of the core is unchanged. + The access labels (Part 6) are page buttons over the drawing, outside the layer. +- Create: `apps/app/src/anatomy/annotationPick.ts` +- Modify: + - `apps/app/src/editor/annotations/press.ts`: `Hit` gains `access: boolean`; `pressTarget` prefers the first + non-access annotation hit; + - `usePressGesture.ts` (`hitOf` reads `data-anno-kind`); + - `apps/app/src/components/catalogue/CatalogueCanvas.tsx:126-140`: click through `pickAnnotation` at the click + point; + - `apps/app/src/catalogue/useEmptyTap.ts:73-77,116-117`: same pick at the press; + - `apps/app/src/components/canvas/AnatomyCanvas.tsx:30-33,93,128`: click and tooltip through `pickAnnotation`. +- Tests: + - new `apps/app/tests/unit/anatomy.annotationPick.test.ts`; + - `annotations.press.test.ts`; + - `components.AnatomyCanvas.test.tsx`; + - `routes.catalogue.test.tsx`. + +**Interfaces:** + +```ts +// apps/app/src/anatomy/annotationPick.ts +const ANNOTATED = '[data-anno-id]' + +/** D11 (owner 2026-11-22): among the elements under the pointer, top first, the first + * annotation that is not an access wins; an access answers only when no other annotation is + * there. `within` bounds the search to one canvas (the bilan shows two: the page and the + * detail window). */ +export function pickAnnotation(elements: readonly Element[], within: Element): Element | null { + let access: Element | null = null + for (const element of elements) { + const annotated = element.closest(ANNOTATED) + if (annotated === null || !within.contains(annotated)) continue + if (annotated.getAttribute('data-anno-kind') !== 'detail_trigger') return annotated + access ??= annotated + } + return access +} + +/** The same pick at a client point. */ +export function annotationAt(x: number, y: number, within: Element): Element | null { + return pickAnnotation(document.elementsFromPoint(x, y), within) +} +``` + +`press.ts`: + +```ts +// Hit's annotation arm gains the kind: + | { kind: 'annotation'; id: string; access: boolean } +// pressTarget, instead of the first annotation hit: + const annotations = hits.filter((hit) => hit.kind === 'annotation') + const chosen = annotations.find((hit) => !hit.access) ?? annotations[0] +``` + +- [ ] **Step 1: Failing tests.** + - `pickAnnotation`: built DOM fragments in happy-dom: + - a trigger over a point's hitbox returns the point; + - a trigger alone returns the trigger; + - an element outside `within` is skipped; + - a twin with no `data-anno-id` of its own resolves to its annotation. + - `pressTarget` with hits `[access a, annotation p]` gives `other p`. + - The catalogue: with `document.elementsFromPoint` stubbed to `[trigger, point ring]`, a click selects the point. + - The bilan: the same stub makes `onZoneClick` receive the point's id. The tooltip shows the point's name, not + nothing. +- [ ] **Step 2: Implement.** + - The catalogue and bilan handlers keep their current guards: `swallowClick` and the empty-tap verdicts. + - `useEmptyTap` uses `annotationAt(e.clientX, e.clientY, viewport)` at the press, so a press over a ring decides + « marker », as today. +- [ ] **Step 3: Run** the four test files, `editor-deselect.test.tsx` and `catalogue.useFraming.test.ts`, then + `pnpm typecheck`. +- [ ] **Step 4: Commit.** + - Files: the doc change and the code. + - Message: `feat(anatomy): annotations win over accesses under the pointer on every surface`. + +## Part 6 · Label placement and accessibility + +### Task 18: D25 placement (pure, the board's rule ported) + +Board panels 08, 15, 16, 17. Decisions D12, D25. Review Focus 4. The port below was run against the board's own +`placeTabsStrict` in the pinned Chromium on panel 15's inputs and reproduced it exactly. It also passed 2 000 random +layouts on the invariants of Step 1. + +**Files:** +- Create: `apps/app/src/anatomy/accessLabels.ts` +- Create: `apps/app/tests/fixtures/d25/panel-15.json` (content below) +- Create: `apps/app/tests/unit/anatomy.accessLabels.test.ts` + +**Interfaces:** +- Produces the exports used by Tasks 19 and 20: + - the types `Box`, `Disc`, `Segment`, `LabelRequest`, `LabelLayoutInput`, `PlacedLabel`, `LabelLayout`; + - the constants `LABEL_H` (20) and `LABEL_MAX_W` (180); + - the function `placeAccessLabels(input)`. + +`apps/app/tests/fixtures/d25/panel-15.json`. This is panel 15 of the validated board in CSS px of the 343 × 257 drawing. +The `w` values are the board's measured tab widths, and the points are discs of radius max(r, 11) + 4 px. + +```json +{ + "area": {"x": 0, "y": 0, "w": 343, "h": 257}, + "labels": [ + {"id": "Tête (vue latérale gauche)", "access": {"x": 33.852, "y": 23.659, "w": 45.741, "h": 50.157}, "w": 165.093}, + {"id": "Épaule", "access": {"x": 107.983, "y": 119.399, "w": 47.318, "h": 47.318}, "w": 58.904}, + {"id": "Coude", "access": {"x": 115.712, "y": 178.704, "w": 18.927, "h": 18.927}, "w": 57.248}, + {"id": "Genou antérieur", "access": {"x": 118.393, "y": 192.427, "w": 14.195, "h": 12.618}, "w": 113.997}, + {"id": "Boulet antérieur", "access": {"x": 109.718, "y": 193.058, "w": 28.391, "h": 43.533}, "w": 113.073} + ], + "obstacles": [ + {"cx": 248.203, "cy": 220.344, "r": 15}, + {"cx": 251.199, "cy": 182.805, "r": 15}, + {"cx": 238.897, "cy": 144.793, "r": 15}, + {"cx": 257.982, "cy": 96.529, "r": 15}, + {"cx": 236.688, "cy": 91.166, "r": 15}, + {"cx": 131.642, "cy": 143.058, "r": 15}, + {"cx": 125.183, "cy": 188.168, "r": 15}, + {"cx": 125.491, "cy": 197.474, "r": 15}, + {"cx": 124.072, "cy": 217.505, "r": 15}, + {"cx": 131.642, "cy": 216.243, "r": 15}, + {"cx": 232.588, "cy": 81.229, "r": 15}, + {"cx": 184.323, "cy": 83.28, "r": 15}, + {"cx": 144.418, "cy": 83.28, "r": 15} + ], + "expected": { + "placed": [ + {"id": "Tête (vue latérale gauche)", "box": {"x": 37.852, "y": 27.659, "w": 165.093, "h": 20}, "leader": null}, + {"id": "Boulet antérieur", "box": {"x": 109.718, "y": 108.058, "w": 113.073, "h": 20}, "leader": {"x1": 109.718, "y1": 128.058, "x2": 109.718, "y2": 193.058}} + ], + "overflow": ["Épaule", "Coude", "Genou antérieur"] + } +} +``` + +- [ ] **Step 1: Write the failing tests.** The cases give `area` {0,0,400,300} and button 110 × 28 unless stated. + - **Free:** access {100,100,60,40}, w 50 → box {100,77,50,20}, no leader. + - **Above right (the owner's case):** the same access plus a point disc {98,87,r 6} on the first place → box + {110,77,50,20}. + - **Below left:** access {100,10,60,40} (no room above) → box {100,53,50,20}. + - **Inside:** access {100,10,120,270}, w 50 → box {104,14,50,20}. + - **Slid:** + - access {100,100,160,40}, w 50; + - discs {102,87,6}, {255,87,6}, {100,152,6}, {258,152,6}, {110,112,6}; + - → box {108,77,50,20}, no leader. + - **Stacked:** + - access {200,200,40,30}, w 60; + - discs {210,185,12}, {235,185,12}, {210,245,12}, {230,214,6}; + - → box {200,153,60,20} with leader {200,173 → 200,200}. + - **No place:** the same access with one disc {210,185,r 200} → `placed` empty, `overflow` ['b'], `button` + {284,6,110,28}. + - **Cut by the edge (panel 17):** access {-20,-10,80,60}, w 90 → box {4,4,90,20} with leader {30,24 → 30,25}. + - **Off screen:** access {500,100,60,40} → neither placed nor in overflow. + - **Long name:** request w 260 → box width 180. + - **Panel 15:** the fixture's inputs, button 110 × 28 → `placed` equal to `expected.placed` within 0.002 px, + `overflow` equal, `button` {227,6,110,28}. + - **Property test,** 2 000 seeded random layouts: area 200 to 1 100 × 150 to 750, 1 to 8 accesses partly outside, 0 + to 15 discs. Each access is placed or in overflow exactly when it is at least partly visible, and every placed box: + - lies 4 px inside the area; + - overlaps no other box and no disc, nor the button when there is one; + - has no leader crossing another leader or another box. +- [ ] **Step 2: Run, expect failure.** +- [ ] **Step 3: Implement.** + +```ts +/** D25 (board `docs/design/v1-2-6-u2-detail-views`, revision 4, validated 2026-11-22): where + * each access label goes on a canvas, in CSS px of the canvas box. The board's + * `placeTabsStrict`, ported, plus the accesses cut by the visible edge (panel 17) and the room + * of « Autres vues (N) ». Pure: the page measures, this decides, the same way on the editor, + * the catalogue and the bilan. */ + +export interface Box { x: number; y: number; w: number; h: number } +/** A point marker to keep clear of (its disc and hit ring), or a handle. */ +export interface Disc { cx: number; cy: number; r: number } +export interface Segment { x1: number; y1: number; x2: number; y2: number } +export interface LabelRequest { + /** The access annotation id; requests come in the document order of the accesses. */ + id: string + /** The access shape's box on screen. */ + access: Box + /** The label's measured width, text and padding. */ + w: number +} +export interface LabelLayoutInput { + area: Box + labels: readonly LabelRequest[] + obstacles: readonly Disc[] + /** The measured size of the « Autres vues (N) » button. */ + button: { w: number; h: number } +} +export interface PlacedLabel { id: string; box: Box; leader: Segment | null } +export interface LabelLayout { + /** Document order. */ + placed: PlacedLabel[] + /** Ids of the accesses listed in « Autres vues (N) », document order. */ + overflow: string[] + /** Where « Autres vues (N) » goes; null when nothing overflows. */ + button: Box | null +} + +export const LABEL_H = 20 +export const LABEL_MAX_W = 180 +const MARGIN = 4 +const GAP = 3 +const INSET = 4 +const STEP = 2 +const BUTTON_INSET = 6 + +interface XY { x: number; y: number } +interface Wanted { id: string; a: Box; w: number; cut: boolean; order: number } +interface Item { id: string; box: Box; leader: Segment | null; order: number } +interface Room { area: Box; obstacles: readonly Disc[]; taken: Box[] } + +const overlaps = (a: Box, b: Box): boolean => + a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h +const clamp = (v: number, lo: number, hi: number): number => Math.min(Math.max(v, lo), Math.max(lo, hi)) +const centreOf = (a: Box): XY => ({ x: a.x + a.w / 2, y: a.y + a.h / 2 }) + +function hitsDisc(d: Disc, r: Box): boolean { + const dx = Math.max(r.x - d.cx, 0, d.cx - r.x - r.w) + const dy = Math.max(r.y - d.cy, 0, d.cy - r.y - r.h) + return dx * dx + dy * dy < d.r * d.r +} + +function visiblePart(access: Box, area: Box): Box | null { + const x = Math.max(access.x, area.x) + const y = Math.max(access.y, area.y) + const r = Math.min(access.x + access.w, area.x + area.w) + const b = Math.min(access.y + access.h, area.y + area.h) + return r > x && b > y ? { x, y, w: r - x, h: b - y } : null +} + +/** Whether the visible edge cuts the access (zoomed in, panned). */ +function isCut(access: Box, area: Box): boolean { + return access.x < area.x || access.y < area.y || + access.x + access.w > area.x + area.w || access.y + access.h > area.y + area.h +} + +function inside(r: Box, area: Box): boolean { + return r.x >= area.x + MARGIN && r.y >= area.y + MARGIN && + r.x + r.w <= area.x + area.w - MARGIN && r.y + r.h <= area.y + area.h - MARGIN +} + +function free(r: Box, room: Room): boolean { + return inside(r, room.area) && !room.taken.some((t) => overlaps(r, t)) && + !room.obstacles.some((d) => hitsDisc(d, r)) +} + +/** The five places in order: above top-left, above top-right, below bottom-left, below + * bottom-right, inside top-left. */ +function places(a: Box, w: number): Box[] { + const top = a.y - GAP - LABEL_H + const below = a.y + a.h + GAP + return [ + { x: a.x, y: top, w, h: LABEL_H }, + { x: a.x + a.w - w, y: top, w, h: LABEL_H }, + { x: a.x, y: below, w, h: LABEL_H }, + { x: a.x + a.w - w, y: below, w, h: LABEL_H }, + { x: a.x + INSET, y: a.y + INSET, w, h: LABEL_H }, + ] +} + +function fitInto(r: Box, area: Box): Box { + const x = clamp(r.x, area.x + MARGIN, area.x + area.w - MARGIN - r.w) + const y = clamp(r.y, area.y + MARGIN, area.y + area.h - MARGIN - r.h) + return { x, y, w: r.w, h: r.h } +} + +/** Along the access's top edge, left to right. */ +function slid(a: Box, w: number, room: Room): Box | null { + const y = a.y - GAP - LABEL_H + for (let x = a.x; x <= a.x + a.w - w; x += STEP) { + const r = { x, y, w, h: LABEL_H } + if (free(r, room)) return r + } + return null +} + +/** Higher and higher above the access's left edge. */ +function stacked(a: Box, w: number, room: Room): Box | null { + for (let y = a.y - GAP - LABEL_H - STEP; y > room.area.y; y -= STEP) { + const r = { x: a.x, y, w, h: LABEL_H } + if (free(r, room)) return r + } + return null +} + +/** A thin line from the label's nearest point to `anchor`; none when the anchor is under it. */ +function leaderTo(anchor: XY, r: Box): Segment | null { + const sx = clamp(anchor.x, r.x, r.x + r.w) + const sy = clamp(anchor.y, r.y, r.y + r.h) + return sx !== anchor.x || sy !== anchor.y ? { x1: sx, y1: sy, x2: anchor.x, y2: anchor.y } : null +} + +function cornerOf(a: Box, area: Box): XY { + return { + x: clamp(a.x, area.x + MARGIN, area.x + area.w - MARGIN), + y: clamp(a.y, area.y + MARGIN, area.y + area.h - MARGIN), + } +} + +function turn(p: XY, q: XY, r: XY): number { + return (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x) +} + +function segmentsCross(s: Segment, t: Segment): boolean { + const p = { x: s.x1, y: s.y1 } + const q = { x: s.x2, y: s.y2 } + const r = { x: t.x1, y: t.y1 } + const u = { x: t.x2, y: t.y2 } + return turn(p, q, r) * turn(p, q, u) < 0 && turn(r, u, p) * turn(r, u, q) < 0 +} + +function segmentHitsBox(s: Segment, b: Box): boolean { + const within = (x: number, y: number) => x > b.x && x < b.x + b.w && y > b.y && y < b.y + b.h + if (within(s.x1, s.y1) || within(s.x2, s.y2)) return true + const c = [{ x: b.x, y: b.y }, { x: b.x + b.w, y: b.y }, { x: b.x + b.w, y: b.y + b.h }, { x: b.x, y: b.y + b.h }] + return c.some((v, i) => segmentsCross(s, { x1: v.x, y1: v.y, x2: c[(i + 1) % 4].x, y2: c[(i + 1) % 4].y })) +} + +/** The visible accesses, document order; an access entirely outside the area gets no label. */ +function wantedOf(labels: readonly LabelRequest[], area: Box): Wanted[] { + const wanted: Wanted[] = [] + labels.forEach((label, order) => { + const seen = visiblePart(label.access, area) + if (seen === null) return + const cut = isCut(label.access, area) + wanted.push({ id: label.id, a: cut ? seen : label.access, w: Math.min(label.w, LABEL_MAX_W), cut, order }) + }) + return wanted +} + +/** The five places, then the slide; a cut access first tries its label held against the + * visible edge, with a leader to the visible part. */ +function firstPlace(it: Wanted, room: Room): Item | null { + const held = it.cut ? [fitInto(places(it.a, it.w)[0], room.area)] : [] + const box = [...held, ...places(it.a, it.w)].find((r) => free(r, room)) ?? slid(it.a, it.w, room) + if (box === null) return null + return { id: it.id, box, leader: it.cut ? leaderTo(centreOf(it.a), box) : null, order: it.order } +} + +/** A label whose leader crosses another leader or another label goes to the list. */ +function dropCrossings(items: Item[], overflow: Wanted[], wanted: readonly Wanted[]): void { + for (let bad = true; bad; ) { + bad = false + for (const it of items) { + const leader = it.leader + if (leader === null) continue + const crosses = items.some((o) => o !== it && + ((o.leader !== null && segmentsCross(leader, o.leader)) || segmentHitsBox(leader, o.box))) + if (!crosses) continue + items.splice(items.indexOf(it), 1) + overflow.push(wanted.find((w) => w.id === it.id) as Wanted) + bad = true + break + } + } +} + +function layout(input: LabelLayoutInput, reserved: Box | null): { placed: PlacedLabel[]; overflow: string[] } { + const room: Room = { area: input.area, obstacles: input.obstacles, taken: reserved ? [reserved] : [] } + const wanted = wantedOf(input.labels, input.area) + const items: Item[] = [] + const needy: Wanted[] = [] + for (const it of wanted) { + const item = firstPlace(it, room) + if (item === null) needy.push(it) + else { room.taken.push(item.box); items.push(item) } + } + const overflow: Wanted[] = [] + needy.sort((p, q) => p.a.x - q.a.x || p.order - q.order) + for (const it of needy) { + const box = stacked(it.a, it.w, room) + if (box === null) { overflow.push(it); continue } + room.taken.push(box) + items.push({ id: it.id, box, leader: leaderTo(cornerOf(it.a, input.area), box), order: it.order }) + } + dropCrossings(items, overflow, wanted) + items.sort((p, q) => p.order - q.order) + overflow.sort((p, q) => p.order - q.order) + return { placed: items.map(({ id, box, leader }) => ({ id, box, leader })), overflow: overflow.map((w) => w.id) } +} + +/** D25: every label placed or listed, never lost. When some must go to the list, the corner + * of « Autres vues (N) » is reserved and the placement runs once more around it. */ +export function placeAccessLabels(input: LabelLayoutInput): LabelLayout { + const first = layout(input, null) + if (first.overflow.length === 0) return { ...first, button: null } + const button = { + x: input.area.x + input.area.w - BUTTON_INSET - input.button.w, + y: input.area.y + BUTTON_INSET, + w: input.button.w, + h: input.button.h, + } + const second = layout(input, button) + return { ...second, button: second.overflow.length > 0 ? button : null } +} +``` + + `layout`, `firstPlace` and `dropCrossings` stay over 25 lines only where the board's loop is kept whole for + traceability. The reviewer checks they match the board line for line, not the length limit. +- [ ] **Step 4: Run, expect pass:** `pnpm --filter @faunosteo/app exec vitest run tests/unit/anatomy.accessLabels.test.ts`. +- [ ] **Step 5: Commit.** Message: `feat(anatomy): D25 access label placement with its « Autres vues » fallback`. + +### Task 19: The label buttons and « Autres vues (N) » + +Board panels 08, 15, 16, 17. Decisions D12, D21, D25. + +**Files:** +- Create: `apps/app/src/components/canvas/AccessLabels.tsx` +- Create: `apps/app/src/components/canvas/useAccessLabels.ts` +- Modify: `apps/app/src/i18n/fr.ts`, `en.ts` +- Test: new `apps/app/tests/unit/components.AccessLabels.test.tsx` + +**Interfaces:** + +```ts +export interface AccessLabelsProps { + /** The canvas box the labels sit in (the element `area` is measured from). */ + box: RefObject + /** The drawing host holding the core's layer. */ + drawing: RefObject + /** Recompute triggers: view, framing transform, selection (handles), locale. */ + layoutKey: string + hidden: boolean + onActivate: (accessId: string, opensViewId: string) => void +} +``` + +Behaviour: + +1. **`useAccessLabels`, after layout** (`useLayoutEffect`, and again on `layoutKey` changes, `ResizeObserver` on + `box`, and an rAF throttle). It measures, relative to `box`'s client rect: + - each `[data-anno-kind="detail_trigger"]` element's client rect, in document order (the layer keeps it); + - each point marker's disc: the hitbox circle's client rect centre, radius max(rect.w / 2, 11) + 4; + - each `[data-handle]`'s centre and hit radius; + - the label widths from a hidden measuring row of the same buttons; + - the « Autres vues » button's size. + It then calls `placeAccessLabels`. Nothing reaches the core (BDR-050). +2. **Each placed label** is a `