From 26097852ff37d4578f833f70e9feee08f03ee056 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 4 Nov 2026 13:49:41 +0100 Subject: [PATCH] feat(app): editor Annotations tab, core-decided placement, repair rules --- .../2026-11-03-v1-2-6-label-proposals.md | 82 ++ .../editor/annotations/AnnotationCanvas.tsx | 208 +++++ .../editor/annotations/AnnotationFields.tsx | 189 +++++ .../editor/annotations/AnnotationList.tsx | 71 ++ .../editor/annotations/AnnotationOverlay.tsx | 153 ++++ .../editor/annotations/CorrectionNotice.tsx | 44 ++ .../editor/annotations/CreationPanel.tsx | 342 ++++++++ .../annotations/EditableAnnotations.tsx | 254 ++++++ .../editor/annotations/GeometryGroup.tsx | 284 +++++++ .../editor/annotations/KeyboardAdd.tsx | 39 + .../editor/annotations/PropertiesPanel.tsx | 244 ++++++ .../editor/annotations/ReviewBadge.tsx | 18 + .../editor/annotations/SelectionTag.tsx | 25 + .../editor/annotations/ToolColumn.tsx | 130 +++ .../editor/annotations/TracingBar.tsx | 28 + .../editor/annotations/ViewSwitcher.tsx | 40 + .../components/editor/tabs/AnnotationsTab.tsx | 99 ++- .../editor/annotations/annotationCommit.ts | 103 +++ apps/app/src/editor/annotations/correction.ts | 68 ++ apps/app/src/editor/annotations/creation.ts | 155 ++++ apps/app/src/editor/annotations/frame.ts | 147 ++++ .../src/editor/annotations/geometryEdit.ts | 118 +++ apps/app/src/editor/annotations/gesture.ts | 59 ++ apps/app/src/editor/annotations/uiState.ts | 108 +++ .../src/editor/annotations/useCanvasBuild.ts | 72 ++ .../src/editor/annotations/useMoveGesture.ts | 107 +++ .../src/editor/annotations/usePlacement.ts | 109 +++ .../src/editor/annotations/useViewModel.ts | 54 ++ apps/app/src/i18n/en.ts | 75 ++ apps/app/src/i18n/fr.ts | 75 ++ apps/app/tests/helpers/annotationsCore.ts | 109 +++ .../unit/editor-annotations-commit.test.ts | 356 +++++++++ .../unit/editor-annotations-tab.test.tsx | 738 ++++++++++++++++++ apps/app/tests/unit/editor-frame.test.ts | 278 +++++++ .../tests/unit/editor-route-recovery.test.tsx | 4 +- apps/app/tests/unit/editor-route.test.tsx | 3 +- docs/ANNOTATION-RENDERING.md | 19 + 37 files changed, 5001 insertions(+), 6 deletions(-) create mode 100644 apps/app/src/components/editor/annotations/AnnotationCanvas.tsx create mode 100644 apps/app/src/components/editor/annotations/AnnotationFields.tsx create mode 100644 apps/app/src/components/editor/annotations/AnnotationList.tsx create mode 100644 apps/app/src/components/editor/annotations/AnnotationOverlay.tsx create mode 100644 apps/app/src/components/editor/annotations/CorrectionNotice.tsx create mode 100644 apps/app/src/components/editor/annotations/CreationPanel.tsx create mode 100644 apps/app/src/components/editor/annotations/EditableAnnotations.tsx create mode 100644 apps/app/src/components/editor/annotations/GeometryGroup.tsx create mode 100644 apps/app/src/components/editor/annotations/KeyboardAdd.tsx create mode 100644 apps/app/src/components/editor/annotations/PropertiesPanel.tsx create mode 100644 apps/app/src/components/editor/annotations/ReviewBadge.tsx create mode 100644 apps/app/src/components/editor/annotations/SelectionTag.tsx create mode 100644 apps/app/src/components/editor/annotations/ToolColumn.tsx create mode 100644 apps/app/src/components/editor/annotations/TracingBar.tsx create mode 100644 apps/app/src/components/editor/annotations/ViewSwitcher.tsx create mode 100644 apps/app/src/editor/annotations/annotationCommit.ts create mode 100644 apps/app/src/editor/annotations/correction.ts create mode 100644 apps/app/src/editor/annotations/creation.ts create mode 100644 apps/app/src/editor/annotations/frame.ts create mode 100644 apps/app/src/editor/annotations/geometryEdit.ts create mode 100644 apps/app/src/editor/annotations/gesture.ts create mode 100644 apps/app/src/editor/annotations/uiState.ts create mode 100644 apps/app/src/editor/annotations/useCanvasBuild.ts create mode 100644 apps/app/src/editor/annotations/useMoveGesture.ts create mode 100644 apps/app/src/editor/annotations/usePlacement.ts create mode 100644 apps/app/src/editor/annotations/useViewModel.ts create mode 100644 apps/app/tests/helpers/annotationsCore.ts create mode 100644 apps/app/tests/unit/editor-annotations-commit.test.ts create mode 100644 apps/app/tests/unit/editor-annotations-tab.test.tsx create mode 100644 apps/app/tests/unit/editor-frame.test.ts diff --git a/.claude/audits/2026-11-03-v1-2-6-label-proposals.md b/.claude/audits/2026-11-03-v1-2-6-label-proposals.md index d4959b4c..cdb03561 100644 --- a/.claude/audits/2026-11-03-v1-2-6-label-proposals.md +++ b/.claude/audits/2026-11-03-v1-2-6-label-proposals.md @@ -291,3 +291,85 @@ Removed: `editor.views.drawing.detail` (raw core detail no longer shown). | `editor.findings.mark_reviewed` | Marquer comme relu | Mark as reviewed | Selected element action | ratified REVUE | | `editor.findings.reset_to_confirm` | Remettre à confirmer | Reset to confirm | Selected element action | ratified REVUE | + +## Lot H (Annotations tab: canvas, tools, creation, properties, geometry group) + +Every key below is a proposal for the owner's separate review; none is declared approved. « plan wording FR » = quoted in the plan or ratified by the owner (FR verbatim, EN proposed). + +| Key | FR | EN | Where | Status | +|---|---|---|---|---| +| `editor.annotations.tools` | Outils | Tools | Tool column accessible name | proposal | +| `editor.annotations.tool.select` | Sélectionner et déplacer | Select and move | Tool button | plan wording FR; EN proposal | +| `editor.annotations.tool.point` | Point | Point | Tool button | plan wording FR; EN proposal | +| `editor.annotations.tool.zone` | Zone | Zone | Tool button | plan wording FR; EN proposal | +| `editor.annotations.tool.link` | Accès à une vue détaillée | Link to a detail view | Tool button | plan wording FR; EN proposal | +| `editor.annotations.undo` | Annuler | Undo | Tool column | plan wording FR; EN proposal | +| `editor.annotations.redo` | Rétablir | Redo | Tool column | plan wording FR; EN proposal | +| `editor.annotations.tool_hint.select` | Outil : sélectionner et déplacer · Échap annule un tracé | Tool: select and move · Esc cancels a tracing | Line above the canvas (board 04) | board 04 FR; EN proposal | +| `editor.annotations.tool_hint.point` | Outil : point · cliquez dans le dessin pour placer un point. | Tool: point · click in the drawing to place a point. | Line above the canvas | proposal | +| `editor.annotations.tool_hint.zone` | Outil : zone · cliquez pour poser les sommets ; Entrée ou « Fermer le tracé » termine, Échap annule. | Tool: zone · click to place the vertices; Enter or « Close the tracing » finishes, Esc cancels. | Line above the canvas | proposal | +| `editor.annotations.tool_hint.link` | Outil : accès à une vue détaillée · tracez le contour qui ouvre la vue ; Entrée termine, Échap annule. | Tool: link to a detail view · trace the outline that opens the view; Enter finishes, Esc cancels. | Line above the canvas | proposal | +| `editor.annotations.views` | Vues | Views | View chips group name | proposal | +| `editor.annotations.unmeasured.hint` | Ce dessin n'est pas mesurable : ajoutez ou corrigez son illustration (onglet Vues et illustrations) avant de placer ou de déplacer des éléments. | This drawing cannot be measured: add or fix its illustration (tab Views and illustrations) before placing or moving elements. | Unmeasured view (C32) | plan wording FR; EN proposal | +| `editor.annotations.outside` | Cliquez à l'intérieur du dessin. | Click inside the drawing. | Point click outside the frame | plan wording FR; EN proposal | +| `editor.annotations.correction` | Le point ne tient pas à l'endroit choisi. Position corrigée proposée : x = {x}, y = {y}. | The point does not fit where you clicked. Corrected position proposed: x = {x}, y = {y}. | Corrected-position confirmation (C26) | plan wording FR; EN proposal | +| `editor.annotations.correction_use` | Utiliser cette position | Use this position | Corrected-position confirmation | plan wording FR; EN proposal | +| `editor.annotations.correction_cancel` | Annuler | Cancel | Corrected-position confirmation | plan wording FR; EN proposal | +| `editor.annotations.no_category` | Créez d'abord une catégorie d'annotation (onglet Général). | Create an annotation category first (tab General). | Drawing tools disabled | plan wording FR; EN proposal | +| `editor.annotations.no_child_view` | Aucune vue détaillée ne s'ouvre depuis cette vue : créez-en une dans l'onglet Vues et illustrations. | No detail view opens from this view: create one in the Views and illustrations tab. | Link tool disabled | proposal | +| `editor.annotations.add.point` | Ajouter un point | Add a point | Keyboard creation button | plan wording FR; EN proposal | +| `editor.annotations.add.zone` | Ajouter une zone | Add a zone | Keyboard creation button | plan wording FR; EN proposal | +| `editor.annotations.add.detail_trigger` | Ajouter un accès | Add a link | Keyboard creation button | plan wording FR; EN proposal | +| `editor.annotations.new.point` | Nouveau point | New point | Creation panel title | plan wording FR; EN proposal | +| `editor.annotations.new.zone` | Nouvelle zone | New zone | Creation panel title | plan wording FR; EN proposal | +| `editor.annotations.new.detail_trigger` | Nouvel accès | New link | Creation panel title | plan wording FR; EN proposal | +| `editor.annotations.create` | Créer | Create | Creation panel button | plan wording FR; EN proposal | +| `editor.annotations.create_cancel` | Annuler | Cancel | Creation panel button | plan wording FR; EN proposal | +| `editor.annotations.name_fr` | Nom (FR) | Name (FR) | Field | plan wording FR; EN proposal | +| `editor.annotations.name_en` | Nom (EN) | Name (EN) | Field | plan wording FR; EN proposal | +| `editor.annotations.category` | Catégorie | Category | Field | plan wording FR; EN proposal | +| `editor.annotations.color` | Couleur | Colour | Field | plan wording FR; EN proposal | +| `editor.annotations.color_hint` | Laissez vide pour la couleur de la catégorie, ou indiquez une valeur hexadécimale (#rrggbb). | Leave empty for the category colour, or enter a hexadecimal value (#rrggbb). | Colour field hint | proposal | +| `editor.annotations.laterality` | Latéralité | Laterality | Field | plan wording FR; EN proposal | +| `editor.annotations.laterality.unpaired` | Non latéralisée | Unpaired | Laterality option | board 04 FR; EN proposal | +| `editor.annotations.laterality.bilateral` | Bilatérale | Bilateral | Laterality option | proposal | +| `editor.annotations.laterality.left` | Gauche | Left | Laterality option | proposal | +| `editor.annotations.laterality.right` | Droite | Right | Laterality option | proposal | +| `editor.annotations.region` | Région vertébrale | Vertebral region | Field | plan wording FR; EN proposal | +| `editor.annotations.zone` | Zone de constats | Findings zone | Field | plan wording FR; EN proposal | +| `editor.annotations.opens` | Vue ouverte | Opened view | Field (link) | plan wording FR; EN proposal | +| `editor.annotations.none` | Aucune | None | Optional select, empty option | proposal | +| `editor.annotations.required.fields` | Choisissez la catégorie et la latéralité (et la vue ouverte pour un accès). | Choose the category and the laterality (and the opened view for a link). | Creation refused before the core | proposal | +| `editor.annotations.required.names` | Renseignez le nom en français et en anglais. | Enter the name in French and in English. | Creation refused before the core (a link's name is both languages or none) | proposal | +| `editor.annotations.kind.point` | Point | Point | Annotation kind | proposal | +| `editor.annotations.kind.zone` | Zone | Zone | Annotation kind | proposal | +| `editor.annotations.kind.detail_trigger` | Accès | Link | Annotation kind | proposal | +| `editor.annotations.status.to_confirm` | À confirmer | To confirm | Review badge | plan wording FR; EN proposal | +| `editor.annotations.status.reviewed` | Relu | Reviewed | Review badge | plan wording FR; EN proposal | +| `editor.annotations.status.inherited` | Hérité, non relu | Inherited, not reviewed | Review badge | plan wording FR; EN proposal | +| `editor.annotations.mark_reviewed` | Marquer comme relu | Mark as reviewed | Properties action | plan wording FR; EN proposal | +| `editor.annotations.to_confirm` | Remettre à confirmer | Reset to confirm | Properties action | plan wording FR; EN proposal | +| `editor.annotations.list` | Annotations de la vue | Annotations of the view | List accessible name | proposal | +| `editor.annotations.list_empty` | Aucune annotation dans cette vue. | No annotation in this view. | Empty list | proposal | +| `editor.annotations.selection` | Sélection : {kind} « {name} » | Selection: {kind} « {name} » | Tag over the drawing (board 04) | plan wording FR; EN proposal | +| `editor.annotations.select_hint` | Sélectionnez une annotation sur le dessin ou dans la liste pour voir ses propriétés. | Select an annotation on the drawing or in the list to see its properties. | Empty properties panel | proposal | +| `editor.annotations.properties` | Propriétés de l'annotation | Annotation properties | Properties panel accessible name | proposal | +| `editor.annotations.tracing` | {count} sommet(s) posé(s). | {count} vertex(es) placed. | Tracing bar | proposal | +| `editor.annotations.trace_close` | Fermer le tracé | Close the tracing | Tracing bar | plan wording FR; EN proposal | +| `editor.annotations.trace_cancel` | Annuler le tracé | Cancel the tracing | Tracing bar | plan wording FR; EN proposal | +| `editor.annotations.replace_polygon` | Remplacer par un polygone | Replace with a polygon | Properties (path or missing geometry) | plan wording FR; EN proposal | +| `editor.annotations.no_geometry` | Cette annotation n'a pas de géométrie : tracez un polygone pour lui en donner une. | This annotation has no geometry: trace a polygon to give it one. | Properties, geometry missing | proposal | +| `editor.annotations.path` | Cette annotation est un tracé libre (path) : ses données ne se modifient pas ici. | This annotation is a free path: its data cannot be edited here. | Properties, path geometry | proposal | +| `editor.annotations.geometry.circle` | Position et rayon | Position and radius | Geometry group legend | proposal | +| `editor.annotations.geometry.polygon` | Sommets | Vertices | Geometry group legend | proposal | +| `editor.annotations.geometry.cx` | Centre x | Centre x | Field | proposal | +| `editor.annotations.geometry.cy` | Centre y | Centre y | Field | proposal | +| `editor.annotations.geometry.r` | Rayon | Radius | Field | proposal | +| `editor.annotations.geometry.vertex_x` | x du sommet {n} | x of vertex {n} | Field | proposal | +| `editor.annotations.geometry.vertex_y` | y du sommet {n} | y of vertex {n} | Field | proposal | +| `editor.annotations.geometry.vertices` | {count} sommets | {count} vertices | Polygon rows | proposal | +| `editor.annotations.geometry.add_vertex` | Ajouter un sommet | Add a vertex | Polygon rows | plan wording FR; EN proposal | +| `editor.annotations.geometry.unapplied` | Valeurs non appliquées : le brouillon est inchangé. | Values not applied: the draft is unchanged. | Geometry group after a refusal | proposal | +| `editor.annotations.geometry.unapplied_tag` | non appliqué | not applied | Marker on a field of an unapplied group | plan wording FR; EN proposal | +| `editor.annotations.geometry.revert` | Revenir aux valeurs enregistrées | Back to the saved values | Geometry group after a refusal | plan wording FR; EN proposal | +| `editor.annotations.geometry.number` | Chaque champ doit contenir un nombre. | Each field must hold a number. | Geometry group, input shape | proposal | diff --git a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx new file mode 100644 index 00000000..55430e55 --- /dev/null +++ b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx @@ -0,0 +1,208 @@ +import { useEffect, useRef, type PointerEvent } from 'react' +import type { Geometry } from '@faunosteo/core-wasm/types' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { coreFailureMessage } from '@/core/failure' +import { useCoreStopped } from '@/core/runtime' +import { transformOf } from '@/catalogue/framing' +import { useFraming } from '@/catalogue/useFraming' +import { clientToDrawing } from '@/editor/annotations/gesture' +import type { XY } from '@/editor/annotations/frame' +import { + annotationIdOf, + useCanvasBuild, + type RootAttributes, + useSelectionMark, +} from '@/editor/annotations/useCanvasBuild' +import { + useMoveGesture, + type MoveTarget, +} from '@/editor/annotations/useMoveGesture' +import type { ToolId } from '@/editor/annotations/uiState' +import { useT } from '@/i18n/useT' +import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay' +import ToolColumn, { type ToolColumnProps } from './ToolColumn' + +type OverlayData = Omit< + OverlayProps, + 'svgRef' | 'viewBox' | 'ratio' | 'dragged' +> + +export interface AnnotationCanvasProps { + viewId: string + viewName: string + tool: ToolId + selectedId: string | null + /** The selected annotation when it can be moved now. */ + moveTarget: MoveTarget | null + overlay: OverlayData + tools: Omit + /** The composed root's `viewBox` text, as rebuilt; null on failure. */ + onRoot: (viewBox: string | null) => void + onSelect: (id: string) => void + /** A click with a drawing tool, in drawing units. */ + onPlace: (at: XY) => void + onDrop: (id: string, geometry: Geometry) => void +} + +/** + * The edit canvas: the core's composed view, the numbers-only overlay above it in the + * same transformed box, the tool column beside it. Select and place work on `click` + * (a press that moved is a drag and swallows it); a drag from the selected marker moves + * it after 4 CSS px. `touch-action: none` only while a drawing tool or a drag is active. + */ +export default function AnnotationCanvas(props: AnnotationCanvasProps) { + const overlayRef = useRef(null) + const viewport = useRef(null) + const build = useCanvasBuild(props.viewId) + const move = useMoveGesture({ + overlay: overlayRef, + target: props.moveTarget, + onDrop: props.onDrop, + }) + const framing = useFraming(viewport, props.viewId, { + canPan: (event) => props.tool === 'select' && !move.claims(event), + }) + useSelectionMark(build.host, props.selectedId, build.root) + const { onRoot } = props + const viewBox = build.root?.viewBox ?? null + useReportRoot(viewBox, onRoot) + + const onClick = (event: React.MouseEvent) => { + if (framing.swallowClick()) return + const id = annotationIdOf(event.target) + if (props.tool === 'select') return id ? props.onSelect(id) : undefined + const at = clientToDrawing(overlayRef.current, { + x: event.clientX, + y: event.clientY, + }) + if (at) props.onPlace(at) + } + const handlers = composed(framing.handlers, move.handlers) + const touchNone = + props.tool !== 'select' || move.armed || framing.framing.scale !== 1 + return ( +
+ +
+
+ +
+ +
+
+ ) +} + +/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */ +function DrawingLayer({ + host, + root, + transform, + overlay, +}: { + host: React.RefObject + root: RootAttributes | null + transform: string + overlay: Omit +}) { + return ( +
+
+ {root?.viewBox && ( + + )} +
+ ) +} + +function useReportRoot( + viewBox: string | null, + onRoot: (v: string | null) => void, +) { + useEffect(() => onRoot(viewBox), [viewBox, onRoot]) +} + +/** Each pointer handler of the framing and of the move gesture, one after the other. */ +function composed( + a: ReturnType['handlers'], + b: ReturnType['handlers'], +) { + const both = + (first: (e: PointerEvent) => void, second: (e: PointerEvent) => void) => + (event: PointerEvent) => { + first(event) + second(event) + } + return { + onPointerDown: both(a.onPointerDown, b.onPointerDown), + onPointerMove: both(a.onPointerMove, b.onPointerMove), + onPointerUp: both(a.onPointerUp, b.onPointerUp), + onPointerCancel: both(a.onPointerCancel, b.onPointerCancel), + onLostPointerCapture: b.onLostPointerCapture, + onKeyDown: a.onKeyDown, + } +} + +function CanvasFailure({ + failure, + retry, +}: { + failure: 'engine' | 'view' | null + retry: () => void +}) { + const t = useT() + const stopped = useCoreStopped() + if (!failure) return null + return ( +
+
+ + {failure === 'view' + ? t('catalogue.failure.view') + : coreFailureMessage(t, 'sheet.core_unavailable')} + + {failure === 'engine' && !stopped && ( + + )} +
+
+ ) +} diff --git a/apps/app/src/components/editor/annotations/AnnotationFields.tsx b/apps/app/src/components/editor/annotations/AnnotationFields.tsx new file mode 100644 index 00000000..54305671 --- /dev/null +++ b/apps/app/src/components/editor/annotations/AnnotationFields.tsx @@ -0,0 +1,189 @@ +import type { + AnatomicalSheetDocument, + Annotation, + Laterality, +} from '@faunosteo/core-wasm/types' +import SelectField from '@/components/editor/fields/SelectField' +import TextField from '@/components/editor/fields/TextField' +import { LATERALITIES, directChildren } from '@/editor/annotations/creation' +import { isBlank, nullable } from '@/editor/sheetDocument' +import type { EditCommandApi } from '@/editor/useEditCommand' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' + +interface Props { + annotation: Annotation + doc: AnatomicalSheetDocument + readOnly: boolean + edit: EditCommandApi +} + +/** One `update` carrying the whole annotation with `patch` applied. */ +function useSend({ annotation, edit }: Props) { + return (field: string, patch: Record) => + edit.run(field, { + op: 'update', + key: { kind: 'annotation', id: annotation.id }, + element: { + kind: 'annotation', + value: { ...annotation, ...patch } as Annotation, + }, + }) +} + +const noneOption = (label: string) => ({ value: '', label }) + +/** Names: both or none for a link (its name is optional), both required otherwise. */ +function NameFields(props: Props) { + const t = useT() + const send = useSend(props) + const { annotation, edit, readOnly } = props + const isLink = annotation.kind === 'detail_trigger' + const rename = (locale: 'fr' | 'en') => (value: string) => { + const name = { + fr: annotation.name?.fr ?? '', + en: annotation.name?.en ?? '', + [locale]: value, + } + const blanks = [name.fr, name.en].filter(isBlank).length + if (isLink && blanks === 2) return send(locale, { name: null }) + if (blanks > 0) return edit.reject(locale, 'editor.field.required_names') + return send(locale, { name }) + } + return ( + <> + {(['fr', 'en'] as const).map((locale) => ( + + ))} + + ) +} + +export default function AnnotationFields(props: Props) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const send = useSend(props) + const { annotation, doc, readOnly, edit } = props + const categories = doc.categories.map((c) => ({ + value: c.id, + label: c.name[locale], + })) + const sides = LATERALITIES.map((l: Laterality) => ({ + value: l, + label: t(`editor.annotations.laterality.${l}`), + })) + return ( +
+ + send('category', { category_id: value })} + readOnly={readOnly} + error={edit.fieldError('category')} + /> + send('color', { color: nullable(value) })} + readOnly={readOnly} + hint={t('editor.annotations.color_hint')} + error={edit.fieldError('color')} + /> + send('laterality', { laterality: value })} + readOnly={readOnly} + error={edit.fieldError('laterality')} + /> + {annotation.kind === 'detail_trigger' ? ( + + ) : ( + + )} +
+ ) +} + +function OpensField({ annotation, doc, readOnly, edit }: Props) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const send = useSend({ annotation, doc, readOnly, edit }) + if (annotation.kind !== 'detail_trigger') return null + const options = directChildren(doc.views, annotation.view_id).map((v) => ({ + value: v.id, + label: v.name[locale], + })) + const current = doc.views.find((v) => v.id === annotation.opens_view_id) + if (current && !options.some((o) => o.value === current.id)) { + options.push({ value: current.id, label: current.name[locale] }) + } + return ( + send('opens', { opens_view_id: value })} + readOnly={readOnly} + error={edit.fieldError('opens')} + /> + ) +} + +function LinkFields(props: Props) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const send = useSend(props) + const { annotation, doc, readOnly, edit } = props + if (annotation.kind === 'detail_trigger') return null + const regions = [ + noneOption(t('editor.annotations.none')), + ...doc.vertebral_config.regions.map((r) => ({ + value: r.code, + label: r.name[locale], + })), + ] + const zones = [ + noneOption(t('editor.annotations.none')), + ...doc.finding_zones.map((z) => ({ value: z.id, label: z.name[locale] })), + ] + return ( + <> + + send('region', { vertebral_region_code: nullable(value) }) + } + readOnly={readOnly} + error={edit.fieldError('region')} + /> + send('zone', { finding_zone_id: nullable(value) })} + readOnly={readOnly} + error={edit.fieldError('zone')} + /> + + ) +} diff --git a/apps/app/src/components/editor/annotations/AnnotationList.tsx b/apps/app/src/components/editor/annotations/AnnotationList.tsx new file mode 100644 index 00000000..75a15021 --- /dev/null +++ b/apps/app/src/components/editor/annotations/AnnotationList.tsx @@ -0,0 +1,71 @@ +import type { Annotation, SheetView } from '@faunosteo/core-wasm/types' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' +import ReviewBadge from './ReviewBadge' + +/** The name an annotation shows: its own, else (an unnamed link) the view it opens. */ +export function annotationName( + annotation: Annotation, + views: readonly SheetView[], + locale: 'fr' | 'en', +): string { + if (annotation.name) return annotation.name[locale] + if (annotation.kind !== 'detail_trigger') return annotation.id + const opened = views.find((view) => view.id === annotation.opens_view_id) + return opened?.name[locale] ?? annotation.id +} + +/** + * The annotations of the view: name, kind, review badge; each row a button, reachable + * from the keyboard. Selection works in every mode, so a read-only draft is browsable. + */ +export default function AnnotationList({ + annotations, + views, + selectedId, + onSelect, +}: { + annotations: readonly Annotation[] + views: readonly SheetView[] + selectedId: string | null + onSelect: (id: string) => void +}) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + if (annotations.length === 0) { + return ( +

