Files
faunosteo/apps/app/src/components/editor/annotations/EditableAnnotations.tsx
T
bchanot ebcf2723a0 fix(editor): overview rows ask first, no empty save, board 31 icons
U2 Task 6 review by self:

- The overview stays shown during a selection (A3): its rows and view
  rows now go through the drawing guard, so a started move or redraw
  asks before a click there drops it (R-12). Was a regression: the
  column was unreachable while selected before Task 6.
- The edit form compares and merges trimmed names and colour: a space
  typed alone is no change and writes no `update`.
- A layer opened with no opener (reload, Forward) returns the focus
  to its row on close.
- Board 31 A: icons on « Modifier », « Modifier la forme » (the
  shape's glyph), « Marquer comme relu »; « Supprimer » as red text
  with its trash icon.
- Tests: overview row and view row ask during a started move; a row
  asks during a started redraw; whitespace-only save; unnamed link
  read rows; focus back to the row with no opener. Dead helpers
  removed (tests/helpers openProperties, e2e propertiesDialog).

Mapping: the point-edit « Enter on the selected row … asks first »
test (which replaced « Toutes les annotations asks first ») keeps its
place; the overview-row path it did not cover now has its own test.
2026-11-17 22:17:20 +01:00

417 lines
13 KiB
TypeScript

import { useEffect, useReducer, useState, type Dispatch } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
Geometry,
} from '@faunosteo/core-wasm/types'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import { useAnnotationRequest } from '@/editor/annotations/focusTarget'
import { keyboardPending, type NewKind } from '@/editor/annotations/creation'
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 { 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 { isEditable } from '@/editor/annotations/geometryEdit'
import { useSelectionEscape } from '@/editor/annotations/deselect'
import {
useLayerFollow,
type OpenDialog,
} from '@/editor/annotations/dialogOpening'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { useGestureMessage } from '@/editor/annotations/useGestureMessage'
import {
initialUi,
uiReducer,
type ToolId,
type UiAction,
type UiState,
} from '@/editor/annotations/uiState'
import type { RootAttributes } from '@/editor/annotations/useCanvasBuild'
import {
mainViewId,
useViewModel,
type ViewModel,
} from '@/editor/annotations/useViewModel'
import type { AnnotationSection } from '@/editor/navigation'
import { usePlaceVisible } from '@/lib/placeVisibility'
import type { EditorPlaceProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import AnnotationCanvas from './AnnotationCanvas'
import { annotationName } from './AnnotationList'
import CreationPanel from './CreationPanel'
import GestureMessage from './GestureMessage'
import KeyboardAdd from './KeyboardAdd'
import OverviewPanel from './OverviewPanel'
import SceneStrip from './SceneStrip'
import ViewSwitcher from './ViewSwitcher'
interface Props {
doc: AnatomicalSheetDocument
navigate: EditorPlaceProps['navigate']
onOpenSection: (section: AnnotationSection, opener: HTMLElement) => void
focus: EditorPlaceProps['focus']
/** Opens the properties dialog (A1); the layer's id, which the selection follows. */
onOpen: OpenDialog
layerId: string | null
}
/** What both columns read: the tab's state, the view, its frame and its selection. */
export interface Scene {
doc: AnatomicalSheetDocument
ui: UiState
dispatch: Dispatch<UiAction>
viewId: string
model: ViewModel
/** F of the current view, only while the core measures it and the build is its own. */
frame: Frame | null
selected: Annotation | undefined
setRoot: (root: RootAttributes | null) => void
navigate: EditorPlaceProps['navigate']
onOpenSection: Props['onOpenSection']
onOpen: OpenDialog
}
/**
* The shown view no longer exists (an undo, a deletion in the views section): the full
* reset to the main view drops the pending creation, the tracing and the selection, so
* nothing pending is inserted on another view. It fires only for a view absent from the
* document, since `view` always returns a new state.
*/
function useViewFallback(
doc: AnatomicalSheetDocument,
shown: string | null,
dispatch: Dispatch<UiAction>,
) {
useEffect(() => {
if (shown === null || doc.views.some((view) => view.id === shown)) return
const main = mainViewId(doc)
if (doc.views.some((view) => view.id === main)) {
dispatch({ type: 'view', viewId: main })
}
}, [doc, shown, dispatch])
}
/** « Aller à » an annotation: the request, with what it needs of the drawing's state. */
function useSceneRequest(
{ doc, focus, layerId }: Props,
ui: UiState,
viewId: string,
dispatch: Dispatch<UiAction>,
) {
useViewFallback(doc, ui.viewId, dispatch)
const show = (view: string, id: string) => {
if (view !== viewId) dispatch({ type: 'view', viewId: view })
dispatch({ type: 'select', id })
}
useAnnotationRequest(focus, doc, {
viewId,
selectedId: ui.selectedId,
busy: ui.pending ? 'creation' : ui.tracing ? 'tracing' : null,
show,
})
useLayerFollow(layerId, doc, {
viewId,
selectedId: ui.selectedId,
show,
clear: () => dispatch({ type: 'select', id: null }),
})
}
function useScene(props: Props): Scene {
const { doc, navigate, onOpenSection, onOpen } = props
const [ui, dispatch] = useReducer(uiReducer, initialUi)
const [root, setRoot] = useState<RootAttributes | null>(null)
const viewId = ui.viewId ?? mainViewId(doc)
const model = useViewModel(doc, viewId)
const own = model.measured && root?.viewId === viewId
useSceneRequest(props, ui, viewId, dispatch)
return {
doc,
ui,
dispatch,
viewId,
model,
frame: own ? parseFrame(root.viewBox) : null,
selected: model.annotations.find((a) => a.id === ui.selectedId),
setRoot,
navigate,
onOpenSection,
onOpen,
}
}
function useCommitContext(): CommitContext {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return { t, locale }
}
/**
* 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 = 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,
zone,
target,
insertsHidden,
setInsertsHidden,
}
}
export type Work = ReturnType<typeof useWork>
export default function EditableAnnotations(props: Props) {
const scene = useScene(props)
const work = useWork(scene)
const { ui, selected } = scene
const visible = usePlaceVisible()
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => scene.dispatch({ type: 'select', id: 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 (
<div className="space-y-3">
<SceneStrip scene={scene} work={work} />
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn scene={scene} work={work} onDeselect={byDrawing} />
<aside ref={asideRef} data-annotation-aside="edit">
<SidePanel scene={scene} context={work.context} />
</aside>
</div>
</div>
)
}
/** 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()
}
function CanvasColumn({
scene,
work,
onDeselect,
}: {
scene: Scene
work: Work
onDeselect: () => void
}) {
const { doc, dispatch, model } = scene
const noCategory = doc.categories.length === 0
return (
<div className="min-w-0 space-y-3">
<ViewSwitcher
views={doc.views}
current={scene.viewId}
onSelect={(id) =>
guarded(() => dispatch({ type: 'view', viewId: id }))()
}
/>
<CanvasStage scene={scene} work={work} onDeselect={onDeselect} />
<GestureMessage messages={work.message}>
<KeyboardAdd
disabled={!model.measured || noCategory || scene.frame === null}
linkDisabled={model.children.length === 0}
onAdd={(kind) => guarded(() => addAtCentre(kind, scene))()}
/>
</GestureMessage>
</div>
)
}
/** The handle of the movable selected circle, named « Point {nom} » (« Accès {nom} »). */
function useHandle(target: Annotation | null, doc: AnatomicalSheetDocument) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
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')
.replace('{kind}', () => kind)
.replace('{name}', () => name)
return {
annotationId: target.id,
label,
stored: target.geometry,
}
}
function CanvasStage({
scene,
work,
onDeselect,
}: {
scene: Scene
work: Work
onDeselect: () => void
}) {
const locale = useLocaleStore((s) => s.locale)
// Hidden (the editor is read-only): no drag in flight survives, none is committed.
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
return (
<AnnotationCanvas
viewId={scene.viewId}
viewName={view.name[locale]}
tool={ui.tool}
selectedId={ui.selectedId}
moveTarget={shown ? moveTargetOf(selected, model, ui.tool) : null}
overlay={overlayOf(ui, selected, frame, work.message.message?.place)}
handles={{
handle,
onKeyDown: work.edit.onHandleKey,
onBlur: work.edit.onHandleBlur,
zone,
zoneKeys: work.zone,
onInsertsHidden: work.setInsertsHidden,
}}
tools={{
tool: ui.tool,
onTool: (tool) => guarded(() => dispatch({ type: 'tool', tool }))(),
drawingDisabled: blocked,
linkDisabled: model.children.length === 0,
}}
onRoot={scene.setRoot}
onSelect={(id) => dispatch({ type: 'select', id })}
onOpen={(id) => scene.onOpen(id, 'drawing')}
onPlace={work.placement.onPlace}
onDrop={work.placement.onDrop}
onHandle={work.zone.onHandle}
onDeselect={onDeselect}
onTraceKey={work.placement.onTraceKey}
/>
)
}
function addAtCentre(
kind: NewKind,
{ frame, doc, viewId, ui, dispatch }: Scene,
) {
if (!frame) return
const size = newPointSize(doc.annotations, viewId, frame, ui.size)
dispatch({ type: 'pending_new', pending: keyboardPending(kind, frame, size) })
}
/** The creation panel while an element is pending, else the overview (A3). */
function SidePanel({
scene,
context,
}: {
scene: Scene
context: CommitContext
}) {
const { doc, ui, dispatch, frame } = scene
if (ui.pending) {
return (
<CreationPanel
key={ui.serial}
pending={ui.pending}
viewId={scene.viewId}
doc={doc}
frame={frame}
dispatch={dispatch}
context={context}
/>
)
}
return (
<OverviewPanel
doc={doc}
viewId={scene.viewId}
readOnly={false}
filter={ui.filter}
onFilter={(term) => dispatch({ type: 'filter', term })}
// The column stays shown during a selection (A3): a row or a view that would drop
// a started move or redraw asks first (R-12).
onSelectView={(id) =>
guarded(() => dispatch({ type: 'view', viewId: id }))()
}
selectedId={scene.selected?.id ?? null}
onSelectAnnotation={(id) =>
guarded(() => dispatch({ type: 'select', id }))()
}
onOpenAnnotation={(id) => scene.onOpen(id, 'drawing')}
onOpenSection={scene.onOpenSection}
/>
)
}
function moveTargetOf(
selected: Annotation | undefined,
model: ViewModel,
tool: ToolId,
) {
if (!selected || !model.measured || tool !== 'select') return null
return isEditable(selected.geometry)
? { id: selected.id, kind: selected.kind, geometry: selected.geometry }
: null
}
/** 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 {
return moveTargetOf(selected, model, tool) !== null ? selected! : null
}
function overlayOf(
ui: UiState,
selected: Annotation | undefined,
frame: Frame | null,
refused: Geometry | null | undefined,
) {
return {
frame,
selectedId: selected?.id ?? null,
refused: refused ?? null,
selected: selected?.geometry ?? null,
pending: ui.pending?.geometry ?? null,
tracing: ui.tracing?.points ?? null,
correction: ui.pending?.correction ?? null,
redrawing: ui.tracing?.target === 'replace',
}
}