feat(editor): vertex handles, insert and remove, zone move, redraw

U2 Task 5. A selected polygon gets its vertex, « + » and « − » handles
(R-9, hidden « + » under two hit radii, R-18 zoom hint in the strip),
the handle cap at 40 (R-7), vertex drag and keys, the move mode on the
zone or the chosen vertex, « Redessiner » as a redraw mode kept in step
with its tracing (R-12 guard, R-13 drop), close radius in CSS px
(R-11). The numeric group leaves the properties panel (D1).

Removed or rewritten assertions (numeric group -> replacement):
- tab « shows its exact stored numbers » (Centre x field) -> the overlay
  selection circle's cx attribute, same exact value.
- tab « a numeric edit » x3 -> « an edit on the drawing »: Enter on the
  handle without a step commits nothing, a step + Enter commits once;
  a refused handle drag keeps the stored shape then a drag inside the
  frame repairs it (issues gone); Escape drops a pending series.
- tab C26 « Centre x 15 » -> overlay cx 15.
- tab C32 unmeasured « Centre x as text » -> no handle, no field.
- tab « adds and removes a vertex as part of the whole group » -> « + »
  then « − » on the drawing; « never offers to remove below three » ->
  « − » aria-disabled at 3.
- tab H8 « refused Remplacer drops the tracing » -> keeps it open with
  « Fermeture refusée » (board 33 A); « refused vertex add/remove stay
  non appliqué » -> a refused vertex drag restores the shape exactly.
- tab Désélectionner and D6b (typed Centre x committed, refused, undone)
  x6 and strip « a new commit replaces the message » -> the same with
  the Nom (FR) field (a blank name is the refused value).
- focus-request « Centre x 20 » -> overlay cx 20.
- escape « strip commands keep their Escape » -> a redraw: Escape on the
  strip or the box cancels it (R-12 row 4); kept for a new zone tracing.
- keep-alive « Remplacer tracing kept across Aller à » -> ended by a tab
  when empty, asked once a vertex is placed (R-12).
- e2e annotations: numeric cx edit + undo/redo -> handle keys + undo/
  redo; jitter/drag and Task 4 point reads -> overlay attributes (the
  stored place during the mode -> overlay-old-place); keyboard-only cy
  and vertex x typed -> handle and vertex keys.
- e2e deselect: Centre x typed/refused/committed -> Nom (FR).
- e2e geometry, shell-crossing: Centre x/cy reads -> overlay attributes.
- e2e journey: cx +3 and vertex x +4 typed -> 3 and 4 arrow steps + Enter;
  a far typed value + revert -> a far handle drag refused.
- e2e equine latency: typed cx rounds -> handle arrow + Enter rounds.
This commit is contained in:
bchanot committed 2026-11-17 20:24:49 +01:00
1 parent ba8e766fe8
commit 6211046537
44 files changed
+3790 -1050

No files matched your search

