import type { Dispatch, KeyboardEvent } from 'react' import type { Annotation, AnatomicalSheetDocument, Geometry, Point, } from '@faunosteo/core-wasm/types' import { useT } from '@/i18n/useT' import { updateGeometry, type CommitContext } from './annotationCommit' import { emptyForm, pendingForClick, type NewKind } from './creation' import { closeTrace, placePending, popVertex, traceVertex, type CreationStart, } from './creationWork' import { askCreation } from './creationAsk' import { round2, type Frame, type XY } from './frame' import { newPointSize } from './pointSize' import { endMode, useAnnotationWork } from './workStore' import type { ToolId, Tracing, UiAction, UiState } from './uiState' import type { GestureMessages } from './useGestureMessage' const TOOL_TARGET: Record, NewKind> = { point: 'point', zone: 'zone', link: 'detail_trigger', } export interface PlacementInput { ui: UiState /** The tracing shown: a redraw's (the reducer's) or a new shape's (the creation's). */ tracing: Tracing | null dispatch: Dispatch frame: Frame | null doc: AnatomicalSheetDocument viewId: string context: CommitContext /** The line under the drawing: a kept drop says so with « Défaire », a refused one in red. */ message: Pick } const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)] /** R-11: `reach` is the closing radius of the pointer, in drawing units. */ function nearFirstVertex(tracing: Tracing, at: XY, reach: number): boolean { const first = tracing.points[0] if (!first || tracing.points.length < 3) return false return Math.hypot(first[0] - at.x, first[1] - at.y) <= reach } /** * A redraw's close commits the polygon at once. The mode leaves first, so the commit is * never said as an abandoned redraw (R-13); a refusal brings it back and keeps the * tracing open with the core's message (board 33 A). */ function closeRedraw(input: PlacementInput, tracing: Tracing): void { const { doc, context, dispatch } = input const annotation = doc.annotations.find((a) => a.id === tracing.annotationId) if (!annotation) return dispatch({ type: 'trace_cancel' }) const held = useAnnotationWork.getState().mode endMode() const polygon = { type: 'polygon' as const, points: tracing.points } const result = updateGeometry(annotation, polygon, context) if (!result.ok) { useAnnotationWork.setState({ mode: held }) return dispatch({ type: 'trace_refused', hint: result.messages.join(' ') }) } dispatch({ type: 'select', id: annotation.id }) const text = context.t( `editor.annotations.message.redrawn.${annotation.kind}`, ) input.message.show(text, { undo: true, tone: 'info' }) } /** Where a creation on this view starts: F, the origin, a fresh form (A4). */ export const creationStart = ( { viewId, frame, doc }: Pick, origin: CreationStart['origin'], ): CreationStart => ({ viewId, frame, origin, form: emptyForm(doc) }) const isRedraw = (tracing: Tracing | null) => tracing?.target === 'replace' /** Backspace or « Retirer le dernier sommet »: the redraw's vertex, or the creation's. */ function popTrace({ tracing, dispatch }: PlacementInput): void { if (isRedraw(tracing)) dispatch({ type: 'trace_pop' }) else popVertex() } /** * Tracing with the zone and link tools: vertices, closing, Enter, Backspace and Escape. A * redraw's tracing is the reducer's; a new shape's is the creation's (A12): its Escape * asks « Abandonner la création ? » (board 32 row 3). */ function tracingActions(input: PlacementInput) { const { tracing, dispatch } = input const closeTracing = () => { if (!tracing || tracing.points.length < 3) return if (isRedraw(tracing)) return closeRedraw(input, tracing) closeTrace() } const trace = ( tool: Exclude, at: XY, reach: number, ) => { if (tracing && nearFirstVertex(tracing, at, reach)) return closeTracing() if (isRedraw(tracing)) return dispatch({ type: 'trace_add', point: asPoint(at) }) traceVertex(creationStart(input, 'tool'), TOOL_TARGET[tool], asPoint(at)) } const onTraceKey = (event: KeyboardEvent) => { if (!tracing) return if (event.key === 'Enter') closeTracing() if (event.key === 'Backspace') { event.preventDefault() popTrace(input) } if (event.key === 'Escape') { event.preventDefault() if (isRedraw(tracing)) dispatch({ type: 'trace_cancel' }) else askCreation() } } return { closeTracing, trace, onTraceKey } } /** * A move (drag, move mode, arrow keys) or a size change of the selection, a vertex * moved, added or removed. */ export type GeometryChange = 'move' | 'size' | 'vertex' | 'insert' | 'remove' const KEPT: Record, string> = { size: 'resized', vertex: 'vertex_moved', insert: 'vertex_added', remove: 'vertex_removed', } /** The message keys of a kept and of a refused change. */ function changeKeys(change: GeometryChange, kind: Annotation['kind']) { const kept = change === 'move' ? `moved.${kind}` : KEPT[change] if (change === 'size') return { kept, refused: 'size_refused' } const moved = change === 'move' || change === 'vertex' return { kept, refused: moved ? 'move_refused' : 'edit_refused' } } /** * A drop commits one update; the line under the drawing says it, or the core's refusal * with the refused place drawn (the shape stays where it was). */ function dropAction({ doc, context, message, dispatch }: PlacementInput) { return ( id: string, geometry: Geometry, change: GeometryChange = 'move', ): boolean => { const annotation = doc.annotations.find((a) => a.id === id) if (!annotation) return false const keys = changeKeys(change, annotation.kind) const result = updateGeometry(annotation, geometry, context) if (result.ok) { // A kept move ends any refusal the strip still shows. dispatch({ type: 'hint', hint: null }) const text = context.t(`editor.annotations.message.${keys.kept}`) message.show(text, { undo: true, tone: 'info' }) return true } const text = context .t(`editor.annotations.message.${keys.refused}`) .replace('{text}', () => result.messages.join(' ')) message.show(text, { undo: false, tone: 'error', place: geometry }) return false } } export type Drop = ReturnType /** * 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. * `onTraceKey` is for the canvas viewport only (a key from a button is the button's). */ export function usePlacement(input: PlacementInput) { const t = useT() const tracing = tracingActions(input) const { ui, dispatch, frame } = input /** `reach`: the pointer's closing radius in drawing units (R-11). */ const onPlace = (at: XY, reach: number) => { if (ui.tool === 'zone' || ui.tool === 'link') return tracing.trace(ui.tool, at, reach) if (ui.tool !== 'point' || !frame) return const { doc, viewId } = input const size = newPointSize(doc.annotations, viewId, frame, ui.size) const outcome = pendingForClick(frame, at, size) if (outcome.kind === 'pending') { dispatch({ type: 'hint', hint: null }) return placePending(creationStart(input, 'tool'), outcome.pending) } dispatch({ type: 'hint', hint: t('editor.annotations.outside') }) } return { onPlace, onDrop: dropAction(input), onTraceKey: tracing.onTraceKey, closeTracing: tracing.closeTracing, popVertex: () => popTrace(input), } }