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

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

No files matched your search

@@ -0,0 +1,103 @@
import type {
Annotation,
EditCommand,
Geometry,
} from '@faunosteo/core-wasm/types'
import type { Locale } from '@/i18n/types'
import { frameRefusalMessage } from '../frameRefusal'
import { newElementId } from '../ids'
import { geometryAccept, type GeometryRefusal } from '../issues'
import { refusalMessage } from '../refusal'
import { useEditorStore } from '../state/editorStore'
import type { CommitOutcome } from '../state/editorTypes'
type Translate = (key: string) => string
/** What a geometry commit answers: kept, or the words and the core's codes at fault. */
export type CommitResult =
| { ok: true; id?: string }
| { ok: false; messages: string[]; codes: string[]; duplicate?: boolean }
export interface CommitContext {
t: Translate
locale: Locale
}
function describe(
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
{ t, locale }: CommitContext,
): CommitResult {
if (outcome.reason !== 'refused') {
const duplicate =
outcome.reason === 'core' && outcome.failure.kind === 'duplicate_key'
return {
ok: false,
messages: [refusalMessage(t, outcome)],
codes: [],
duplicate,
}
}
const { refusal } = outcome
const doc = useEditorStore.getState().previewState?.document ?? null
if (refusal.reason === 'changed_invalid') {
const messages = [...new Set(refusal.issues.map((i) => i.message))]
return { ok: false, messages, codes: refusal.issues.map((i) => i.code) }
}
const message =
refusal.reason === 'newly_invalid'
? frameRefusalMessage(t, refusal, doc, locale)
: t('editor.annotations.unmeasured.hint')
return { ok: false, messages: [message], codes: [] }
}
/** One command through the store with the geometry `accept` of the changed annotation. */
function commitGeometry(
command: EditCommand,
annotationId: string,
context: CommitContext,
): CommitResult {
const store = useEditorStore.getState()
const before = store.previewState
if (before === null) {
return {
ok: false,
messages: [context.t('editor.refusal.blocked')],
codes: [],
}
}
const accept = geometryAccept({ before, changedIds: [annotationId] })
const outcome = store.commit(command, { accept })
return outcome.ok ? { ok: true } : describe(outcome, context)
}
/** Inserts a new annotation under a fresh id; one regeneration on `duplicate_key`. */
export function insertAnnotation(
build: (id: string) => Annotation,
context: CommitContext,
): CommitResult {
const attempt = () => {
const annotation = build(newElementId('anno'))
const command: EditCommand = {
op: 'insert',
element: { kind: 'annotation', value: annotation },
}
const result = commitGeometry(command, annotation.id, context)
return result.ok ? { ok: true as const, id: annotation.id } : result
}
const first = attempt()
return !first.ok && first.duplicate ? attempt() : first
}
/** Replaces one annotation's geometry (move, numeric group, vertex, polygon) under `accept`. */
export function updateGeometry(
annotation: Annotation,
geometry: Geometry,
context: CommitContext,
): CommitResult {
const command: EditCommand = {
op: 'update',
key: { kind: 'annotation', id: annotation.id },
element: { kind: 'annotation', value: { ...annotation, geometry } },
}
return commitGeometry(command, annotation.id, context)
}
@@ -0,0 +1,68 @@
import {
correctedCircle,
defaultRadius,
sameCircle,
type CircleShape,
type Frame,
type XY,
} from './frame'
import type { CommitResult } from './annotationCommit'
/** The corrected position offered to the user, with the position it replaces. */
export interface Correction {
/** The position the user chose (drawn as a hollow cross, apart from the proposal). */
click: XY
circle: CircleShape
}
const OUT_OF_FRAME = 'annotation.geometry.out_of_frame'
/**
* Candidate C is offered when the core refused a point proposal that was either a
* reduced radius (B) or refused `out_of_frame` (A at a float edge). An A refused
* `too_small` (r0 already capped) offers nothing: the issue is shown instead.
*/
export function correctionFor(
frame: Frame,
attempted: CircleShape,
refusedCodes: readonly string[],
): Correction | null {
const reduced = attempted.r < defaultRadius(frame)
if (!reduced && !refusedCodes.includes(OUT_OF_FRAME)) return null
const click = { x: attempted.cx, y: attempted.cy }
const circle = correctedCircle(frame, click)
return sameCircle(circle, attempted) ? null : { click, circle }
}
/** The creation of a point as the panel runs it: the core's verdict decides each step. */
export type PointAttempt =
| { status: 'created'; id?: string }
| { status: 'correction'; correction: Correction }
| { status: 'refused'; messages: string[] }
export type InsertCircle = (circle: CircleShape) => CommitResult
/** « Créer »: insert the pending circle; on a refusal, offer C (never insert it unasked). */
export function attemptPoint(
frame: Frame,
circle: CircleShape,
insert: InsertCircle,
): PointAttempt {
const result = insert(circle)
if (result.ok) return { status: 'created', id: result.id }
const correction = correctionFor(frame, circle, result.codes)
return correction
? { status: 'correction', correction }
: { status: 'refused', messages: result.messages }
}
/** « Utiliser cette position »: C goes through the same insert and the same verdict. */
export function confirmCorrection(
correction: Correction,
insert: InsertCircle,
): PointAttempt {
const result = insert(correction.circle)
return result.ok
? { status: 'created', id: result.id }
: { status: 'refused', messages: result.messages }
}
+155
View File
@@ -0,0 +1,155 @@
import type {
Annotation,
AnatomicalSheetDocument,
Geometry,
Laterality,
SheetView,
} from '@faunosteo/core-wasm/types'
import {
centreCircle,
centreTriangle,
defaultRadius,
proposePoint,
round2,
type Frame,
type XY,
} from './frame'
import type { Correction } from './correction'
import type { EditableGeometry } from './geometryEdit'
export type NewKind = 'point' | 'zone' | 'detail_trigger'
/** The element being created: its geometry is held here, outside the document. */
export interface PendingElement {
kind: NewKind
geometry: EditableGeometry
/** Candidate C awaiting the user's confirmation (a point only). */
correction?: Correction | null
}
/** What the creation panel collects (no default labels: names and laterality are typed). */
export interface CreationForm {
fr: string
en: string
categoryId: string
laterality: Laterality | ''
opensViewId: string
zoneId: string
regionCode: string
}
export const LATERALITIES: readonly Laterality[] = [
'unpaired',
'bilateral',
'left',
'right',
]
export function emptyForm(doc: AnatomicalSheetDocument): CreationForm {
return {
fr: '',
en: '',
categoryId: doc.categories[0]?.id ?? '',
laterality: '',
opensViewId: '',
zoneId: '',
regionCode: '',
}
}
/** Detail views that open from `viewId`: the core allows only a direct child. */
export function directChildren(
views: readonly SheetView[],
viewId: string,
): SheetView[] {
return views.filter(
(view) => view.kind === 'detail' && view.parent_view_id === viewId,
)
}
/** The pending element a keyboard « Ajouter … » button holds at the centre of F. */
export function keyboardPending(kind: NewKind, frame: Frame): PendingElement {
if (kind === 'point') {
return { kind, geometry: { type: 'circle', ...centreCircle(frame) } }
}
return { kind, geometry: { type: 'polygon', points: centreTriangle(frame) } }
}
export type FormProblem = 'names' | 'fields'
const blank = (value: string) => value.trim() === ''
/** Input shape only: what the core requires to exist, collected before the insert. */
export function formProblem(
kind: NewKind,
form: CreationForm,
): FormProblem | null {
if (form.categoryId === '' || form.laterality === '') return 'fields'
if (kind === 'detail_trigger') {
if (form.opensViewId === '') return 'fields'
return blank(form.fr) !== blank(form.en) ? 'names' : null
}
return blank(form.fr) || blank(form.en) ? 'names' : null
}
const orNull = (value: string): string | null => (blank(value) ? null : value)
/** The annotation the form and the pending geometry describe, under a given id. */
export function annotationOf(
id: string,
viewId: string,
pending: PendingElement,
form: CreationForm,
): Annotation {
const common = {
id,
view_id: viewId,
category_id: form.categoryId,
laterality: form.laterality as Laterality,
geometry: pending.geometry as Geometry,
review_status: 'to_confirm' as const,
color: null,
}
if (pending.kind === 'detail_trigger') {
const named = !blank(form.fr)
return {
...common,
kind: 'detail_trigger',
name: named ? { fr: form.fr, en: form.en } : null,
opens_view_id: form.opensViewId,
}
}
return {
...common,
kind: pending.kind,
name: { fr: form.fr, en: form.en },
finding_zone_id: orNull(form.zoneId),
vertebral_region_code: orNull(form.regionCode),
}
}
export type ClickOutcome =
| { kind: 'outside' }
| { kind: 'pending'; pending: PendingElement }
/**
* The pending point a click with the point tool holds: A or B at the click, or, when
* neither fits, the click with r0 and candidate C waiting for the user's confirmation.
*/
export function pendingForClick(frame: Frame, click: XY): ClickOutcome {
const proposal = proposePoint(frame, click)
if (proposal.kind === 'outside') return { kind: 'outside' }
if (proposal.kind === 'circle') {
const geometry = { type: 'circle' as const, ...proposal.circle }
return { kind: 'pending', pending: { kind: 'point', geometry } }
}
const at = { x: round2(click.x), y: round2(click.y) }
const geometry = {
type: 'circle' as const,
cx: at.x,
cy: at.y,
r: defaultRadius(frame),
}
const correction = { click: at, circle: proposal.circle }
return { kind: 'pending', pending: { kind: 'point', geometry, correction } }
}
+147
View File
@@ -0,0 +1,147 @@
/**
* Proposal arithmetic for a new point (plan « Default point and the frame », C26). The
* page only PROPOSES values; the core decides every one of them on the candidate
* document. Nothing here copies a core rule (no visibility constant, no preview size,
* no twin radius, no edge tolerance).
*/
export interface Frame {
x: number
y: number
w: number
h: number
}
export interface XY {
x: number
y: number
}
export interface CircleShape {
cx: number
cy: number
r: number
}
export type PointProposal =
| { kind: 'outside' }
| { kind: 'circle'; circle: CircleShape; shrunk: boolean }
| { kind: 'corrected'; circle: CircleShape }
/** Float noise of `v × 100` must not move a value across a hundredth. */
const EPSILON = 1e-9
export const round2 = (value: number): number => Math.round(value * 100) / 100
const floor2 = (value: number): number =>
Math.floor(value * 100 + EPSILON) / 100
const ceil2 = (value: number): number => Math.ceil(value * 100 - EPSILON) / 100
/**
* F from the composed root's `viewBox` attribute TEXT (the property `baseVal` is held in
* f32). Null when it is not four finite numbers or the span is not positive: the caller
* then has no frame, never the fallback `0 0 100 100`.
*/
export function parseFrame(viewBox: string | null): Frame | null {
if (viewBox === null) return null
const parts = viewBox
.trim()
.split(/[\s,]+/)
.map(Number)
if (parts.length !== 4 || !parts.every(Number.isFinite)) return null
const [x, y, w, h] = parts
return w > 0 && h > 0 ? { x, y, w, h } : null
}
/** r0 = min(12 + 0.03 × max(w, h), min(w, h) / 2), floored to 0.01. */
export function defaultRadius(frame: Frame): number {
const wanted = 12 + 0.03 * Math.max(frame.w, frame.h)
return floor2(Math.min(wanted, Math.min(frame.w, frame.h) / 2))
}
/** Where a keyboard-created point sits: the centre of F, which fits by construction. */
export function centreCircle(frame: Frame): CircleShape {
return {
cx: round2(frame.x + frame.w / 2),
cy: round2(frame.y + frame.h / 2),
r: defaultRadius(frame),
}
}
function distanceToEdge(frame: Frame, at: XY): number {
return Math.min(
at.x - frame.x,
frame.x + frame.w - at.x,
at.y - frame.y,
frame.y + frame.h - at.y,
)
}
/** One axis of candidate C: clamped inward on the hundredth grid, else exactly. */
function clampAxis(value: number, low: number, high: number): number {
const inwardLow = ceil2(low)
const inwardHigh = floor2(high)
if (inwardLow <= inwardHigh) {
return Math.min(Math.max(value, inwardLow), inwardHigh)
}
return Math.min(Math.max(value, low), high)
}
/**
* Candidate C: radius r0, the centre clamped per axis into [x + r0, x + w − r0] and
* [y + r0, y + h − r0], rounded inward to 0.01. When that rounding leaves an empty
* interval (r0 = min(w, h) / 2 with an origin off the grid) the exact clamped value is
* used: the core accepts any decimals.
*/
export function correctedCircle(frame: Frame, at: XY): CircleShape {
const r = defaultRadius(frame)
return {
cx: clampAxis(round2(at.x), frame.x + r, frame.x + frame.w - r),
cy: clampAxis(round2(at.y), frame.y + r, frame.y + frame.h - r),
r,
}
}
/**
* The proposal at a click (c rounded to 0.01, d its distance to the nearest edge of F):
* A (c, r0) when d ≥ r0; B (c, floor₀.₀₁(d)) when that radius is at least 0.01, else C
* at once; nothing outside F (the edge is inclusive).
*/
export function proposePoint(frame: Frame, click: XY): PointProposal {
if (distanceToEdge(frame, click) < 0) return { kind: 'outside' }
const at = { x: round2(click.x), y: round2(click.y) }
// A click inside F whose rounding lands outside it has no room: straight to C.
const distance = Math.max(distanceToEdge(frame, at), 0)
const r0 = defaultRadius(frame)
if (distance >= r0) {
return {
kind: 'circle',
circle: { cx: at.x, cy: at.y, r: r0 },
shrunk: false,
}
}
const smaller = floor2(distance)
if (smaller < 0.01) {
return { kind: 'corrected', circle: correctedCircle(frame, at) }
}
return {
kind: 'circle',
circle: { cx: at.x, cy: at.y, r: smaller },
shrunk: true,
}
}
/** The three vertices of a keyboard-created zone or link: 10 % of the smaller side. */
export function centreTriangle(frame: Frame): [number, number][] {
const side = 0.1 * Math.min(frame.w, frame.h)
const cx = frame.x + frame.w / 2
const cy = frame.y + frame.h / 2
const corners: [number, number][] = [
[cx, cy - side / 2],
[cx + side / 2, cy + side / 2],
[cx - side / 2, cy + side / 2],
]
return corners.map(([x, y]) => [round2(x), round2(y)])
}
export const sameCircle = (a: CircleShape, b: CircleShape): boolean =>
a.cx === b.cx && a.cy === b.cy && a.r === b.r
@@ -0,0 +1,118 @@
import type { Geometry, Point } from '@faunosteo/core-wasm/types'
import { round2 } from './frame'
/** The geometry group as typed: numbers stay text until the group is applied whole. */
export type GroupFields =
| { type: 'circle'; cx: string; cy: string; r: string }
| { type: 'polygon'; rows: { x: string; y: string }[] }
export type EditableGeometry = Extract<Geometry, { type: 'circle' | 'polygon' }>
export type GroupParse =
| { ok: true; geometry: EditableGeometry }
| { ok: false }
/** The stored numbers exactly as JSON prints them (no display rounding). */
export function fieldsOf(geometry: EditableGeometry): GroupFields {
if (geometry.type === 'circle') {
return {
type: 'circle',
cx: String(geometry.cx),
cy: String(geometry.cy),
r: String(geometry.r),
}
}
return {
type: 'polygon',
rows: geometry.points.map(([x, y]) => ({ x: String(x), y: String(y) })),
}
}
export function isEditable(
geometry: Geometry | null,
): geometry is EditableGeometry {
return geometry?.type === 'circle' || geometry?.type === 'polygon'
}
/** Input shape only: a blank or non-numeric field is no number. The core judges the rest. */
function numberOf(text: string): number | null {
if (text.trim() === '') return null
const value = Number(text)
return Number.isFinite(value) ? value : null
}
export function parseFields(fields: GroupFields): GroupParse {
if (fields.type === 'circle') {
const [cx, cy, r] = [fields.cx, fields.cy, fields.r].map(numberOf)
if (cx === null || cy === null || r === null) return { ok: false }
return { ok: true, geometry: { type: 'circle', cx, cy, r } }
}
const points: Point[] = []
for (const row of fields.rows) {
const [x, y] = [numberOf(row.x), numberOf(row.y)]
if (x === null || y === null) return { ok: false }
points.push([x, y])
}
return { ok: true, geometry: { type: 'polygon', points } }
}
/** True when every typed number equals the stored one: nothing to propose. */
export function sameAsStored(
fields: GroupFields,
stored: EditableGeometry,
): boolean {
const parsed = parseFields(fields)
if (!parsed.ok) return false
return JSON.stringify(parsed.geometry) === JSON.stringify(stored)
}
/** The rows whose text differs from the stored value: the ones marked « non appliqué ». */
export function changedFieldNames(
fields: GroupFields,
stored: EditableGeometry,
): Set<string> {
const base = fieldsOf(stored)
const changed = new Set<string>()
if (fields.type === 'circle' && base.type === 'circle') {
for (const key of ['cx', 'cy', 'r'] as const) {
if (fields[key] !== base[key]) changed.add(key)
}
return changed
}
if (fields.type === 'polygon' && base.type === 'polygon') {
fields.rows.forEach((row, index) => {
if (row.x !== base.rows[index]?.x) changed.add(`x${index}`)
if (row.y !== base.rows[index]?.y) changed.add(`y${index}`)
})
}
return changed
}
/** A new vertex halfway between the selected row and the next (wrapping), 2 decimals. */
export function withVertexAfter(
fields: Extract<GroupFields, { type: 'polygon' }>,
after: number,
): Extract<GroupFields, { type: 'polygon' }> {
const rows = fields.rows
const from = rows[after] ?? rows[rows.length - 1]
const to = rows[(after + 1) % rows.length] ?? from
const middle = (a: string, b: string) => {
const value = round2((Number(a) + Number(b)) / 2)
return Number.isFinite(value) && a.trim() !== '' && b.trim() !== ''
? String(value)
: ''
}
const added = { x: middle(from.x, to.x), y: middle(from.y, to.y) }
const at = Math.min(after, rows.length - 1) + 1
return {
type: 'polygon',
rows: [...rows.slice(0, at), added, ...rows.slice(at)],
}
}
export function withoutVertex(
fields: Extract<GroupFields, { type: 'polygon' }>,
index: number,
): Extract<GroupFields, { type: 'polygon' }> {
return { type: 'polygon', rows: fields.rows.filter((_, i) => i !== index) }
}
@@ -0,0 +1,59 @@
import type { Geometry } from '@faunosteo/core-wasm/types'
import { round2, type XY } from './frame'
/** CSS px a press must travel before it is a drag (a click with jitter never moves). */
export const DRAG_START_PX = 4
export function pastDragThreshold(from: XY, to: XY): boolean {
return Math.hypot(to.x - from.x, to.y - from.y) > DRAG_START_PX
}
/** A circle or polygon translated as a block by a drawing-unit delta, rounded to 0.01. */
export function translatedGeometry(
geometry: Geometry,
delta: XY,
): Geometry | null {
if (geometry.type === 'circle') {
return {
...geometry,
cx: round2(geometry.cx + delta.x),
cy: round2(geometry.cy + delta.y),
}
}
if (geometry.type === 'polygon') {
return {
type: 'polygon',
points: geometry.points.map(([x, y]) => [
round2(x + delta.x),
round2(y + delta.y),
]),
}
}
return null
}
interface Matrix {
a: number
b: number
c: number
d: number
e: number
f: number
}
/**
* Pointer → drawing coordinates through the overlay's `getScreenCTM().inverse()`. Null
* where the browser gives no matrix (nothing is proposed then).
*/
export function clientToDrawing(
svg: SVGSVGElement | null,
client: XY,
): XY | null {
const matrix = svg?.getScreenCTM?.()
const inverse: Matrix | undefined = matrix?.inverse()
if (!inverse) return null
return {
x: inverse.a * client.x + inverse.c * client.y + inverse.e,
y: inverse.b * client.x + inverse.d * client.y + inverse.f,
}
}
+108
View File
@@ -0,0 +1,108 @@
import type { Point } from '@faunosteo/core-wasm/types'
import type { NewKind, PendingElement } from './creation'
export type ToolId = 'select' | 'point' | 'zone' | 'link'
/** A tracing in progress: a new zone or link, or a polygon replacing a geometry. */
export interface Tracing {
target: NewKind | 'replace'
/** The annotation whose geometry the tracing replaces (target `replace`). */
annotationId: string | null
points: Point[]
}
export interface UiState {
viewId: string | null
tool: ToolId
selectedId: string | null
pending: PendingElement | null
/** Bumped by every new pending element: keys the creation form's own state. */
serial: number
tracing: Tracing | null
hint: string | null
}
export type UiAction =
| { type: 'view'; viewId: string }
| { type: 'tool'; tool: ToolId }
| { type: 'select'; id: string | null }
| { type: 'pending_new'; pending: PendingElement }
| { type: 'pending_update'; pending: PendingElement }
| { type: 'pending_drop' }
| { type: 'trace_start'; target: Tracing['target']; annotationId?: string }
| { type: 'trace_add'; point: Point }
| { type: 'trace_cancel' }
| { type: 'hint'; hint: string | null }
export const initialUi: UiState = {
viewId: null,
tool: 'select',
selectedId: null,
pending: null,
serial: 0,
tracing: null,
hint: null,
}
const TOOL_OF: Record<Tracing['target'], ToolId> = {
point: 'point',
zone: 'zone',
detail_trigger: 'link',
replace: 'zone',
}
export function uiReducer(state: UiState, action: UiAction): UiState {
switch (action.type) {
case 'view':
return { ...initialUi, viewId: action.viewId }
case 'tool':
return { ...state, tool: action.tool, tracing: null, hint: null }
case 'select':
return {
...state,
selectedId: action.id,
pending: null,
tracing: null,
hint: null,
}
case 'pending_new':
return {
...state,
pending: action.pending,
serial: state.serial + 1,
selectedId: null,
tracing: null,
hint: null,
}
case 'pending_update':
return state.pending ? { ...state, pending: action.pending } : state
case 'pending_drop':
return { ...state, pending: null, hint: null }
case 'trace_start':
return {
...state,
tool: TOOL_OF[action.target],
pending: null,
hint: null,
tracing: {
target: action.target,
annotationId: action.annotationId ?? null,
points: [],
},
}
case 'trace_add':
return state.tracing
? {
...state,
tracing: {
...state.tracing,
points: [...state.tracing.points, action.point],
},
}
: state
case 'trace_cancel':
return { ...state, tracing: null, hint: null }
case 'hint':
return { ...state, hint: action.hint }
}
}
@@ -0,0 +1,72 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { buildView } from '@/components/catalogue/CatalogueCanvas'
import { coreRuntime } from '@/core/runtime'
import { useEditorStore } from '../state/editorStore'
/** The composed root's own attributes, read as text (never `baseVal`). */
export interface RootAttributes {
viewBox: string | null
ratio: string
}
export type CanvasFailure = 'engine' | 'view'
const ANNOTATED = '[data-anno-id]'
/**
* Builds the core's composed view into `host`, again on every accepted handle change or
* retry (plan « Rendering and canvas »): the edit canvas follows the handle. Reports the
* root's attributes; a failure is the engine notice (retry) or the view notice.
*/
export function useCanvasBuild(viewId: string) {
const preview = useEditorStore((s) => s.preview)
const handleVersion = useEditorStore((s) => s.handleVersion)
const host = useRef<HTMLDivElement | null>(null)
const [attempt, setAttempt] = useState(0)
const [root, setRoot] = useState<RootAttributes | null>(null)
const [failure, setFailure] = useState<CanvasFailure | null>(null)
useEffect(() => {
const element = host.current
if (!element || !preview) return
const built = buildView(preview, viewId)
element.replaceChildren(...(built.ok ? [built.svg] : []))
setFailure(built.ok ? null : built.failure)
setRoot(
built.ok
? {
viewBox: built.svg.getAttribute('viewBox'),
ratio:
built.svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet',
}
: null,
)
}, [preview, viewId, handleVersion, attempt])
const retry = useCallback(() => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}, [])
return { host, root, failure, retry, handleVersion }
}
/** The selected annotation's markers wear `data-state="current"`, restyled in place. */
export function useSelectionMark(
host: React.RefObject<HTMLDivElement | null>,
selectedId: string | null,
rebuilt: unknown,
): void {
useEffect(() => {
host.current?.querySelectorAll<Element>(ANNOTATED).forEach((el) => {
if (el.getAttribute('data-anno-id') === selectedId) {
el.setAttribute('data-state', 'current')
} else el.removeAttribute('data-state')
})
}, [host, selectedId, rebuilt])
}
export const annotationIdOf = (target: EventTarget | null): string | null =>
target instanceof Element
? (target.closest(ANNOTATED)?.getAttribute('data-anno-id') ?? null)
: null
@@ -0,0 +1,107 @@
import {
useEffect,
useRef,
useState,
type PointerEvent,
type RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import type { XY } from './frame'
import {
clientToDrawing,
pastDragThreshold,
translatedGeometry,
} from './gesture'
import type { EditableGeometry } from './geometryEdit'
import { annotationIdOf } from './useCanvasBuild'
export interface MoveTarget {
id: string
geometry: EditableGeometry
}
export interface MoveOptions {
overlay: RefObject<SVGSVGElement | null>
/** The selected annotation, when it can be moved (editable, measured, circle or polygon). */
target: MoveTarget | null
/** One `update` on pointer-up; the verdict and the message are the caller's. */
onDrop: (id: string, geometry: Geometry) => void
}
interface Drag {
start: XY
origin: XY
started: boolean
}
const clientOf = (event: PointerEvent): XY => ({
x: event.clientX,
y: event.clientY,
})
/**
* Drag of the selected circle or polygon as a block (plan « Select »): it starts only
* after 4 CSS px from the press, so a click with jitter never moves it; the overlay
* previews the translated outline; pointer-up commits once, pointer-cancel and lost
* capture drop it with no command; losing the target (read-only mode) drops it too.
*/
export function useMoveGesture({ overlay, target, onDrop }: MoveOptions) {
const drag = useRef<Drag | null>(null)
const [preview, setPreview] = useState<Geometry | null>(null)
const [armed, setArmed] = useState(false)
const stop = () => {
drag.current = null
setPreview(null)
setArmed(false)
}
useEffect(() => {
if (target === null) stop()
}, [target])
const translated = (event: PointerEvent): Geometry | null => {
const now = clientToDrawing(overlay.current, clientOf(event))
const gesture = drag.current
if (!now || !gesture || !target) return null
return translatedGeometry(target.geometry, {
x: now.x - gesture.origin.x,
y: now.y - gesture.origin.y,
})
}
const claims = (event: PointerEvent): boolean =>
target !== null && annotationIdOf(event.target) === target.id
const onPointerDown = (event: PointerEvent) => {
if (!claims(event) || event.button !== 0) return
const origin = clientToDrawing(overlay.current, clientOf(event))
if (!origin) return
drag.current = { start: clientOf(event), origin, started: false }
event.currentTarget.setPointerCapture?.(event.pointerId)
setArmed(true)
}
const onPointerMove = (event: PointerEvent) => {
const gesture = drag.current
if (!gesture) return
if (!gesture.started && !pastDragThreshold(gesture.start, clientOf(event)))
return
gesture.started = true
setPreview(translated(event))
}
const onPointerUp = (event: PointerEvent) => {
const gesture = drag.current
const dropped = gesture?.started ? translated(event) : null
stop()
if (dropped && target) onDrop(target.id, dropped)
}
return {
preview,
armed,
claims,
handlers: {
onPointerDown,
onPointerMove,
onPointerUp,
onPointerCancel: stop,
onLostPointerCapture: stop,
},
}
}
@@ -0,0 +1,109 @@
import type { Dispatch, KeyboardEvent } from 'react'
import type {
AnatomicalSheetDocument,
Geometry,
Point,
} from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { updateGeometry, type CommitContext } from './annotationCommit'
import { pendingForClick, type NewKind } from './creation'
import { round2, type Frame, type XY } from './frame'
import type { ToolId, Tracing, UiAction, UiState } from './uiState'
/** A click on the first vertex closes the tracing when within this share of F's span. */
const CLOSE_SHARE = 0.015
const TOOL_TARGET: Record<Exclude<ToolId, 'select'>, NewKind> = {
point: 'point',
zone: 'zone',
link: 'detail_trigger',
}
export interface PlacementInput {
ui: UiState
dispatch: Dispatch<UiAction>
frame: Frame | null
doc: AnatomicalSheetDocument
context: CommitContext
}
const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)]
function nearFirstVertex(tracing: Tracing, at: XY, frame: Frame): boolean {
const first = tracing.points[0]
if (!first || tracing.points.length < 3) return false
const reach = CLOSE_SHARE * Math.max(frame.w, frame.h)
return Math.hypot(first[0] - at.x, first[1] - at.y) <= reach
}
/**
* What closing a tracing does: a new zone or link becomes the pending element; a polygon
* replacing a geometry is committed at once under `accept`, and a refusal drops the
* tracing with the core's message (the annotation is unchanged).
*/
export function closingActions(
tracing: Tracing | null,
doc: AnatomicalSheetDocument,
context: CommitContext,
): UiAction[] {
if (!tracing || tracing.points.length < 3) return []
const polygon = { type: 'polygon' as const, points: tracing.points }
if (tracing.target !== 'replace') {
const pending = { kind: tracing.target, geometry: polygon }
return [{ type: 'pending_new', pending }]
}
const annotation = doc.annotations.find((a) => a.id === tracing.annotationId)
if (!annotation) return [{ type: 'trace_cancel' }]
const result = updateGeometry(annotation, polygon, context)
if (result.ok) return [{ type: 'select', id: annotation.id }]
return [
{ type: 'trace_cancel' },
{ type: 'hint', hint: result.messages.join(' ') },
]
}
/**
* What a click, a key or a drop does with the current tool. Every geometry it proposes is
* arithmetic over F; the core decides at « Créer » or at the commit of an existing one.
*/
export function usePlacement(input: PlacementInput) {
const t = useT()
const { ui, dispatch, frame, doc, context } = input
const placePoint = (frame: Frame, at: XY) => {
const outcome = pendingForClick(frame, at)
if (outcome.kind === 'pending') {
return dispatch({ type: 'pending_new', pending: outcome.pending })
}
dispatch({ type: 'hint', hint: t('editor.annotations.outside') })
}
const closeTracing = () =>
closingActions(ui.tracing, doc, context).forEach(dispatch)
const trace = (tool: Exclude<ToolId, 'select' | 'point'>, at: XY) => {
if (!frame) return
if (ui.tracing && nearFirstVertex(ui.tracing, at, frame)) {
return closeTracing()
}
if (!ui.tracing)
dispatch({ type: 'trace_start', target: TOOL_TARGET[tool] })
dispatch({ type: 'trace_add', point: asPoint(at) })
}
const onPlace = (at: XY) => {
if (ui.tool === 'point' && frame) placePoint(frame, at)
else if (ui.tool === 'zone' || ui.tool === 'link') trace(ui.tool, at)
}
const onDrop = (id: string, geometry: Geometry) => {
const annotation = doc.annotations.find((a) => a.id === id)
if (!annotation) return
const result = updateGeometry(annotation, geometry, context)
const hint = result.ok ? null : result.messages.join(' ')
dispatch({ type: 'hint', hint })
}
const onKeyDown = (event: KeyboardEvent) => {
if (!ui.tracing) return
if (event.key === 'Enter') closeTracing()
if (event.key === 'Escape') dispatch({ type: 'trace_cancel' })
}
return { onPlace, onDrop, onKeyDown, closeTracing }
}
@@ -0,0 +1,54 @@
import { useEffect, useMemo } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
SheetView,
} from '@faunosteo/core-wasm/types'
import { unmeasuredViews } from '../issues'
import { useEditorStore } from '../state/editorStore'
import { directChildren } from './creation'
export interface ViewModel {
annotations: Annotation[]
/** The core measures this view: a frame can be read and geometry edited. */
measured: boolean
children: SheetView[]
}
export const mainViewId = (doc: AnatomicalSheetDocument): string =>
doc.views.find((view) => view.kind === 'main')?.id ?? doc.views[0]?.id ?? ''
export function useViewModel(
doc: AnatomicalSheetDocument,
viewId: string,
): ViewModel {
const state = useEditorStore((s) => s.previewState)
return useMemo(() => {
const unmeasured = state ? unmeasuredViews(state) : new Set<string>()
return {
annotations: doc.annotations.filter((a) => a.view_id === viewId),
measured: state !== null && !unmeasured.has(viewId),
children: directChildren(doc.views, viewId),
}
}, [doc, state, viewId])
}
const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]'
/** Ctrl+Z undoes and Ctrl+Shift+Z redoes, outside text fields (no Ctrl+Y). */
export function useUndoShortcuts(): void {
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
const target = event.target
if (target instanceof Element && target.closest(TEXT_TARGET)) return
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z')
return
event.preventDefault()
const store = useEditorStore.getState()
if (event.shiftKey) store.redoStep()
else store.undoStep()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [])
}