feat(app): editor Annotations tab, core-decided placement, repair rules

This commit is contained in:
bchanot committed 2026-11-04 13:49:41 +01:00
1 parent 92c595caa1
commit 26097852ff
37 files changed
+5001 -6

No files matched your search

@@ -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 |
@@ -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<ToolColumnProps, 'onZoomIn' | 'onZoomOut' | 'onFit'>
/** 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<SVGSVGElement | null>(null)
const viewport = useRef<HTMLDivElement | null>(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 (
<div className="flex flex-col gap-2 lg:flex-row">
<ToolColumn
{...props.tools}
onZoomIn={framing.zoomIn}
onZoomOut={framing.zoomOut}
onFit={framing.reset}
/>
<div className="relative min-w-0 flex-1 overflow-hidden rounded-xl border border-[var(--color-border)] bg-white">
<div
ref={viewport}
tabIndex={0}
role="group"
aria-label={props.viewName}
data-testid="annotation-canvas"
className={`svg-canvas aspect-[4/3] w-full select-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] ${
props.tool === 'select' ? 'cursor-grab' : 'cursor-crosshair'
}`}
style={{ touchAction: touchNone ? 'none' : 'pan-x pan-y' }}
onClick={onClick}
{...handlers}
>
<DrawingLayer
host={build.host}
root={build.root}
transform={transformOf(framing.framing)}
overlay={{
...props.overlay,
svgRef: overlayRef,
dragged: move.preview,
}}
/>
</div>
<CanvasFailure failure={build.failure} retry={build.retry} />
</div>
</div>
)
}
/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */
function DrawingLayer({
host,
root,
transform,
overlay,
}: {
host: React.RefObject<HTMLDivElement | null>
root: RootAttributes | null
transform: string
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
}) {
return (
<div
className="relative h-full w-full origin-top-left"
style={{ transform }}
>
<div
ref={host}
data-testid="annotation-canvas-drawing"
className="h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
/>
{root?.viewBox && (
<AnnotationOverlay
{...overlay}
viewBox={root.viewBox}
ratio={root.ratio}
/>
)}
</div>
)
}
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<typeof useFraming>['handlers'],
b: ReturnType<typeof useMoveGesture>['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 (
<div className="absolute inset-0 grid place-items-center bg-[var(--color-surface)] p-4">
<div className="max-w-sm space-y-3">
<Notice tone="error">
{failure === 'view'
? t('catalogue.failure.view')
: coreFailureMessage(t, 'sheet.core_unavailable')}
</Notice>
{failure === 'engine' && !stopped && (
<Button onClick={retry}>{t('sheet.core_retry')}</Button>
)}
</div>
</div>
)
}
@@ -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<string, unknown>) =>
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) => (
<TextField
key={locale}
id={`annotation-name-${locale}`}
label={t(`editor.annotations.name_${locale}`)}
value={annotation.name?.[locale] ?? ''}
onCommit={rename(locale)}
readOnly={readOnly}
error={edit.fieldError(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 (
<div className="grid gap-3 sm:grid-cols-2">
<NameFields {...props} />
<SelectField
id="annotation-category"
label={t('editor.annotations.category')}
value={annotation.category_id}
options={categories}
onCommit={(value) => send('category', { category_id: value })}
readOnly={readOnly}
error={edit.fieldError('category')}
/>
<TextField
id="annotation-color"
label={t('editor.annotations.color')}
value={annotation.color ?? ''}
onCommit={(value) => send('color', { color: nullable(value) })}
readOnly={readOnly}
hint={t('editor.annotations.color_hint')}
error={edit.fieldError('color')}
/>
<SelectField
id="annotation-laterality"
label={t('editor.annotations.laterality')}
value={annotation.laterality}
options={sides}
onCommit={(value) => send('laterality', { laterality: value })}
readOnly={readOnly}
error={edit.fieldError('laterality')}
/>
{annotation.kind === 'detail_trigger' ? (
<OpensField {...props} />
) : (
<LinkFields {...props} annotation={annotation} />
)}
</div>
)
}
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 (
<SelectField
id="annotation-opens"
label={t('editor.annotations.opens')}
value={annotation.opens_view_id}
options={options}
onCommit={(value) => 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 (
<>
<SelectField
id="annotation-region"
label={t('editor.annotations.region')}
value={annotation.vertebral_region_code ?? ''}
options={regions}
onCommit={(value) =>
send('region', { vertebral_region_code: nullable(value) })
}
readOnly={readOnly}
error={edit.fieldError('region')}
/>
<SelectField
id="annotation-zone"
label={t('editor.annotations.zone')}
value={annotation.finding_zone_id ?? ''}
options={zones}
onCommit={(value) => send('zone', { finding_zone_id: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('zone')}
/>
</>
)
}
@@ -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 (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.list_empty')}
</p>
)
}
return (
<ul
aria-label={t('editor.annotations.list')}
className="max-h-64 divide-y divide-[var(--color-border)] overflow-y-auto rounded-lg border border-[var(--color-border)]"
>
{annotations.map((annotation) => (
<li key={annotation.id}>
<button
type="button"
aria-current={annotation.id === selectedId}
onClick={() => onSelect(annotation.id)}
className={`flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] ${
annotation.id === selectedId
? 'bg-[var(--color-surface-strong)]'
: ''
}`}
>
<span className="min-w-0 truncate">
<span className="text-[var(--color-ink-muted)]">
{t(`editor.annotations.kind.${annotation.kind}`)}
</span>{' '}
{annotationName(annotation, views, locale)}
</span>
<ReviewBadge status={annotation.review_status} />
</button>
</li>
))}
</ul>
)
}
@@ -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<SVGSVGElement>
/** 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 (
<circle cx={geometry.cx} cy={geometry.cy} r={geometry.r} {...style} />
)
}
if (geometry.type === 'polygon') {
return <polygon points={geometry.points.join(' ')} {...style} />
}
return null
}
function Vertices({ geometry, size }: { geometry: Geometry; size: number }) {
if (geometry.type !== 'polygon') return null
return (
<>
{geometry.points.map(([x, y], index) => (
<circle
key={index}
cx={x}
cy={y}
r={size}
fill="white"
stroke="var(--color-ink)"
strokeWidth={1.5}
vectorEffect="non-scaling-stroke"
/>
))}
</>
)
}
/** 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 (
<g data-testid="overlay-click-cross">
<path
d={`M ${at.x - size} ${at.y - size} L ${at.x + size} ${at.y + size}`}
{...style}
/>
<path
d={`M ${at.x - size} ${at.y + size} L ${at.x + size} ${at.y - size}`}
{...style}
/>
</g>
)
}
function TracingPath({ points, size }: { points: Point[]; size: number }) {
if (points.length === 0) return null
const shape: Geometry = { type: 'polygon', points }
return (
<>
<polyline
points={points.join(' ')}
{...STROKE}
stroke="var(--color-accent)"
strokeWidth={2}
strokeDasharray="6 4"
/>
<Vertices geometry={shape} size={size} />
</>
)
}
/**
* 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 (
<svg
ref={props.svgRef}
aria-hidden="true"
data-testid="annotation-overlay"
viewBox={props.viewBox}
preserveAspectRatio={props.ratio}
className="pointer-events-none absolute inset-0 h-full w-full"
>
{shown && isEditable(shown) && (
<>
<Outline geometry={shown} dashed colour="var(--color-ink)" />
<Vertices geometry={shown} size={size} />
</>
)}
{pending && (
<Outline
geometry={pending}
dashed={false}
colour="var(--color-accent)"
/>
)}
{correction && (
<>
<Outline
geometry={{ type: 'circle', ...correction.circle }}
dashed
colour="var(--color-accent)"
/>
<HollowCross at={correction.click} size={size * 1.5} />
</>
)}
{tracing && <TracingPath points={tracing} size={size} />}
</svg>
)
}
@@ -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 (
<Notice tone="info">
<div className="space-y-2" data-testid="correction-notice">
<p>{message}</p>
<div className="flex gap-2">
<Button type="button" size="sm" onClick={onConfirm}>
{t('editor.annotations.correction_use')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
onClick={onCancel}
>
{t('editor.annotations.correction_cancel')}
</Button>
</div>
</div>
</Notice>
)
}
@@ -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<UiAction>
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<CreationForm>(() => emptyForm(doc))
const [messages, setMessages] = useState<string[]>([])
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 (
<section
aria-label={t(`editor.annotations.new.${pending.kind}`)}
data-testid="annotation-creation"
className="space-y-3 rounded-xl border border-[var(--color-border)] p-4"
>
<h3 className="text-base font-semibold">
{t(`editor.annotations.new.${pending.kind}`)}
</h3>
<CreationFields
kind={pending.kind}
viewId={props.viewId}
form={form}
doc={doc}
onChange={(patch) => setForm({ ...form, ...patch })}
/>
<GeometryGroup
idPrefix="creation"
geometry={pending.geometry}
onApply={setGeometry}
locked={false}
/>
{pending.correction && (
<CorrectionNotice
correction={pending.correction}
onConfirm={() =>
settle(confirmAttempt(props, form, pending.correction!))
}
onCancel={() => update({ ...pending, correction: null })}
/>
)}
<Messages messages={messages} />
<div className="flex gap-2">
<Button
type="button"
onClick={() => settle(createAttempt(props, form, words))}
>
{t('editor.annotations.create')}
</Button>
<Button
type="button"
variant="secondary"
onClick={() => dispatch({ type: 'pending_drop' })}
>
{t('editor.annotations.create_cancel')}
</Button>
</div>
</section>
)
}
function Messages({ messages }: { messages: string[] }) {
if (messages.length === 0) return null
return (
<div
role="alert"
className="space-y-1 text-sm text-[var(--color-danger-strong)]"
>
{messages.map((message) => (
<p key={message}>{message}</p>
))}
</div>
)
}
interface FieldsProps {
doc: AnatomicalSheetDocument
form: CreationForm
onChange: (patch: Partial<CreationForm>) => 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 (
<FormField id={id} label={label}>
<Select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
{blank && <option value="">{t('editor.field.choose')}</option>}
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Select>
</FormField>
)
}
/** 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 (
<div className="grid gap-3 sm:grid-cols-2">
<DraftField
id="creation-fr"
label={t('editor.annotations.name_fr')}
value={form.fr}
onChange={(fr) => onChange({ fr })}
/>
<DraftField
id="creation-en"
label={t('editor.annotations.name_en')}
value={form.en}
onChange={(en) => onChange({ en })}
/>
<OptionSelect
id="creation-category"
label={t('editor.annotations.category')}
value={form.categoryId}
options={categories}
blank={false}
onChange={(categoryId) => onChange({ categoryId })}
/>
<OptionSelect
id="creation-laterality"
label={t('editor.annotations.laterality')}
value={form.laterality}
options={sides}
blank
onChange={(laterality) =>
onChange({ laterality: laterality as CreationForm['laterality'] })
}
/>
{kind === 'detail_trigger' ? (
<OpensSelect {...fields} viewId={viewId} />
) : (
<LinkSelects {...fields} />
)}
</div>
)
}
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 (
<OptionSelect
id="creation-opens"
label={t('editor.annotations.opens')}
value={form.opensViewId}
options={options}
blank
onChange={(opensViewId) => 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 (
<>
<OptionSelect
id="creation-zone"
label={t('editor.annotations.zone')}
value={form.zoneId}
options={zones}
blank
onChange={(zoneId) => onChange({ zoneId })}
/>
<OptionSelect
id="creation-region"
label={t('editor.annotations.region')}
value={form.regionCode}
options={regions}
blank
onChange={(regionCode) => onChange({ regionCode })}
/>
</>
)
}
@@ -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<string | null>(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 (
<div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn {...scene} placement={placement} onRoot={setViewBox} />
<aside>
<SidePanel {...scene} viewId={viewId} context={context} />
</aside>
</div>
)
}
/** What both columns read: the document, the tab's state, the view and its frame. */
interface Scene extends Props {
ui: UiState
dispatch: Dispatch<UiAction>
model: ViewModel
frame: Frame | null
selected: Annotation | undefined
}
function CanvasColumn({
placement,
onRoot,
...scene
}: Scene & {
placement: ReturnType<typeof usePlacement>
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 (
<div className="min-w-0 space-y-3" onKeyDown={placement.onKeyDown}>
<ViewSwitcher
views={doc.views}
current={viewId}
onSelect={(id) => dispatch({ type: 'view', viewId: id })}
/>
<ToolNotes
tool={ui.tool}
hint={ui.hint}
model={model}
noCategory={noCategory}
onSelectTab={scene.onSelectTab}
/>
{selected && (
<SelectionTag
kind={selected.kind}
name={annotationName(selected, doc.views, locale)}
/>
)}
<AnnotationCanvas
viewId={viewId}
viewName={view.name[locale]}
tool={ui.tool}
selectedId={ui.selectedId}
moveTarget={moveTargetOf(selected, model, ui.tool)}
overlay={overlayOf(ui, selected, frame)}
tools={{
tool: ui.tool,
onTool: (tool) => dispatch({ type: 'tool', tool }),
drawingDisabled: blocked,
linkDisabled: model.children.length === 0,
}}
onRoot={onRoot}
onSelect={select}
onPlace={placement.onPlace}
onDrop={placement.onDrop}
/>
{ui.tracing && (
<TracingBar
count={ui.tracing.points.length}
onClose={placement.closeTracing}
onCancel={() => dispatch({ type: 'trace_cancel' })}
/>
)}
<KeyboardAdd
disabled={blocked || frame === null}
linkDisabled={model.children.length === 0}
onAdd={(kind) => addAtCentre(kind, frame, dispatch)}
/>
<AnnotationList
annotations={model.annotations}
views={doc.views}
selectedId={ui.selectedId}
onSelect={select}
/>
</div>
)
}
function addAtCentre(
kind: NewKind,
frame: Frame | null,
dispatch: Dispatch<UiAction>,
) {
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 (
<CreationPanel
key={ui.serial}
pending={ui.pending}
viewId={viewId}
doc={doc}
frame={frame}
dispatch={dispatch}
context={context}
/>
)
}
if (!selected) {
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.select_hint')}
</p>
)
}
return (
<PropertiesPanel
key={selected.id}
annotation={selected}
doc={doc}
readOnly={false}
geometryLocked={!model.measured}
dispatch={dispatch}
context={context}
onSelectTab={scene.onSelectTab}
/>
)
}
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 (
<div className="space-y-1 text-sm text-[var(--color-ink-muted)]">
<p>{t(`editor.annotations.tool_hint.${tool}`)}</p>
{!model.measured && <UnmeasuredHint onSelectTab={onSelectTab} />}
{noCategory && <p>{t('editor.annotations.no_category')}</p>}
{linkBlocked && <p>{t('editor.annotations.no_child_view')}</p>}
{hint && (
<p role="alert" className="text-[var(--color-danger-strong)]">
{hint}
</p>
)}
</div>
)
}
@@ -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<GroupFields, { type: 'polygon' }>
/**
* 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<Fields>(stored)
const [seen, setSeen] = useState(storedKey)
const [messages, setMessages] = useState<string[]>([])
// 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 (
<GroupBody
{...view}
onChange={setDraft}
onPropose={apply}
onRevert={revert}
/>
)
}
interface BodyProps extends Omit<GeometryGroupProps, 'onApply'> {
draft: Fields
pending: Set<string>
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 (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">
{t(
draft.type === 'circle'
? 'editor.annotations.geometry.circle'
: 'editor.annotations.geometry.polygon',
)}
</legend>
{draft.type === 'circle' ? (
<CircleRows {...props} fields={draft} />
) : (
<PolygonRows {...props} fields={draft} />
)}
{unapplied && <Unapplied {...props} />}
</fieldset>
)
}
function Unapplied({ messages, onRevert }: BodyProps) {
const t = useT()
const words = messages.map((m) =>
m === 'number' ? t('editor.annotations.geometry.number') : m,
)
return (
<div role="alert" className="space-y-1 text-sm">
<p className="font-medium text-[var(--color-danger-strong)]">
{t('editor.annotations.geometry.unapplied')}
</p>
{words.map((word) => (
<p key={word} className="text-[var(--color-danger-strong)]">
{word}
</p>
))}
<Button type="button" variant="secondary" size="sm" onClick={onRevert}>
{t('editor.annotations.geometry.revert')}
</Button>
</div>
)
}
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 (
<p className="text-sm">
<span className="font-medium">{label}</span> {value}
</p>
)
}
const hint = unapplied
? t('editor.annotations.geometry.unapplied_tag')
: undefined
return (
<FormField id={id} label={label} hint={hint}>
<Input
id={id}
inputMode="decimal"
value={value}
aria-invalid={unapplied}
aria-describedby={fieldDescribedBy(id, hint)}
onChange={(e) => onType(e.target.value)}
onBlur={onApply}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) onApply()
}}
/>
</FormField>
)
}
type RowsProps<F extends Fields> = BodyProps & { fields: F }
function CircleRows(props: RowsProps<Extract<Fields, { type: 'circle' }>>) {
const t = useT()
const { fields, pending, locked, idPrefix } = props
return (
<div className="grid grid-cols-3 gap-2">
{(['cx', 'cy', 'r'] as const).map((key) => (
<NumberInput
key={key}
id={`${idPrefix}-${key}`}
label={t(`editor.annotations.geometry.${key}`)}
value={fields[key]}
unapplied={pending.has(key)}
locked={locked}
onType={(value) => props.onChange({ ...fields, [key]: value })}
onApply={() => props.onPropose(fields)}
/>
))}
</div>
)
}
function PolygonRows(props: RowsProps<PolygonFields>) {
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 (
<div className="space-y-2">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.geometry.vertices').replace(
'{count}',
String(fields.rows.length),
)}
</p>
{fields.rows.map((row, index) => (
<div
key={index}
className="grid grid-cols-[2rem_1fr_1fr] items-end gap-2"
onFocus={() => setSelected(index)}
>
<span className="pb-2 text-sm">{index + 1}</span>
{(['x', 'y'] as const).map((axis) => (
<NumberInput
key={axis}
id={`${props.idPrefix}-${axis}${index}`}
label={t(`editor.annotations.geometry.vertex_${axis}`).replace(
'{n}',
String(index + 1),
)}
value={row[axis]}
unapplied={props.pending.has(`${axis}${index}`)}
locked={locked}
onType={(value) => change(index, axis, value)}
onApply={() => props.onPropose(fields)}
/>
))}
</div>
))}
{!locked && (
<VertexButtons
fields={fields}
selected={selected}
onApply={props.onPropose}
/>
)}
</div>
)
}
function VertexButtons({
fields,
selected,
onApply,
}: {
fields: PolygonFields
selected: number
onApply: (fields: Fields) => void
}) {
const t = useT()
return (
<div className="flex flex-wrap gap-2">
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => onApply(withVertexAfter(fields, selected))}
>
{t('editor.annotations.geometry.add_vertex')}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
disabled={fields.rows.length <= 3}
onClick={() => onApply(withoutVertex(fields, selected))}
>
{t('editor.action.remove')}
</Button>
</div>
)
}
@@ -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 (
<div className="flex flex-wrap gap-2">
{KINDS.map((kind) => (
<Button
key={kind}
type="button"
variant="secondary"
size="sm"
disabled={disabled || (kind === 'detail_trigger' && linkDisabled)}
onClick={() => onAdd(kind)}
>
{t(`editor.annotations.add.${kind}`)}
</Button>
))}
</div>
)
}
@@ -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<UiAction>
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 (
<section
aria-label={t('editor.annotations.properties')}
data-testid="annotation-properties"
className="space-y-4 rounded-xl border border-[var(--color-border)] p-4"
>
<header className="flex items-start justify-between gap-2">
<h3 className="text-base font-semibold">
{t(`editor.annotations.kind.${annotation.kind}`)}
</h3>
<ReviewBadge status={annotation.review_status} />
</header>
<AnnotationFields
annotation={annotation}
doc={doc}
readOnly={readOnly}
edit={edit}
/>
<GeometrySection {...props} />
<StatusActions annotation={annotation} readOnly={readOnly} edit={edit} />
<Deletion id={annotation.id} name={name} readOnly={readOnly} />
</section>
)
}
function GeometrySection(props: PropertiesPanelProps) {
const t = useT()
const { annotation, readOnly, geometryLocked } = props
const locked = readOnly || geometryLocked
const { geometry } = annotation
return (
<div className="space-y-2">
{geometryLocked && !readOnly && <UnmeasuredHint {...props} />}
{isEditable(geometry) ? (
<GeometryGroup
key={annotation.id}
idPrefix="annotation"
geometry={geometry}
locked={locked}
onApply={(next) => applyGeometry(annotation, next, props.context)}
/>
) : (
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
geometry === null
? 'editor.annotations.no_geometry'
: 'editor.annotations.path',
)}
</p>
)}
{!locked && !isEditable(geometry) && (
<TraceReplacement id={annotation.id} dispatch={props.dispatch} />
)}
<GeometryIssues id={annotation.id} />
</div>
)
}
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<UiAction>
}) {
const t = useT()
return (
<Button
type="button"
variant="secondary"
size="sm"
onClick={() =>
dispatch({ type: 'trace_start', target: 'replace', annotationId: id })
}
>
{t('editor.annotations.replace_polygon')}
</Button>
)
}
function GeometryIssues({ id }: { id: string }) {
const issues = useGeometryIssues(id)
if (issues.length === 0) return null
return (
<ul
role="alert"
data-testid="annotation-geometry-issues"
className="list-disc pl-5 text-sm text-[var(--color-danger-strong)]"
>
{issues.map((issue) => (
<li key={issue}>{issue}</li>
))}
</ul>
)
}
export function UnmeasuredHint({
onSelectTab,
}: Pick<PropertiesPanelProps, 'onSelectTab'>) {
const t = useT()
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.unmeasured.hint')}{' '}
<button
type="button"
className="underline"
onClick={() => onSelectTab('views')}
>
{t('editor.tab.views')}
</button>
</p>
)
}
function StatusActions({
annotation,
readOnly,
edit,
}: {
annotation: Annotation
readOnly: boolean
edit: ReturnType<typeof useEditCommand>
}) {
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 (
<div className="space-y-1">
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={() => mark(reviewed ? 'to_confirm' : 'reviewed')}
>
{t(
reviewed
? 'editor.annotations.to_confirm'
: 'editor.annotations.mark_reviewed',
)}
</ActionButton>
{edit.fieldError('status') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('status')}
</p>
)}
</div>
)
}
function Deletion({
id,
name,
readOnly,
}: {
id: string
name: string
readOnly: boolean
}) {
const t = useT()
const [open, setOpen] = useState(false)
return (
<>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={() => setOpen(true)}
>
{t('editor.action.delete')}
</ActionButton>
<DeleteDialog
target={open ? { key: { kind: 'annotation', id }, label: name } : null}
onClose={() => setOpen(false)}
/>
</>
)
}
@@ -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 (
<Badge tone={TONES[status]}>
{t(`editor.annotations.status.${status}`)}
</Badge>
)
}
@@ -0,0 +1,25 @@
import { useT } from '@/i18n/useT'
/** Board 04's tag over the drawing: « Sélection : <type> « <nom> ». */
export default function SelectionTag({
kind,
name,
}: {
kind: string
name: string
}) {
const t = useT()
return (
<p
data-testid="annotation-selection-tag"
className="pointer-events-none inline-block rounded-md bg-[var(--color-surface-strong)] px-2 py-1 text-xs"
>
{t('editor.annotations.selection')
.replace(
'{kind}',
t(`editor.annotations.kind.${kind}`).toLocaleLowerCase(),
)
.replace('{name}', name)}
</p>
)
}
@@ -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<string, string> = {
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 (
<button
type="button"
aria-label={label}
title={label}
aria-pressed={pressed}
disabled={disabled}
onClick={onClick}
className={`grid h-11 w-11 place-items-center rounded-lg border border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
pressed
? 'bg-[var(--color-ink)] text-white'
: 'bg-[var(--color-surface)] text-[var(--color-ink)]'
}`}
>
<svg
viewBox="0 0 24 24"
width="20"
height="20"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d={GLYPHS[glyph]} />
</svg>
</button>
)
}
/** 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) => (
<ToolButton
glyph={id}
label={t(`editor.annotations.tool.${id}`)}
pressed={props.tool === id}
disabled={disabled}
onClick={() => props.onTool(id)}
/>
)
return (
<div
role="toolbar"
aria-orientation="vertical"
aria-label={t('editor.annotations.tools')}
className="flex flex-row gap-2 lg:flex-col"
>
{tool('select', false)}
{tool('point', props.drawingDisabled)}
{tool('zone', props.drawingDisabled)}
{tool('link', props.drawingDisabled || props.linkDisabled)}
<hr className="hidden border-[var(--color-border)] lg:block" />
<ToolButton
glyph="out"
label={t('catalogue.zoom.out')}
onClick={props.onZoomOut}
/>
<ToolButton
glyph="in"
label={t('catalogue.zoom.in')}
onClick={props.onZoomIn}
/>
<ToolButton
glyph="fit"
label={t('catalogue.zoom.fit')}
onClick={props.onFit}
/>
<hr className="hidden border-[var(--color-border)] lg:block" />
<ToolButton
glyph="undo"
label={t('editor.annotations.undo')}
disabled={!undoable}
onClick={() => useEditorStore.getState().undoStep()}
/>
<ToolButton
glyph="redo"
label={t('editor.annotations.redo')}
disabled={!redoable}
onClick={() => useEditorStore.getState().redoStep()}
/>
</div>
)
}
@@ -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 (
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.tracing').replace('{count}', String(count))}
</p>
<Button type="button" size="sm" disabled={count < 3} onClick={onClose}>
{t('editor.annotations.trace_close')}
</Button>
<Button type="button" size="sm" variant="ghost" onClick={onCancel}>
{t('editor.annotations.trace_cancel')}
</Button>
</div>
)
}
@@ -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 (
<div
role="group"
aria-label={t('editor.annotations.views')}
className="flex flex-wrap gap-2"
>
{views.map((view) => (
<button
key={view.id}
type="button"
aria-pressed={view.id === current}
onClick={() => onSelect(view.id)}
className={`rounded-full border border-[var(--color-border)] px-3 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
view.id === current
? 'bg-[var(--color-ink)] text-white'
: 'bg-[var(--color-surface)]'
}`}
>
{view.name[locale]}
</button>
))}
</div>
)
}
@@ -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 (
<section
data-testid="editor-tab-annotations"
aria-label={t('editor.tab.annotations')}
className="min-h-24"
/>
className="min-h-24 space-y-3"
>
{doc && preview && props.readOnly && (
<ReadOnlyAnnotations doc={doc} onSelectTab={props.onSelectTab} />
)}
{doc && preview && !props.readOnly && (
<EditableAnnotations doc={doc} onSelectTab={props.onSelectTab} />
)}
</section>
)
}
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<string | null>(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 (
<div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
<div className="min-w-0 space-y-3">
<ViewSwitcher
views={doc.views}
current={viewId}
onSelect={(id) => {
setViewId(id)
setSelectedId(null)
}}
/>
{selected && (
<SelectionTag
kind={selected.kind}
name={annotationName(selected, doc.views, locale)}
/>
)}
<CatalogueCanvas
key={handleVersion}
preview={preview}
viewId={viewId}
viewName={view.name[locale]}
selectedId={selectedId}
onAnnotation={setSelectedId}
/>
<AnnotationList
annotations={model.annotations}
views={doc.views}
selectedId={selectedId}
onSelect={setSelectedId}
/>
</div>
{selected && (
<PropertiesPanel
key={selected.id}
annotation={selected}
doc={doc}
readOnly
geometryLocked={!model.measured}
dispatch={() => undefined}
context={{ t: (key) => key, locale }}
onSelectTab={onSelectTab}
/>
)}
</div>
)
}
@@ -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<CommitOutcome<GeometryRefusal>, { 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)
}
@@ -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 }
}
+155
View File
@@ -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 } }
}
+147
View File
@@ -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
@@ -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<Geometry, { type: 'circle' | 'polygon' }>
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<string> {
const base = fieldsOf(stored)
const changed = new Set<string>()
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<GroupFields, { type: 'polygon' }>,
after: number,
): Extract<GroupFields, { type: 'polygon' }> {
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<GroupFields, { type: 'polygon' }>,
index: number,
): Extract<GroupFields, { type: 'polygon' }> {
return { type: 'polygon', rows: fields.rows.filter((_, i) => i !== index) }
}
@@ -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,
}
}
+108
View File
@@ -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<Tracing['target'], ToolId> = {
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 }
}
}
@@ -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<HTMLDivElement | null>(null)
const [attempt, setAttempt] = useState(0)
const [root, setRoot] = useState<RootAttributes | null>(null)
const [failure, setFailure] = useState<CanvasFailure | null>(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<HTMLDivElement | null>,
selectedId: string | null,
rebuilt: unknown,
): void {
useEffect(() => {
host.current?.querySelectorAll<Element>(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
@@ -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<SVGSVGElement | null>
/** 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<Drag | null>(null)
const [preview, setPreview] = useState<Geometry | null>(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,
},
}
}
@@ -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<Exclude<ToolId, 'select'>, NewKind> = {
point: 'point',
zone: 'zone',
link: 'detail_trigger',
}
export interface PlacementInput {
ui: UiState
dispatch: Dispatch<UiAction>
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<ToolId, 'select' | 'point'>, 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 }
}
@@ -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<string>()
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)
}, [])
}
+75
View File
@@ -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.',
}
+75
View File
@@ -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.',
}
+109
View File
@@ -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<string, unknown> {
const state = b.preview.state()
if (!state.ok) throw new Error(state.kind)
return geometryErrorsById(state.value)
}
export { drawnText, edit, insert, point }
@@ -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<typeof import('@faunosteo/supabase')>()),
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<typeof point>) =>
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<void> {
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 =
'<svg xmlns="http://www.w3.org/2000/svg"><rect width="4" height="4"/></svg>'
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)
})
})
@@ -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<typeof import('@faunosteo/supabase')>()),
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(<AnnotationsTab {...props} readOnly={options.readOnly ?? false} />)
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<typeof userEvent.setup>) {
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(<AnnotationsTab {...props} />)
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 })
})
})
+278
View File
@@ -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)
})
})
@@ -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/),
+2 -1
View File
@@ -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',
+19
View File
@@ -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 `<svg>` 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