@@ -13,6 +13,8 @@ import {
} from '@/editor/annotations/useCanvasBuild'
import { useCanvasGestures } from '@/editor/annotations/useCanvasGestures'
import type { MoveTarget } from '@/editor/annotations/useBlockDrag'
import type { Drop } from '@/editor/annotations/usePlacement'
import type { HandleAction } from '@/editor/annotations/usePressGesture'
import type { ToolId } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
@@ -27,7 +29,7 @@ type OverlayData = Omit<
/** The handle layer's content: the handle and its keys (the layer measures itself). */
export type HandleData = Pick<
HandleLayerProps,
'handle' | 'onKeyDown' | 'onBlur'
'handle' | 'onKeyDown' | 'onBlur' | 'zone' | 'zoneKeys' | 'onInsertsHidden'
>
export interface AnnotationCanvasProps {
@@ -43,9 +45,10 @@ export interface AnnotationCanvasProps {
/** The composed root as rebuilt (with its view); null on failure. */
onRoot: (root: RootAttributes | 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
/** A click with a drawing tool, in drawing units, and its closing reach (R-11). */
onPlace: (at: XY, reach: number) => void
onDrop: Drop
onHandle: (action: HandleAction) => void
onDeselect: () => void
onTraceKey: (event: KeyboardEvent) => void
}
@@ -88,7 +91,11 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
svgRef: overlay,
dragged: gestures.drag,
},
handles: { ...props.handles, scale: gestures.framing.framing.scale },
handles: {
...props.handles,
scale: gestures.framing.framing.scale,
dragged: gestures.drag,
},
}}
/>
</div>
@@ -144,7 +151,7 @@ interface LayerProps {
root: RootAttributes | null
transform: string
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
handles: HandleData & { scale: number }
handles: HandleData & { scale: number; dragged: Geometry | null }
}
/**
@@ -19,6 +19,8 @@ export interface OverlayProps {
pending: Geometry | null
tracing: Point[] | null
correction: Correction | null
/** A redraw runs: the stored outline stays as the old place until the close (06 C). */
redrawing: boolean
}
const STROKE = { fill: 'none', vectorEffect: 'non-scaling-stroke' } as const
@@ -130,7 +132,8 @@ export default function AnnotationOverlay(props: OverlayProps) {
const size = frame ? Math.max(frame.w, frame.h) / 200 : 1
const preview = usePreviewOf(props.selectedId)
const moved = props.dragged ?? preview
const shown = moved ?? selected
const old = moved !== null || props.redrawing
const shown = props.redrawing ? null : (moved ?? selected)
return (
<svg
ref={props.svgRef}
@@ -140,7 +143,7 @@ export default function AnnotationOverlay(props: OverlayProps) {
preserveAspectRatio={props.ratio}
className="pointer-events-none absolute inset-0 h-full w-full"
>
{moved && selected && isEditable(selected) && (
{old && selected && isEditable(selected) && (
<g data-testid="overlay-old-place">
<Outline geometry={selected} dashed colour="var(--color-ink-muted)" />
</g>
@@ -155,10 +158,10 @@ export default function AnnotationOverlay(props: OverlayProps) {
</g>
)}
{shown && isEditable(shown) && (
<>
<g data-testid="overlay-selection">
<Outline geometry={shown} dashed colour="var(--color-ink)" />
<Vertices geometry={shown} size={size} />
</>
</g>
)}
{pending && (
<Outline
@@ -1,5 +1,4 @@
import { useEffect, useReducer, useState, type Dispatch } from 'react'
import Button from '@/components/ui/Button'
import type {
AnatomicalSheetDocument,
Annotation,
@@ -12,7 +11,14 @@ import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { newPointSize } from '@/editor/annotations/pointSize'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { usePointEdit } from '@/editor/annotations/usePointEdit'
import { endMode, useAnnotationWork } from '@/editor/annotations/workStore'
import { useZoneEdit } from '@/editor/annotations/useZoneEdit'
import { useRedrawFollowsTracing } from '@/editor/annotations/redraw'
import {
useDroppedNotice,
useModeFollowsSelection,
} from '@/editor/annotations/modeEnds'
import { handledPoints } from '@/editor/annotations/zoneEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { useSelectionEscape } from '@/editor/annotations/deselect'
import { usePlacement } from '@/editor/annotations/usePlacement'
@@ -20,7 +26,6 @@ import { stripLeadOf } from '@/editor/annotations/stripLead'
import {
useGestureMessage,
type GestureMessage as ShownMessage,
type GestureMessages,
} from '@/editor/annotations/useGestureMessage'
import {
initialUi,
@@ -49,6 +54,8 @@ import {
} from './PointCommands'
import CreationPanel from './CreationPanel'
import EditStrip, { type StripNotice } from './EditStrip'
import TracingCommands from './TracingCommands'
import ZoneCommands, { moveTitleKey, useChosenVertex } from './ZoneCommands'
import GestureMessage from './GestureMessage'
import KeyboardAdd from './KeyboardAdd'
import OverviewPanel from './OverviewPanel'
@@ -145,59 +152,41 @@ function useCommitContext(): CommitContext {
}
/**
* The tab's work: the commit context, the line under the drawing, the placement and the
* point editing (handle keys, slider, move mode) on the movable selected circle.
* The tab's work: the commit context, the line under the drawing, the placement, the
* editing of the movable selection (point handle keys, slider, move mode) and of a
* polygon's vertices, the redraw kept in step with its tracing.
*/
function useWork(scene: Scene) {
const context = useCommitContext()
const message = useGestureMessage()
const placement = usePlacement({ ...scene, context, message })
const target = circleTargetOf(scene.selected, scene.model, scene.ui.tool)
const edit = usePointEdit({
target,
frame: scene.frame,
onDrop: placement.onDrop,
const target = movableOf(scene.selected, scene.model, scene.ui.tool)
const onDrop = placement.onDrop
const edit = usePointEdit({ target, frame: scene.frame, onDrop })
const polygon = target?.geometry?.type === 'polygon' ? target : null
const zone = useZoneEdit({
...{ target: polygon, frame: scene.frame, onDrop, message },
t: context.t,
confirmMove: edit.confirmMove,
})
const [insertsHidden, setInsertsHidden] = useState(false)
useModeFollowsSelection(scene.ui.selectedId)
useRedrawFollowsTracing(scene.ui.tracing, scene.dispatch)
useDroppedNotice(message)
return { context, message, placement, edit, target }
return {
context,
message,
placement,
edit,
zone,
target,
insertsHidden,
setInsertsHidden,
}
}
type Work = ReturnType<typeof useWork>
/**
* The move mode belongs to the selection: another selection (a list row, a view change)
* ends it. A read-only flip keeps the body and its selection, so it suspends the mode
* instead (R-14).
*/
function useModeFollowsSelection(selectedId: string | null) {
const modeId = useAnnotationWork((s) => s.mode?.annotationId ?? null)
useEffect(() => {
if (modeId === null || modeId === selectedId) return
const { mode } = useAnnotationWork.getState()
endMode()
// Never silent (R-13): a started move that ends this way is said.
if (mode?.started) useAnnotationWork.setState({ dropped: mode.kind })
}, [modeId, selectedId])
}
/**
* R-13: a started mode a change made elsewhere dropped is said on the line, once the body
* is shown (a drop while read-only is said on the way back).
*/
function useDroppedNotice(message: GestureMessages) {
const t = useT()
const visible = usePlaceVisible()
const dropped = useAnnotationWork((s) => s.dropped)
const show = message.show
useEffect(() => {
if (dropped === null || !visible) return
useAnnotationWork.setState({ dropped: null })
const text = t(`editor.annotations.dropped.${dropped}`)
show(text, { undo: false, tone: 'info' })
}, [dropped, visible, show, t])
}
export default function EditableAnnotations(props: Props) {
const scene = useScene(props)
const work = useWork(scene)
@@ -206,7 +195,10 @@ export default function EditableAnnotations(props: Props) {
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => scene.dispatch({ type: 'select', id: null }),
visible && selected !== undefined && ui.tracing === null,
// A redraw's Escape cancels it at once (R-12); a new tracing keeps its own keys.
visible &&
selected !== undefined &&
(ui.tracing === null || ui.tracing.target === 'replace'),
{ editable: true, creating: ui.pending !== null },
)
return (
@@ -222,8 +214,6 @@ export default function EditableAnnotations(props: Props) {
)
}
type Placement = ReturnType<typeof usePlacement>
/** A move that drops the drawing's work asks first (R-12): the action runs once allowed. */
const guarded = (action: () => void) => () => {
if (guardDrawing(action)) action()
@@ -265,7 +255,7 @@ function CanvasColumn({
function useHandle(target: Annotation | null, doc: AnatomicalSheetDocument) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (!target?.geometry) return null
if (target?.geometry?.type !== 'circle') return null
const name = annotationName(target, doc.views, locale)
const kind = t(`editor.annotations.kind.${target.kind}`)
const label = t('editor.annotations.handle.shape')
@@ -292,6 +282,8 @@ function CanvasStage({
const shown = usePlaceVisible()
const { doc, ui, dispatch, model, frame, selected } = scene
const handle = useHandle(shown ? work.target : null, doc)
const points = shown ? handledPoints(work.target?.geometry ?? null) : null
const zone = points && { annotationId: work.target!.id, points }
const view = doc.views.find((v) => v.id === scene.viewId)
const blocked = !model.measured || doc.categories.length === 0
if (!view) return null
@@ -307,6 +299,9 @@ function CanvasStage({
handle,
onKeyDown: work.edit.onHandleKey,
onBlur: work.edit.onHandleBlur,
zone,
zoneKeys: work.zone,
onInsertsHidden: work.setInsertsHidden,
}}
tools={{
tool: ui.tool,
@@ -318,6 +313,7 @@ function CanvasStage({
onSelect={(id) => dispatch({ type: 'select', id })}
onPlace={work.placement.onPlace}
onDrop={work.placement.onDrop}
onHandle={work.zone.onHandle}
onDeselect={onDeselect}
onTraceKey={work.placement.onTraceKey}
/>
@@ -379,7 +375,6 @@ function SidePanel({
readOnly={false}
geometryLocked={!model.measured}
dispatch={dispatch}
context={context}
navigate={scene.navigate}
// « Tout afficher » leaves the selection: a started move asks first (R-12).
onShowAll={guarded(() => dispatch({ type: 'select', id: null }))}
@@ -399,14 +394,13 @@ function moveTargetOf(
: null
}
/** The selected point or link circle, when it can be moved now (R-9: its handle). */
function circleTargetOf(
/** The selection when it can be moved now: a circle (its handle) or a polygon (R-9). */
function movableOf(
selected: Annotation | undefined,
model: ViewModel,
tool: ToolId,
): Annotation | null {
const movable = moveTargetOf(selected, model, tool) !== null
return movable && selected?.geometry?.type === 'circle' ? selected : null
return moveTargetOf(selected, model, tool) !== null ? selected! : null
}
function overlayOf(
@@ -423,6 +417,7 @@ function overlayOf(
pending: ui.pending?.geometry ?? null,
tracing: ui.tracing?.points ?? null,
correction: ui.pending?.correction ?? null,
redrawing: ui.tracing?.target === 'replace',
}
}
@@ -433,31 +428,47 @@ function overlayOf(
function SceneStrip({ scene, work }: { scene: Scene; work: Work }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const notice = useStripNotice(scene, work.message.message)
const moving = useAnnotationWork((s) => s.mode?.kind === 'move')
useMoveFocusReturn(moving)
const notice = useStripNotice(scene, work)
const mode = useAnnotationWork((s) =>
s.mode?.kind === 'move' ? s.mode : null,
)
useMoveFocusReturn(mode !== null)
const { ui, selected, doc } = scene
const lead = moving
const chosenVertex = useChosenVertex(selected?.id)
const lead = mode
? {
title: t('editor.annotations.move.point'),
title: t(moveTitleKey(mode, work.target?.kind)),
detail: t('editor.annotations.move.hint'),
icon: 'move' as const,
}
: stripLeadOf(ui, selected, doc, { t, locale })
: stripLeadOf(ui, selected, doc, { t, locale, chosenVertex })
const commandsKey = commandsKeyOf(
ui,
mode !== null,
work.target,
chosenVertex,
)
return (
<EditStrip
lead={lead}
notice={notice}
commands={<SceneCommands scene={scene} work={work} />}
commandsKey={commandsKeyOf(ui, moving, work.target?.kind === 'point')}
commandsKey={commandsKey}
/>
)
}
function commandsKeyOf(ui: UiState, moving: boolean, point: boolean) {
/** One box per set of commands: a wider set never moves an existing box (A14). */
function commandsKeyOf(
ui: UiState,
moving: boolean,
target: Annotation | null,
chosen: number | null,
) {
if (ui.tracing) return 'tracing'
if (moving) return 'move'
return point ? 'point' : `tool-${ui.tool}`
if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}`
return target?.kind === 'point' ? 'point' : `tool-${ui.tool}`
}
/** A tracing's commands, a movable point's, or the Point tool's size (A5). */
@@ -467,11 +478,18 @@ function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
return (
<TracingCommands
count={ui.tracing.points.length}
placement={work.placement}
onClose={work.placement.closeTracing}
onPop={work.placement.popVertex}
onCancel={() => dispatch({ type: 'trace_cancel' })}
/>
)
}
if (work.target?.geometry?.type === 'polygon') {
const edit = work.edit
return (
<ZoneCommands annotation={work.target} edit={edit} dispatch={dispatch} />
)
}
// A link circle keeps its handle but has no size and no move mode (R-10; no label).
if (work.target?.kind === 'point') {
const props = { doc, viewId, frame, edit: work.edit }
@@ -497,10 +515,12 @@ function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
*/
function useStripNotice(
scene: Scene,
message: ShownMessage | null,
work: Pick<Work, 'message' | 'insertsHidden'>,
): StripNotice | null {
const t = useT()
const issues = useGeometryIssues(scene.selected?.id ?? '')
const inMode = useAnnotationWork((s) => s.mode !== null)
const message: ShownMessage | null = work.message.message
const { ui, model, doc } = scene
if (ui.hint) return { tone: 'error', text: ui.hint }
if (message?.tone === 'error') {
@@ -509,6 +529,10 @@ function useStripNotice(
if (scene.selected && issues.length > 0) {
return { tone: 'error', text: issues[0]!, more: issues.length - 1 }
}
// R-18: a « + » hidden for its short segment; never in a mode (move, redraw).
if (work.insertsHidden && !inMode && !ui.tracing) {
return { tone: 'info', text: t('editor.annotations.strip.zoom_hint') }
}
if (!model.measured) return unmeasuredNotice(scene, t)
if (doc.categories.length === 0) {
return { tone: 'info', text: t('editor.annotations.no_category') }
@@ -534,54 +558,3 @@ function unmeasuredNotice(
},
}
}
const COMMAND = 'min-h-11 xl:min-h-9'
/** While a zone or link is traced: close (3 vertices at least), take one back, or drop it. */
function TracingCommands({
count,
placement,
onCancel,
}: {
count: number
placement: Placement
onCancel: () => void
}) {
const t = useT()
return (
<div
tabIndex={-1}
data-testid="tracing-commands"
className="flex items-center gap-2 outline-none"
>
<Button
type="button"
size="sm"
className={COMMAND}
disabled={count < 3}
onClick={placement.closeTracing}
>
{t('editor.annotations.trace_close')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={placement.popVertex}
>
{t('editor.annotations.trace_pop')}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={onCancel}
>
{t('editor.annotations.trace_cancel')}
</Button>
</div>
)
}
@@ -1,4 +1,5 @@
import {
useEffect,
useLayoutEffect,
useRef,
useState,
@@ -13,6 +14,11 @@ import {
type HandleSizes,
} from '@/editor/annotations/handleSize'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import ZoneHandles, {
shownInserts,
type ZoneHandle,
type ZoneKeys,
} from './ZoneHandles'
/** The selected point (or link circle) whose handle the layer draws. */
export interface PointHandle {
@@ -30,6 +36,13 @@ export interface HandleLayerProps {
handle: PointHandle | null
onKeyDown: (event: KeyboardEvent<SVGGElement>) => void
onBlur: (event: FocusEvent<SVGGElement>) => void
/** The selected polygon under the cap, and its handles' keys. */
zone: ZoneHandle | null
zoneKeys: ZoneKeys
/** The canvas-local drag preview: the handles follow it. */
dragged: Geometry | null
/** Whether a « + » is hidden for its short segment (R-18's hint). */
onInsertsHidden: (hidden: boolean) => void
}
/** The svg's own box in CSS px before the framing's transform. */
@@ -79,6 +92,8 @@ export default function HandleLayer(props: HandleLayerProps) {
const svg = useRef<SVGSVGElement | null>(null)
const unit = unitsPerPx(props.viewBox, useBoxSize(svg), props.scale)
const sizes = useHandleSizes()
const zone = useShownZone(props.zone, props.dragged)
useReportHidden(zone, { unit, sizes }, props.onInsertsHidden)
return (
<svg
ref={svg}
@@ -95,10 +110,40 @@ export default function HandleLayer(props: HandleLayerProps) {
unit={unit}
/>
)}
{zone && (
<ZoneHandles
zone={zone}
scale={{ unit, sizes }}
keys={props.zoneKeys}
/>
)}
</svg>
)
}
/** The polygon as shown now: the drag in flight, the pending preview, else the stored one. */
function useShownZone(
zone: ZoneHandle | null,
dragged: Geometry | null,
): ZoneHandle | null {
const id = zone?.annotationId ?? null
const preview = useAnnotationWork((s) =>
id !== null && s.preview?.annotationId === id ? s.preview.geometry : null,
)
const shown = dragged ?? preview
if (!zone || shown?.type !== 'polygon') return zone
return { ...zone, points: shown.points }
}
function useReportHidden(
zone: ZoneHandle | null,
scale: Parameters<typeof shownInserts>[1],
report: (hidden: boolean) => void,
) {
const hidden = zone ? shownInserts(zone.points, scale).includes(false) : false
useEffect(() => report(hidden), [hidden, report])
}
function PointHandleShape({
handle,
unit,
@@ -3,19 +3,15 @@ import { flushSync } from 'react-dom'
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 { useDeselect } from '@/editor/annotations/deselect'
import EditorGlyph from '@/components/editor/EditorGlyph'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { beginRedraw } from '@/editor/annotations/redraw'
import type { UiAction } from '@/editor/annotations/uiState'
import { geometryErrorsById } from '@/editor/issues'
import { focusRow } from '@/editor/focusRequest'
@@ -26,9 +22,7 @@ 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 {
@@ -39,7 +33,6 @@ export interface PropertiesPanelProps {
/** The view is not measured: geometry is shown as text only, the rest stays editable. */
geometryLocked: boolean
dispatch: Dispatch<UiAction>
context: CommitContext
navigate: EditorPlaceProps['navigate']
/** Clears the selection: the overview shows again. */
onShowAll: () => void
@@ -142,25 +135,22 @@ function DeselectButton({
)
}
/**
* The geometry's state: no coordinate field (A8, U2 Task 5: circles and polygons are
* edited on the drawing); a path or a missing geometry says so and offers the redraw.
*/
function GeometrySection(props: PropertiesPanelProps) {
const t = useT()
const { annotation, readOnly, geometryLocked } = props
const locked = readOnly || geometryLocked
const { geometry } = annotation
const editable = isEditable(geometry)
return (
<div className="space-y-2">
{geometryLocked && !readOnly && (
<UnmeasuredHint navigate={props.navigate} viewId={annotation.view_id} />
)}
{isEditable(geometry) ? (
<GeometryGroup
key={annotation.id}
idPrefix={`${props.idPrefix ?? ''}annotation`}
geometry={geometry}
locked={locked}
onApply={(next) => applyGeometry(annotation, next, props.context)}
/>
) : (
{!editable && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
geometry === null
@@ -169,7 +159,7 @@ function GeometrySection(props: PropertiesPanelProps) {
)}
</p>
)}
{!locked && !isEditable(geometry) && (
{!locked && !editable && (
<TraceReplacement id={annotation.id} dispatch={props.dispatch} />
)}
<GeometryIssues id={annotation.id} />
@@ -177,15 +167,6 @@ function GeometrySection(props: PropertiesPanelProps) {
)
}
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,
@@ -199,9 +180,8 @@ function TraceReplacement({
type="button"
variant="secondary"
size="sm"
onClick={() =>
dispatch({ type: 'trace_start', target: 'replace', annotationId: id })
}
// The same redraw as « Redessiner »: the drawing guard asks before it is lost.
onClick={() => beginRedraw(id, dispatch)}
>
{t('editor.annotations.replace_polygon')}
</Button>
@@ -0,0 +1,57 @@
import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
const COMMAND = 'min-h-11 xl:min-h-9'
export interface TracingCommandsProps {
count: number
onClose: () => void
onPop: () => void
onCancel: () => void
}
/** While a zone or link is traced: close (3 vertices at least), take one back, or drop it. */
export default function TracingCommands({
count,
onClose,
onPop,
onCancel,
}: TracingCommandsProps) {
const t = useT()
return (
<div
tabIndex={-1}
data-testid="tracing-commands"
className="flex items-center gap-2 outline-none"
>
<Button
type="button"
size="sm"
className={COMMAND}
disabled={count < 3}
onClick={onClose}
>
{t('editor.annotations.trace_close')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={onPop}
>
{t('editor.annotations.trace_pop')}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={onCancel}
>
{t('editor.annotations.trace_cancel')}
</Button>
</div>
)
}
@@ -0,0 +1,99 @@
import type { Dispatch } from 'react'
import type { Annotation } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import { beginRedraw } from '@/editor/annotations/redraw'
import type { UiAction } from '@/editor/annotations/uiState'
import type { PointEdit } from '@/editor/annotations/usePointEdit'
import {
useAnnotationWork,
type ModeWork,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from '../EditorGlyph'
import MoveModeBar from './MoveModeBar'
const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9'
/** The move mode's title: « Déplacer le sommet », « … la zone » or « … le point ». */
export function moveTitleKey(
mode: ModeWork,
kind: Annotation['kind'] | undefined,
) {
if (mode.vertex !== null) return 'editor.annotations.move.vertex'
return kind === 'zone'
? 'editor.annotations.move.zone'
: 'editor.annotations.move.point'
}
/** The chosen vertex of `annotationId`, as the work store holds it. */
export function useChosenVertex(
annotationId: string | undefined,
): number | null {
return useAnnotationWork((s) =>
annotationId !== undefined && s.chosen?.annotationId === annotationId
? s.chosen.vertex
: null,
)
}
export interface ZoneCommandsProps {
/** The selected polygon, movable now. */
annotation: Annotation
edit: PointEdit
dispatch: Dispatch<UiAction>
}
/**
* The strip's commands for a selected polygon (board 05): « Déplacer la zone » (« Déplacer
* le sommet » while a vertex is chosen) and « Redessiner »; during the move mode, its bar
* (board 06 B). A link traced as a polygon gets « Redessiner » only (no move label).
*/
export default function ZoneCommands({
annotation,
edit,
dispatch,
}: ZoneCommandsProps) {
const t = useT()
const chosen = useChosenVertex(annotation.id)
const inMode = useAnnotationWork(
(s) => s.mode?.kind === 'move' && s.mode.annotationId === annotation.id,
)
if (inMode) {
return (
<MoveModeBar
onStep={edit.stepMove}
onConfirm={edit.confirmMove}
onCancel={edit.cancelMove}
/>
)
}
const moveKey = chosen === null ? 'move.zone' : 'move.vertex'
return (
<>
{annotation.kind === 'zone' && (
<Button
// R-12: the focus comes back here when the mode ends (useMoveFocusReturn).
data-move-entry=""
type="button"
size="sm"
variant="secondary"
className={COMMAND}
onClick={edit.startMove}
>
<EditorGlyph name="move" size={16} />
{t(`editor.annotations.${moveKey}`)}
</Button>
)}
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
onClick={() => beginRedraw(annotation.id, dispatch)}
>
<EditorGlyph name="zone" size={16} />
{t('editor.annotations.redraw')}
</Button>
</>
)
}
@@ -0,0 +1,325 @@
import { useLayoutEffect, useRef, type KeyboardEvent } from 'react'
import type { Point } from '@faunosteo/core-wasm/types'
import type { HandleSizes } from '@/editor/annotations/handleSize'
import { MIN_VERTICES, showsInsert } from '@/editor/annotations/polygonEdit'
import type { ZoneEdit } from '@/editor/annotations/useZoneEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
/** The selected polygon whose vertex, « + » and « − » handles the layer draws. */
export interface ZoneHandle {
annotationId: string
points: Point[]
}
export type ZoneKeys = Pick<
ZoneEdit,
| 'onVertexKey'
| 'onVertexFocus'
| 'onVertexBlur'
| 'onInsertKey'
| 'onRemoveKey'
>
interface Scale {
/** Drawing units per CSS px. */
unit: number
sizes: HandleSizes
}
const segmentPx = (a: Point, b: Point, unit: number) =>
Math.hypot(b[0] - a[0], b[1] - a[1]) / unit
/** R-9: the « + » of segment `i` (vertex i to the next) shows at the current zoom. */
export function shownInserts(points: readonly Point[], { unit, sizes }: Scale) {
return points.map((p, i) =>
showsInsert(segmentPx(p, points[(i + 1) % points.length], unit), sizes.hit),
)
}
const RING = 'invisible group-focus-visible:visible'
function FocusRing({ cx, cy, r }: { cx: number; cy: number; r: number }) {
return (
<circle
cx={cx}
cy={cy}
r={r}
fill="none"
stroke="var(--color-accent)"
strokeWidth={2}
vectorEffect="non-scaling-stroke"
className={RING}
/>
)
}
const LINE = { vectorEffect: 'non-scaling-stroke', strokeWidth: 2 } as const
function Insert({
at,
after,
label,
scale,
onKeyDown,
}: {
at: [number, number]
after: number
label: string
scale: Scale
onKeyDown: (event: KeyboardEvent) => void
}) {
const { unit, sizes } = scale
const [cx, cy] = at
const r = (sizes.insert / 2) * unit
const arm = r * 0.5
return (
<g
role="button"
tabIndex={0}
aria-label={label}
className="group outline-none"
onKeyDown={onKeyDown}
>
<circle
cx={cx}
cy={cy}
r={r}
fill="white"
stroke="var(--color-accent)"
{...LINE}
/>
<path
d={`M ${cx - arm} ${cy} H ${cx + arm} M ${cx} ${cy - arm} V ${cy + arm}`}
stroke="var(--color-accent)"
{...LINE}
/>
<circle
cx={cx}
cy={cy}
r={Math.max(sizes.hit * unit, r)}
data-handle={JSON.stringify({ kind: 'insert', after })}
fill="transparent"
className="pointer-events-auto cursor-copy"
/>
<FocusRing cx={cx} cy={cy} r={r + 3 * unit} />
</g>
)
}
function Vertex({
at,
index,
chosen,
label,
scale,
keys,
}: {
at: Point
index: number
chosen: boolean
label: string
scale: Scale
keys: ZoneKeys
}) {
const { unit, sizes } = scale
const [cx, cy] = at
// A chosen vertex is bigger, filled and ringed: never told by colour alone.
const r = (sizes.vertex / 2 + (chosen ? 2 : 0)) * unit
return (
<g
role="button"
tabIndex={0}
aria-label={label}
aria-pressed={chosen}
data-vertex={index}
// Its arrow series commits on blur; the drawing guard blurs it before leaving.
data-series=""
className="group outline-none"
onKeyDown={(event) => keys.onVertexKey(index, event)}
onFocus={() => keys.onVertexFocus(index)}
onBlur={keys.onVertexBlur}
>
{chosen && (
<circle
cx={cx}
cy={cy}
r={r + 3 * unit}
fill="none"
stroke="var(--color-accent)"
{...LINE}
/>
)}
<circle
cx={cx}
cy={cy}
r={r}
fill={chosen ? 'var(--color-accent)' : 'white'}
stroke="var(--color-ink)"
{...LINE}
/>
<circle
cx={cx}
cy={cy}
r={Math.max(sizes.hit * unit, r)}
data-handle={JSON.stringify({ kind: 'vertex', index })}
fill="transparent"
className="pointer-events-auto cursor-move"
/>
<FocusRing cx={cx} cy={cy} r={r + 6 * unit} />
</g>
)
}
/** The « − » bubble over the chosen vertex (board 05), greyed at three vertices (12 B). */
function Remove({
at,
index,
disabled,
label,
scale,
onKeyDown,
}: {
at: Point
index: number
disabled: boolean
label: string
scale: Scale
onKeyDown: (event: KeyboardEvent) => void
}) {
const { unit, sizes } = scale
const w = sizes.bubble.w * unit
const h = sizes.bubble.h * unit
const x = at[0] - w / 2
const y = at[1] - (sizes.vertex / 2 + 6) * unit - h
const fill = disabled
? 'var(--color-ink-muted)'
: 'var(--color-danger-strong)'
return (
<g
role="button"
tabIndex={0}
aria-label={label}
aria-disabled={disabled}
className="group outline-none"
onKeyDown={onKeyDown}
>
<rect
x={x}
y={y}
width={w}
height={h}
rx={6 * unit}
fill={fill}
data-handle={JSON.stringify({ kind: 'remove', index })}
className={`pointer-events-auto ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
/>
<path
d={`M ${x + w * 0.3} ${y + h / 2} H ${x + w * 0.7}`}
stroke="white"
{...LINE}
/>
<rect
x={x - 3 * unit}
y={y - 3 * unit}
width={w + 6 * unit}
height={h + 6 * unit}
rx={8 * unit}
fill="none"
stroke="var(--color-accent)"
{...LINE}
className={RING}
/>
</g>
)
}
/** The chosen vertex of this polygon, as the store holds it now. */
function useChosen(annotationId: string, count: number): number | null {
return useAnnotationWork((s) => {
const chosen = s.chosen
if (chosen?.annotationId !== annotationId) return null
return chosen.vertex < count ? chosen.vertex : null
})
}
/**
* A keyboard choice (« + », Insert, Delete) moves the focus to the vertex now chosen, so
* the keys keep acting where the user looks; a pointer choice leaves the focus alone.
*/
function useFocusFollowsChoice(chosen: number | null) {
const group = useRef<SVGGElement | null>(null)
useLayoutEffect(() => {
const active = document.activeElement
if (chosen === null || !group.current?.contains(active)) return
if (active?.getAttribute('data-vertex') === String(chosen)) return
const target = group.current.querySelector(`[data-vertex="${chosen}"]`)
if (target instanceof SVGElement) target.focus()
}, [chosen])
return group
}
const midpoint = (a: Point, b: Point): [number, number] => [
(a[0] + b[0]) / 2,
(a[1] + b[1]) / 2,
]
/**
* The polygon's handles (docs/ANNOTATION-RENDERING.md « Editor overlay »): the « + » of the
* segments long enough on screen, every vertex, then the « − » bubble of the chosen one,
* in that order (Tab walks them so). No handle covers the interior.
*/
export default function ZoneHandles({
zone,
scale,
keys,
}: {
zone: ZoneHandle
scale: Scale
keys: ZoneKeys
}) {
const t = useT()
const { points } = zone
const chosen = useChosen(zone.annotationId, points.length)
const group = useFocusFollowsChoice(chosen)
const inserts = shownInserts(points, scale)
const named = (key: string, n: number) =>
t(`editor.annotations.handle.${key}`).replace('{n}', String(n + 1))
return (
<g ref={group} data-testid="zone-handles">
{points.map((p, i) =>
inserts[i] ? (
<Insert
key={`insert-${i}`}
at={midpoint(p, points[(i + 1) % points.length])}
after={i}
label={named('insert', i)}
scale={scale}
onKeyDown={(event) => keys.onInsertKey(i, event)}
/>
) : null,
)}
{points.map((p, i) => (
<Vertex
key={`vertex-${i}`}
at={p}
index={i}
chosen={chosen === i}
label={named('vertex', i)}
scale={scale}
keys={keys}
/>
))}
{chosen !== null && (
<Remove
at={points[chosen]}
index={chosen}
disabled={points.length <= MIN_VERTICES}
label={named('remove', chosen)}
scale={scale}
onKeyDown={(event) => keys.onRemoveKey(chosen, event)}
/>
)}
</g>
)
}
@@ -208,7 +208,6 @@ function ReadOnlyAnnotations({
readOnly
geometryLocked={!model.measured}
dispatch={() => undefined}
context={{ t: (key) => key, locale }}
navigate={navigate}
onShowAll={() => setSelectedId(null)}
/>