fix(app): annotations tab split, editor-wide undo keys, keyboard point fits, typed radius message

This commit is contained in:
bchanot committed 2026-11-04 14:00:57 +01:00
1 parent 447d0a4272
commit 3f15762d95
25 files changed
+1398 -653

No files matched your search

@@ -18,15 +18,19 @@ export interface Correction {
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.
* Candidate C is offered when the core refused the page's own proposal (its radius still
* `proposedRadius`) and that proposal was either a reduced radius (B) or refused
* `out_of_frame` (A at a float edge). A radius the user typed is an explicit value, and
* an A refused `too_small` (r0 already capped) offers nothing: the core's issue is shown.
*/
export function correctionFor(
frame: Frame,
attempted: CircleShape,
refusedCodes: readonly string[],
proposedRadius: number | undefined,
): Correction | null {
if (proposedRadius === undefined || attempted.r !== proposedRadius)
return null
const reduced = attempted.r < defaultRadius(frame)
if (!reduced && !refusedCodes.includes(OUT_OF_FRAME)) return null
const click = { x: attempted.cx, y: attempted.cy }
@@ -47,10 +51,11 @@ export function attemptPoint(
frame: Frame,
circle: CircleShape,
insert: InsertCircle,
proposedRadius: number | undefined,
): PointAttempt {
const result = insert(circle)
if (result.ok) return { status: 'created', id: result.id }
const correction = correctionFor(frame, circle, result.codes)
const correction = correctionFor(frame, circle, result.codes, proposedRadius)
return correction
? { status: 'correction', correction }
: { status: 'refused', messages: result.messages }
+34 -3
View File
@@ -25,6 +25,23 @@ export interface PendingElement {
geometry: EditableGeometry
/** Candidate C awaiting the user's confirmation (a point only). */
correction?: Correction | null
/** The radius the page proposed; a radius typed since is the user's own value. */
proposedRadius?: number
}
/** The pending element with a geometry the user typed: C and the proposal lapse with it. */
export function withGeometry(
pending: PendingElement,
geometry: EditableGeometry,
): PendingElement {
const kept =
geometry.type === 'circle' && geometry.r === pending.proposedRadius
return {
...pending,
geometry,
correction: null,
proposedRadius: kept ? pending.proposedRadius : undefined,
}
}
/** What the creation panel collects (no default labels: names and laterality are typed). */
@@ -70,7 +87,12 @@ export function directChildren(
/** 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) } }
const circle = centreCircle(frame)
return {
kind,
geometry: { type: 'circle', ...circle },
proposedRadius: circle.r,
}
}
return { kind, geometry: { type: 'polygon', points: centreTriangle(frame) } }
}
@@ -141,7 +163,12 @@ export function pendingForClick(frame: Frame, click: XY): ClickOutcome {
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 pending = {
kind: 'point' as const,
geometry,
proposedRadius: proposal.circle.r,
}
return { kind: 'pending', pending }
}
const at = { x: round2(click.x), y: round2(click.y) }
const geometry = {
@@ -151,5 +178,9 @@ export function pendingForClick(frame: Frame, click: XY): ClickOutcome {
r: defaultRadius(frame),
}
const correction = { click: at, circle: proposal.circle }
return { kind: 'pending', pending: { kind: 'point', geometry, correction } }
const pending = { kind: 'point' as const, geometry, correction }
return {
kind: 'pending',
pending: { ...pending, proposedRadius: geometry.r },
}
}
@@ -0,0 +1,74 @@
import type { Annotation } from '@faunosteo/core-wasm/types'
import {
insertAnnotation,
type CommitContext,
type CommitResult,
} from './annotationCommit'
import {
attemptPoint,
confirmCorrection,
type Correction,
type PointAttempt,
} from './correction'
import {
annotationOf,
formProblem,
type CreationForm,
type PendingElement,
} from './creation'
import type { Frame } from './frame'
import type { EditableGeometry } from './geometryEdit'
/** What « Créer » or the confirmation of C works from. */
export interface CreationInput {
pending: PendingElement
viewId: string
/** F of the current view; null while it is not measured. */
frame: Frame | null
context: CommitContext
}
export type Attempt = PointAttempt | { status: 'invalid'; problem: string }
/** The insert of the pending element under a given geometry, through `accept`. */
function inserterOf(input: CreationInput, form: CreationForm) {
return (geometry: EditableGeometry): CommitResult =>
insertAnnotation(
(id): Annotation =>
annotationOf(id, input.viewId, { ...input.pending, geometry }, form),
input.context,
)
}
/** « Créer »: a point lets the core's verdict offer C; nothing else is ever invented. */
export function createAttempt(
input: CreationInput,
form: CreationForm,
): Attempt {
const { pending, frame } = input
const problem = formProblem(pending.kind, form)
if (problem) return { status: 'invalid', problem }
const insert = inserterOf(input, form)
const { geometry } = pending
if (pending.kind === 'point' && geometry.type === 'circle' && frame) {
return attemptPoint(
frame,
geometry,
(c) => insert({ type: 'circle', ...c }),
pending.proposedRadius,
)
}
const result = insert(geometry)
return result.ok
? { status: 'created', id: result.id }
: { status: 'refused', messages: result.messages }
}
export function confirmAttempt(
input: CreationInput,
form: CreationForm,
correction: Correction,
): Attempt {
const insert = inserterOf(input, form)
return confirmCorrection(correction, (c) => insert({ type: 'circle', ...c }))
}
+11 -9
View File
@@ -58,15 +58,6 @@ export function defaultRadius(frame: Frame): number {
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,
@@ -143,5 +134,16 @@ export function centreTriangle(frame: Frame): [number, number][] {
return corners.map(([x, y]) => [round2(x), round2(y)])
}
/**
* Where a keyboard-created point sits: the centre of F with r0. Clamped as candidate C is,
* so it fits even with an origin off the 0.01 grid and r0 = min(w, h) / 2.
*/
export function centreCircle(frame: Frame): CircleShape {
return correctedCircle(frame, {
x: frame.x + frame.w / 2,
y: frame.y + frame.h / 2,
})
}
export const sameCircle = (a: CircleShape, b: CircleShape): boolean =>
a.cx === b.cx && a.cy === b.cy && a.r === b.r
+5 -1
View File
@@ -69,7 +69,11 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
return {
...state,
pending: action.pending,
serial: state.serial + 1,
// A second click with the same kind keeps the typed fields (same panel).
serial:
state.pending?.kind === action.pending.kind
? state.serial
: state.serial + 1,
selectedId: null,
tracing: null,
hint: null,
@@ -3,52 +3,68 @@ 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`). */
/** The composed root's own attributes, read as text (never `baseVal`), and its view. */
export interface RootAttributes {
/** The view this build was made for: a frame is never paired with another view's. */
viewId: string
viewBox: string | null
ratio: string
}
export type CanvasFailure = 'engine' | 'view'
interface Built {
root: RootAttributes | null
failure: CanvasFailure | null
}
const ANNOTATED = '[data-anno-id]'
function rootOf(viewId: string, svg: Element): RootAttributes {
return {
viewId,
viewBox: svg.getAttribute('viewBox'),
ratio: svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet',
}
}
/** What the canvas rebuilds on: the handle and its version counter. */
function useHandle() {
const preview = useEditorStore((s) => s.preview)
const version = useEditorStore((s) => s.handleVersion)
return { preview, version }
}
/**
* 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.
* retry (plan « Rendering and canvas »): the edit canvas follows the handle. Root and
* failure come from the same build; 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 handle = useHandle()
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)
const [built, setBuilt] = useState<Built>({ root: null, failure: 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,
if (!element || !handle.preview) return
const result = buildView(handle.preview, viewId)
element.replaceChildren(...(result.ok ? [result.svg] : []))
setBuilt(
result.ok
? { root: rootOf(viewId, result.svg), failure: null }
: { root: null, failure: result.failure },
)
}, [preview, viewId, handleVersion, attempt])
}, [handle.preview, viewId, handle.version, attempt])
const retry = useCallback(() => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}, [])
return { host, root, failure, retry, handleVersion }
return { host, ...built, retry }
}
/** The selected annotation's markers wear `data-state="current"`, restyled in place. */
@@ -0,0 +1,109 @@
import type {
CSSProperties,
KeyboardEvent,
MouseEvent,
PointerEvent,
RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import { useFraming } from '@/catalogue/useFraming'
import type { XY } from './frame'
import { clientToDrawing } from './gesture'
import type { ToolId } from './uiState'
import { annotationIdOf } from './useCanvasBuild'
import { useMoveGesture, type MoveTarget } from './useMoveGesture'
export interface GestureInput {
viewId: string
tool: ToolId
moveTarget: MoveTarget | null
overlay: RefObject<SVGSVGElement | null>
viewport: RefObject<HTMLDivElement | null>
onSelect: (id: string) => void
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
onDrop: (id: string, geometry: Geometry) => void
/** Enter and Escape while the canvas box itself has the focus (a tracing). */
onTraceKey: (event: KeyboardEvent) => void
}
type Framing = ReturnType<typeof useFraming>
type Move = ReturnType<typeof useMoveGesture>
/** Each pointer handler of the framing and of the move gesture, one after the other. */
function composedPointer(framing: Framing, move: Move) {
const both =
(
name:
| 'onPointerDown'
| 'onPointerMove'
| 'onPointerUp'
| 'onPointerCancel',
) =>
(event: PointerEvent) => {
framing.handlers[name](event)
move.handlers[name](event)
}
return {
onPointerDown: both('onPointerDown'),
onPointerMove: both('onPointerMove'),
onPointerUp: both('onPointerUp'),
onPointerCancel: both('onPointerCancel'),
onLostPointerCapture: move.handlers.onLostPointerCapture,
}
}
/** A click selects with the select tool, places with a drawing tool; a drag swallows it. */
function clickHandler(input: GestureInput, framing: Framing) {
return (event: MouseEvent) => {
if (framing.swallowClick()) return
if (input.tool === 'select') {
const id = annotationIdOf(event.target)
if (id) input.onSelect(id)
return
}
const client = { x: event.clientX, y: event.clientY }
const at = clientToDrawing(input.overlay.current, client)
if (at) input.onPlace(at)
}
}
/** `touch-action: none` only while a drawing tool, a drag or a zoom is active. */
function touchStyle(
tool: ToolId,
armed: boolean,
scale: number,
): CSSProperties {
const none = tool !== 'select' || armed || scale !== 1
return { touchAction: none ? 'none' : 'pan-x pan-y' }
}
/**
* Everything the canvas box listens to: zoom and pan, the move gesture, the click, and
* the keys. Enter and Escape only count when the box itself is the target, so Enter on
* « Annuler le tracé » (or a list row) is that button's, never a close of the tracing.
*/
export function useCanvasGestures(input: GestureInput) {
const move = useMoveGesture({
overlay: input.overlay,
target: input.moveTarget,
onDrop: input.onDrop,
})
const framing = useFraming(input.viewport, input.viewId, {
canPan: (event) => input.tool === 'select' && !move.claims(event),
})
const onKeyDown = (event: KeyboardEvent) => {
framing.handlers.onKeyDown(event)
if (event.target === event.currentTarget) input.onTraceKey(event)
}
return {
framing,
drag: move.preview,
boxProps: {
...composedPointer(framing, move),
onKeyDown,
onClick: clickHandler(input, framing),
style: touchStyle(input.tool, move.armed, framing.framing.scale),
},
}
}
@@ -39,13 +39,8 @@ const clientOf = (event: PointerEvent): XY => ({
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) {
/** The drag in flight (a ref, read by the handlers) and what the page shows of it. */
function useDragState(target: MoveTarget | null) {
const drag = useRef<Drag | null>(null)
const [preview, setPreview] = useState<Geometry | null>(null)
const [armed, setArmed] = useState(false)
@@ -54,54 +49,80 @@ export function useMoveGesture({ overlay, target, onDrop }: MoveOptions) {
setPreview(null)
setArmed(false)
}
const stopRef = useRef(stop)
stopRef.current = stop
// Losing the target (a switch to read-only, another selection) drops the drag.
useEffect(() => {
if (target === null) stop()
if (target === null) stopRef.current()
}, [target])
return { drag, preview, setPreview, armed, setArmed, stop }
}
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,
})
}
type DragState = ReturnType<typeof useDragState>
/** The geometry the pointer's position gives the target, translated as a block. */
function translatedAt(
overlay: MoveOptions['overlay'],
gesture: Drag | null,
target: MoveTarget | null,
event: PointerEvent,
): Geometry | null {
const now = clientToDrawing(overlay.current, clientOf(event))
if (!now || !gesture || !target) return null
return translatedGeometry(target.geometry, {
x: now.x - gesture.origin.x,
y: now.y - gesture.origin.y,
})
}
function pointerHandlers(options: MoveOptions, state: DragState) {
const { overlay, target, onDrop } = options
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 }
state.drag.current = { start: clientOf(event), origin, started: false }
event.currentTarget.setPointerCapture?.(event.pointerId)
setArmed(true)
state.setArmed(true)
}
const onPointerMove = (event: PointerEvent) => {
const gesture = drag.current
const gesture = state.drag.current
if (!gesture) return
if (!gesture.started && !pastDragThreshold(gesture.start, clientOf(event)))
return
gesture.started = true
setPreview(translated(event))
state.setPreview(translatedAt(overlay, gesture, target, event))
}
const onPointerUp = (event: PointerEvent) => {
const gesture = drag.current
const dropped = gesture?.started ? translated(event) : null
stop()
const gesture = state.drag.current
const dropped = gesture?.started
? translatedAt(overlay, gesture, target, event)
: null
state.stop()
if (dropped && target) onDrop(target.id, dropped)
}
return {
preview,
armed,
claims,
handlers: {
onPointerDown,
onPointerMove,
onPointerUp,
onPointerCancel: stop,
onLostPointerCapture: stop,
onPointerCancel: state.stop,
onLostPointerCapture: state.stop,
},
}
}
/**
* 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(options: MoveOptions) {
const state = useDragState(options.target)
const { claims, handlers } = pointerHandlers(options, state)
return { preview: state.preview, armed: state.armed, claims, handlers }
}
+44 -30
View File
@@ -62,24 +62,11 @@ export function closingActions(
]
}
/**
* 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') })
}
/** Tracing with the zone and link tools: vertices, closing, Enter and Escape. */
function tracingActions(input: PlacementInput) {
const { ui, dispatch, frame } = input
const closeTracing = () =>
closingActions(ui.tracing, doc, context).forEach(dispatch)
closingActions(ui.tracing, input.doc, input.context).forEach(dispatch)
const trace = (tool: Exclude<ToolId, 'select' | 'point'>, at: XY) => {
if (!frame) return
if (ui.tracing && nearFirstVertex(ui.tracing, at, frame)) {
@@ -89,21 +76,48 @@ export function usePlacement(input: PlacementInput) {
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) => {
const onTraceKey = (event: KeyboardEvent) => {
if (!ui.tracing) return
if (event.key === 'Enter') closeTracing()
if (event.key === 'Escape') dispatch({ type: 'trace_cancel' })
}
return { onPlace, onDrop, onKeyDown, closeTracing }
return { closeTracing, trace, onTraceKey }
}
/** A drop commits one update; the hint holds the core's words on a refusal. */
function dropAction(input: PlacementInput) {
return (id: string, geometry: Geometry) => {
const annotation = input.doc.annotations.find((a) => a.id === id)
if (!annotation) return
const result = updateGeometry(annotation, geometry, input.context)
const hint = result.ok ? null : result.messages.join(' ')
input.dispatch({ type: 'hint', hint })
}
}
/**
* 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
const onPlace = (at: XY) => {
if (ui.tool === 'zone' || ui.tool === 'link')
return tracing.trace(ui.tool, at)
if (ui.tool !== 'point' || !frame) return
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') })
}
return {
onPlace,
onDrop: dropAction(input),
onTraceKey: tracing.onTraceKey,
closeTracing: tracing.closeTracing,
}
}
@@ -1,4 +1,4 @@
import { useEffect, useMemo } from 'react'
import { useMemo } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
@@ -32,23 +32,3 @@ export function useViewModel(
}
}, [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)
}, [])
}