+ {t('editor.annotations.list_empty')} +

+ ) + } + return ( +
    + {annotations.map((annotation) => ( +
  • + +
  • + ))} +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx b/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx new file mode 100644 index 00000000..aefe2eab --- /dev/null +++ b/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx @@ -0,0 +1,153 @@ +import type { Ref } from 'react' +import type { Geometry, Point } from '@faunosteo/core-wasm/types' +import type { Correction } from '@/editor/annotations/correction' +import type { Frame } from '@/editor/annotations/frame' +import { isEditable } from '@/editor/annotations/geometryEdit' + +export interface OverlayProps { + svgRef: Ref + /** The composed root's own attributes: the overlay shares its coordinates. */ + viewBox: string + ratio: string + frame: Frame | null + selected: Geometry | null + dragged: Geometry | null + pending: Geometry | null + tracing: Point[] | null + correction: Correction | null +} + +const STROKE = { fill: 'none', vectorEffect: 'non-scaling-stroke' } as const + +function Outline({ + geometry, + dashed, + colour, +}: { + geometry: Geometry + dashed: boolean + colour: string +}) { + const style = { + ...STROKE, + stroke: colour, + strokeWidth: 2, + strokeDasharray: dashed ? '6 4' : undefined, + } + if (geometry.type === 'circle') { + return ( + + ) + } + if (geometry.type === 'polygon') { + return + } + return null +} + +function Vertices({ geometry, size }: { geometry: Geometry; size: number }) { + if (geometry.type !== 'polygon') return null + return ( + <> + {geometry.points.map(([x, y], index) => ( + + ))} + + ) +} + +/** The hollow cross of the position the user chose, drawn apart from the proposal. */ +function HollowCross({ + at, + size, +}: { + at: { x: number; y: number } + size: number +}) { + const style = { ...STROKE, stroke: 'var(--color-ink)', strokeWidth: 2 } + return ( + + + + + ) +} + +function TracingPath({ points, size }: { points: Point[]; size: number }) { + if (points.length === 0) return null + const shape: Geometry = { type: 'polygon', points } + return ( + <> + + + + ) +} + +/** + * The page-drawn overlay (docs/ANNOTATION-RENDERING.md « Editor overlay »): numbers only, + * no annotation. Selection outline, vertex circles, the tracing in progress, the pending + * or dragged outline, a corrected position with the click marked apart. It never takes + * the pointer: the canvas box does. + */ +export default function AnnotationOverlay(props: OverlayProps) { + const { frame, selected, dragged, pending, tracing, correction } = props + const size = frame ? Math.max(frame.w, frame.h) / 200 : 1 + const shown = dragged ?? selected + return ( + + ) +} diff --git a/apps/app/src/components/editor/annotations/CorrectionNotice.tsx b/apps/app/src/components/editor/annotations/CorrectionNotice.tsx new file mode 100644 index 00000000..4bb52cac --- /dev/null +++ b/apps/app/src/components/editor/annotations/CorrectionNotice.tsx @@ -0,0 +1,44 @@ +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import type { Correction } from '@/editor/annotations/correction' +import { useT } from '@/i18n/useT' + +/** + * The corrected position is never taken silently: the page says where the point would + * sit, the overlay shows it with the click marked apart, and only « Utiliser cette + * position » inserts it. + */ +export default function CorrectionNotice({ + correction, + onConfirm, + onCancel, +}: { + correction: Correction + onConfirm: () => void + onCancel: () => void +}) { + const t = useT() + const message = t('editor.annotations.correction') + .replace('{x}', String(correction.circle.cx)) + .replace('{y}', String(correction.circle.cy)) + return ( + +
+

{message}

+
+ + +
+
+
+ ) +} diff --git a/apps/app/src/components/editor/annotations/CreationPanel.tsx b/apps/app/src/components/editor/annotations/CreationPanel.tsx new file mode 100644 index 00000000..da3e4429 --- /dev/null +++ b/apps/app/src/components/editor/annotations/CreationPanel.tsx @@ -0,0 +1,342 @@ +import { useState, type Dispatch } from 'react' +import type { + AnatomicalSheetDocument, + Laterality, +} from '@faunosteo/core-wasm/types' +import DraftField from '@/components/editor/fields/DraftField' +import FormField from '@/components/ui/FormField' +import Button from '@/components/ui/Button' +import Select from '@/components/ui/Select' +import { + insertAnnotation, + type CommitContext, + type CommitResult, +} from '@/editor/annotations/annotationCommit' +import { + attemptPoint, + confirmCorrection, + type Correction, + type PointAttempt, +} from '@/editor/annotations/correction' +import { + LATERALITIES, + annotationOf, + directChildren, + emptyForm, + formProblem, + type CreationForm, + type PendingElement, +} from '@/editor/annotations/creation' +import type { Frame } from '@/editor/annotations/frame' +import type { EditableGeometry } from '@/editor/annotations/geometryEdit' +import type { UiAction } from '@/editor/annotations/uiState' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' +import CorrectionNotice from './CorrectionNotice' +import GeometryGroup from './GeometryGroup' + +export interface CreationPanelProps { + pending: PendingElement + viewId: string + doc: AnatomicalSheetDocument + /** F of the current view; null while it is not measured. */ + frame: Frame | null + dispatch: Dispatch + context: CommitContext +} + +type Attempt = PointAttempt | { status: 'invalid'; messages: string[] } + +/** The insert of this panel's element under a given geometry, through `accept`. */ +function inserterOf(props: CreationPanelProps, form: CreationForm) { + return (geometry: EditableGeometry): CommitResult => + insertAnnotation( + (id) => + annotationOf(id, props.viewId, { ...props.pending, geometry }, form), + props.context, + ) +} + +/** « Créer »: a point lets the core's verdict offer C; nothing else is ever invented. */ +function createAttempt( + props: CreationPanelProps, + form: CreationForm, + words: (problem: string) => string, +): Attempt { + const { pending, frame } = props + const problem = formProblem(pending.kind, form) + if (problem) return { status: 'invalid', messages: [words(problem)] } + const insert = inserterOf(props, form) + const { geometry } = pending + if (pending.kind === 'point' && geometry.type === 'circle' && frame) { + return attemptPoint(frame, geometry, (c) => + insert({ type: 'circle', ...c }), + ) + } + const result = insert(geometry) + return result.ok + ? { status: 'created', id: result.id } + : { status: 'refused', messages: result.messages } +} + +function confirmAttempt( + props: CreationPanelProps, + form: CreationForm, + correction: Correction, +): Attempt { + const insert = inserterOf(props, form) + return confirmCorrection(correction, (c) => insert({ type: 'circle', ...c })) +} + +/** + * « Nouveau point / Nouvelle zone / Nouvel accès »: the fields the core requires are + * collected first, then « Créer » inserts once through `accept` (no default labels). + * The geometry stays here, outside the document, until then. + */ +export default function CreationPanel(props: CreationPanelProps) { + const t = useT() + const { pending, doc, dispatch } = props + const [form, setForm] = useState(() => emptyForm(doc)) + const [messages, setMessages] = useState([]) + const update = (next: PendingElement) => + dispatch({ type: 'pending_update', pending: next }) + const settle = (attempt: Attempt) => { + setMessages( + attempt.status === 'refused' || attempt.status === 'invalid' + ? attempt.messages + : [], + ) + if (attempt.status === 'created') { + dispatch({ type: 'select', id: attempt.id ?? null }) + } + if (attempt.status === 'correction') { + update({ ...pending, correction: attempt.correction }) + } + } + const words = (problem: string) => t(`editor.annotations.required.${problem}`) + const setGeometry = (geometry: EditableGeometry) => { + update({ ...pending, geometry, correction: null }) + return { ok: true as const } + } + return ( +
+

+ {t(`editor.annotations.new.${pending.kind}`)} +

+ setForm({ ...form, ...patch })} + /> + + {pending.correction && ( + + settle(confirmAttempt(props, form, pending.correction!)) + } + onCancel={() => update({ ...pending, correction: null })} + /> + )} + +
+ + +
+
+ ) +} + +function Messages({ messages }: { messages: string[] }) { + if (messages.length === 0) return null + return ( +
+ {messages.map((message) => ( +

{message}

+ ))} +
+ ) +} + +interface FieldsProps { + doc: AnatomicalSheetDocument + form: CreationForm + onChange: (patch: Partial) => void +} + +interface Option { + value: string + label: string +} + +function OptionSelect({ + id, + label, + value, + options, + blank, + onChange, +}: { + id: string + label: string + value: string + options: Option[] + /** A « Choisir… » entry: the choice is required and has no default. */ + blank: boolean + onChange: (value: string) => void +}) { + const t = useT() + return ( + + + + ) +} + +/** The fields the core requires, collected before the insert. */ +function CreationFields({ + kind, + viewId, + ...fields +}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const { doc, form, onChange } = fields + const categories = doc.categories.map((c) => ({ + value: c.id, + label: c.name[locale], + })) + const sides = LATERALITIES.map((l: Laterality) => ({ + value: l, + label: t(`editor.annotations.laterality.${l}`), + })) + return ( +
+ onChange({ fr })} + /> + onChange({ en })} + /> + onChange({ categoryId })} + /> + + onChange({ laterality: laterality as CreationForm['laterality'] }) + } + /> + {kind === 'detail_trigger' ? ( + + ) : ( + + )} +
+ ) +} + +function OpensSelect({ + doc, + form, + onChange, + viewId, +}: FieldsProps & { viewId: string }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const options = directChildren(doc.views, viewId).map((v) => ({ + value: v.id, + label: v.name[locale], + })) + return ( + onChange({ opensViewId })} + /> + ) +} + +/** Findings zone and vertebral region: optional links of a point or a zone. */ +function LinkSelects({ doc, form, onChange }: FieldsProps) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const zones = doc.finding_zones.map((z) => ({ + value: z.id, + label: z.name[locale], + })) + const regions = doc.vertebral_config.regions.map((r) => ({ + value: r.code, + label: r.name[locale], + })) + return ( + <> + onChange({ zoneId })} + /> + onChange({ regionCode })} + /> + + ) +} diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx new file mode 100644 index 00000000..928a7a12 --- /dev/null +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -0,0 +1,254 @@ +import { useReducer, useState, type Dispatch } from 'react' +import type { + AnatomicalSheetDocument, + Annotation, +} from '@faunosteo/core-wasm/types' +import { type CommitContext } from '@/editor/annotations/annotationCommit' +import { keyboardPending, type NewKind } from '@/editor/annotations/creation' +import { parseFrame, type Frame } from '@/editor/annotations/frame' +import { isEditable } from '@/editor/annotations/geometryEdit' +import { usePlacement } from '@/editor/annotations/usePlacement' +import { + initialUi, + uiReducer, + type ToolId, + type UiAction, + type UiState, +} from '@/editor/annotations/uiState' +import { + mainViewId, + useUndoShortcuts, + useViewModel, + type ViewModel, +} from '@/editor/annotations/useViewModel' +import type { EditorTabProps } from '@/editor/tabs' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' +import AnnotationCanvas from './AnnotationCanvas' +import AnnotationList, { annotationName } from './AnnotationList' +import CreationPanel from './CreationPanel' +import KeyboardAdd from './KeyboardAdd' +import PropertiesPanel, { UnmeasuredHint } from './PropertiesPanel' +import SelectionTag from './SelectionTag' +import TracingBar from './TracingBar' +import ViewSwitcher from './ViewSwitcher' + +interface Props { + doc: AnatomicalSheetDocument + onSelectTab: EditorTabProps['onSelectTab'] +} + +export default function EditableAnnotations({ doc, onSelectTab }: Props) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const [ui, dispatch] = useReducer(uiReducer, initialUi) + const [viewBox, setViewBox] = useState(null) + const viewId = ui.viewId ?? mainViewId(doc) + const model = useViewModel(doc, viewId) + const frame = model.measured ? parseFrame(viewBox) : null + const context: CommitContext = { t, locale } + const placement = usePlacement({ ui, dispatch, frame, doc, context }) + useUndoShortcuts() + const selected = model.annotations.find((a) => a.id === ui.selectedId) + const scene = { doc, ui, dispatch, model, frame, selected, onSelectTab } + return ( +
+ + +
+ ) +} + +/** What both columns read: the document, the tab's state, the view and its frame. */ +interface Scene extends Props { + ui: UiState + dispatch: Dispatch + model: ViewModel + frame: Frame | null + selected: Annotation | undefined +} + +function CanvasColumn({ + placement, + onRoot, + ...scene +}: Scene & { + placement: ReturnType + onRoot: (viewBox: string | null) => void +}) { + const locale = useLocaleStore((s) => s.locale) + const { doc, ui, dispatch, model, frame, selected } = scene + const viewId = ui.viewId ?? mainViewId(doc) + const view = doc.views.find((v) => v.id === viewId) + const noCategory = doc.categories.length === 0 + const blocked = !model.measured || noCategory + const select = (id: string) => dispatch({ type: 'select', id }) + if (!view) return null + return ( +
+ dispatch({ type: 'view', viewId: id })} + /> + + {selected && ( + + )} + dispatch({ type: 'tool', tool }), + drawingDisabled: blocked, + linkDisabled: model.children.length === 0, + }} + onRoot={onRoot} + onSelect={select} + onPlace={placement.onPlace} + onDrop={placement.onDrop} + /> + {ui.tracing && ( + dispatch({ type: 'trace_cancel' })} + /> + )} + addAtCentre(kind, frame, dispatch)} + /> + +
+ ) +} + +function addAtCentre( + kind: NewKind, + frame: Frame | null, + dispatch: Dispatch, +) { + if (!frame) return + dispatch({ type: 'pending_new', pending: keyboardPending(kind, frame) }) +} + +/** The creation panel while an element is pending, else the selection's properties. */ +function SidePanel({ + viewId, + context, + ...scene +}: Scene & { viewId: string; context: CommitContext }) { + const t = useT() + const { doc, ui, dispatch, model, frame, selected } = scene + if (ui.pending) { + return ( + + ) + } + if (!selected) { + return ( +

+ {t('editor.annotations.select_hint')} +

+ ) + } + return ( + + ) +} + +function moveTargetOf( + selected: Annotation | undefined, + model: ViewModel, + tool: ToolId, +) { + if (!selected || !model.measured || tool !== 'select') return null + return isEditable(selected.geometry) + ? { id: selected.id, geometry: selected.geometry } + : null +} + +function overlayOf( + ui: UiState, + selected: Annotation | undefined, + frame: Frame | null, +) { + return { + frame, + selected: selected?.geometry ?? null, + pending: ui.pending?.geometry ?? null, + tracing: ui.tracing?.points ?? null, + correction: ui.pending?.correction ?? null, + } +} + +/** The tool line and the reasons a tool cannot be used now. */ +function ToolNotes({ + tool, + hint, + model, + noCategory, + onSelectTab, +}: { + tool: ToolId + hint: string | null + model: ViewModel + noCategory: boolean + onSelectTab: EditorTabProps['onSelectTab'] +}) { + const t = useT() + const linkBlocked = tool === 'link' && model.children.length === 0 + return ( +
+

{t(`editor.annotations.tool_hint.${tool}`)}

+ {!model.measured && } + {noCategory &&

{t('editor.annotations.no_category')}

} + {linkBlocked &&

{t('editor.annotations.no_child_view')}

} + {hint && ( +

+ {hint} +

+ )} +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/GeometryGroup.tsx b/apps/app/src/components/editor/annotations/GeometryGroup.tsx new file mode 100644 index 00000000..a9e4afed --- /dev/null +++ b/apps/app/src/components/editor/annotations/GeometryGroup.tsx @@ -0,0 +1,284 @@ +import { useState } from 'react' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Button from '@/components/ui/Button' +import Input from '@/components/ui/Input' +import { + changedFieldNames, + fieldsOf, + parseFields, + sameAsStored, + withVertexAfter, + withoutVertex, + type EditableGeometry, + type GroupFields, +} from '@/editor/annotations/geometryEdit' +import { useT } from '@/i18n/useT' + +/** What applying the group answers: kept, or the words that say why not. */ +export type ApplyResult = { ok: true } | { ok: false; messages: string[] } + +export interface GeometryGroupProps { + idPrefix: string + /** The stored (or pending) geometry the fields start from. */ + geometry: EditableGeometry + /** Proposes the WHOLE group; the core's verdict comes back as the result. */ + onApply: (geometry: EditableGeometry) => ApplyResult + /** Fields shown as text: read-only mode or an unmeasured view. */ + locked: boolean +} + +type Fields = GroupFields +type PolygonFields = Extract + +/** + * The geometry fields as ONE group held in component state (plan « Repair through a + * temporary form »): Enter or leaving a field proposes the whole group as one update; + * a refusal keeps the typed values marked « non appliqué » with the core's message and + * the document unchanged. Selecting another element unmounts it: an unapplied group was + * never in the document and is dropped (no commit on unmount). + */ +export default function GeometryGroup(props: GeometryGroupProps) { + const stored = fieldsOf(props.geometry) + const storedKey = JSON.stringify(stored) + const [draft, setDraft] = useState(stored) + const [seen, setSeen] = useState(storedKey) + const [messages, setMessages] = useState([]) + // A new stored value (undo, restore, an accepted move) replaces what was typed. + if (seen !== storedKey) { + setSeen(storedKey) + setDraft(stored) + setMessages([]) + } + const apply = (next: Fields) => { + setDraft(next) + if (sameAsStored(next, props.geometry)) return setMessages([]) + const parsed = parseFields(next) + if (!parsed.ok) return setMessages(['number']) + const result = props.onApply(parsed.geometry) + setMessages(result.ok ? [] : result.messages) + } + const revert = () => { + setDraft(stored) + setMessages([]) + } + const pending = changedFieldNames(draft, props.geometry) + const view = { ...props, draft, pending, messages } + return ( + + ) +} + +interface BodyProps extends Omit { + draft: Fields + pending: Set + messages: string[] + onChange: (fields: Fields) => void + onPropose: (fields: Fields) => void + onRevert: () => void +} + +function GroupBody(props: BodyProps) { + const t = useT() + const { draft, pending, messages } = props + const unapplied = pending.size > 0 && messages.length > 0 + return ( +
+ + {t( + draft.type === 'circle' + ? 'editor.annotations.geometry.circle' + : 'editor.annotations.geometry.polygon', + )} + + {draft.type === 'circle' ? ( + + ) : ( + + )} + {unapplied && } +
+ ) +} + +function Unapplied({ messages, onRevert }: BodyProps) { + const t = useT() + const words = messages.map((m) => + m === 'number' ? t('editor.annotations.geometry.number') : m, + ) + return ( +
+

+ {t('editor.annotations.geometry.unapplied')} +

+ {words.map((word) => ( +

+ {word} +

+ ))} + +
+ ) +} + +function NumberInput({ + id, + label, + value, + unapplied, + locked, + onType, + onApply, +}: { + id: string + label: string + value: string + unapplied: boolean + locked: boolean + onType: (value: string) => void + onApply: () => void +}) { + const t = useT() + if (locked) { + return ( +

+ {label} {value} +

+ ) + } + const hint = unapplied + ? t('editor.annotations.geometry.unapplied_tag') + : undefined + return ( + + onType(e.target.value)} + onBlur={onApply} + onKeyDown={(e) => { + if (e.key === 'Enter' && !e.nativeEvent.isComposing) onApply() + }} + /> + + ) +} + +type RowsProps = BodyProps & { fields: F } + +function CircleRows(props: RowsProps>) { + const t = useT() + const { fields, pending, locked, idPrefix } = props + return ( +
+ {(['cx', 'cy', 'r'] as const).map((key) => ( + props.onChange({ ...fields, [key]: value })} + onApply={() => props.onPropose(fields)} + /> + ))} +
+ ) +} + +function PolygonRows(props: RowsProps) { + const t = useT() + const [selected, setSelected] = useState(0) + const { fields, locked } = props + const change = (index: number, axis: 'x' | 'y', value: string) => + props.onChange({ + type: 'polygon', + rows: fields.rows.map((row, i) => + i === index ? { ...row, [axis]: value } : row, + ), + }) + return ( +
+

+ {t('editor.annotations.geometry.vertices').replace( + '{count}', + String(fields.rows.length), + )} +

+ {fields.rows.map((row, index) => ( +
setSelected(index)} + > + {index + 1} + {(['x', 'y'] as const).map((axis) => ( + change(index, axis, value)} + onApply={() => props.onPropose(fields)} + /> + ))} +
+ ))} + {!locked && ( + + )} +
+ ) +} + +function VertexButtons({ + fields, + selected, + onApply, +}: { + fields: PolygonFields + selected: number + onApply: (fields: Fields) => void +}) { + const t = useT() + return ( +
+ + +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/KeyboardAdd.tsx b/apps/app/src/components/editor/annotations/KeyboardAdd.tsx new file mode 100644 index 00000000..2e40f8d0 --- /dev/null +++ b/apps/app/src/components/editor/annotations/KeyboardAdd.tsx @@ -0,0 +1,39 @@ +import Button from '@/components/ui/Button' +import type { NewKind } from '@/editor/annotations/creation' +import { useT } from '@/i18n/useT' + +const KINDS: readonly NewKind[] = ['point', 'zone', 'detail_trigger'] + +/** + * The keyboard creation path (C7): each button holds a pending element at the centre of + * the frame and opens the creation panel; every coordinate is then typed in the fields. + */ +export default function KeyboardAdd({ + disabled, + linkDisabled, + onAdd, +}: { + /** No measured frame, or no category: nothing can be placed. */ + disabled: boolean + /** No detail view directly under this view: no link can be placed. */ + linkDisabled: boolean + onAdd: (kind: NewKind) => void +}) { + const t = useT() + return ( +
+ {KINDS.map((kind) => ( + + ))} +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/PropertiesPanel.tsx b/apps/app/src/components/editor/annotations/PropertiesPanel.tsx new file mode 100644 index 00000000..929f0057 --- /dev/null +++ b/apps/app/src/components/editor/annotations/PropertiesPanel.tsx @@ -0,0 +1,244 @@ +import { useState, type Dispatch } from 'react' +import type { + AnatomicalSheetDocument, + Annotation, + Geometry, + Marking, +} from '@faunosteo/core-wasm/types' +import ActionButton from '@/components/editor/fields/ActionButton' +import DeleteDialog from '@/components/editor/DeleteDialog' +import Button from '@/components/ui/Button' +import { + updateGeometry, + type CommitContext, +} from '@/editor/annotations/annotationCommit' +import { isEditable } from '@/editor/annotations/geometryEdit' +import type { UiAction } from '@/editor/annotations/uiState' +import { geometryErrorsById } from '@/editor/issues' +import type { EditorTabId } from '@/editor/tabs' +import { useEditCommand } from '@/editor/useEditCommand' +import { useEditorStore } from '@/editor/state/editorStore' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' +import AnnotationFields from './AnnotationFields' +import type { ApplyResult } from './GeometryGroup' +import { annotationName } from './AnnotationList' +import GeometryGroup from './GeometryGroup' +import ReviewBadge from './ReviewBadge' + +export interface PropertiesPanelProps { + annotation: Annotation + doc: AnatomicalSheetDocument + /** Not editable now: every field shows as text and no action is offered. */ + readOnly: boolean + /** The view is not measured: geometry is shown as text only, the rest stays editable. */ + geometryLocked: boolean + dispatch: Dispatch + context: CommitContext + onSelectTab: (tab: EditorTabId) => void +} + +/** What still names this annotation as invalid: never hidden, never shown as valid. */ +function useGeometryIssues(id: string): string[] { + const state = useEditorStore((s) => s.previewState) + const issues = state ? geometryErrorsById(state).get(id) : undefined + return [...new Set((issues ?? []).map((issue) => issue.message))] +} + +export default function PropertiesPanel(props: PropertiesPanelProps) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const { annotation, doc, readOnly } = props + const edit = useEditCommand() + const name = annotationName(annotation, doc.views, locale) + return ( +
+
+

+ {t(`editor.annotations.kind.${annotation.kind}`)} +

+ +
+ + + + +
+ ) +} + +function GeometrySection(props: PropertiesPanelProps) { + const t = useT() + const { annotation, readOnly, geometryLocked } = props + const locked = readOnly || geometryLocked + const { geometry } = annotation + return ( +
+ {geometryLocked && !readOnly && } + {isEditable(geometry) ? ( + applyGeometry(annotation, next, props.context)} + /> + ) : ( +

+ {t( + geometry === null + ? 'editor.annotations.no_geometry' + : 'editor.annotations.path', + )} +

+ )} + {!locked && !isEditable(geometry) && ( + + )} + +
+ ) +} + +function applyGeometry( + annotation: Annotation, + next: Geometry, + context: CommitContext, +): ApplyResult { + const result = updateGeometry(annotation, next, context) + return result.ok ? { ok: true } : { ok: false, messages: result.messages } +} + +function TraceReplacement({ + id, + dispatch, +}: { + id: string + dispatch: Dispatch +}) { + const t = useT() + return ( + + ) +} + +function GeometryIssues({ id }: { id: string }) { + const issues = useGeometryIssues(id) + if (issues.length === 0) return null + return ( +
    + {issues.map((issue) => ( +
  • {issue}
  • + ))} +
+ ) +} + +export function UnmeasuredHint({ + onSelectTab, +}: Pick) { + const t = useT() + return ( +

+ {t('editor.annotations.unmeasured.hint')}{' '} + +

+ ) +} + +function StatusActions({ + annotation, + readOnly, + edit, +}: { + annotation: Annotation + readOnly: boolean + edit: ReturnType +}) { + const t = useT() + const mark = (status: Marking) => + edit.run('status', { + op: 'set_status', + key: { kind: 'annotation', id: annotation.id }, + status, + }) + const reviewed = annotation.review_status === 'reviewed' + return ( +
+ mark(reviewed ? 'to_confirm' : 'reviewed')} + > + {t( + reviewed + ? 'editor.annotations.to_confirm' + : 'editor.annotations.mark_reviewed', + )} + + {edit.fieldError('status') && ( +

+ {edit.fieldError('status')} +

+ )} +
+ ) +} + +function Deletion({ + id, + name, + readOnly, +}: { + id: string + name: string + readOnly: boolean +}) { + const t = useT() + const [open, setOpen] = useState(false) + return ( + <> + setOpen(true)} + > + {t('editor.action.delete')} + + setOpen(false)} + /> + + ) +} diff --git a/apps/app/src/components/editor/annotations/ReviewBadge.tsx b/apps/app/src/components/editor/annotations/ReviewBadge.tsx new file mode 100644 index 00000000..bf9e1504 --- /dev/null +++ b/apps/app/src/components/editor/annotations/ReviewBadge.tsx @@ -0,0 +1,18 @@ +import type { ReviewStatus } from '@faunosteo/core-wasm/types' +import Badge from '@/components/ui/Badge' +import { useT } from '@/i18n/useT' + +const TONES = { + to_confirm: 'warn', + reviewed: 'accent', + inherited: 'neutral', +} as const + +export default function ReviewBadge({ status }: { status: ReviewStatus }) { + const t = useT() + return ( + + {t(`editor.annotations.status.${status}`)} + + ) +} diff --git a/apps/app/src/components/editor/annotations/SelectionTag.tsx b/apps/app/src/components/editor/annotations/SelectionTag.tsx new file mode 100644 index 00000000..8882b0fe --- /dev/null +++ b/apps/app/src/components/editor/annotations/SelectionTag.tsx @@ -0,0 +1,25 @@ +import { useT } from '@/i18n/useT' + +/** Board 04's tag over the drawing: « Sélection : « ». */ +export default function SelectionTag({ + kind, + name, +}: { + kind: string + name: string +}) { + const t = useT() + return ( +

+ {t('editor.annotations.selection') + .replace( + '{kind}', + t(`editor.annotations.kind.${kind}`).toLocaleLowerCase(), + ) + .replace('{name}', name)} +

+ ) +} diff --git a/apps/app/src/components/editor/annotations/ToolColumn.tsx b/apps/app/src/components/editor/annotations/ToolColumn.tsx new file mode 100644 index 00000000..b6b2145d --- /dev/null +++ b/apps/app/src/components/editor/annotations/ToolColumn.tsx @@ -0,0 +1,130 @@ +import type { ReactNode } from 'react' +import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore' +import type { ToolId } from '@/editor/annotations/uiState' +import { useT } from '@/i18n/useT' + +export interface ToolColumnProps { + tool: ToolId + onTool: (tool: ToolId) => void + /** Point, zone and link need a measured view and a category. */ + drawingDisabled: boolean + /** The link tool needs a detail view directly under the current one. */ + linkDisabled: boolean + onZoomIn: () => void + onZoomOut: () => void + onFit: () => void +} + +const GLYPHS: Record = { + select: 'M5 3l12 7-5 1-3 5z', + point: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 3v3M12 18v3M3 12h3M18 12h3', + zone: 'M12 3l8 6-3 10H7L4 9z', + link: 'M4 4h8v8H4zM12 12h8v8h-8z', + in: 'M11 5v12M5 11h12M20 20l-4-4', + out: 'M5 11h12M20 20l-4-4', + fit: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', + undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10', + redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10', +} + +function ToolButton({ + glyph, + label, + pressed, + disabled, + onClick, +}: { + glyph: string + label: string + pressed?: boolean + disabled?: boolean + onClick: () => void +}): ReactNode { + return ( + + ) +} + +/** Board 04's tool column: tools, zoom, then undo and redo (icon buttons). */ +export default function ToolColumn(props: ToolColumnProps) { + const t = useT() + const undoable = useEditorStore(canUndo) + const redoable = useEditorStore(canRedo) + const tool = (id: ToolId, disabled: boolean) => ( + props.onTool(id)} + /> + ) + return ( +
+ {tool('select', false)} + {tool('point', props.drawingDisabled)} + {tool('zone', props.drawingDisabled)} + {tool('link', props.drawingDisabled || props.linkDisabled)} +
+ + + +
+ useEditorStore.getState().undoStep()} + /> + useEditorStore.getState().redoStep()} + /> +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/TracingBar.tsx b/apps/app/src/components/editor/annotations/TracingBar.tsx new file mode 100644 index 00000000..e9513143 --- /dev/null +++ b/apps/app/src/components/editor/annotations/TracingBar.tsx @@ -0,0 +1,28 @@ +import Button from '@/components/ui/Button' +import { useT } from '@/i18n/useT' + +/** While a zone or link is being traced: close (3 vertices at least) or drop it. */ +export default function TracingBar({ + count, + onClose, + onCancel, +}: { + count: number + onClose: () => void + onCancel: () => void +}) { + const t = useT() + return ( +
+

+ {t('editor.annotations.tracing').replace('{count}', String(count))} +

+ + +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/ViewSwitcher.tsx b/apps/app/src/components/editor/annotations/ViewSwitcher.tsx new file mode 100644 index 00000000..7919932e --- /dev/null +++ b/apps/app/src/components/editor/annotations/ViewSwitcher.tsx @@ -0,0 +1,40 @@ +import type { SheetView } from '@faunosteo/core-wasm/types' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' + +/** One chip per view (board 04): the main view, then each detail view. */ +export default function ViewSwitcher({ + views, + current, + onSelect, +}: { + views: readonly SheetView[] + current: string + onSelect: (viewId: string) => void +}) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + return ( +
+ {views.map((view) => ( + + ))} +
+ ) +} diff --git a/apps/app/src/components/editor/tabs/AnnotationsTab.tsx b/apps/app/src/components/editor/tabs/AnnotationsTab.tsx index c166c455..c19a4a77 100644 --- a/apps/app/src/components/editor/tabs/AnnotationsTab.tsx +++ b/apps/app/src/components/editor/tabs/AnnotationsTab.tsx @@ -1,14 +1,105 @@ +import { useState } from 'react' +import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' +import CatalogueCanvas from '@/components/catalogue/CatalogueCanvas' +import AnnotationList, { + annotationName, +} from '@/components/editor/annotations/AnnotationList' +import EditableAnnotations from '@/components/editor/annotations/EditableAnnotations' +import PropertiesPanel from '@/components/editor/annotations/PropertiesPanel' +import ViewSwitcher from '@/components/editor/annotations/ViewSwitcher' +import SelectionTag from '@/components/editor/annotations/SelectionTag' +import { mainViewId, useViewModel } from '@/editor/annotations/useViewModel' +import { useSheetDocument } from '@/editor/sheetDocument' +import { useEditorStore } from '@/editor/state/editorStore' import type { EditorTabProps } from '@/editor/tabs' import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' -/** Placeholder: Lot H replaces the body and keeps the props contract (`EditorTabProps`). */ -export default function AnnotationsTab(_props: EditorTabProps) { +/** + * Annotations: the canvas with its tools, the list of the view, the creation and + * properties panels. Read-only, the same view is browsable (canvas, list, properties as + * text) with no tool and no action. + */ +export default function AnnotationsTab(props: EditorTabProps) { const t = useT() + const doc = useSheetDocument() + const preview = useEditorStore((s) => s.preview) return (
+ className="min-h-24 space-y-3" + > + {doc && preview && props.readOnly && ( + + )} + {doc && preview && !props.readOnly && ( + + )} +
+ ) +} + +function ReadOnlyAnnotations({ + doc, + onSelectTab, +}: { + doc: AnatomicalSheetDocument + onSelectTab: EditorTabProps['onSelectTab'] +}) { + const locale = useLocaleStore((s) => s.locale) + const preview = useEditorStore((s) => s.preview) + const handleVersion = useEditorStore((s) => s.handleVersion) + const [viewId, setViewId] = useState(mainViewId(doc)) + const [selectedId, setSelectedId] = useState(null) + const model = useViewModel(doc, viewId) + const view = doc.views.find((v) => v.id === viewId) + const selected = model.annotations.find((a) => a.id === selectedId) + if (!preview || !view) return null + return ( +
+
+ { + setViewId(id) + setSelectedId(null) + }} + /> + {selected && ( + + )} + + +
+ {selected && ( + undefined} + context={{ t: (key) => key, locale }} + onSelectTab={onSelectTab} + /> + )} +
) } diff --git a/apps/app/src/editor/annotations/annotationCommit.ts b/apps/app/src/editor/annotations/annotationCommit.ts new file mode 100644 index 00000000..f79d739f --- /dev/null +++ b/apps/app/src/editor/annotations/annotationCommit.ts @@ -0,0 +1,103 @@ +import type { + Annotation, + EditCommand, + Geometry, +} from '@faunosteo/core-wasm/types' +import type { Locale } from '@/i18n/types' +import { frameRefusalMessage } from '../frameRefusal' +import { newElementId } from '../ids' +import { geometryAccept, type GeometryRefusal } from '../issues' +import { refusalMessage } from '../refusal' +import { useEditorStore } from '../state/editorStore' +import type { CommitOutcome } from '../state/editorTypes' + +type Translate = (key: string) => string + +/** What a geometry commit answers: kept, or the words and the core's codes at fault. */ +export type CommitResult = + | { ok: true; id?: string } + | { ok: false; messages: string[]; codes: string[]; duplicate?: boolean } + +export interface CommitContext { + t: Translate + locale: Locale +} + +function describe( + outcome: Exclude, { ok: true }>, + { t, locale }: CommitContext, +): CommitResult { + if (outcome.reason !== 'refused') { + const duplicate = + outcome.reason === 'core' && outcome.failure.kind === 'duplicate_key' + return { + ok: false, + messages: [refusalMessage(t, outcome)], + codes: [], + duplicate, + } + } + const { refusal } = outcome + const doc = useEditorStore.getState().previewState?.document ?? null + if (refusal.reason === 'changed_invalid') { + const messages = [...new Set(refusal.issues.map((i) => i.message))] + return { ok: false, messages, codes: refusal.issues.map((i) => i.code) } + } + const message = + refusal.reason === 'newly_invalid' + ? frameRefusalMessage(t, refusal, doc, locale) + : t('editor.annotations.unmeasured.hint') + return { ok: false, messages: [message], codes: [] } +} + +/** One command through the store with the geometry `accept` of the changed annotation. */ +function commitGeometry( + command: EditCommand, + annotationId: string, + context: CommitContext, +): CommitResult { + const store = useEditorStore.getState() + const before = store.previewState + if (before === null) { + return { + ok: false, + messages: [context.t('editor.refusal.blocked')], + codes: [], + } + } + const accept = geometryAccept({ before, changedIds: [annotationId] }) + const outcome = store.commit(command, { accept }) + return outcome.ok ? { ok: true } : describe(outcome, context) +} + +/** Inserts a new annotation under a fresh id; one regeneration on `duplicate_key`. */ +export function insertAnnotation( + build: (id: string) => Annotation, + context: CommitContext, +): CommitResult { + const attempt = () => { + const annotation = build(newElementId('anno')) + const command: EditCommand = { + op: 'insert', + element: { kind: 'annotation', value: annotation }, + } + const result = commitGeometry(command, annotation.id, context) + return result.ok ? { ok: true as const, id: annotation.id } : result + } + const first = attempt() + return !first.ok && first.duplicate ? attempt() : first +} + +/** Replaces one annotation's geometry (move, numeric group, vertex, polygon) under `accept`. */ +export function updateGeometry( + annotation: Annotation, + geometry: Geometry, + context: CommitContext, +): CommitResult { + const command: EditCommand = { + op: 'update', + key: { kind: 'annotation', id: annotation.id }, + element: { kind: 'annotation', value: { ...annotation, geometry } }, + } + return commitGeometry(command, annotation.id, context) +} diff --git a/apps/app/src/editor/annotations/correction.ts b/apps/app/src/editor/annotations/correction.ts new file mode 100644 index 00000000..252728b8 --- /dev/null +++ b/apps/app/src/editor/annotations/correction.ts @@ -0,0 +1,68 @@ +import { + correctedCircle, + defaultRadius, + sameCircle, + type CircleShape, + type Frame, + type XY, +} from './frame' +import type { CommitResult } from './annotationCommit' + +/** The corrected position offered to the user, with the position it replaces. */ +export interface Correction { + /** The position the user chose (drawn as a hollow cross, apart from the proposal). */ + click: XY + circle: CircleShape +} + +const OUT_OF_FRAME = 'annotation.geometry.out_of_frame' + +/** + * Candidate C is offered when the core refused a point proposal that was either a + * reduced radius (B) or refused `out_of_frame` (A at a float edge). An A refused + * `too_small` (r0 already capped) offers nothing: the issue is shown instead. + */ +export function correctionFor( + frame: Frame, + attempted: CircleShape, + refusedCodes: readonly string[], +): Correction | null { + const reduced = attempted.r < defaultRadius(frame) + if (!reduced && !refusedCodes.includes(OUT_OF_FRAME)) return null + const click = { x: attempted.cx, y: attempted.cy } + const circle = correctedCircle(frame, click) + return sameCircle(circle, attempted) ? null : { click, circle } +} + +/** The creation of a point as the panel runs it: the core's verdict decides each step. */ +export type PointAttempt = + | { status: 'created'; id?: string } + | { status: 'correction'; correction: Correction } + | { status: 'refused'; messages: string[] } + +export type InsertCircle = (circle: CircleShape) => CommitResult + +/** « Créer »: insert the pending circle; on a refusal, offer C (never insert it unasked). */ +export function attemptPoint( + frame: Frame, + circle: CircleShape, + insert: InsertCircle, +): PointAttempt { + const result = insert(circle) + if (result.ok) return { status: 'created', id: result.id } + const correction = correctionFor(frame, circle, result.codes) + return correction + ? { status: 'correction', correction } + : { status: 'refused', messages: result.messages } +} + +/** « Utiliser cette position »: C goes through the same insert and the same verdict. */ +export function confirmCorrection( + correction: Correction, + insert: InsertCircle, +): PointAttempt { + const result = insert(correction.circle) + return result.ok + ? { status: 'created', id: result.id } + : { status: 'refused', messages: result.messages } +} diff --git a/apps/app/src/editor/annotations/creation.ts b/apps/app/src/editor/annotations/creation.ts new file mode 100644 index 00000000..8eeea291 --- /dev/null +++ b/apps/app/src/editor/annotations/creation.ts @@ -0,0 +1,155 @@ +import type { + Annotation, + AnatomicalSheetDocument, + Geometry, + Laterality, + SheetView, +} from '@faunosteo/core-wasm/types' +import { + centreCircle, + centreTriangle, + defaultRadius, + proposePoint, + round2, + type Frame, + type XY, +} from './frame' +import type { Correction } from './correction' +import type { EditableGeometry } from './geometryEdit' + +export type NewKind = 'point' | 'zone' | 'detail_trigger' + +/** The element being created: its geometry is held here, outside the document. */ +export interface PendingElement { + kind: NewKind + geometry: EditableGeometry + /** Candidate C awaiting the user's confirmation (a point only). */ + correction?: Correction | null +} + +/** What the creation panel collects (no default labels: names and laterality are typed). */ +export interface CreationForm { + fr: string + en: string + categoryId: string + laterality: Laterality | '' + opensViewId: string + zoneId: string + regionCode: string +} + +export const LATERALITIES: readonly Laterality[] = [ + 'unpaired', + 'bilateral', + 'left', + 'right', +] + +export function emptyForm(doc: AnatomicalSheetDocument): CreationForm { + return { + fr: '', + en: '', + categoryId: doc.categories[0]?.id ?? '', + laterality: '', + opensViewId: '', + zoneId: '', + regionCode: '', + } +} + +/** Detail views that open from `viewId`: the core allows only a direct child. */ +export function directChildren( + views: readonly SheetView[], + viewId: string, +): SheetView[] { + return views.filter( + (view) => view.kind === 'detail' && view.parent_view_id === viewId, + ) +} + +/** The pending element a keyboard « Ajouter … » button holds at the centre of F. */ +export function keyboardPending(kind: NewKind, frame: Frame): PendingElement { + if (kind === 'point') { + return { kind, geometry: { type: 'circle', ...centreCircle(frame) } } + } + return { kind, geometry: { type: 'polygon', points: centreTriangle(frame) } } +} + +export type FormProblem = 'names' | 'fields' + +const blank = (value: string) => value.trim() === '' + +/** Input shape only: what the core requires to exist, collected before the insert. */ +export function formProblem( + kind: NewKind, + form: CreationForm, +): FormProblem | null { + if (form.categoryId === '' || form.laterality === '') return 'fields' + if (kind === 'detail_trigger') { + if (form.opensViewId === '') return 'fields' + return blank(form.fr) !== blank(form.en) ? 'names' : null + } + return blank(form.fr) || blank(form.en) ? 'names' : null +} + +const orNull = (value: string): string | null => (blank(value) ? null : value) + +/** The annotation the form and the pending geometry describe, under a given id. */ +export function annotationOf( + id: string, + viewId: string, + pending: PendingElement, + form: CreationForm, +): Annotation { + const common = { + id, + view_id: viewId, + category_id: form.categoryId, + laterality: form.laterality as Laterality, + geometry: pending.geometry as Geometry, + review_status: 'to_confirm' as const, + color: null, + } + if (pending.kind === 'detail_trigger') { + const named = !blank(form.fr) + return { + ...common, + kind: 'detail_trigger', + name: named ? { fr: form.fr, en: form.en } : null, + opens_view_id: form.opensViewId, + } + } + return { + ...common, + kind: pending.kind, + name: { fr: form.fr, en: form.en }, + finding_zone_id: orNull(form.zoneId), + vertebral_region_code: orNull(form.regionCode), + } +} + +export type ClickOutcome = + | { kind: 'outside' } + | { kind: 'pending'; pending: PendingElement } + +/** + * The pending point a click with the point tool holds: A or B at the click, or, when + * neither fits, the click with r0 and candidate C waiting for the user's confirmation. + */ +export function pendingForClick(frame: Frame, click: XY): ClickOutcome { + const proposal = proposePoint(frame, click) + if (proposal.kind === 'outside') return { kind: 'outside' } + if (proposal.kind === 'circle') { + const geometry = { type: 'circle' as const, ...proposal.circle } + return { kind: 'pending', pending: { kind: 'point', geometry } } + } + const at = { x: round2(click.x), y: round2(click.y) } + const geometry = { + type: 'circle' as const, + cx: at.x, + cy: at.y, + r: defaultRadius(frame), + } + const correction = { click: at, circle: proposal.circle } + return { kind: 'pending', pending: { kind: 'point', geometry, correction } } +} diff --git a/apps/app/src/editor/annotations/frame.ts b/apps/app/src/editor/annotations/frame.ts new file mode 100644 index 00000000..e46a3dc7 --- /dev/null +++ b/apps/app/src/editor/annotations/frame.ts @@ -0,0 +1,147 @@ +/** + * Proposal arithmetic for a new point (plan « Default point and the frame », C26). The + * page only PROPOSES values; the core decides every one of them on the candidate + * document. Nothing here copies a core rule (no visibility constant, no preview size, + * no twin radius, no edge tolerance). + */ + +export interface Frame { + x: number + y: number + w: number + h: number +} + +export interface XY { + x: number + y: number +} + +export interface CircleShape { + cx: number + cy: number + r: number +} + +export type PointProposal = + | { kind: 'outside' } + | { kind: 'circle'; circle: CircleShape; shrunk: boolean } + | { kind: 'corrected'; circle: CircleShape } + +/** Float noise of `v × 100` must not move a value across a hundredth. */ +const EPSILON = 1e-9 + +export const round2 = (value: number): number => Math.round(value * 100) / 100 +const floor2 = (value: number): number => + Math.floor(value * 100 + EPSILON) / 100 +const ceil2 = (value: number): number => Math.ceil(value * 100 - EPSILON) / 100 + +/** + * F from the composed root's `viewBox` attribute TEXT (the property `baseVal` is held in + * f32). Null when it is not four finite numbers or the span is not positive: the caller + * then has no frame, never the fallback `0 0 100 100`. + */ +export function parseFrame(viewBox: string | null): Frame | null { + if (viewBox === null) return null + const parts = viewBox + .trim() + .split(/[\s,]+/) + .map(Number) + if (parts.length !== 4 || !parts.every(Number.isFinite)) return null + const [x, y, w, h] = parts + return w > 0 && h > 0 ? { x, y, w, h } : null +} + +/** r0 = min(12 + 0.03 × max(w, h), min(w, h) / 2), floored to 0.01. */ +export function defaultRadius(frame: Frame): number { + const wanted = 12 + 0.03 * Math.max(frame.w, frame.h) + return floor2(Math.min(wanted, Math.min(frame.w, frame.h) / 2)) +} + +/** Where a keyboard-created point sits: the centre of F, which fits by construction. */ +export function centreCircle(frame: Frame): CircleShape { + return { + cx: round2(frame.x + frame.w / 2), + cy: round2(frame.y + frame.h / 2), + r: defaultRadius(frame), + } +} + +function distanceToEdge(frame: Frame, at: XY): number { + return Math.min( + at.x - frame.x, + frame.x + frame.w - at.x, + at.y - frame.y, + frame.y + frame.h - at.y, + ) +} + +/** One axis of candidate C: clamped inward on the hundredth grid, else exactly. */ +function clampAxis(value: number, low: number, high: number): number { + const inwardLow = ceil2(low) + const inwardHigh = floor2(high) + if (inwardLow <= inwardHigh) { + return Math.min(Math.max(value, inwardLow), inwardHigh) + } + return Math.min(Math.max(value, low), high) +} + +/** + * Candidate C: radius r0, the centre clamped per axis into [x + r0, x + w − r0] and + * [y + r0, y + h − r0], rounded inward to 0.01. When that rounding leaves an empty + * interval (r0 = min(w, h) / 2 with an origin off the grid) the exact clamped value is + * used: the core accepts any decimals. + */ +export function correctedCircle(frame: Frame, at: XY): CircleShape { + const r = defaultRadius(frame) + return { + cx: clampAxis(round2(at.x), frame.x + r, frame.x + frame.w - r), + cy: clampAxis(round2(at.y), frame.y + r, frame.y + frame.h - r), + r, + } +} + +/** + * The proposal at a click (c rounded to 0.01, d its distance to the nearest edge of F): + * A (c, r0) when d ≥ r0; B (c, floor₀.₀₁(d)) when that radius is at least 0.01, else C + * at once; nothing outside F (the edge is inclusive). + */ +export function proposePoint(frame: Frame, click: XY): PointProposal { + if (distanceToEdge(frame, click) < 0) return { kind: 'outside' } + const at = { x: round2(click.x), y: round2(click.y) } + // A click inside F whose rounding lands outside it has no room: straight to C. + const distance = Math.max(distanceToEdge(frame, at), 0) + const r0 = defaultRadius(frame) + if (distance >= r0) { + return { + kind: 'circle', + circle: { cx: at.x, cy: at.y, r: r0 }, + shrunk: false, + } + } + const smaller = floor2(distance) + if (smaller < 0.01) { + return { kind: 'corrected', circle: correctedCircle(frame, at) } + } + return { + kind: 'circle', + circle: { cx: at.x, cy: at.y, r: smaller }, + shrunk: true, + } +} + +/** The three vertices of a keyboard-created zone or link: 10 % of the smaller side. */ +export function centreTriangle(frame: Frame): [number, number][] { + const side = 0.1 * Math.min(frame.w, frame.h) + const cx = frame.x + frame.w / 2 + const cy = frame.y + frame.h / 2 + const corners: [number, number][] = [ + [cx, cy - side / 2], + [cx + side / 2, cy + side / 2], + [cx - side / 2, cy + side / 2], + ] + return corners.map(([x, y]) => [round2(x), round2(y)]) +} + +export const sameCircle = (a: CircleShape, b: CircleShape): boolean => + a.cx === b.cx && a.cy === b.cy && a.r === b.r diff --git a/apps/app/src/editor/annotations/geometryEdit.ts b/apps/app/src/editor/annotations/geometryEdit.ts new file mode 100644 index 00000000..f4dc1406 --- /dev/null +++ b/apps/app/src/editor/annotations/geometryEdit.ts @@ -0,0 +1,118 @@ +import type { Geometry, Point } from '@faunosteo/core-wasm/types' +import { round2 } from './frame' + +/** The geometry group as typed: numbers stay text until the group is applied whole. */ +export type GroupFields = + | { type: 'circle'; cx: string; cy: string; r: string } + | { type: 'polygon'; rows: { x: string; y: string }[] } + +export type EditableGeometry = Extract + +export type GroupParse = + | { ok: true; geometry: EditableGeometry } + | { ok: false } + +/** The stored numbers exactly as JSON prints them (no display rounding). */ +export function fieldsOf(geometry: EditableGeometry): GroupFields { + if (geometry.type === 'circle') { + return { + type: 'circle', + cx: String(geometry.cx), + cy: String(geometry.cy), + r: String(geometry.r), + } + } + return { + type: 'polygon', + rows: geometry.points.map(([x, y]) => ({ x: String(x), y: String(y) })), + } +} + +export function isEditable( + geometry: Geometry | null, +): geometry is EditableGeometry { + return geometry?.type === 'circle' || geometry?.type === 'polygon' +} + +/** Input shape only: a blank or non-numeric field is no number. The core judges the rest. */ +function numberOf(text: string): number | null { + if (text.trim() === '') return null + const value = Number(text) + return Number.isFinite(value) ? value : null +} + +export function parseFields(fields: GroupFields): GroupParse { + if (fields.type === 'circle') { + const [cx, cy, r] = [fields.cx, fields.cy, fields.r].map(numberOf) + if (cx === null || cy === null || r === null) return { ok: false } + return { ok: true, geometry: { type: 'circle', cx, cy, r } } + } + const points: Point[] = [] + for (const row of fields.rows) { + const [x, y] = [numberOf(row.x), numberOf(row.y)] + if (x === null || y === null) return { ok: false } + points.push([x, y]) + } + return { ok: true, geometry: { type: 'polygon', points } } +} + +/** True when every typed number equals the stored one: nothing to propose. */ +export function sameAsStored( + fields: GroupFields, + stored: EditableGeometry, +): boolean { + const parsed = parseFields(fields) + if (!parsed.ok) return false + return JSON.stringify(parsed.geometry) === JSON.stringify(stored) +} + +/** The rows whose text differs from the stored value: the ones marked « non appliqué ». */ +export function changedFieldNames( + fields: GroupFields, + stored: EditableGeometry, +): Set { + const base = fieldsOf(stored) + const changed = new Set() + if (fields.type === 'circle' && base.type === 'circle') { + for (const key of ['cx', 'cy', 'r'] as const) { + if (fields[key] !== base[key]) changed.add(key) + } + return changed + } + if (fields.type === 'polygon' && base.type === 'polygon') { + fields.rows.forEach((row, index) => { + if (row.x !== base.rows[index]?.x) changed.add(`x${index}`) + if (row.y !== base.rows[index]?.y) changed.add(`y${index}`) + }) + } + return changed +} + +/** A new vertex halfway between the selected row and the next (wrapping), 2 decimals. */ +export function withVertexAfter( + fields: Extract, + after: number, +): Extract { + const rows = fields.rows + const from = rows[after] ?? rows[rows.length - 1] + const to = rows[(after + 1) % rows.length] ?? from + const middle = (a: string, b: string) => { + const value = round2((Number(a) + Number(b)) / 2) + return Number.isFinite(value) && a.trim() !== '' && b.trim() !== '' + ? String(value) + : '' + } + const added = { x: middle(from.x, to.x), y: middle(from.y, to.y) } + const at = Math.min(after, rows.length - 1) + 1 + return { + type: 'polygon', + rows: [...rows.slice(0, at), added, ...rows.slice(at)], + } +} + +export function withoutVertex( + fields: Extract, + index: number, +): Extract { + return { type: 'polygon', rows: fields.rows.filter((_, i) => i !== index) } +} diff --git a/apps/app/src/editor/annotations/gesture.ts b/apps/app/src/editor/annotations/gesture.ts new file mode 100644 index 00000000..c1b37ff0 --- /dev/null +++ b/apps/app/src/editor/annotations/gesture.ts @@ -0,0 +1,59 @@ +import type { Geometry } from '@faunosteo/core-wasm/types' +import { round2, type XY } from './frame' + +/** CSS px a press must travel before it is a drag (a click with jitter never moves). */ +export const DRAG_START_PX = 4 + +export function pastDragThreshold(from: XY, to: XY): boolean { + return Math.hypot(to.x - from.x, to.y - from.y) > DRAG_START_PX +} + +/** A circle or polygon translated as a block by a drawing-unit delta, rounded to 0.01. */ +export function translatedGeometry( + geometry: Geometry, + delta: XY, +): Geometry | null { + if (geometry.type === 'circle') { + return { + ...geometry, + cx: round2(geometry.cx + delta.x), + cy: round2(geometry.cy + delta.y), + } + } + if (geometry.type === 'polygon') { + return { + type: 'polygon', + points: geometry.points.map(([x, y]) => [ + round2(x + delta.x), + round2(y + delta.y), + ]), + } + } + return null +} + +interface Matrix { + a: number + b: number + c: number + d: number + e: number + f: number +} + +/** + * Pointer → drawing coordinates through the overlay's `getScreenCTM().inverse()`. Null + * where the browser gives no matrix (nothing is proposed then). + */ +export function clientToDrawing( + svg: SVGSVGElement | null, + client: XY, +): XY | null { + const matrix = svg?.getScreenCTM?.() + const inverse: Matrix | undefined = matrix?.inverse() + if (!inverse) return null + return { + x: inverse.a * client.x + inverse.c * client.y + inverse.e, + y: inverse.b * client.x + inverse.d * client.y + inverse.f, + } +} diff --git a/apps/app/src/editor/annotations/uiState.ts b/apps/app/src/editor/annotations/uiState.ts new file mode 100644 index 00000000..3c59c0da --- /dev/null +++ b/apps/app/src/editor/annotations/uiState.ts @@ -0,0 +1,108 @@ +import type { Point } from '@faunosteo/core-wasm/types' +import type { NewKind, PendingElement } from './creation' + +export type ToolId = 'select' | 'point' | 'zone' | 'link' + +/** A tracing in progress: a new zone or link, or a polygon replacing a geometry. */ +export interface Tracing { + target: NewKind | 'replace' + /** The annotation whose geometry the tracing replaces (target `replace`). */ + annotationId: string | null + points: Point[] +} + +export interface UiState { + viewId: string | null + tool: ToolId + selectedId: string | null + pending: PendingElement | null + /** Bumped by every new pending element: keys the creation form's own state. */ + serial: number + tracing: Tracing | null + hint: string | null +} + +export type UiAction = + | { type: 'view'; viewId: string } + | { type: 'tool'; tool: ToolId } + | { type: 'select'; id: string | null } + | { type: 'pending_new'; pending: PendingElement } + | { type: 'pending_update'; pending: PendingElement } + | { type: 'pending_drop' } + | { type: 'trace_start'; target: Tracing['target']; annotationId?: string } + | { type: 'trace_add'; point: Point } + | { type: 'trace_cancel' } + | { type: 'hint'; hint: string | null } + +export const initialUi: UiState = { + viewId: null, + tool: 'select', + selectedId: null, + pending: null, + serial: 0, + tracing: null, + hint: null, +} + +const TOOL_OF: Record = { + point: 'point', + zone: 'zone', + detail_trigger: 'link', + replace: 'zone', +} + +export function uiReducer(state: UiState, action: UiAction): UiState { + switch (action.type) { + case 'view': + return { ...initialUi, viewId: action.viewId } + case 'tool': + return { ...state, tool: action.tool, tracing: null, hint: null } + case 'select': + return { + ...state, + selectedId: action.id, + pending: null, + tracing: null, + hint: null, + } + case 'pending_new': + return { + ...state, + pending: action.pending, + serial: state.serial + 1, + selectedId: null, + tracing: null, + hint: null, + } + case 'pending_update': + return state.pending ? { ...state, pending: action.pending } : state + case 'pending_drop': + return { ...state, pending: null, hint: null } + case 'trace_start': + return { + ...state, + tool: TOOL_OF[action.target], + pending: null, + hint: null, + tracing: { + target: action.target, + annotationId: action.annotationId ?? null, + points: [], + }, + } + case 'trace_add': + return state.tracing + ? { + ...state, + tracing: { + ...state.tracing, + points: [...state.tracing.points, action.point], + }, + } + : state + case 'trace_cancel': + return { ...state, tracing: null, hint: null } + case 'hint': + return { ...state, hint: action.hint } + } +} diff --git a/apps/app/src/editor/annotations/useCanvasBuild.ts b/apps/app/src/editor/annotations/useCanvasBuild.ts new file mode 100644 index 00000000..bcb75875 --- /dev/null +++ b/apps/app/src/editor/annotations/useCanvasBuild.ts @@ -0,0 +1,72 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { buildView } from '@/components/catalogue/CatalogueCanvas' +import { coreRuntime } from '@/core/runtime' +import { useEditorStore } from '../state/editorStore' + +/** The composed root's own attributes, read as text (never `baseVal`). */ +export interface RootAttributes { + viewBox: string | null + ratio: string +} + +export type CanvasFailure = 'engine' | 'view' + +const ANNOTATED = '[data-anno-id]' + +/** + * Builds the core's composed view into `host`, again on every accepted handle change or + * retry (plan « Rendering and canvas »): the edit canvas follows the handle. Reports the + * root's attributes; a failure is the engine notice (retry) or the view notice. + */ +export function useCanvasBuild(viewId: string) { + const preview = useEditorStore((s) => s.preview) + const handleVersion = useEditorStore((s) => s.handleVersion) + const host = useRef(null) + const [attempt, setAttempt] = useState(0) + const [root, setRoot] = useState(null) + const [failure, setFailure] = useState(null) + + useEffect(() => { + const element = host.current + if (!element || !preview) return + const built = buildView(preview, viewId) + element.replaceChildren(...(built.ok ? [built.svg] : [])) + setFailure(built.ok ? null : built.failure) + setRoot( + built.ok + ? { + viewBox: built.svg.getAttribute('viewBox'), + ratio: + built.svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet', + } + : null, + ) + }, [preview, viewId, handleVersion, attempt]) + + const retry = useCallback(() => { + void coreRuntime() + .retry() + .finally(() => setAttempt((n) => n + 1)) + }, []) + return { host, root, failure, retry, handleVersion } +} + +/** The selected annotation's markers wear `data-state="current"`, restyled in place. */ +export function useSelectionMark( + host: React.RefObject, + selectedId: string | null, + rebuilt: unknown, +): void { + useEffect(() => { + host.current?.querySelectorAll(ANNOTATED).forEach((el) => { + if (el.getAttribute('data-anno-id') === selectedId) { + el.setAttribute('data-state', 'current') + } else el.removeAttribute('data-state') + }) + }, [host, selectedId, rebuilt]) +} + +export const annotationIdOf = (target: EventTarget | null): string | null => + target instanceof Element + ? (target.closest(ANNOTATED)?.getAttribute('data-anno-id') ?? null) + : null diff --git a/apps/app/src/editor/annotations/useMoveGesture.ts b/apps/app/src/editor/annotations/useMoveGesture.ts new file mode 100644 index 00000000..8e84bf8e --- /dev/null +++ b/apps/app/src/editor/annotations/useMoveGesture.ts @@ -0,0 +1,107 @@ +import { + useEffect, + useRef, + useState, + type PointerEvent, + type RefObject, +} from 'react' +import type { Geometry } from '@faunosteo/core-wasm/types' +import type { XY } from './frame' +import { + clientToDrawing, + pastDragThreshold, + translatedGeometry, +} from './gesture' +import type { EditableGeometry } from './geometryEdit' +import { annotationIdOf } from './useCanvasBuild' + +export interface MoveTarget { + id: string + geometry: EditableGeometry +} + +export interface MoveOptions { + overlay: RefObject + /** The selected annotation, when it can be moved (editable, measured, circle or polygon). */ + target: MoveTarget | null + /** One `update` on pointer-up; the verdict and the message are the caller's. */ + onDrop: (id: string, geometry: Geometry) => void +} + +interface Drag { + start: XY + origin: XY + started: boolean +} + +const clientOf = (event: PointerEvent): XY => ({ + x: event.clientX, + y: event.clientY, +}) + +/** + * Drag of the selected circle or polygon as a block (plan « Select »): it starts only + * after 4 CSS px from the press, so a click with jitter never moves it; the overlay + * previews the translated outline; pointer-up commits once, pointer-cancel and lost + * capture drop it with no command; losing the target (read-only mode) drops it too. + */ +export function useMoveGesture({ overlay, target, onDrop }: MoveOptions) { + const drag = useRef(null) + const [preview, setPreview] = useState(null) + const [armed, setArmed] = useState(false) + const stop = () => { + drag.current = null + setPreview(null) + setArmed(false) + } + useEffect(() => { + if (target === null) stop() + }, [target]) + + const translated = (event: PointerEvent): Geometry | null => { + const now = clientToDrawing(overlay.current, clientOf(event)) + const gesture = drag.current + if (!now || !gesture || !target) return null + return translatedGeometry(target.geometry, { + x: now.x - gesture.origin.x, + y: now.y - gesture.origin.y, + }) + } + const claims = (event: PointerEvent): boolean => + target !== null && annotationIdOf(event.target) === target.id + + const onPointerDown = (event: PointerEvent) => { + if (!claims(event) || event.button !== 0) return + const origin = clientToDrawing(overlay.current, clientOf(event)) + if (!origin) return + drag.current = { start: clientOf(event), origin, started: false } + event.currentTarget.setPointerCapture?.(event.pointerId) + setArmed(true) + } + const onPointerMove = (event: PointerEvent) => { + const gesture = drag.current + if (!gesture) return + if (!gesture.started && !pastDragThreshold(gesture.start, clientOf(event))) + return + gesture.started = true + setPreview(translated(event)) + } + const onPointerUp = (event: PointerEvent) => { + const gesture = drag.current + const dropped = gesture?.started ? translated(event) : null + stop() + if (dropped && target) onDrop(target.id, dropped) + } + return { + preview, + armed, + claims, + handlers: { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerCancel: stop, + onLostPointerCapture: stop, + }, + } +} diff --git a/apps/app/src/editor/annotations/usePlacement.ts b/apps/app/src/editor/annotations/usePlacement.ts new file mode 100644 index 00000000..7c65d141 --- /dev/null +++ b/apps/app/src/editor/annotations/usePlacement.ts @@ -0,0 +1,109 @@ +import type { Dispatch, KeyboardEvent } from 'react' +import type { + AnatomicalSheetDocument, + Geometry, + Point, +} from '@faunosteo/core-wasm/types' +import { useT } from '@/i18n/useT' +import { updateGeometry, type CommitContext } from './annotationCommit' +import { pendingForClick, type NewKind } from './creation' +import { round2, type Frame, type XY } from './frame' +import type { ToolId, Tracing, UiAction, UiState } from './uiState' + +/** A click on the first vertex closes the tracing when within this share of F's span. */ +const CLOSE_SHARE = 0.015 + +const TOOL_TARGET: Record, NewKind> = { + point: 'point', + zone: 'zone', + link: 'detail_trigger', +} + +export interface PlacementInput { + ui: UiState + dispatch: Dispatch + frame: Frame | null + doc: AnatomicalSheetDocument + context: CommitContext +} + +const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)] + +function nearFirstVertex(tracing: Tracing, at: XY, frame: Frame): boolean { + const first = tracing.points[0] + if (!first || tracing.points.length < 3) return false + const reach = CLOSE_SHARE * Math.max(frame.w, frame.h) + return Math.hypot(first[0] - at.x, first[1] - at.y) <= reach +} + +/** + * What closing a tracing does: a new zone or link becomes the pending element; a polygon + * replacing a geometry is committed at once under `accept`, and a refusal drops the + * tracing with the core's message (the annotation is unchanged). + */ +export function closingActions( + tracing: Tracing | null, + doc: AnatomicalSheetDocument, + context: CommitContext, +): UiAction[] { + if (!tracing || tracing.points.length < 3) return [] + const polygon = { type: 'polygon' as const, points: tracing.points } + if (tracing.target !== 'replace') { + const pending = { kind: tracing.target, geometry: polygon } + return [{ type: 'pending_new', pending }] + } + const annotation = doc.annotations.find((a) => a.id === tracing.annotationId) + if (!annotation) return [{ type: 'trace_cancel' }] + const result = updateGeometry(annotation, polygon, context) + if (result.ok) return [{ type: 'select', id: annotation.id }] + return [ + { type: 'trace_cancel' }, + { type: 'hint', hint: result.messages.join(' ') }, + ] +} + +/** + * What a click, a key or a drop does with the current tool. Every geometry it proposes is + * arithmetic over F; the core decides at « Créer » or at the commit of an existing one. + */ +export function usePlacement(input: PlacementInput) { + const t = useT() + const { ui, dispatch, frame, doc, context } = input + + const placePoint = (frame: Frame, at: XY) => { + const outcome = pendingForClick(frame, at) + if (outcome.kind === 'pending') { + return dispatch({ type: 'pending_new', pending: outcome.pending }) + } + dispatch({ type: 'hint', hint: t('editor.annotations.outside') }) + } + const closeTracing = () => + closingActions(ui.tracing, doc, context).forEach(dispatch) + + const trace = (tool: Exclude, at: XY) => { + if (!frame) return + if (ui.tracing && nearFirstVertex(ui.tracing, at, frame)) { + return closeTracing() + } + if (!ui.tracing) + dispatch({ type: 'trace_start', target: TOOL_TARGET[tool] }) + dispatch({ type: 'trace_add', point: asPoint(at) }) + } + const onPlace = (at: XY) => { + if (ui.tool === 'point' && frame) placePoint(frame, at) + else if (ui.tool === 'zone' || ui.tool === 'link') trace(ui.tool, at) + } + const onDrop = (id: string, geometry: Geometry) => { + const annotation = doc.annotations.find((a) => a.id === id) + if (!annotation) return + const result = updateGeometry(annotation, geometry, context) + const hint = result.ok ? null : result.messages.join(' ') + dispatch({ type: 'hint', hint }) + } + const onKeyDown = (event: KeyboardEvent) => { + if (!ui.tracing) return + if (event.key === 'Enter') closeTracing() + if (event.key === 'Escape') dispatch({ type: 'trace_cancel' }) + } + return { onPlace, onDrop, onKeyDown, closeTracing } +} diff --git a/apps/app/src/editor/annotations/useViewModel.ts b/apps/app/src/editor/annotations/useViewModel.ts new file mode 100644 index 00000000..3b9e7a3d --- /dev/null +++ b/apps/app/src/editor/annotations/useViewModel.ts @@ -0,0 +1,54 @@ +import { useEffect, useMemo } from 'react' +import type { + AnatomicalSheetDocument, + Annotation, + SheetView, +} from '@faunosteo/core-wasm/types' +import { unmeasuredViews } from '../issues' +import { useEditorStore } from '../state/editorStore' +import { directChildren } from './creation' + +export interface ViewModel { + annotations: Annotation[] + /** The core measures this view: a frame can be read and geometry edited. */ + measured: boolean + children: SheetView[] +} + +export const mainViewId = (doc: AnatomicalSheetDocument): string => + doc.views.find((view) => view.kind === 'main')?.id ?? doc.views[0]?.id ?? '' + +export function useViewModel( + doc: AnatomicalSheetDocument, + viewId: string, +): ViewModel { + const state = useEditorStore((s) => s.previewState) + return useMemo(() => { + const unmeasured = state ? unmeasuredViews(state) : new Set() + return { + annotations: doc.annotations.filter((a) => a.view_id === viewId), + measured: state !== null && !unmeasured.has(viewId), + children: directChildren(doc.views, viewId), + } + }, [doc, state, viewId]) +} + +const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]' + +/** Ctrl+Z undoes and Ctrl+Shift+Z redoes, outside text fields (no Ctrl+Y). */ +export function useUndoShortcuts(): void { + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + const target = event.target + if (target instanceof Element && target.closest(TEXT_TARGET)) return + if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z') + return + event.preventDefault() + const store = useEditorStore.getState() + if (event.shiftKey) store.redoStep() + else store.undoStep() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, []) +} diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 9eb253f6..85f8a57f 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1434,4 +1434,79 @@ export const en: Dict = { 'editor.findings.empty': 'No findings zone yet.', 'editor.findings.mark_reviewed': 'Mark as reviewed', 'editor.findings.reset_to_confirm': 'Reset to confirm', + 'editor.annotations.tools': 'Tools', + 'editor.annotations.tool.select': 'Select and move', + 'editor.annotations.tool.point': 'Point', + 'editor.annotations.tool.zone': 'Zone', + 'editor.annotations.tool.link': 'Link to a detail view', + 'editor.annotations.undo': 'Undo', + 'editor.annotations.redo': 'Redo', + 'editor.annotations.tool_hint.select': 'Tool: select and move · Esc cancels a tracing', + 'editor.annotations.tool_hint.point': 'Tool: point · click in the drawing to place a point.', + 'editor.annotations.tool_hint.zone': 'Tool: zone · click to place the vertices; Enter or « Close the tracing » finishes, Esc cancels.', + 'editor.annotations.tool_hint.link': 'Tool: link to a detail view · trace the outline that opens the view; Enter finishes, Esc cancels.', + 'editor.annotations.views': 'Views', + 'editor.annotations.unmeasured.hint': 'This drawing cannot be measured: add or fix its illustration (tab Views and illustrations) before placing or moving elements.', + 'editor.annotations.outside': 'Click inside the drawing.', + 'editor.annotations.correction': 'The point does not fit where you clicked. Corrected position proposed: x = {x}, y = {y}.', + 'editor.annotations.correction_use': 'Use this position', + 'editor.annotations.correction_cancel': 'Cancel', + 'editor.annotations.no_category': 'Create an annotation category first (tab General).', + 'editor.annotations.no_child_view': 'No detail view opens from this view: create one in the Views and illustrations tab.', + 'editor.annotations.add.point': 'Add a point', + 'editor.annotations.add.zone': 'Add a zone', + 'editor.annotations.add.detail_trigger': 'Add a link', + 'editor.annotations.new.point': 'New point', + 'editor.annotations.new.zone': 'New zone', + 'editor.annotations.new.detail_trigger': 'New link', + 'editor.annotations.create': 'Create', + 'editor.annotations.create_cancel': 'Cancel', + 'editor.annotations.name_fr': 'Name (FR)', + 'editor.annotations.name_en': 'Name (EN)', + 'editor.annotations.category': 'Category', + 'editor.annotations.color': 'Colour', + 'editor.annotations.color_hint': 'Leave empty for the category colour, or enter a hexadecimal value (#rrggbb).', + 'editor.annotations.laterality': 'Laterality', + 'editor.annotations.laterality.unpaired': 'Unpaired', + 'editor.annotations.laterality.bilateral': 'Bilateral', + 'editor.annotations.laterality.left': 'Left', + 'editor.annotations.laterality.right': 'Right', + 'editor.annotations.region': 'Vertebral region', + 'editor.annotations.zone': 'Findings zone', + 'editor.annotations.opens': 'Opened view', + 'editor.annotations.none': 'None', + 'editor.annotations.required.fields': 'Choose the category and the laterality (and the opened view for a link).', + 'editor.annotations.required.names': 'Enter the name in French and in English.', + 'editor.annotations.kind.point': 'Point', + 'editor.annotations.kind.zone': 'Zone', + 'editor.annotations.kind.detail_trigger': 'Link', + 'editor.annotations.status.to_confirm': 'To confirm', + 'editor.annotations.status.reviewed': 'Reviewed', + 'editor.annotations.status.inherited': 'Inherited, not reviewed', + 'editor.annotations.mark_reviewed': 'Mark as reviewed', + 'editor.annotations.to_confirm': 'Reset to confirm', + 'editor.annotations.list': 'Annotations of the view', + 'editor.annotations.list_empty': 'No annotation in this view.', + 'editor.annotations.selection': 'Selection: {kind} « {name} »', + 'editor.annotations.select_hint': 'Select an annotation on the drawing or in the list to see its properties.', + 'editor.annotations.properties': 'Annotation properties', + 'editor.annotations.tracing': '{count} vertex(es) placed.', + 'editor.annotations.trace_close': 'Close the tracing', + 'editor.annotations.trace_cancel': 'Cancel the tracing', + 'editor.annotations.replace_polygon': 'Replace with a polygon', + 'editor.annotations.no_geometry': 'This annotation has no geometry: trace a polygon to give it one.', + 'editor.annotations.path': 'This annotation is a free path: its data cannot be edited here.', + 'editor.annotations.geometry.circle': 'Position and radius', + 'editor.annotations.geometry.polygon': 'Vertices', + 'editor.annotations.geometry.cx': 'Centre x', + 'editor.annotations.geometry.cy': 'Centre y', + 'editor.annotations.geometry.r': 'Radius', + 'editor.annotations.geometry.vertex_x': 'x of vertex {n}', + 'editor.annotations.geometry.vertex_y': 'y of vertex {n}', + 'editor.annotations.geometry.vertices': '{count} vertices', + 'editor.annotations.geometry.add_vertex': 'Add a vertex', + 'editor.annotations.geometry.unapplied': 'Values not applied: the draft is unchanged.', + 'editor.annotations.geometry.unapplied_tag': 'not applied', + 'editor.annotations.geometry.revert': 'Back to the saved values', + 'editor.annotations.geometry.number': 'Each field must hold a number.', } diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 92940543..b6c43efc 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1465,4 +1465,79 @@ export const fr: Dict = { 'editor.findings.empty': "Aucune zone de constats pour l'instant.", 'editor.findings.mark_reviewed': 'Marquer comme relu', 'editor.findings.reset_to_confirm': 'Remettre à confirmer', + 'editor.annotations.tools': 'Outils', + 'editor.annotations.tool.select': 'Sélectionner et déplacer', + 'editor.annotations.tool.point': 'Point', + 'editor.annotations.tool.zone': 'Zone', + 'editor.annotations.tool.link': 'Accès à une vue détaillée', + 'editor.annotations.undo': 'Annuler', + 'editor.annotations.redo': 'Rétablir', + 'editor.annotations.tool_hint.select': 'Outil : sélectionner et déplacer · Échap annule un tracé', + 'editor.annotations.tool_hint.point': 'Outil : point · cliquez dans le dessin pour placer un point.', + 'editor.annotations.tool_hint.zone': 'Outil : zone · cliquez pour poser les sommets ; Entrée ou « Fermer le tracé » termine, Échap annule.', + 'editor.annotations.tool_hint.link': 'Outil : accès à une vue détaillée · tracez le contour qui ouvre la vue ; Entrée termine, Échap annule.', + 'editor.annotations.views': 'Vues', + 'editor.annotations.unmeasured.hint': "Ce dessin n'est pas mesurable : ajoutez ou corrigez son illustration (onglet Vues et illustrations) avant de placer ou de déplacer des éléments.", + 'editor.annotations.outside': "Cliquez à l'intérieur du dessin.", + 'editor.annotations.correction': "Le point ne tient pas à l'endroit choisi. Position corrigée proposée : x = {x}, y = {y}.", + 'editor.annotations.correction_use': 'Utiliser cette position', + 'editor.annotations.correction_cancel': 'Annuler', + 'editor.annotations.no_category': "Créez d'abord une catégorie d'annotation (onglet Général).", + 'editor.annotations.no_child_view': "Aucune vue détaillée ne s'ouvre depuis cette vue : créez-en une dans l'onglet Vues et illustrations.", + 'editor.annotations.add.point': 'Ajouter un point', + 'editor.annotations.add.zone': 'Ajouter une zone', + 'editor.annotations.add.detail_trigger': 'Ajouter un accès', + 'editor.annotations.new.point': 'Nouveau point', + 'editor.annotations.new.zone': 'Nouvelle zone', + 'editor.annotations.new.detail_trigger': 'Nouvel accès', + 'editor.annotations.create': 'Créer', + 'editor.annotations.create_cancel': 'Annuler', + 'editor.annotations.name_fr': 'Nom (FR)', + 'editor.annotations.name_en': 'Nom (EN)', + 'editor.annotations.category': 'Catégorie', + 'editor.annotations.color': 'Couleur', + 'editor.annotations.color_hint': 'Laissez vide pour la couleur de la catégorie, ou indiquez une valeur hexadécimale (#rrggbb).', + 'editor.annotations.laterality': 'Latéralité', + 'editor.annotations.laterality.unpaired': 'Non latéralisée', + 'editor.annotations.laterality.bilateral': 'Bilatérale', + 'editor.annotations.laterality.left': 'Gauche', + 'editor.annotations.laterality.right': 'Droite', + 'editor.annotations.region': 'Région vertébrale', + 'editor.annotations.zone': 'Zone de constats', + 'editor.annotations.opens': 'Vue ouverte', + 'editor.annotations.none': 'Aucune', + 'editor.annotations.required.fields': 'Choisissez la catégorie et la latéralité (et la vue ouverte pour un accès).', + 'editor.annotations.required.names': 'Renseignez le nom en français et en anglais.', + 'editor.annotations.kind.point': 'Point', + 'editor.annotations.kind.zone': 'Zone', + 'editor.annotations.kind.detail_trigger': 'Accès', + 'editor.annotations.status.to_confirm': 'À confirmer', + 'editor.annotations.status.reviewed': 'Relu', + 'editor.annotations.status.inherited': 'Hérité, non relu', + 'editor.annotations.mark_reviewed': 'Marquer comme relu', + 'editor.annotations.to_confirm': 'Remettre à confirmer', + 'editor.annotations.list': 'Annotations de la vue', + 'editor.annotations.list_empty': 'Aucune annotation dans cette vue.', + 'editor.annotations.selection': 'Sélection : {kind} « {name} »', + 'editor.annotations.select_hint': 'Sélectionnez une annotation sur le dessin ou dans la liste pour voir ses propriétés.', + 'editor.annotations.properties': "Propriétés de l'annotation", + 'editor.annotations.tracing': '{count} sommet(s) posé(s).', + 'editor.annotations.trace_close': 'Fermer le tracé', + 'editor.annotations.trace_cancel': 'Annuler le tracé', + 'editor.annotations.replace_polygon': 'Remplacer par un polygone', + 'editor.annotations.no_geometry': "Cette annotation n'a pas de géométrie : tracez un polygone pour lui en donner une.", + 'editor.annotations.path': 'Cette annotation est un tracé libre (path) : ses données ne se modifient pas ici.', + 'editor.annotations.geometry.circle': 'Position et rayon', + 'editor.annotations.geometry.polygon': 'Sommets', + 'editor.annotations.geometry.cx': 'Centre x', + 'editor.annotations.geometry.cy': 'Centre y', + 'editor.annotations.geometry.r': 'Rayon', + 'editor.annotations.geometry.vertex_x': 'x du sommet {n}', + 'editor.annotations.geometry.vertex_y': 'y du sommet {n}', + 'editor.annotations.geometry.vertices': '{count} sommets', + 'editor.annotations.geometry.add_vertex': 'Ajouter un sommet', + 'editor.annotations.geometry.unapplied': 'Valeurs non appliquées : le brouillon est inchangé.', + 'editor.annotations.geometry.unapplied_tag': 'non appliqué', + 'editor.annotations.geometry.revert': 'Revenir aux valeurs enregistrées', + 'editor.annotations.geometry.number': 'Chaque champ doit contenir un nombre.', } diff --git a/apps/app/tests/helpers/annotationsCore.ts b/apps/app/tests/helpers/annotationsCore.ts new file mode 100644 index 00000000..2fbace66 --- /dev/null +++ b/apps/app/tests/helpers/annotationsCore.ts @@ -0,0 +1,109 @@ +import type { + Annotation, + PreviewState, + ViewBox, +} from '@faunosteo/core-wasm/types' +import { CataloguePreview } from '@/catalogue/preview' +import { buildView } from '@/components/catalogue/CatalogueCanvas' +import { coreRuntime } from '@/core/runtime' +import type { CommitResult } from '@/editor/annotations/annotationCommit' +import { + parseFrame, + type CircleShape, + type Frame, +} from '@/editor/annotations/frame' +import { applyEdit } from '@/editor/core/editOps' +import { + geometryAccept, + geometryErrorsById, + type GeometryRefusal, +} from '@/editor/issues' +import { + ASSET, + drawnText, + edit, + insert, + point, + svgBytes, +} from './editorFixtures' + +/** A draft on the Node core: its main drawing's viewBox, optionally with a crop view. */ +export interface Bed { + preview: CataloguePreview + text: string + state: PreviewState +} + +export function bed( + viewBox: string, + text = drawnText(), + withDrawing = true, +): Bed { + const drawing = svgBytes(viewBox) + const drawings = withDrawing + ? [{ assetId: ASSET, sha256: drawing.sha256, bytes: drawing.bytes }] + : [] + const preview = new CataloguePreview( + coreRuntime(), + { status: 'draft', document: text }, + drawings, + ) + const state = preview.state() + if (!state.ok) throw new Error(state.kind) + return { preview, text, state: state.value } +} + +export function withCrop(text: string, crop: ViewBox, id = 'view-det'): string { + return insert(text, { + kind: 'view', + value: { + kind: 'detail', + id, + name: { fr: 'D', en: 'D' }, + svg_asset_id: null, + view_box: crop, + parent_view_id: 'view-main', + }, + }) +} + +/** F as the page reads it: the composed root's `viewBox` text. */ +export function frameOf(b: Bed, viewId = 'view-main'): Frame | null { + const built = buildView(b.preview, viewId) + return built.ok ? parseFrame(built.svg.getAttribute('viewBox')) : null +} + +/** The insert of `circle` on `viewId` through the core under the geometry `accept`. */ +export function circleInserter(b: Bed, viewId = 'view-main', id = 'anno-new') { + return (circle: CircleShape): CommitResult => { + const element = point(id, circle.cx, circle.cy, circle.r, viewId) + const edited = applyEdit(b.preview.document, { op: 'insert', element }) + if (!edited.ok) return { ok: false, messages: [edited.kind], codes: [] } + const accept = geometryAccept({ before: b.state, changedIds: [id] }) + const outcome = b.preview.replaceDocument(edited.value, accept) + if (outcome.ok) return { ok: true } + if (outcome.reason !== 'refused') + return { ok: false, messages: ['core'], codes: [] } + const { issues } = outcome.refusal as GeometryRefusal + return { + ok: false, + messages: issues.map((i) => i.message), + codes: issues.map((i) => i.code), + } + } +} + +export function annotationOn(b: Bed, id: string): Annotation | undefined { + const state = b.preview.state() + return state.ok + ? state.value.document.annotations.find((a) => a.id === id) + : undefined +} + +export function currentErrors(b: Bed): Map { + const state = b.preview.state() + if (!state.ok) throw new Error(state.kind) + return geometryErrorsById(state.value) +} + +export { drawnText, edit, insert, point } diff --git a/apps/app/tests/unit/editor-annotations-commit.test.ts b/apps/app/tests/unit/editor-annotations-commit.test.ts new file mode 100644 index 00000000..72f83ef2 --- /dev/null +++ b/apps/app/tests/unit/editor-annotations-commit.test.ts @@ -0,0 +1,356 @@ +/** + * Lot H: every geometry commit goes through the store under the geometry `accept` (C26, + * C32, C33): proof on the Node core that no page action leaves an annotation with a + * geometry error it did not already have, and that an invalid one can be repaired. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Annotation, Geometry, ViewBox } from '@faunosteo/core-wasm/types' +import { + insertAnnotation, + updateGeometry, + type CommitContext, +} from '@/editor/annotations/annotationCommit' +import { translatedGeometry } from '@/editor/annotations/gesture' +import { + geometryAccept, + geometryErrorsById, + unmeasuredViews, +} from '@/editor/issues' +import { + ASSET, + drawnText, + insert, + point, + svgBytes, +} from '../helpers/editorFixtures' +import { + USER, + VERSION, + openReady, + resetStore, + sb, + store, + versionAnswer, +} from '../helpers/editorHarness' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +const context: CommitContext = { t: (key) => key, locale: 'fr' } +afterEach(resetStore) + +const state = () => store.getState().previewState! +const annotation = (id: string): Annotation => { + const found = state().document.annotations.find((a) => a.id === id) + if (!found) throw new Error(`no ${id}`) + return found +} +const errors = () => geometryErrorsById(state()) +const circle = (cx: number, cy: number, r: number): Geometry => ({ + type: 'circle', + cx, + cy, + r, +}) +const asAnnotation = (element: ReturnType) => + element.value as Annotation + +function zoneText(id: string, geometry: Geometry, base = drawnText()): string { + const value = { + ...asAnnotation(point(id, 0, 0, 1)), + kind: 'zone', + geometry, + } as Annotation + return insert(base, { kind: 'annotation', value }) +} + +/** Opens a draft whose main drawing has `viewBox`, or none (a missing drawing). */ +async function openWith(text: string, viewBox: string | null): Promise { + const drawing = svgBytes(viewBox ?? '0 0 100 100') + const answer = versionAnswer(text, 3, viewBox !== null) + sb.getSheetVersion.mockResolvedValue({ + ...answer, + drawings: + viewBox === null ? [] : [{ asset_id: ASSET, sha256: drawing.sha256 }], + } as never) + sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes) + store.getState().open(VERSION, USER, { canEdit: true }) + await vi.waitFor(() => expect(store.getState().status).not.toBe('loading')) +} + +describe('a new point (C26)', () => { + it('is refused out of frame, the store and the handle unchanged', async () => { + await openReady({ text: drawnText() }) + const version = store.getState().handleVersion + const result = insertAnnotation( + (id) => asAnnotation(point(id, 150, 50, 5)), + context, + ) + expect(result).toMatchObject({ + ok: false, + codes: ['annotation.geometry.out_of_frame'], + }) + expect(store.getState().handleVersion).toBe(version) + expect(store.getState().documentText).toBe(drawnText()) + expect(store.getState().unsaved).toBe(false) + }) + + it('is kept when valid, with no geometry error', async () => { + await openReady({ text: drawnText() }) + expect( + insertAnnotation((id) => asAnnotation(point(id, 50, 50, 5)), context), + ).toMatchObject({ ok: true }) + expect(state().document.annotations).toHaveLength(1) + expect(errors().size).toBe(0) + }) +}) + +describe('a move or a typed value on a valid point', () => { + const open = () => + openReady({ text: insert(drawnText(), point('anno-a', 50, 50, 5)) }) + + it('rolls back a drag that drops it half out of the frame', async () => { + await open() + const before = store.getState().documentText + const dropped = translatedGeometry(circle(50, 50, 5), { x: 48, y: 0 })! + const result = updateGeometry(annotation('anno-a'), dropped, context) + expect(result).toMatchObject({ + ok: false, + codes: ['annotation.geometry.out_of_frame'], + }) + expect(store.getState().documentText).toBe(before) + expect(errors().size).toBe(0) + }) + + it('commits a drag that stays inside, rounded to two decimals', async () => { + await open() + const moved = translatedGeometry(circle(50, 50, 5), { + x: 10.004, + y: -3.333, + })! + expect(updateGeometry(annotation('anno-a'), moved, context)).toEqual({ + ok: true, + }) + expect(annotation('anno-a').geometry).toEqual(circle(60, 46.67, 5)) + }) + + it('refuses a typed radius the core reports too_small', async () => { + await openWith( + insert(drawnText(), point('anno-a', 2500, 2500, 400)), + '0 0 5000 5000', + ) + expect(errors().size).toBe(0) + const result = updateGeometry( + annotation('anno-a'), + circle(2500, 2500, 1), + context, + ) + expect(result).toMatchObject({ + ok: false, + codes: ['annotation.geometry.too_small'], + }) + expect(annotation('anno-a').geometry).toEqual(circle(2500, 2500, 400)) + }) +}) + +describe('repairing an annotation that is already invalid (C33)', () => { + it('refuses cx alone, keeps the error visible, applies the coherent set', async () => { + await openReady({ text: insert(drawnText(), point('anno-a', 150, 150, 5)) }) + expect(errors().has('anno-a')).toBe(true) + const before = store.getState().documentText + const half = updateGeometry( + annotation('anno-a'), + circle(50, 150, 5), + context, + ) + expect(half).toMatchObject({ + ok: false, + codes: ['annotation.geometry.out_of_frame'], + }) + expect(store.getState().documentText).toBe(before) + expect(errors().has('anno-a')).toBe(true) + expect( + updateGeometry(annotation('anno-a'), circle(50, 50, 5), context), + ).toEqual({ ok: true }) + expect(errors().size).toBe(0) + }) + + it('repairs a polygon the same way, one vertex then the whole set', async () => { + const bad: Geometry = { + type: 'polygon', + points: [ + [150, 150], + [190, 150], + [170, 190], + ], + } + await openReady({ text: zoneText('zone-a', bad) }) + expect(errors().has('zone-a')).toBe(true) + const partial: Geometry = { + type: 'polygon', + points: [ + [20, 20], + [190, 150], + [170, 190], + ], + } + expect(updateGeometry(annotation('zone-a'), partial, context).ok).toBe( + false, + ) + const whole: Geometry = { + type: 'polygon', + points: [ + [20, 20], + [80, 20], + [50, 80], + ], + } + expect(updateGeometry(annotation('zone-a'), whole, context)).toEqual({ + ok: true, + }) + expect(errors().size).toBe(0) + }) + + it('repairs an invalid point that came back from a restored copy', async () => { + const invalid = JSON.parse(insert(drawnText(), point('anno-a', 150, 50, 5))) + sessionStorage.setItem( + `osteo:sheet-draft:${USER}:${VERSION}`, + JSON.stringify({ + v: 1, + user_id: USER, + version_id: VERSION, + sheet_id: 'sheet-1', + sheet_name: 'Fiche', + revision: 3, + written_at: '2026-11-03T10:00:00Z', + document: invalid, + drawings: [{ asset_id: ASSET, sha256: svgBytes().sha256 }], + }), + ) + await openReady({ + text: insert(drawnText(), point('anno-a', 50, 50, 5)), + revision: 3, + }) + expect(await store.getState().restoreCopy()).toEqual({ ok: true }) + expect(errors().has('anno-a')).toBe(true) + expect( + updateGeometry(annotation('anno-a'), circle(50, 50, 5), context), + ).toEqual({ ok: true }) + expect(errors().size).toBe(0) + }) + + it('refuses a drop that leaves an already-invalid point invalid', async () => { + await openReady({ text: insert(drawnText(), point('anno-a', 150, 50, 5)) }) + const result = updateGeometry( + annotation('anno-a'), + circle(140, 50, 5), + context, + ) + expect(result.ok).toBe(false) + expect(annotation('anno-a').geometry).toEqual(circle(150, 50, 5)) + }) +}) + +describe('a frame change (rule 7)', () => { + const crop = (box: ViewBox) => { + const main = state().document.views.find((v) => v.kind === 'main')! + const command = { + op: 'update' as const, + key: { kind: 'view' as const, id: main.id }, + element: { kind: 'view' as const, value: { ...main, view_box: box } }, + } + const accept = geometryAccept({ before: state(), changedIds: [] }) + return store.getState().commit(command, { accept }) + } + + it('is refused when it pushes a valid point out of the frame', async () => { + await openReady({ text: insert(drawnText(), point('anno-a', 50, 50, 5)) }) + const before = store.getState().documentText + expect(crop({ min_x: 0, min_y: 0, width: 40, height: 40 }).ok).toBe(false) + expect(store.getState().documentText).toBe(before) + }) + + it('is accepted when only an already-invalid point is affected', async () => { + await openReady({ text: insert(drawnText(), point('anno-a', 150, 50, 5)) }) + expect(crop({ min_x: 0, min_y: 0, width: 80, height: 80 }).ok).toBe(true) + }) +}) + +describe('an unmeasured view (C32)', () => { + const valid = () => insert(drawnText(), point('anno-a', 50, 50, 5)) + + it('refuses a creation and a move when the drawing is missing', async () => { + await openWith(valid(), null) + expect(unmeasuredViews(state()).has('view-main')).toBe(true) + const created = insertAnnotation( + (id) => asAnnotation(point(id, 40, 40, 5)), + context, + ) + expect(created).toEqual({ + ok: false, + messages: ['editor.annotations.unmeasured.hint'], + codes: [], + }) + const moved = updateGeometry( + annotation('anno-a'), + circle(60, 50, 5), + context, + ) + expect(moved.ok).toBe(false) + expect(annotation('anno-a').geometry).toEqual(circle(50, 50, 5)) + }) + + it('refuses them on a crop of span 0.5', async () => { + const view = { + kind: 'view' as const, + value: { + kind: 'detail' as const, + id: 'view-det', + name: { fr: 'D', en: 'D' }, + svg_asset_id: null, + view_box: { min_x: 0, min_y: 0, width: 0.5, height: 0.5 }, + parent_view_id: 'view-main', + }, + } + await openReady({ text: insert(drawnText(), view) }) + expect(unmeasuredViews(state()).has('view-det')).toBe(true) + const created = insertAnnotation( + (id) => asAnnotation(point(id, 0.25, 0.25, 0.1, 'view-det')), + context, + ) + expect(created.ok).toBe(false) + expect(state().document.annotations).toHaveLength(0) + }) + + it('refuses them on a drawing without viewBox', async () => { + const bare = + '' + const { cleanSvg } = await import('@/editor/core/cleaning') + const cleaned = cleanSvg(new TextEncoder().encode(bare)) + if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256) + throw new Error('svg') + sb.getSheetVersion.mockResolvedValue({ + ...versionAnswer(valid(), 3), + drawings: [{ asset_id: ASSET, sha256: cleaned.value.sha256 }], + } as never) + sb.downloadSheetDrawing.mockResolvedValue( + new TextEncoder().encode(cleaned.value.stored), + ) + store.getState().open(VERSION, USER, { canEdit: true }) + await vi.waitFor(() => expect(store.getState().status).not.toBe('loading')) + expect(unmeasuredViews(state()).has('view-main')).toBe(true) + const moved = updateGeometry( + annotation('anno-a'), + circle(60, 50, 5), + context, + ) + expect(moved.ok).toBe(false) + }) +}) diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx new file mode 100644 index 00000000..edbf36ad --- /dev/null +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -0,0 +1,738 @@ +/** Lot H: the Annotations tab (creation, corrected position, gestures, read-only, repair). */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { Annotation } from '@faunosteo/core-wasm/types' +import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' +import { useLocaleStore } from '@/state/localeStore' +import { + ASSET, + drawnText, + insert, + point, + svgBytes, +} from '../helpers/editorFixtures' +import { + USER, + VERSION, + openReady, + resetStore, + sb, + store, + versionAnswer, +} from '../helpers/editorHarness' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() } +const named = (id: string, cx: number, cy: number, r: number) => + point(id, cx, cy, r) +const annotations = () => store.getState().previewState!.document.annotations +const geometryOf = (id: string) => + annotations().find((a: Annotation) => a.id === id)?.geometry + +/** Screen = drawing: the overlay's inverse CTM is the identity in the page under test. */ +function stubCtm(): void { + const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } + Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', { + configurable: true, + value: () => ({ ...identity, inverse: () => identity }), + }) +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + stubCtm() +}) +afterEach(() => { + cleanup() + resetStore() +}) + +const text = () => insert(drawnText(), named('anno-a', 50, 50, 5)) + +async function mount(options: { text?: string; readOnly?: boolean } = {}) { + await openReady({ text: options.text ?? text() }) + render() + const drawing = options.readOnly + ? 'catalogue-canvas-drawing' + : 'annotation-canvas-drawing' + await waitFor(() => + expect(screen.getByTestId(drawing).querySelector('svg')).not.toBeNull(), + ) +} + +async function selectFromList(name: RegExp | string = /N/) { + const list = await screen.findByRole('list', { + name: 'Annotations de la vue', + }) + await userEvent.setup().click(within(list).getAllByRole('button')[0]) + void name + return screen.findByTestId('annotation-properties') +} + +describe('selection and the list', () => { + it('lists the view annotations, selects one and shows its exact stored numbers', async () => { + await mount({ + text: insert(drawnText(), named('anno-a', 743.0451049804688, 50, 5)), + }) + const panel = await selectFromList() + expect(within(panel).getByLabelText('Centre x')).toHaveValue( + '743.0451049804688', + ) + expect(screen.getByTestId('annotation-selection-tag')).toHaveTextContent( + 'Sélection : point', + ) + }) +}) + +describe('a numeric edit', () => { + it('commits only when the typed number differs from the stored one', async () => { + await mount() + const panel = await selectFromList() + const user = userEvent.setup() + const version = store.getState().handleVersion + const cx = within(panel).getByLabelText('Centre x') + await user.click(cx) + await user.keyboard('{Enter}') + expect(store.getState().handleVersion).toBe(version) + await user.clear(cx) + await user.type(cx, '60{Enter}') + expect(geometryOf('anno-a')).toEqual({ + type: 'circle', + cx: 60, + cy: 50, + r: 5, + }) + expect(store.getState().handleVersion).toBe(version + 1) + }) + + it('keeps a refused value as « non appliqué » with the document unchanged, then applies a coherent set', async () => { + await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) }) + const panel = await selectFromList() + const user = userEvent.setup() + const before = store.getState().documentText + expect( + within(panel).getByTestId('annotation-geometry-issues'), + ).toBeInTheDocument() + const cx = within(panel).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '50{Enter}') + expect(store.getState().documentText).toBe(before) + expect(within(panel).getByText('non appliqué')).toBeInTheDocument() + expect( + within(panel).getByText(/Valeurs non appliquées/), + ).toBeInTheDocument() + expect( + within(panel).getByRole('button', { + name: 'Revenir aux valeurs enregistrées', + }), + ).toBeInTheDocument() + expect(within(panel).getByLabelText('Centre x')).toHaveValue('50') + const cy = within(panel).getByLabelText('Centre y') + await user.clear(cy) + await user.type(cy, '50{Enter}') + expect(geometryOf('anno-a')).toEqual({ + type: 'circle', + cx: 50, + cy: 50, + r: 5, + }) + expect(screen.queryByTestId('annotation-geometry-issues')).toBeNull() + }) + + it('reverts the group to the saved values', async () => { + await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) }) + const panel = await selectFromList() + const user = userEvent.setup() + const cx = within(panel).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '50{Enter}') + await user.click( + within(panel).getByRole('button', { + name: 'Revenir aux valeurs enregistrées', + }), + ) + expect(within(panel).getByLabelText('Centre x')).toHaveValue('150') + }) +}) + +async function fillCreation(user: ReturnType) { + const panel = await screen.findByTestId('annotation-creation') + await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque') + await user.type(within(panel).getByLabelText('Nom (EN)'), 'Poll') + await user.selectOptions( + within(panel).getByLabelText('Latéralité'), + 'unpaired', + ) + return panel +} + +describe('the keyboard creation path', () => { + it('holds a point at the frame centre, asks the required fields, then inserts once', async () => { + await mount({ text: drawnText() }) + const user = userEvent.setup() + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Ajouter un point' }), + ).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Ajouter un point' })) + const panel = await fillCreation(user) + expect(within(panel).getByLabelText('Centre x')).toHaveValue('50') + expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired') + expect(annotations()).toHaveLength(0) + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(annotations()).toHaveLength(1) + expect(annotations()[0]).toMatchObject({ + kind: 'point', + name: { fr: 'Nuque', en: 'Poll' }, + laterality: 'unpaired', + geometry: { type: 'circle', cx: 50, cy: 50 }, + }) + expect( + await screen.findByTestId('annotation-properties'), + ).toBeInTheDocument() + }) + + it('refuses a creation without laterality and creates nothing', async () => { + await mount({ text: drawnText() }) + const user = userEvent.setup() + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Ajouter une zone' }), + ).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Ajouter une zone' })) + const panel = await screen.findByTestId('annotation-creation') + await user.type(within(panel).getByLabelText('Nom (FR)'), 'A') + await user.type(within(panel).getByLabelText('Nom (EN)'), 'B') + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(within(panel).getByRole('alert')).toHaveTextContent( + 'Choisissez la catégorie et la latéralité', + ) + expect(annotations()).toHaveLength(0) + }) + + it('applies the geometry group to a pending zone, the core deciding at « Créer »', async () => { + await mount({ text: drawnText() }) + const user = userEvent.setup() + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Ajouter une zone' }), + ).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Ajouter une zone' })) + const panel = await fillCreation(user) + const x = within(panel).getByLabelText('x du sommet 1') + await user.clear(x) + await user.type(x, '500{Enter}') + expect(within(panel).getByLabelText('x du sommet 1')).toHaveValue('500') + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(annotations()).toHaveLength(0) + expect(within(panel).getByRole('alert')).toBeInTheDocument() + expect(within(panel).getByLabelText('x du sommet 1')).toHaveValue('500') + }) +}) + +describe('the point tool and the corrected position (C26)', () => { + async function clickCorner() { + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Point' })) + fireEvent.click(screen.getByTestId('annotation-canvas'), { + clientX: 0, + clientY: 0, + }) + return user + } + + it('proposes C with the click marked apart, inserts it only on confirmation', async () => { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(), + ) + const user = await clickCorner() + const notice = await screen.findByTestId('correction-notice') + expect(notice).toHaveTextContent( + 'Position corrigée proposée : x = 15, y = 15.', + ) + expect(screen.getByTestId('overlay-click-cross')).toBeInTheDocument() + const panel = await fillCreation(user) + expect(annotations()).toHaveLength(0) + await user.click( + within(notice).getByRole('button', { name: 'Utiliser cette position' }), + ) + expect(geometryOf(annotations()[0].id)).toEqual({ + type: 'circle', + cx: 15, + cy: 15, + r: 15, + }) + expect(panel).not.toBeInTheDocument() + expect(screen.queryByTestId('overlay-click-cross')).toBeNull() + const props = await screen.findByTestId('annotation-properties') + expect(within(props).getByLabelText('Centre x')).toHaveValue('15') + }) + + it('keeps the pending point at the click when the correction is cancelled', async () => { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(), + ) + const user = await clickCorner() + const notice = await screen.findByTestId('correction-notice') + await user.click(within(notice).getByRole('button', { name: 'Annuler' })) + expect(screen.queryByTestId('correction-notice')).toBeNull() + expect(screen.queryByTestId('overlay-click-cross')).toBeNull() + const panel = screen.getByTestId('annotation-creation') + expect(within(panel).getByLabelText('Centre x')).toHaveValue('0') + expect(annotations()).toHaveLength(0) + }) + + it('offers the correction when the core refuses a pending point', async () => { + await mount({ text: drawnText() }) + const user = userEvent.setup() + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Ajouter un point' }), + ).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Ajouter un point' })) + const panel = await fillCreation(user) + const cx = within(panel).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '98{Enter}') + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(await screen.findByTestId('correction-notice')).toHaveTextContent( + 'x = 85', + ) + expect(annotations()).toHaveLength(0) + }) + + it('says to click inside the drawing, and proposes nothing, outside the frame', async () => { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(), + ) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Point' })) + fireEvent.click(screen.getByTestId('annotation-canvas'), { + clientX: -5, + clientY: 50, + }) + expect( + await screen.findByText("Cliquez à l'intérieur du dessin."), + ).toBeInTheDocument() + expect(screen.queryByTestId('annotation-creation')).toBeNull() + }) +}) + +function marker(id: string): Element { + const found = screen + .getByTestId('annotation-canvas-drawing') + .querySelector(`[data-anno-id="${id}"]`) + if (!found) throw new Error(`no marker ${id}`) + return found +} + +describe('select and move gestures (C34)', () => { + const down = (el: Element, x: number, y: number) => + fireEvent.pointerDown(el, { + clientX: x, + clientY: y, + button: 0, + pointerId: 1, + }) + const moveTo = (el: Element, x: number, y: number) => + fireEvent.pointerMove(el, { clientX: x, clientY: y, pointerId: 1 }) + const up = (el: Element, x: number, y: number) => + fireEvent.pointerUp(el, { clientX: x, clientY: y, pointerId: 1 }) + + async function selected() { + await mount() + await selectFromList() + return marker('anno-a') + } + + it('treats a press and release under 4 px as a click: nothing is committed', async () => { + const hit = await selected() + const version = store.getState().handleVersion + down(hit, 50, 50) + moveTo(hit, 52, 51) + up(hit, 52, 51) + expect(store.getState().handleVersion).toBe(version) + expect(geometryOf('anno-a')).toEqual({ + type: 'circle', + cx: 50, + cy: 50, + r: 5, + }) + }) + + it('moves the selected circle as a block after 4 px, in one update rounded to 2 decimals', async () => { + const hit = await selected() + const version = store.getState().handleVersion + down(hit, 50, 50) + moveTo(hit, 58, 50) + expect(screen.getByTestId('annotation-overlay')).toBeInTheDocument() + up(hit, 60.004, 40) + expect(geometryOf('anno-a')).toEqual({ + type: 'circle', + cx: 60, + cy: 40, + r: 5, + }) + expect(store.getState().handleVersion).toBe(version + 1) + }) + + it('rolls a drop half out of the frame back, with the core message', async () => { + const hit = await selected() + const before = store.getState().documentText + down(hit, 50, 50) + moveTo(hit, 90, 50) + up(hit, 98, 50) + expect(store.getState().documentText).toBe(before) + expect(await screen.findByRole('alert')).toBeInTheDocument() + }) + + it('drops the drag on pointer cancel with no command', async () => { + const hit = await selected() + const version = store.getState().handleVersion + down(hit, 50, 50) + moveTo(hit, 70, 50) + fireEvent.pointerCancel(hit, { pointerId: 1 }) + up(hit, 70, 50) + expect(store.getState().handleVersion).toBe(version) + }) + + it('does not move an annotation that is not selected', async () => { + await mount() + const hit = marker('anno-a') + const version = store.getState().handleVersion + down(hit, 50, 50) + moveTo(hit, 70, 50) + up(hit, 70, 50) + expect(store.getState().handleVersion).toBe(version) + }) +}) + +describe('an unmeasured view (C32)', () => { + async function mountMissing() { + const drawing = svgBytes() + sb.getSheetVersion.mockResolvedValue({ + ...versionAnswer(text(), 3), + drawings: [], + } as never) + sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes) + store.getState().open(VERSION, USER, { canEdit: true }) + await waitFor(() => expect(store.getState().status).toBe('ready')) + render() + void ASSET + } + + it('disables every tool and add button, shows the hint, keeps the annotation selectable read-only', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + await mountMissing() + for (const name of [ + 'Point', + 'Zone', + 'Accès à une vue détaillée', + 'Ajouter un point', + 'Ajouter une zone', + 'Ajouter un accès', + ]) { + expect(screen.getByRole('button', { name })).toBeDisabled() + } + expect( + screen.getAllByText(/Ce dessin n'est pas mesurable/).length, + ).toBeGreaterThan(0) + const panel = await selectFromList() + expect( + within(panel).queryByRole('textbox', { name: 'Centre x' }), + ).toBeNull() + expect( + within(panel).getByText('Centre x', { exact: false }), + ).toBeInTheDocument() + expect( + within(panel).getByText(/Ce dessin n'est pas mesurable/), + ).toBeInTheDocument() + }) +}) + +describe('tools and categories', () => { + it('disables the drawing tools until an annotation category exists', async () => { + const bare = JSON.parse(drawnText()) + bare.categories = [] + await mount({ text: JSON.stringify(bare) }) + expect(screen.getByRole('button', { name: 'Point' })).toBeDisabled() + expect( + screen.getByText( + "Créez d'abord une catégorie d'annotation (onglet Général).", + ), + ).toBeInTheDocument() + }) + + it('enables the link tool only when the view has a direct detail child', async () => { + await mount({ text: drawnText() }) + expect( + screen.getByRole('button', { name: 'Accès à une vue détaillée' }), + ).toBeDisabled() + expect( + screen.getByRole('button', { name: 'Ajouter un accès' }), + ).toBeDisabled() + }) + + it('undoes and redoes through the tool column', async () => { + await mount() + await selectFromList() + const user = userEvent.setup() + const cx = within( + screen.getByTestId('annotation-properties'), + ).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '60{Enter}') + await user.click(screen.getByRole('button', { name: 'Annuler' })) + expect(geometryOf('anno-a')).toMatchObject({ cx: 50 }) + await user.click(screen.getByRole('button', { name: 'Rétablir' })) + expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + }) +}) + +describe('read-only', () => { + it('browses the annotations with no tool, no add button and the fields as text', async () => { + await mount({ readOnly: true }) + expect(screen.queryByRole('button', { name: 'Point' })).toBeNull() + expect( + screen.queryByRole('button', { name: 'Ajouter un point' }), + ).toBeNull() + const panel = await selectFromList() + expect(within(panel).queryByRole('textbox')).toBeNull() + expect( + within(panel).queryByRole('button', { name: 'Supprimer' }), + ).toBeNull() + }) +}) + +const triangle = [ + [20, 20], + [80, 20], + [50, 80], +] +const zoneAnnotation = (geometry: object): Annotation => + ({ + ...(point('zone-a', 0, 0, 1).value as Annotation), + kind: 'zone', + geometry, + }) as Annotation + +describe('tracing a zone or a link', () => { + const clickAt = (x: number, y: number) => + fireEvent.click(screen.getByTestId('annotation-canvas'), { + clientX: x, + clientY: y, + }) + + it('closes on Enter, holds the polygon pending, inserts it on « Créer »', async () => { + await mount({ text: drawnText() }) + const user = userEvent.setup() + await waitFor(() => + expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Zone' })) + triangle.forEach(([x, y]) => clickAt(x, y)) + expect( + screen.getByRole('button', { name: 'Fermer le tracé' }), + ).toBeEnabled() + fireEvent.keyDown(screen.getByTestId('annotation-canvas'), { key: 'Enter' }) + const panel = await fillCreation(user) + expect(within(panel).getByLabelText('x du sommet 3')).toHaveValue('50') + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(annotations()[0]).toMatchObject({ + kind: 'zone', + geometry: { type: 'polygon', points: triangle }, + }) + }) + + it('drops the tracing on Escape with nothing created', async () => { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(), + ) + await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' })) + clickAt(20, 20) + expect(screen.getByText('1 sommet(s) posé(s).')).toBeInTheDocument() + fireEvent.keyDown(screen.getByTestId('annotation-canvas'), { + key: 'Escape', + }) + expect(screen.queryByText('1 sommet(s) posé(s).')).toBeNull() + expect(annotations()).toHaveLength(0) + }) + + it('closes on a click at the first vertex once three are placed', async () => { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(), + ) + await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' })) + triangle.forEach(([x, y]) => clickAt(x, y)) + clickAt(20.5, 20) + expect(await screen.findByTestId('annotation-creation')).toBeInTheDocument() + }) + + it('links only to a detail view directly under this one', async () => { + const withView = insert(drawnText(), { + kind: 'view', + value: { + kind: 'detail', + id: 'view-det', + name: { fr: 'Tête', en: 'Head' }, + svg_asset_id: null, + view_box: { min_x: 10, min_y: 10, width: 80, height: 80 }, + parent_view_id: 'view-main', + }, + }) + await mount({ text: withView }) + const user = userEvent.setup() + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Accès à une vue détaillée' }), + ).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Ajouter un accès' })) + const panel = await fillCreation(user) + const opens = within(panel).getByLabelText('Vue ouverte') + expect( + within(opens) + .getAllByRole('option') + .map((o) => o.textContent), + ).toEqual(['Choisir…', 'Tête']) + await user.selectOptions(opens, 'view-det') + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(annotations()[0]).toMatchObject({ + kind: 'detail_trigger', + opens_view_id: 'view-det', + }) + }) +}) + +describe('polygons and paths', () => { + const zoneText = (geometry: object) => + insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) }) + + it('adds and removes a vertex as part of the whole group', async () => { + await mount({ text: zoneText({ type: 'polygon', points: triangle }) }) + const panel = await selectFromList() + const user = userEvent.setup() + await user.click(within(panel).getByLabelText('x du sommet 1')) + await user.click( + within(panel).getByRole('button', { name: 'Ajouter un sommet' }), + ) + expect(geometryOf('zone-a')).toMatchObject({ + points: [ + [20, 20], + [50, 20], + [80, 20], + [50, 80], + ], + }) + await user.click(within(panel).getByRole('button', { name: 'Retirer' })) + expect(geometryOf('zone-a')).toMatchObject({ + points: triangle.slice(0, 3).map((p, i) => (i === 0 ? [50, 20] : p)), + }) + }) + + it('never offers to remove a vertex below three', async () => { + await mount({ text: zoneText({ type: 'polygon', points: triangle }) }) + const panel = await selectFromList() + expect( + within(panel).getByRole('button', { name: 'Retirer' }), + ).toBeDisabled() + }) + + it('moves a selected polygon as a block', async () => { + await mount({ text: zoneText({ type: 'polygon', points: triangle }) }) + await selectFromList() + const hit = screen + .getByTestId('annotation-canvas-drawing') + .querySelector('[data-anno-id="zone-a"]')! + fireEvent.pointerDown(hit, { + clientX: 50, + clientY: 40, + button: 0, + pointerId: 1, + }) + fireEvent.pointerMove(hit, { clientX: 55, clientY: 40, pointerId: 1 }) + fireEvent.pointerUp(hit, { clientX: 60, clientY: 45, pointerId: 1 }) + expect(geometryOf('zone-a')).toMatchObject({ + points: [ + [30, 25], + [90, 25], + [60, 85], + ], + }) + }) + + it('replaces a path by a traced polygon and never shows its data', async () => { + await mount({ + text: zoneText({ type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }), + }) + const panel = await selectFromList() + expect(within(panel).queryByText(/M 20 20/)).toBeNull() + await userEvent + .setup() + .click( + within(panel).getByRole('button', { + name: 'Remplacer par un polygone', + }), + ) + const canvas = screen.getByTestId('annotation-canvas') + triangle.forEach(([x, y]) => + fireEvent.click(canvas, { clientX: x, clientY: y }), + ) + fireEvent.keyDown(canvas, { key: 'Enter' }) + await waitFor(() => + expect(geometryOf('zone-a')).toEqual({ + type: 'polygon', + points: triangle, + }), + ) + }) +}) + +describe('keyboard shortcuts', () => { + it('undoes with Ctrl+Z outside a text field and not inside one', async () => { + await mount() + await selectFromList() + const user = userEvent.setup() + const cx = within( + screen.getByTestId('annotation-properties'), + ).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '60{Enter}') + fireEvent.keyDown(cx, { key: 'z', ctrlKey: true }) + expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true }) + expect(geometryOf('anno-a')).toMatchObject({ cx: 50 }) + fireEvent.keyDown(document.body, { + key: 'z', + ctrlKey: true, + shiftKey: true, + }) + expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + }) +}) diff --git a/apps/app/tests/unit/editor-frame.test.ts b/apps/app/tests/unit/editor-frame.test.ts new file mode 100644 index 00000000..5342f41d --- /dev/null +++ b/apps/app/tests/unit/editor-frame.test.ts @@ -0,0 +1,278 @@ +/** Lot H: the proposal arithmetic (pure) and the core's verdict on each proposal (C26). */ +import { describe, expect, it } from 'vitest' +import { + attemptPoint, + correctionFor, + confirmCorrection, +} from '@/editor/annotations/correction' +import { + centreCircle, + centreTriangle, + correctedCircle, + defaultRadius, + parseFrame, + proposePoint, + type Frame, +} from '@/editor/annotations/frame' +import { + bed, + circleInserter, + currentErrors, + drawnText, + frameOf, + withCrop, +} from '../helpers/annotationsCore' + +const f = (x: number, y: number, w: number, h: number): Frame => ({ + x, + y, + w, + h, +}) + +describe('parseFrame', () => { + it('reads the attribute text with Number, origin offsets kept', () => { + expect(parseFrame('-50 20 40 30')).toEqual(f(-50, 20, 40, 30)) + expect(parseFrame('0,0,10.5,10')).toEqual(f(0, 0, 10.5, 10)) + expect(parseFrame('743.0451049804688 0 10 10')?.x).toBe(743.0451049804688) + }) + + it('gives no frame for anything but four finite numbers over a positive span', () => { + for (const text of [ + null, + '', + '0 0 100', + '0 0 a 5', + '0 0 0 5', + '0 0 5 -1', + '0 0 Infinity 5', + ]) { + expect(parseFrame(text)).toBeNull() + } + }) +}) + +describe('defaultRadius', () => { + it('is min(12 + 0.03 max, min / 2) floored to 0.01', () => { + expect(defaultRadius(f(0, 0, 40, 30))).toBe(13.2) + expect(defaultRadius(f(0, 0, 500, 380))).toBe(27) + expect(defaultRadius(f(0, 0, 20, 20))).toBe(10) + expect(defaultRadius(f(0, 0, 1000, 30))).toBe(15) + expect(defaultRadius(f(0, 0, 1, 1))).toBe(0.5) + expect(defaultRadius(f(0, 0, 0.0299, 5))).toBe(0.01) + }) +}) + +describe('proposePoint', () => { + const frame = f(0, 0, 40, 30) + + it('keeps the click with r0 when it is r0 or more from every edge (A)', () => { + expect(proposePoint(frame, { x: 20.004, y: 15.006 })).toEqual({ + kind: 'circle', + circle: { cx: 20, cy: 15.01, r: 13.2 }, + shrunk: false, + }) + expect(proposePoint(frame, { x: 13.2, y: 15 })).toMatchObject({ + shrunk: false, + }) + }) + + it('keeps the click with a smaller radius when it is nearer an edge (B)', () => { + expect(proposePoint(frame, { x: 13.19, y: 15 })).toEqual({ + kind: 'circle', + circle: { cx: 13.19, cy: 15, r: 13.19 }, + shrunk: true, + }) + expect(proposePoint(frame, { x: 5.555, y: 15 })).toMatchObject({ + circle: { cx: 5.56, r: 5.56 }, + }) + }) + + it('goes straight to C when B would be under 0.01, and nothing outside F', () => { + expect(proposePoint(frame, { x: 0, y: 0 }).kind).toBe('corrected') + expect(proposePoint(frame, { x: 40, y: 15 }).kind).toBe('corrected') + expect(proposePoint(frame, { x: 0.004, y: 15 }).kind).toBe('corrected') + expect(proposePoint(frame, { x: -0.1, y: 15 })).toEqual({ kind: 'outside' }) + expect(proposePoint(frame, { x: 20, y: 30.01 })).toEqual({ + kind: 'outside', + }) + }) +}) + +describe('correctedCircle (C)', () => { + it('clamps per axis with r0, inward on the hundredth grid', () => { + expect(correctedCircle(f(0, 0, 40, 30), { x: 0, y: 0 })).toEqual({ + cx: 13.2, + cy: 13.2, + r: 13.2, + }) + expect(correctedCircle(f(0, 0, 40, 30), { x: 40, y: 30 })).toEqual({ + cx: 26.8, + cy: 16.8, + r: 13.2, + }) + expect(correctedCircle(f(0.003, 0, 40, 30), { x: 0.003, y: 15 }).cx).toBe( + 13.21, + ) + }) + + it('uses the exact clamped value when the grid leaves an empty interval', () => { + const frame = f(0.003, 0.004, 20, 20) + expect(correctedCircle(frame, { x: 0.003, y: 0.004 })).toEqual({ + cx: 10.003, + cy: 10.004, + r: 10, + }) + }) +}) + +describe('keyboard proposals', () => { + it('holds a point at the centre of F with r0 and a triangle of 10 % of the smaller side', () => { + expect(centreCircle(f(-50, 20, 40, 30))).toEqual({ + cx: -30, + cy: 35, + r: 13.2, + }) + expect(centreTriangle(f(0, 0, 100, 50))).toEqual([ + [50, 22.5], + [52.5, 27.5], + [47.5, 27.5], + ]) + }) +}) + +describe('correctionFor', () => { + const frame = f(0, 0, 40, 30) + + it('offers C for a refused B or an A refused out_of_frame, never for A too_small', () => { + const reduced = { cx: 13.19, cy: 15, r: 13.19 } + expect( + correctionFor(frame, reduced, ['annotation.geometry.too_small']), + ).not.toBeNull() + const edge = { cx: 5, cy: 15, r: 13.2 } + expect( + correctionFor(frame, edge, ['annotation.geometry.out_of_frame'])?.circle + .cx, + ).toBe(13.2) + expect( + correctionFor(frame, { cx: 20, cy: 15, r: 13.2 }, [ + 'annotation.geometry.too_small', + ]), + ).toBeNull() + }) + + it('offers nothing when C is the circle that was just refused', () => { + const circle = { cx: 13.2, cy: 13.2, r: 13.2 } + expect( + correctionFor(frame, circle, ['annotation.geometry.out_of_frame']), + ).toBeNull() + }) +}) + +const FRAMES = [ + '0 0 40 30', + '0 0 20 20', + '0 0 100 300', + '0 0 500 380', + '0 0 640 480', + '0 0 200 150', + '0 0 4000 200', + '-50 20 40 30', + '0.003 0.004 20 20', + '1040000 1040000 8000 6000', +] + +function clicksOf(frame: Frame) { + const r0 = defaultRadius(frame) + const mid = { x: frame.x + frame.w / 2, y: frame.y + frame.h / 2 } + const right = frame.x + frame.w + const bottom = frame.y + frame.h + return [ + { x: frame.x, y: frame.y }, + { x: right, y: frame.y }, + { x: frame.x, y: bottom }, + { x: right, y: bottom }, + { x: mid.x, y: frame.y }, + { x: mid.x, y: bottom }, + { x: frame.x, y: mid.y }, + { x: right, y: mid.y }, + mid, + { x: frame.x + r0, y: mid.y }, + { x: frame.x + r0 - 0.005, y: mid.y }, + ] +} + +describe.each(FRAMES)('a point placed in the frame %s', (viewBox) => { + it('is created or corrected for every click, and the core never keeps an invalid one', () => { + const frame = frameOf(bed(viewBox))! + for (const click of clicksOf(frame)) { + const b = bed(viewBox) + const proposal = proposePoint(frame, click) + expect(proposal.kind).not.toBe('outside') + if (proposal.kind === 'outside') continue + const insert = circleInserter(b) + const attempt = attemptPoint(frame, proposal.circle, insert) + expect(attempt).toMatchObject({ status: 'created' }) + expect(currentErrors(b).size).toBe(0) + } + }) + + it('a corrected proposal is inserted only through the confirmation', () => { + const frame = frameOf(bed(viewBox))! + const proposal = proposePoint(frame, { x: frame.x, y: frame.y }) + if (proposal.kind !== 'corrected') + throw new Error('corner must be corrected') + const b = bed(viewBox) + const correction = { + click: { x: frame.x, y: frame.y }, + circle: proposal.circle, + } + expect(b.preview.state()).toMatchObject({ ok: true }) + expect(b.state.document.annotations).toHaveLength(0) + expect(confirmCorrection(correction, circleInserter(b))).toMatchObject({ + status: 'created', + }) + const kept = b.preview.state() + if (!kept.ok) throw new Error('state') + expect(kept.value.document.annotations[0].geometry).toEqual({ + type: 'circle', + ...proposal.circle, + }) + }) +}) + +describe('a very elongated frame', () => { + it('refuses 1000 × 30 on too_small with the core message and creates nothing', () => { + const b = bed('0 0 1000 30') + const frame = frameOf(b)! + const proposal = proposePoint(frame, { x: 500, y: 15 }) + if (proposal.kind !== 'circle') throw new Error('proposal') + const attempt = attemptPoint(frame, proposal.circle, circleInserter(b)) + expect(attempt.status).toBe('refused') + expect(b.preview.document).toBe(b.text) + }) +}) + +describe('a detail crop', () => { + const crop = { min_x: 100, min_y: 200, width: 100, height: 300 } + const cropBed = () => bed('0 0 1000 1000', withCrop(drawnText(), crop)) + + it('takes F from the composed root of the crop, origin offsets kept', () => { + expect(frameOf(cropBed(), 'view-det')).toEqual(f(100, 200, 100, 300)) + }) + + it('places a point inside the crop and corrects one on its edge, never outside it', () => { + const b = cropBed() + const frame = frameOf(b, 'view-det')! + const inside = proposePoint(frame, { x: 150, y: 350 }) + if (inside.kind !== 'circle') throw new Error('proposal') + const insert = circleInserter(b, 'view-det') + expect(attemptPoint(frame, inside.circle, insert)).toMatchObject({ + status: 'created', + }) + expect(proposePoint(frame, { x: 99, y: 350 })).toEqual({ kind: 'outside' }) + const edge = proposePoint(frame, { x: 100, y: 200 }) + expect(edge.kind).toBe('corrected') + expect(currentErrors(b).size).toBe(0) + }) +}) diff --git a/apps/app/tests/unit/editor-route-recovery.test.tsx b/apps/app/tests/unit/editor-route-recovery.test.tsx index 4fc6b73d..1e27c789 100644 --- a/apps/app/tests/unit/editor-route-recovery.test.tsx +++ b/apps/app/tests/unit/editor-route-recovery.test.tsx @@ -235,7 +235,9 @@ describe('cap and quota', () => { await screen.findByText(fr['editor.draft.status.copy_cap']), ).toBeInTheDocument() expect(storedCopy()).toBeNull() - const items = screen.getAllByRole('listitem') + const items = screen + .getAllByRole('listitem') + .filter((item) => /Autre fiche/.test(item.textContent ?? '')) expect(items).toHaveLength(2) expect( within(items[0]).getByText(/Autre fiche · révision 5 · \d\d:\d\d/), diff --git a/apps/app/tests/unit/editor-route.test.tsx b/apps/app/tests/unit/editor-route.test.tsx index 6b48361b..ff2212e9 100644 --- a/apps/app/tests/unit/editor-route.test.tsx +++ b/apps/app/tests/unit/editor-route.test.tsx @@ -167,7 +167,8 @@ describe('tabs', () => { 'Vérification', ]) await user.click(screen.getByRole('button', { name: 'Plus' })) - const rest = within(screen.getByRole('list')).getAllByRole('button') + const more = document.getElementById('editor-tabs-more') as HTMLElement + const rest = within(more).getAllByRole('button') expect(rest.map((b) => b.textContent)).toEqual([ 'Général', 'Vues et illustrations', diff --git a/docs/ANNOTATION-RENDERING.md b/docs/ANNOTATION-RENDERING.md index ed706231..afde3e2a 100644 --- a/docs/ANNOTATION-RENDERING.md +++ b/docs/ANNOTATION-RENDERING.md @@ -133,6 +133,25 @@ The application stylesheet: `.svg-canvas [data-state='current']` fills the selected markers with the accent colour at 0.85, every `[data-anno-id]` shows a pointer cursor and brightens on hover. +## Editor overlay (V1-2.6) + +The draft editor (admin, tab Annotations and the crop rectangle of tab Views) +puts a second `` over the core's composed view, inside the same transformed +container, with the composed root's own `viewBox` and `preserveAspectRatio` (the +attribute text, read with `Number`, never `viewBox.baseVal`). It draws no +annotation: the markers stay the core's (`view.canvas`) and the drawing is never +modified. The overlay holds numbers only, drawn from the editor's state: the +selection outline (dashed), the vertex circles, the tracing in progress, the +pending or dragged outline, the hollow cross of a corrected position and the +crop rectangle. It sets `pointer-events: none` on its own shapes; the pointer +is read on the canvas box and mapped to drawing units through the overlay's +`getScreenCTM().inverse()`. No overlay shape carries `data-anno-id`, so click +targeting still reads the core's markers only. + +The overlay only proposes geometry. Whether a position, a radius or a polygon +is acceptable (frame, minimum visible size, interior) is the core's verdict on +the candidate document; the page keeps no copy of those rules. + ## PDF highlight The engine composes the observation's zones of one view: the markers of the