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

@@ -1,5 +1,6 @@
import type { Geometry } from '@faunosteo/core-wasm/types'
import { round2, type XY } from './frame'
import { moveVertex } from './polygonEdit'
/** A circle or polygon translated as a block by a drawing-unit delta, rounded to 0.01. */
export function translatedGeometry(
@@ -25,6 +26,21 @@ export function translatedGeometry(
return null
}
/** `geometry` moved by `delta`: as a block, or only its vertex `vertex` (a polygon's). */
export function movedBy(
geometry: Geometry,
delta: XY,
vertex: number | null,
): Geometry | null {
if (vertex === null) return translatedGeometry(geometry, delta)
if (geometry.type !== 'polygon') return null
const at = geometry.points[vertex]
if (!at) return null
const to = { x: at[0] + delta.x, y: at[1] + delta.y }
const points = moveVertex(geometry.points, vertex, to)
return points && { type: 'polygon', points }
}
interface Matrix {
a: number
b: number
@@ -50,3 +66,9 @@ export function clientToDrawing(
y: inverse.b * client.x + inverse.d * client.y + inverse.f,
}
}
/** Drawing units per client px, through the same matrix; null without one. */
export function drawingPerClientPx(svg: SVGSVGElement | null): number | null {
const inverse: Matrix | undefined = svg?.getScreenCTM?.()?.inverse()
return inverse ? Math.hypot(inverse.a, inverse.b) : null
}
+16 -2
View File
@@ -6,10 +6,24 @@ export interface HandleSizes {
insert: number
/** The radius around a handle's centre that a press reaches. */
hit: number
/** The « − » bubble over the chosen vertex. */
bubble: { w: number; h: number }
}
const FINE: HandleSizes = { vertex: 12, insert: 16, hit: 10 }
const COARSE: HandleSizes = { vertex: 18, insert: 24, hit: 22 }
// shortcut: the fine bubble size is read off board 05 (no number given by R-9). Upgrade:
// take the owner's value if the trial asks for another.
const FINE: HandleSizes = {
vertex: 12,
insert: 16,
hit: 10,
bubble: { w: 28, h: 22 },
}
const COARSE: HandleSizes = {
vertex: 18,
insert: 24,
hit: 22,
bubble: { w: 44, h: 36 },
}
function deviceSizes(): HandleSizes {
const coarse =
@@ -0,0 +1,38 @@
import { useEffect } from 'react'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useT } from '@/i18n/useT'
import type { GestureMessages } from './useGestureMessage'
import { endMode, useAnnotationWork } from './workStore'
/**
* 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).
*/
export 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).
*/
export 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])
}
@@ -0,0 +1,64 @@
import type { Point } from '@faunosteo/core-wasm/types'
import { round2, type XY } from './frame'
/** T18 (R-7): above this many vertices, outline and message, no handle. */
export const HANDLE_CAP = 40
export const MIN_VERTICES = 3
const inRange = (points: readonly Point[], i: number) =>
Number.isInteger(i) && i >= 0 && i < points.length
/** « + » on the segment from vertex `after` to the next (wrapping): its midpoint, 0.01 grid. */
export function insertMidpoint(
points: readonly Point[],
after: number,
): Point[] | null {
if (!inRange(points, after)) return null
const [ax, ay] = points[after]
const [bx, by] = points[(after + 1) % points.length]
const middle: Point = [round2((ax + bx) / 2), round2((ay + by) / 2)]
return [...points.slice(0, after + 1), middle, ...points.slice(after + 1)]
}
/** « − »: null at 3 vertices (board 12 B reason shown by the caller). */
export function removeVertex(
points: readonly Point[],
index: number,
): Point[] | null {
if (!inRange(points, index) || points.length <= MIN_VERTICES) return null
return points.filter((_, i) => i !== index)
}
export function moveVertex(
points: readonly Point[],
index: number,
to: XY,
): Point[] | null {
if (
!inRange(points, index) ||
!Number.isFinite(to.x) ||
!Number.isFinite(to.y)
)
return null
return points.map(
(p, i): Point => (i === index ? [round2(to.x), round2(to.y)] : p),
)
}
/** A vertex released on itself or on a neighbour is no change (no commit). */
export function isNoOpMove(
points: readonly Point[],
index: number,
moved: readonly Point[],
): boolean {
const n = points.length
const [x, y] = moved[index]
return [index, (index + 1) % n, (index + n - 1) % n].some(
(j) => points[j][0] === x && points[j][1] === y,
)
}
/** R-9: a « + » shows only when its segment is at least two hit radii long on screen. */
export function showsInsert(segmentPx: number, hitRadiusPx: number): boolean {
return segmentPx >= 2 * hitRadiusPx
}
+6
View File
@@ -7,6 +7,12 @@ export const SLOP_PX: Readonly<Record<PointerKind, number>> = {
pen: 6,
touch: 10,
}
/** R-11: CSS px from the first vertex within which a click closes a tracing. */
export const CLOSE_PX: Readonly<Record<PointerKind, number>> = {
mouse: 12,
pen: 22,
touch: 22,
}
export const DOUBLE_MS = 400
export const DOUBLE_PX = 8
@@ -1,6 +1,6 @@
import type { Geometry } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import { translatedGeometry } from './gesture'
import { movedBy } from './gesture'
import {
endMode,
setModePreview,
@@ -42,19 +42,22 @@ export function shownGeometry(
}
/**
* One step of the selection by `delta` drawing units: into the move mode when it is on,
* else as a keyboard series (`keys`), stamped with the current text.
* One step of the selection by `delta` drawing units: into the move mode when it is on
* (its vertex, or the shape), else as a keyboard series (`keys`) of the shape or of
* `vertex`, stamped with the current text.
*/
export function stepSelection(
annotationId: string,
stored: Geometry,
delta: { x: number; y: number },
vertex: number | null = null,
): void {
const moved = translatedGeometry(shownGeometry(annotationId, stored), delta)
const { mode } = useAnnotationWork.getState()
const inMode = mode?.kind === 'move'
const shown = shownGeometry(annotationId, stored)
const moved = movedBy(shown, delta, inMode ? mode.vertex : vertex)
if (!moved) return
if (useAnnotationWork.getState().mode?.kind === 'move') {
return setModePreview(moved, stored)
}
if (inMode) return setModePreview(moved, stored)
const base = useEditorStore.getState().documentText
const preview: Preview = {
annotationId,
+42
View File
@@ -0,0 +1,42 @@
import { useEffect, useRef, type Dispatch } from 'react'
import { useEditorStore } from '../state/editorStore'
import type { Tracing, UiAction } from './uiState'
import {
endMode,
markRedraw,
startRedraw,
useAnnotationWork,
} from './workStore'
/**
* « Redessiner » (or « Remplacer par un polygone »): the redraw mode, which the drawing
* guard reads (R-12), and the tracing target `replace` that draws the new polygon.
*/
export function beginRedraw(id: string, dispatch: Dispatch<UiAction>): void {
startRedraw(id, useEditorStore.getState().documentText)
dispatch({ type: 'trace_start', target: 'replace', annotationId: id })
}
/**
* The redraw lives in two places, the tab's tracing and the work store's mode; whichever
* ends first ends the other: a tracing gone (closed, « Annuler le tracé », Escape, a
* tool, a view, a selection) ends the mode; a mode gone (« Abandonner », an undo, a
* document change made elsewhere) ends the tracing. The mode is started once the
* tracing holds a vertex, and no longer when it is back to none.
*/
export function useRedrawFollowsTracing(
tracing: Tracing | null,
dispatch: Dispatch<UiAction>,
): void {
const redraw = useAnnotationWork((s) => s.mode?.kind === 'redraw')
const count = tracing?.target === 'replace' ? tracing.points.length : null
// Only the body whose tracing it was ends the mode: another body kept alive has none.
const traced = useRef(false)
useEffect(() => {
const was = traced.current
traced.current = count !== null
if (redraw && count === null && was) endMode()
else if (!redraw && count !== null) dispatch({ type: 'trace_cancel' })
else if (count !== null) markRedraw(count > 0)
}, [redraw, count, dispatch])
}
+34 -14
View File
@@ -9,6 +9,7 @@ import type { GlyphName } from '@/components/editor/EditorGlyph'
import type { Locale } from '@/i18n/types'
import { pluralKey } from '../plural'
import type { PendingElement } from './creation'
import { HANDLE_CAP } from './polygonEdit'
import type { ToolId, Tracing, UiState } from './uiState'
/** The strip's left part: what is selected or in progress, then its type and detail. */
@@ -24,6 +25,8 @@ export interface LeadContext {
locale: Locale
/** The sheet cannot be edited now: the detail says so (board 33 E). */
readOnly?: boolean
/** The chosen vertex of the selected polygon, said after its count. */
chosenVertex?: number | null
}
const ICON: Record<Annotation['kind'], GlyphName> = {
@@ -45,6 +48,23 @@ function counted(
.replace('{kind}', () => kind)
}
/**
* « Zone · 9 sommets », « … · sommet 7 choisi », or above the cap (T18) « Zone · 41
* sommets, trop pour les poignées ».
*/
function polygonDetail(count: number, kind: string, ctx: LeadContext): string {
if (count > HANDLE_CAP && !ctx.readOnly) {
return counted(ctx, 'editor.annotations.strip.too_many', count, kind)
}
const shape = counted(ctx, 'editor.annotations.strip.vertices', count, kind)
const chosen = ctx.chosenVertex
if (chosen === null || chosen === undefined || ctx.readOnly) return shape
return ctx
.t('editor.annotations.strip.vertex_chosen')
.replace('{detail}', () => shape)
.replace('{n}', String(chosen + 1))
}
/** « Point », « Zone · 9 sommets »; « … · fiche en lecture seule » when read-only. */
export function selectionLead(
annotation: Annotation,
@@ -55,12 +75,7 @@ export function selectionLead(
const geometry = annotation.geometry
const shape =
geometry?.type === 'polygon'
? counted(
ctx,
'editor.annotations.strip.vertices',
geometry.points.length,
kind,
)
? polygonDetail(geometry.points.length, kind, ctx)
: kind
return {
title: annotationName(annotation, views, ctx.locale),
@@ -74,17 +89,22 @@ export function selectionLead(
}
}
/** A tracing: « Ajouter une zone » or « Redessiner · {nom} », then the vertices placed. */
/**
* A tracing: « Ajouter une zone » or « Redessiner · {nom} », then the vertices placed;
* « Fermeture refusée » while the core's refusal of its close shows (board 33 A).
*/
function tracingLead(
tracing: Tracing,
replaced: string,
ctx: LeadContext,
ctx: LeadContext & { refused: boolean },
): StripLead {
const title =
tracing.target === 'replace'
? ctx
.t('editor.annotations.strip.redraw')
.replace('{name}', () => replaced)
const redraw = ctx
.t('editor.annotations.strip.redraw')
.replace('{name}', () => replaced)
const title = ctx.refused
? ctx.t('editor.annotations.strip.close_refused')
: tracing.target === 'replace'
? redraw
: ctx.t(`editor.annotations.add.${tracing.target}`)
return {
title,
@@ -149,7 +169,7 @@ export function stripLeadOf(
(a) => a.id === ui.tracing?.annotationId,
)
const name = replaced ? annotationName(replaced, doc.views, ctx.locale) : ''
return tracingLead(ui.tracing, name, ctx)
return tracingLead(ui.tracing, name, { ...ctx, refused: ui.hint !== null })
}
if (selected) return selectionLead(selected, doc.views, ctx)
const lead = TOOL_LEAD[ui.tool]
+11 -1
View File
@@ -60,6 +60,10 @@ const TOOL_OF: Record<Tracing['target'], ToolId> = {
replace: 'zone',
}
/** A redraw lends the zone tool to its tracing: whatever ends it gives the select tool back. */
const toolAfterTracing = (state: UiState): ToolId =>
state.tracing?.target === 'replace' ? 'select' : state.tool
export function uiReducer(state: UiState, action: UiAction): UiState {
switch (action.type) {
case 'view':
@@ -69,6 +73,7 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
case 'select':
return {
...state,
tool: toolAfterTracing(state),
selectedId: action.id,
pending: null,
tracing: null,
@@ -124,7 +129,12 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
}
: state
case 'trace_cancel':
return { ...state, tracing: null, hint: null }
return {
...state,
tool: toolAfterTracing(state),
tracing: null,
hint: null,
}
case 'hint':
return { ...state, hint: action.hint }
case 'filter':
+45 -13
View File
@@ -2,9 +2,12 @@ import { useEffect, useRef, useState, type RefObject } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import type { XY } from './frame'
import { clientToDrawing, translatedGeometry } from './gesture'
import { clientToDrawing, movedBy } from './gesture'
import { isNoOpMove } from './polygonEdit'
import { shownGeometry } from './previewCommit'
import { setModePreview } from './workStore'
import type { GeometryChange } from './usePlacement'
import { chooseVertex } from './zoneEdit'
import { setModePreview, useAnnotationWork } from './workStore'
import type { EditableGeometry } from './geometryEdit'
export interface MoveTarget {
@@ -18,7 +21,7 @@ export interface BlockDragInput {
/** The selected annotation, when it can be moved (editable, measured, circle or polygon). */
target: MoveTarget | null
/** One `update` on the drop; the verdict and the message are the caller's. */
onDrop: (id: string, geometry: Geometry) => void
onDrop: (id: string, geometry: Geometry, change?: GeometryChange) => boolean
}
interface Drag {
@@ -29,6 +32,8 @@ interface Drag {
base: Geometry
/** A drag of the move mode (board 06 B): it moves the mode's preview, never commits. */
mode: boolean
/** The vertex dragged alone (a vertex handle, or the mode's chosen vertex). */
vertex: number | null
}
function translatedAt(
@@ -38,10 +43,27 @@ function translatedAt(
): Geometry | null {
const now = clientToDrawing(overlay.current, client)
if (!now) return null
return translatedGeometry(drag.base, {
x: now.x - drag.origin.x,
y: now.y - drag.origin.y,
})
const delta = { x: now.x - drag.origin.x, y: now.y - drag.origin.y }
return movedBy(drag.base, delta, drag.vertex)
}
/** A vertex released on itself or on a neighbour moves nothing: no commit. */
function isNoOp(drag: Drag, dropped: Geometry): boolean {
const { base, vertex } = drag
if (vertex === null || base.type !== 'polygon') return false
return (
dropped.type === 'polygon' &&
isNoOpMove(base.points, vertex, dropped.points)
)
}
/** A drop outside the mode commits once: the shape moved, or its vertex. */
function commitDrop(input: BlockDragInput, drag: Drag, dropped: Geometry) {
if (drag.mode || isNoOp(drag, dropped)) return
const { id } = drag.target
if (drag.vertex === null) return void input.onDrop(id, dropped, 'move')
// The dragged vertex stays chosen on the new text (board 05 B).
if (input.onDrop(id, dropped, 'vertex')) chooseVertex(id, drag.vertex)
}
/** Losing the target (read-only, another selection) or a document change drops the drag. */
@@ -77,14 +99,24 @@ function dragActions(
drag.current = null
setPreview(null)
}
const start = (pressedAt: XY, client: XY, mode = false) => {
/** `vertex`: a vertex handle's drag; the move mode drags its own vertex, if any. */
const start = (
pressedAt: XY,
client: XY,
mode: boolean,
vertex: number | null,
) => {
const origin = clientToDrawing(input.overlay.current, pressedAt)
const { target } = input
if (!target || !origin) return
const base = mode
? shownGeometry(target.id, target.geometry)
: target.geometry
drag.current = { target, origin, base, mode }
const own = mode
? (useAnnotationWork.getState().mode?.vertex ?? null)
: vertex
if (!mode && vertex !== null) chooseVertex(target.id, vertex)
drag.current = { target, origin, base, mode, vertex: own }
show(translatedAt(input.overlay, drag.current, client))
}
const follow = (client: XY) => {
@@ -98,15 +130,15 @@ function dragActions(
if (gesture?.mode) show(dropped)
drag.current = null
setPreview(null)
if (gesture && !gesture.mode && dropped)
input.onDrop(gesture.target.id, dropped)
if (gesture && dropped) commitDrop(input, gesture, dropped)
}
return { start, follow, drop, cancel }
}
/**
* The selection moved as a block (`drag_shape`, `drag_point`): the overlay previews the
* translated outline, kept local to the canvas for speed; the drop commits once. A drag
* The selection moved as a block (`drag_shape`, `drag_point`) or one of its vertices
* (`drag_vertex`): the overlay previews the outline, kept local to the canvas for speed;
* the drop commits once. A drag
* of the move mode (`drag_mode`) moves the mode's preview instead, and commits nothing.
*/
export function useBlockDrag(input: BlockDragInput) {
+68 -41
View File
@@ -10,12 +10,10 @@ import { updateGeometry, type CommitContext } from './annotationCommit'
import { pendingForClick, type NewKind } from './creation'
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'
/** 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',
@@ -35,47 +33,56 @@ export interface PlacementInput {
const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)]
function nearFirstVertex(tracing: Tracing, at: XY, frame: Frame): boolean {
/** 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
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).
* 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).
*/
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 }]
}
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 [{ type: 'trace_cancel' }]
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) return [{ type: 'select', id: annotation.id }]
return [
{ type: 'trace_cancel' },
{ type: 'hint', hint: result.messages.join(' ') },
]
if (!result.ok) {
useAnnotationWork.setState({ mode: held })
return dispatch({ type: 'hint', 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' })
}
/** Tracing with the zone and link tools: vertices, closing, Enter, Backspace and Escape. */
function tracingActions(input: PlacementInput) {
const { ui, dispatch, frame } = input
const closeTracing = () =>
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)) {
const { ui, dispatch } = input
const closeTracing = () => {
const tracing = ui.tracing
if (!tracing || tracing.points.length < 3) return
if (tracing.target === 'replace') return closeRedraw(input, tracing)
const pending = {
kind: tracing.target,
geometry: { type: 'polygon' as const, points: tracing.points },
}
dispatch({ type: 'pending_new', pending })
}
const trace = (
tool: Exclude<ToolId, 'select' | 'point'>,
at: XY,
reach: number,
) => {
if (ui.tracing && nearFirstVertex(ui.tracing, at, reach)) {
return closeTracing()
}
if (!ui.tracing)
@@ -97,14 +104,25 @@ function tracingActions(input: PlacementInput) {
return { closeTracing, trace, onTraceKey }
}
/** A move (drag, move mode, arrow keys) or a size change of the selection. */
export type GeometryChange = 'move' | 'size'
/**
* 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<Exclude<GeometryChange, 'move'>, 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']) {
return change === 'size'
? { kept: 'resized', refused: 'size_refused' }
: { kept: `moved.${kind}`, refused: 'move_refused' }
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' }
}
/**
@@ -112,24 +130,32 @@ function changeKeys(change: GeometryChange, kind: Annotation['kind']) {
* 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') => {
return (
id: string,
geometry: Geometry,
change: GeometryChange = 'move',
): boolean => {
const annotation = doc.annotations.find((a) => a.id === id)
if (!annotation) return
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}`)
return message.show(text, { undo: true, tone: 'info' })
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<typeof dropAction>
/**
* 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.
@@ -139,9 +165,10 @@ export function usePlacement(input: PlacementInput) {
const t = useT()
const tracing = tracingActions(input)
const { ui, dispatch, frame } = input
const onPlace = (at: XY) => {
/** `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)
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)
@@ -1,9 +1,10 @@
import type { KeyboardEvent } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import type { Annotation } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import { moveStep, type Frame } from './frame'
import type { GeometryChange } from './usePlacement'
import type { Drop } from './usePlacement'
import { takeMove, takePreview, stepSelection } from './previewCommit'
import { chooseVertex, freshChosen } from './zoneEdit'
import {
endMode,
startMove,
@@ -11,10 +12,8 @@ import {
type Preview,
} from './workStore'
type Drop = (id: string, geometry: Geometry, change?: GeometryChange) => void
export interface PointEditInput {
/** The selection when it can be moved now (a circle: a point or a link). */
/** The selection when it can be moved now: a circle (point, link) or a polygon. */
target: Annotation | null
frame: Frame | null
onDrop: Drop
@@ -67,8 +66,13 @@ function commits({ onDrop, target }: PointEditInput) {
}
}
const move = () => {
const vertex = useAnnotationWork.getState().mode?.vertex ?? null
const preview = takeMove()
if (preview) onDrop(preview.annotationId, preview.geometry)
if (!preview) return
const { annotationId: id, geometry } = preview
if (vertex === null) return void onDrop(id, geometry)
// The moved vertex stays chosen on the new text.
if (onDrop(id, geometry, 'vertex')) chooseVertex(id, vertex)
}
return { keys, size, move }
}
@@ -102,9 +106,12 @@ export function usePointEdit(input: PointEditInput) {
// BDR-050: leaving the handle commits its series; a move mode waits for « Valider ».
onHandleBlur: () => commit.keys(),
commitSize: commit.size,
// « Déplacer le sommet » while a vertex is chosen, else the whole shape.
startMove: () => {
if (!input.target) return
startMove(input.target.id, useEditorStore.getState().documentText)
const id = input.target?.id
if (!id) return
const base = useEditorStore.getState().documentText
startMove(id, base, freshChosen(id))
},
stepMove: (direction: Direction) => step(input, direction, false),
confirmMove: commit.move,
@@ -1,7 +1,9 @@
import { useEffect, useRef, type PointerEvent, type RefObject } from 'react'
import type { XY } from './frame'
import { clientToDrawing } from './gesture'
import { clientToDrawing, drawingPerClientPx } from './gesture'
import { HANDLE_CAP } from './polygonEdit'
import {
CLOSE_PX,
clickAction,
dragAction,
isDoubleClick,
@@ -28,8 +30,10 @@ export interface PressInput extends BlockDragInput {
selectedId: string | null
viewport: RefObject<HTMLDivElement | null>
onSelect: (id: string) => void
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
/** A click with a drawing tool, in drawing units, with its closing reach (R-11). */
onPlace: (at: XY, reach: number) => void
/** A click on a vertex handle, a « + » or the « − » bubble. */
onHandle: (action: HandleAction) => void
/** A tap on the empty drawing with the select tool. */
onDeselect: () => void
}
@@ -91,16 +95,23 @@ function doubled(
return id === null ? action : { type: 'open', id }
}
/**
* What a click does with the select tool. `open` (the properties dialog) and the vertex
* handles (`choose_vertex`, `insert`, `remove`) have nothing to act on yet.
*/
export type HandleAction = Extract<
ClickAction,
{ type: 'choose_vertex' | 'insert' | 'remove' }
>
const isHandleAction = (action: ClickAction): action is HandleAction =>
action.type === 'choose_vertex' ||
action.type === 'insert' ||
action.type === 'remove'
/** What a click does with the select tool. `open` (the properties dialog) has nothing yet. */
function runClick(action: ClickAction, input: PressInput): void {
if (action.type === 'select') input.onSelect(action.id)
else if (action.type === 'deselect') input.onDeselect()
else if (action.type === 'unchoose') {
useAnnotationWork.setState({ chosen: null })
}
} else if (isHandleAction(action)) input.onHandle(action)
}
interface Machine {
@@ -123,8 +134,11 @@ interface Feed {
/** A click with a drawing tool places at the pointer-up, in drawing units. */
function place(input: PressInput, event: PointerEvent): void {
const drawn = clientToDrawing(input.overlay.current, clientOf(event))
if (drawn) input.onPlace(drawn)
const svg = input.overlay.current
const drawn = clientToDrawing(svg, clientOf(event))
const perPx = drawingPerClientPx(svg)
if (!drawn || perPx === null) return
input.onPlace(drawn, CLOSE_PX[pointerKindOf(event.pointerType)] * perPx)
}
/** A click with the select tool: its action, or `open` as the second of a double click. */
@@ -144,7 +158,12 @@ function onClick(f: Feed, target: PressTarget, event: PointerEvent): void {
if (!inMoveMode()) selectClick(f, target, event)
}
const BLOCK_DRAGS = new Set(['drag_shape', 'drag_point', 'drag_mode'])
const BLOCK_DRAGS = new Set([
'drag_shape',
'drag_point',
'drag_mode',
'drag_vertex',
])
function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) {
if (effect?.type === 'drag_cancel') f.drag.cancel()
@@ -152,13 +171,22 @@ function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) {
if (effect.type === 'click') onClick(f, effect.target, event)
if (effect.type === 'drag_end') f.drag.drop(clientOf(event))
if (effect.type === 'drag_start' && BLOCK_DRAGS.has(effect.action.type)) {
const mode = effect.action.type === 'drag_mode'
f.drag.start(f.machine.current.pressedAt, clientOf(event), mode)
const { action } = effect
const vertex = action.type === 'drag_vertex' ? action.index : null
const mode = action.type === 'drag_mode'
f.drag.start(f.machine.current.pressedAt, clientOf(event), mode, vertex)
}
}
/** R-7: above the handle cap a polygon keeps the move mode and the redraw only. */
function movable(input: PressInput): boolean {
const geometry = input.target?.geometry
if (!geometry) return false
return geometry.type !== 'polygon' || geometry.points.length <= HANDLE_CAP
}
const contextOf = (input: PressInput) => ({
movable: input.target !== null,
movable: movable(input),
moveMode: inMoveMode(),
})
@@ -0,0 +1,149 @@
import type { KeyboardEvent } from 'react'
import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import { moveStep, type Frame } from './frame'
import { insertMidpoint, removeVertex } from './polygonEdit'
import { stepSelection, takePreview } from './previewCommit'
import type { Drop } from './usePlacement'
import type { GestureMessages } from './useGestureMessage'
import type { HandleAction } from './usePressGesture'
import { chooseVertex, freshChosen } from './zoneEdit'
import { useAnnotationWork } from './workStore'
export interface ZoneEditInput {
/** The selected polygon when its vertices can be edited now (editable, measured). */
target: Annotation | null
frame: Frame | null
onDrop: Drop
message: Pick<GestureMessages, 'show'>
t: (key: string) => string
/** The move mode's own Enter: « Valider la position ». */
confirmMove: () => void
}
const STEP: Record<string, [number, number]> = {
ArrowLeft: [-1, 0],
ArrowUp: [0, -1],
ArrowDown: [0, 1],
ArrowRight: [1, 0],
}
const pointsOf = (target: Annotation | null): Point[] | null =>
target?.geometry?.type === 'polygon' ? target.geometry.points : null
/** « + »: the midpoint commits once, and the new vertex is chosen on the new text. */
function insertAfter(input: ZoneEditInput, after: number): void {
const { target, onDrop } = input
const next = insertMidpoint(pointsOf(target) ?? [], after)
if (!target || !next) return
const polygon = { type: 'polygon' as const, points: next }
if (onDrop(target.id, polygon, 'insert')) chooseVertex(target.id, after + 1)
}
/**
* « − »: only the vertex chosen on the current text (Review Focus 2: an undo drops it, so a
* stale bubble or key removes nothing). At three vertices the reason is said instead.
*/
function removeChosen(input: ZoneEditInput, index: number): boolean {
const { target, onDrop } = input
const points = pointsOf(target)
if (!target || !points || freshChosen(target.id) !== index) return false
const next = removeVertex(points, index)
if (!next) {
const text = input.t('editor.annotations.message.vertex_min')
input.message.show(text, { undo: false, tone: 'error' })
return false
}
return onDrop(target.id, { type: 'polygon', points: next }, 'remove')
}
/** The keyboard series of a vertex commits once, the vertex still chosen after. */
function commitKeys(input: ZoneEditInput): void {
const { target, onDrop } = input
const preview = takePreview('keys')
if (!target || !preview || preview.annotationId !== target.id) return
const same =
JSON.stringify(preview.geometry) === JSON.stringify(target.geometry)
if (same) return
const vertex = freshChosen(target.id)
const kept = onDrop(target.id, preview.geometry, 'vertex')
if (kept && vertex !== null) chooseVertex(target.id, vertex)
}
function stepVertex(input: ZoneEditInput, index: number, event: KeyboardEvent) {
const { target, frame } = input
const [x, y] = STEP[event.key]
if (!target?.geometry || !frame) return
const size = moveStep(frame, event.shiftKey)
stepSelection(target.id, target.geometry, { x: x * size, y: y * size }, index)
}
const inMoveMode = () => useAnnotationWork.getState().mode?.kind === 'move'
/** Delete removes the chosen vertex; the next one is chosen so the focus stays on a vertex. */
function deleteChosen(input: ZoneEditInput): void {
const id = input.target?.id
const chosen = id ? freshChosen(id) : null
if (id === undefined || chosen === null || !removeChosen(input, chosen))
return
const left = pointsOf(input.target)!.length - 2
chooseVertex(id, Math.min(chosen, left))
}
/** A vertex handle's keys (board 32): arrows step it, Enter commits, Insert adds, Delete. */
function vertexKey(input: ZoneEditInput, index: number, event: KeyboardEvent) {
const id = input.target?.id
if (STEP[event.key]) {
event.preventDefault()
return stepVertex(input, index, event)
}
if (event.key === 'Enter') {
event.preventDefault()
return inMoveMode() ? input.confirmMove() : commitKeys(input)
}
const chosen = id ? freshChosen(id) : null
if (event.key === 'Insert' && chosen !== null) insertAfter(input, chosen)
if (event.key === 'Delete') deleteChosen(input)
}
/** Enter or Space on a « + » or on the « − » bubble is its click. */
const isPress = (event: KeyboardEvent) =>
event.key === 'Enter' || event.key === ' '
/**
* Zone editing (R-7 to R-13): a click on a vertex chooses it, « + » inserts at a segment's
* midpoint, « − » removes the chosen vertex, and the vertex handles' keys. Every change
* commits once through `onDrop`, the core deciding.
*/
export function useZoneEdit(input: ZoneEditInput) {
const onHandle = (action: HandleAction) => {
const id = input.target?.id
if (!id) return
if (action.type === 'choose_vertex') chooseVertex(id, action.index)
if (action.type === 'insert') insertAfter(input, action.after)
if (action.type === 'remove') removeChosen(input, action.index)
}
return {
onHandle,
onVertexKey: (index: number, event: KeyboardEvent) =>
vertexKey(input, index, event),
// Focus chooses (board 32: Insert and Delete act on the chosen vertex).
onVertexFocus: (index: number) => {
const id = input.target?.id
if (id && freshChosen(id) !== index) chooseVertex(id, index)
},
// BDR-050: leaving the vertex commits its series; a move mode waits for « Valider ».
onVertexBlur: () => commitKeys(input),
onInsertKey: (after: number, event: KeyboardEvent) => {
if (!isPress(event)) return
event.preventDefault()
insertAfter(input, after)
},
onRemoveKey: (index: number, event: KeyboardEvent) => {
if (!isPress(event)) return
event.preventDefault()
removeChosen(input, index)
},
}
}
export type ZoneEdit = ReturnType<typeof useZoneEdit>
+24 -3
View File
@@ -31,6 +31,8 @@ export interface ModeWork {
annotationId: string
started: boolean
base: string
/** The chosen vertex a move mode moves alone (« Déplacer le sommet »); null: the shape. */
vertex: number | null
}
export type GuardWork = 'creation' | 'move' | 'redraw' | null
/** A navigation held by the drawing guard (R-12): what it asks about, and the move itself. */
@@ -68,15 +70,34 @@ export function endMode(): void {
useAnnotationWork.setState({ mode: null, preview: null })
}
/** « Déplacer … »: the mode on `annotationId`, nothing moved yet. */
export function startMove(annotationId: string, base: string): void {
/** « Déplacer … »: the mode on `annotationId` (or its vertex `vertex`), nothing moved yet. */
export function startMove(
annotationId: string,
base: string,
vertex: number | null = null,
): void {
useAnnotationWork.setState({
mode: { kind: 'move', annotationId, started: false, base },
mode: { kind: 'move', annotationId, started: false, base, vertex },
preview: null,
})
}
/** « Redessiner »: the redraw of `annotationId`, no vertex placed yet (R-12). */
export function startRedraw(annotationId: string, base: string): void {
useAnnotationWork.setState({
mode: { kind: 'redraw', annotationId, started: false, base, vertex: null },
preview: null,
chosen: null,
})
}
/** The redraw is started once its tracing holds a vertex, and no longer at none. */
export function markRedraw(started: boolean): void {
const { mode } = useAnnotationWork.getState()
if (mode?.kind !== 'redraw' || mode.started === started) return
useAnnotationWork.setState({ mode: { ...mode, started } })
}
const sameGeometry = (a: Geometry, b: Geometry) =>
JSON.stringify(a) === JSON.stringify(b)
@@ -0,0 +1,24 @@
import type { Geometry, Point } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import { HANDLE_CAP } from './polygonEdit'
import { useAnnotationWork } from './workStore'
/** A polygon's vertices when it gets handles (R-7: at most HANDLE_CAP), else null. */
export function handledPoints(geometry: Geometry | null): Point[] | null {
if (geometry?.type !== 'polygon') return null
return geometry.points.length > HANDLE_CAP ? null : geometry.points
}
/** The vertex `vertex` of `annotationId` is chosen, stamped with the current text (R-13). */
export function chooseVertex(annotationId: string, vertex: number): void {
const base = useEditorStore.getState().documentText
useAnnotationWork.setState({ chosen: { annotationId, vertex, base } })
}
/** The chosen vertex of `annotationId`, only when it was chosen on the current text. */
export function freshChosen(annotationId: string): number | null {
const { chosen } = useAnnotationWork.getState()
if (chosen?.annotationId !== annotationId) return null
const current = useEditorStore.getState().documentText
return chosen.base === current ? chosen.vertex : null
}