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

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

No files matched your search

@@ -1,23 +1,18 @@
import { useEffect, useRef, type PointerEvent } from 'react'
import { useEffect, useRef, type KeyboardEvent, type RefObject } from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { coreFailureMessage } from '@/core/failure'
import { useCoreStopped } from '@/core/runtime'
import { transformOf } from '@/catalogue/framing'
import { useFraming } from '@/catalogue/useFraming'
import { clientToDrawing } from '@/editor/annotations/gesture'
import type { XY } from '@/editor/annotations/frame'
import {
annotationIdOf,
useCanvasBuild,
type RootAttributes,
useSelectionMark,
} from '@/editor/annotations/useCanvasBuild'
import {
useMoveGesture,
type MoveTarget,
} from '@/editor/annotations/useMoveGesture'
import { useCanvasGestures } from '@/editor/annotations/useCanvasGestures'
import type { MoveTarget } from '@/editor/annotations/useMoveGesture'
import type { ToolId } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
@@ -37,101 +32,107 @@ export interface AnnotationCanvasProps {
moveTarget: MoveTarget | null
overlay: OverlayData
tools: Omit<ToolColumnProps, 'onZoomIn' | 'onZoomOut' | 'onFit'>
/** The composed root's `viewBox` text, as rebuilt; null on failure. */
onRoot: (viewBox: string | null) => void
/** 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
onTraceKey: (event: KeyboardEvent) => void
}
/**
* The edit canvas: the core's composed view, the numbers-only overlay above it in the
* same transformed box, the tool column beside it. Select and place work on `click`
* (a press that moved is a drag and swallows it); a drag from the selected marker moves
* it after 4 CSS px. `touch-action: none` only while a drawing tool or a drag is active.
* it after 4 CSS px.
*/
export default function AnnotationCanvas(props: AnnotationCanvasProps) {
const overlayRef = useRef<SVGSVGElement | null>(null)
const overlay = useRef<SVGSVGElement | null>(null)
const viewport = useRef<HTMLDivElement | null>(null)
const build = useCanvasBuild(props.viewId)
const move = useMoveGesture({
overlay: overlayRef,
target: props.moveTarget,
onDrop: props.onDrop,
})
const framing = useFraming(viewport, props.viewId, {
canPan: (event) => props.tool === 'select' && !move.claims(event),
})
const gestures = useCanvasGestures({ ...props, overlay, viewport })
useSelectionMark(build.host, props.selectedId, build.root)
const { onRoot } = props
const viewBox = build.root?.viewBox ?? null
useReportRoot(viewBox, onRoot)
const onClick = (event: React.MouseEvent) => {
if (framing.swallowClick()) return
const id = annotationIdOf(event.target)
if (props.tool === 'select') return id ? props.onSelect(id) : undefined
const at = clientToDrawing(overlayRef.current, {
x: event.clientX,
y: event.clientY,
})
if (at) props.onPlace(at)
}
const handlers = composed(framing.handlers, move.handlers)
const touchNone =
props.tool !== 'select' || move.armed || framing.framing.scale !== 1
useReportRoot(build.root, props.onRoot)
return (
<div className="flex flex-col gap-2 lg:flex-row">
<ToolColumn
{...props.tools}
onZoomIn={framing.zoomIn}
onZoomOut={framing.zoomOut}
onFit={framing.reset}
onZoomIn={gestures.framing.zoomIn}
onZoomOut={gestures.framing.zoomOut}
onFit={gestures.framing.reset}
/>
<CanvasBox
{...props}
build={build}
viewport={viewport}
boxProps={gestures.boxProps}
layer={{
transform: transformOf(gestures.framing.framing),
overlay: {
...props.overlay,
svgRef: overlay,
dragged: gestures.drag,
},
}}
/>
<div className="relative min-w-0 flex-1 overflow-hidden rounded-xl border border-[var(--color-border)] bg-white">
<div
ref={viewport}
tabIndex={0}
role="group"
aria-label={props.viewName}
data-testid="annotation-canvas"
className={`svg-canvas aspect-[4/3] w-full select-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] ${
props.tool === 'select' ? 'cursor-grab' : 'cursor-crosshair'
}`}
style={{ touchAction: touchNone ? 'none' : 'pan-x pan-y' }}
onClick={onClick}
{...handlers}
>
<DrawingLayer
host={build.host}
root={build.root}
transform={transformOf(framing.framing)}
overlay={{
...props.overlay,
svgRef: overlayRef,
dragged: move.preview,
}}
/>
</div>
<CanvasFailure failure={build.failure} retry={build.retry} />
</div>
</div>
)
}
/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */
function DrawingLayer({
host,
root,
transform,
overlay,
}: {
host: React.RefObject<HTMLDivElement | null>
type Build = ReturnType<typeof useCanvasBuild>
function CanvasBox({
viewId,
viewName,
tool,
build,
viewport,
boxProps,
layer,
}: AnnotationCanvasProps & {
build: Build
viewport: RefObject<HTMLDivElement | null>
boxProps: ReturnType<typeof useCanvasGestures>['boxProps']
layer: Omit<LayerProps, 'host' | 'root'>
}) {
const root = build.root?.viewId === viewId ? build.root : null
const cursor = tool === 'select' ? 'cursor-grab' : 'cursor-crosshair'
return (
<div className={BOX}>
<div
ref={viewport}
tabIndex={0}
role="group"
aria-label={viewName}
data-testid="annotation-canvas"
className={`svg-canvas aspect-[4/3] w-full select-none ${cursor} ${FOCUS_RING}`}
{...boxProps}
>
<DrawingLayer host={build.host} root={root} {...layer} />
</div>
<CanvasFailure failure={build.failure} retry={build.retry} />
</div>
)
}
const BOX =
'relative min-w-0 flex-1 overflow-hidden rounded-xl border ' +
'border-[var(--color-border)] bg-white'
const FOCUS_RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' +
'focus-visible:ring-[var(--color-accent)]'
interface LayerProps {
host: RefObject<HTMLDivElement | null>
root: RootAttributes | null
transform: string
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
}) {
}
/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */
function DrawingLayer({ host, root, transform, overlay }: LayerProps) {
return (
<div
className="relative h-full w-full origin-top-left"
@@ -154,31 +155,10 @@ function DrawingLayer({
}
function useReportRoot(
viewBox: string | null,
onRoot: (v: string | null) => void,
root: RootAttributes | null,
onRoot: (root: RootAttributes | null) => void,
) {
useEffect(() => onRoot(viewBox), [viewBox, onRoot])
}
/** Each pointer handler of the framing and of the move gesture, one after the other. */
function composed(
a: ReturnType<typeof useFraming>['handlers'],
b: ReturnType<typeof useMoveGesture>['handlers'],
) {
const both =
(first: (e: PointerEvent) => void, second: (e: PointerEvent) => void) =>
(event: PointerEvent) => {
first(event)
second(event)
}
return {
onPointerDown: both(a.onPointerDown, b.onPointerDown),
onPointerMove: both(a.onPointerMove, b.onPointerMove),
onPointerUp: both(a.onPointerUp, b.onPointerUp),
onPointerCancel: both(a.onPointerCancel, b.onPointerCancel),
onLostPointerCapture: b.onLostPointerCapture,
onKeyDown: a.onKeyDown,
}
useEffect(() => onRoot(root), [root, onRoot])
}
function CanvasFailure({
@@ -3,6 +3,15 @@ import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import ReviewBadge from './ReviewBadge'
const LIST =
'max-h-64 divide-y divide-[var(--color-border)] overflow-y-auto rounded-lg ' +
'border border-[var(--color-border)]'
const ROW =
'flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm ' +
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' +
'focus-visible:ring-[var(--color-accent)]'
/** The name an annotation shows: its own, else (an unnamed link) the view it opens. */
export function annotationName(
annotation: Annotation,
@@ -40,17 +49,14 @@ export default function AnnotationList({
)
}
return (
<ul
aria-label={t('editor.annotations.list')}
className="max-h-64 divide-y divide-[var(--color-border)] overflow-y-auto rounded-lg border border-[var(--color-border)]"
>
<ul aria-label={t('editor.annotations.list')} className={LIST}>
{annotations.map((annotation) => (
<li key={annotation.id}>
<button
type="button"
aria-current={annotation.id === selectedId}
onClick={() => onSelect(annotation.id)}
className={`flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] ${
className={`${ROW} ${
annotation.id === selectedId
? 'bg-[var(--color-surface-strong)]'
: ''
@@ -0,0 +1,173 @@
import type {
AnatomicalSheetDocument,
Laterality,
} from '@faunosteo/core-wasm/types'
import DraftField from '@/components/editor/fields/DraftField'
import FormField from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
import {
LATERALITIES,
directChildren,
type CreationForm,
type PendingElement,
} from '@/editor/annotations/creation'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
interface FieldsProps {
doc: AnatomicalSheetDocument
form: CreationForm
onChange: (patch: Partial<CreationForm>) => void
}
interface Option {
value: string
label: string
}
function OptionSelect({
id,
label,
value,
options,
blank,
onChange,
}: {
id: string
label: string
value: string
options: Option[]
/** A « Choisir… » entry: the choice is required and has no default. */
blank: boolean
onChange: (value: string) => void
}) {
const t = useT()
return (
<FormField id={id} label={label}>
<Select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
{blank && <option value="">{t('editor.field.choose')}</option>}
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Select>
</FormField>
)
}
/** The fields the core requires, collected before the insert. */
export default function CreationFields({
kind,
viewId,
...fields
}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { doc, form, onChange } = fields
const categories = doc.categories.map((c) => ({
value: c.id,
label: c.name[locale],
}))
const sides = LATERALITIES.map((l: Laterality) => ({
value: l,
label: t(`editor.annotations.laterality.${l}`),
}))
return (
<div className="grid gap-3 sm:grid-cols-2">
<DraftField
id="creation-fr"
label={t('editor.annotations.name_fr')}
value={form.fr}
onChange={(fr) => onChange({ fr })}
/>
<DraftField
id="creation-en"
label={t('editor.annotations.name_en')}
value={form.en}
onChange={(en) => onChange({ en })}
/>
<OptionSelect
id="creation-category"
label={t('editor.annotations.category')}
value={form.categoryId}
options={categories}
blank={false}
onChange={(categoryId) => onChange({ categoryId })}
/>
<OptionSelect
id="creation-laterality"
label={t('editor.annotations.laterality')}
value={form.laterality}
options={sides}
blank
onChange={(laterality) =>
onChange({ laterality: laterality as CreationForm['laterality'] })
}
/>
{kind === 'detail_trigger' ? (
<OpensSelect {...fields} viewId={viewId} />
) : (
<LinkSelects {...fields} />
)}
</div>
)
}
function OpensSelect({
doc,
form,
onChange,
viewId,
}: FieldsProps & { viewId: string }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const options = directChildren(doc.views, viewId).map((v) => ({
value: v.id,
label: v.name[locale],
}))
return (
<OptionSelect
id="creation-opens"
label={t('editor.annotations.opens')}
value={form.opensViewId}
options={options}
blank
onChange={(opensViewId) => onChange({ opensViewId })}
/>
)
}
/** Findings zone and vertebral region: optional links of a point or a zone. */
function LinkSelects({ doc, form, onChange }: FieldsProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const zones = doc.finding_zones.map((z) => ({
value: z.id,
label: z.name[locale],
}))
const regions = doc.vertebral_config.regions.map((r) => ({
value: r.code,
label: r.name[locale],
}))
return (
<>
<OptionSelect
id="creation-zone"
label={t('editor.annotations.zone')}
value={form.zoneId}
options={zones}
blank
onChange={(zoneId) => onChange({ zoneId })}
/>
<OptionSelect
id="creation-region"
label={t('editor.annotations.region')}
value={form.regionCode}
options={regions}
blank
onChange={(regionCode) => onChange({ regionCode })}
/>
</>
)
}
@@ -1,38 +1,24 @@
import { useState, type Dispatch } from 'react'
import type {
AnatomicalSheetDocument,
Laterality,
} from '@faunosteo/core-wasm/types'
import DraftField from '@/components/editor/fields/DraftField'
import FormField from '@/components/ui/FormField'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Select from '@/components/ui/Select'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import {
insertAnnotation,
type CommitContext,
type CommitResult,
} from '@/editor/annotations/annotationCommit'
import {
attemptPoint,
confirmCorrection,
type Correction,
type PointAttempt,
} from '@/editor/annotations/correction'
import {
LATERALITIES,
annotationOf,
directChildren,
emptyForm,
formProblem,
withGeometry,
type CreationForm,
type PendingElement,
} from '@/editor/annotations/creation'
import {
confirmAttempt,
createAttempt,
type Attempt,
type CreationInput,
} from '@/editor/annotations/creationAttempt'
import type { Frame } from '@/editor/annotations/frame'
import type { EditableGeometry } from '@/editor/annotations/geometryEdit'
import type { UiAction } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import CorrectionNotice from './CorrectionNotice'
import CreationFields from './CreationFields'
import GeometryGroup from './GeometryGroup'
export interface CreationPanelProps {
@@ -45,47 +31,44 @@ export interface CreationPanelProps {
context: CommitContext
}
type Attempt = PointAttempt | { status: 'invalid'; messages: string[] }
/** The insert of this panel's element under a given geometry, through `accept`. */
function inserterOf(props: CreationPanelProps, form: CreationForm) {
return (geometry: EditableGeometry): CommitResult =>
insertAnnotation(
(id) =>
annotationOf(id, props.viewId, { ...props.pending, geometry }, form),
props.context,
)
/** What an attempt leaves on screen: the core's words, or the form's own. */
function messagesOf(attempt: Attempt, words: (problem: string) => string) {
if (attempt.status === 'refused') return attempt.messages
return attempt.status === 'invalid' ? [words(attempt.problem)] : []
}
/** « Créer »: a point lets the core's verdict offer C; nothing else is ever invented. */
function createAttempt(
props: CreationPanelProps,
form: CreationForm,
words: (problem: string) => string,
): Attempt {
const { pending, frame } = props
const problem = formProblem(pending.kind, form)
if (problem) return { status: 'invalid', messages: [words(problem)] }
const insert = inserterOf(props, form)
const { geometry } = pending
if (pending.kind === 'point' && geometry.type === 'circle' && frame) {
return attemptPoint(frame, geometry, (c) =>
insert({ type: 'circle', ...c }),
/**
* The typed fields and the outcome of « Créer » / « Utiliser cette position ». The form
* survives a change of the pending geometry (a second click): the panel is not remounted.
*/
function useCreation(props: CreationPanelProps) {
const t = useT()
const [form, setForm] = useState<CreationForm>(() => emptyForm(props.doc))
const [messages, setMessages] = useState<string[]>([])
const settle = (attempt: Attempt) => {
const { dispatch, pending } = props
setMessages(
messagesOf(attempt, (p) => t(`editor.annotations.required.${p}`)),
)
if (attempt.status === 'created') {
dispatch({ type: 'select', id: attempt.id ?? null })
}
if (attempt.status === 'correction') {
const next = { ...pending, correction: attempt.correction }
dispatch({ type: 'pending_update', pending: next })
}
}
const input: CreationInput = props
return {
form,
messages,
patch: (change: Partial<CreationForm>) => setForm({ ...form, ...change }),
create: () => settle(createAttempt(input, form)),
confirm: () => {
const { correction } = props.pending
if (correction) settle(confirmAttempt(input, form, correction))
},
}
const result = insert(geometry)
return result.ok
? { status: 'created', id: result.id }
: { status: 'refused', messages: result.messages }
}
function confirmAttempt(
props: CreationPanelProps,
form: CreationForm,
correction: Correction,
): Attempt {
const insert = inserterOf(props, form)
return confirmCorrection(correction, (c) => insert({ type: 'circle', ...c }))
}
/**
@@ -95,80 +78,74 @@ function confirmAttempt(
*/
export default function CreationPanel(props: CreationPanelProps) {
const t = useT()
const { pending, doc, dispatch } = props
const [form, setForm] = useState<CreationForm>(() => emptyForm(doc))
const [messages, setMessages] = useState<string[]>([])
const update = (next: PendingElement) =>
dispatch({ type: 'pending_update', pending: next })
const settle = (attempt: Attempt) => {
setMessages(
attempt.status === 'refused' || attempt.status === 'invalid'
? attempt.messages
: [],
)
if (attempt.status === 'created') {
dispatch({ type: 'select', id: attempt.id ?? null })
}
if (attempt.status === 'correction') {
update({ ...pending, correction: attempt.correction })
}
}
const words = (problem: string) => t(`editor.annotations.required.${problem}`)
const setGeometry = (geometry: EditableGeometry) => {
update({ ...pending, geometry, correction: null })
return { ok: true as const }
}
const creation = useCreation(props)
const { pending, dispatch } = props
const title = t(`editor.annotations.new.${pending.kind}`)
return (
<section
aria-label={t(`editor.annotations.new.${pending.kind}`)}
aria-label={title}
data-testid="annotation-creation"
className="space-y-3 rounded-xl border border-[var(--color-border)] p-4"
>
<h3 className="text-base font-semibold">
{t(`editor.annotations.new.${pending.kind}`)}
</h3>
<h3 className="text-base font-semibold">{title}</h3>
<CreationFields
kind={pending.kind}
viewId={props.viewId}
form={form}
doc={doc}
onChange={(patch) => setForm({ ...form, ...patch })}
form={creation.form}
doc={props.doc}
onChange={creation.patch}
/>
<GeometryGroup
idPrefix="creation"
geometry={pending.geometry}
onApply={setGeometry}
locked={false}
onApply={(geometry) => {
const next = withGeometry(pending, geometry)
dispatch({ type: 'pending_update', pending: next })
return { ok: true }
}}
/>
{pending.correction && (
<CorrectionNotice
correction={pending.correction}
onConfirm={() =>
settle(confirmAttempt(props, form, pending.correction!))
onConfirm={creation.confirm}
onCancel={() =>
dispatch({
type: 'pending_update',
pending: { ...pending, correction: null },
})
}
onCancel={() => update({ ...pending, correction: null })}
/>
)}
<Messages messages={messages} />
<div className="flex gap-2">
<Button
type="button"
onClick={() => settle(createAttempt(props, form, words))}
>
{t('editor.annotations.create')}
</Button>
<Button
type="button"
variant="secondary"
onClick={() => dispatch({ type: 'pending_drop' })}
>
{t('editor.annotations.create_cancel')}
</Button>
</div>
<Messages messages={creation.messages} />
<CreationActions
onCreate={creation.create}
onCancel={() => dispatch({ type: 'pending_drop' })}
/>
</section>
)
}
function CreationActions({
onCreate,
onCancel,
}: {
onCreate: () => void
onCancel: () => void
}) {
const t = useT()
return (
<div className="flex gap-2">
<Button type="button" onClick={onCreate}>
{t('editor.annotations.create')}
</Button>
<Button type="button" variant="secondary" onClick={onCancel}>
{t('editor.annotations.create_cancel')}
</Button>
</div>
)
}
function Messages({ messages }: { messages: string[] }) {
if (messages.length === 0) return null
return (
@@ -182,161 +159,3 @@ function Messages({ messages }: { messages: string[] }) {
</div>
)
}
interface FieldsProps {
doc: AnatomicalSheetDocument
form: CreationForm
onChange: (patch: Partial<CreationForm>) => void
}
interface Option {
value: string
label: string
}
function OptionSelect({
id,
label,
value,
options,
blank,
onChange,
}: {
id: string
label: string
value: string
options: Option[]
/** A « Choisir… » entry: the choice is required and has no default. */
blank: boolean
onChange: (value: string) => void
}) {
const t = useT()
return (
<FormField id={id} label={label}>
<Select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
{blank && <option value="">{t('editor.field.choose')}</option>}
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Select>
</FormField>
)
}
/** The fields the core requires, collected before the insert. */
function CreationFields({
kind,
viewId,
...fields
}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { doc, form, onChange } = fields
const categories = doc.categories.map((c) => ({
value: c.id,
label: c.name[locale],
}))
const sides = LATERALITIES.map((l: Laterality) => ({
value: l,
label: t(`editor.annotations.laterality.${l}`),
}))
return (
<div className="grid gap-3 sm:grid-cols-2">
<DraftField
id="creation-fr"
label={t('editor.annotations.name_fr')}
value={form.fr}
onChange={(fr) => onChange({ fr })}
/>
<DraftField
id="creation-en"
label={t('editor.annotations.name_en')}
value={form.en}
onChange={(en) => onChange({ en })}
/>
<OptionSelect
id="creation-category"
label={t('editor.annotations.category')}
value={form.categoryId}
options={categories}
blank={false}
onChange={(categoryId) => onChange({ categoryId })}
/>
<OptionSelect
id="creation-laterality"
label={t('editor.annotations.laterality')}
value={form.laterality}
options={sides}
blank
onChange={(laterality) =>
onChange({ laterality: laterality as CreationForm['laterality'] })
}
/>
{kind === 'detail_trigger' ? (
<OpensSelect {...fields} viewId={viewId} />
) : (
<LinkSelects {...fields} />
)}
</div>
)
}
function OpensSelect({
doc,
form,
onChange,
viewId,
}: FieldsProps & { viewId: string }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const options = directChildren(doc.views, viewId).map((v) => ({
value: v.id,
label: v.name[locale],
}))
return (
<OptionSelect
id="creation-opens"
label={t('editor.annotations.opens')}
value={form.opensViewId}
options={options}
blank
onChange={(opensViewId) => onChange({ opensViewId })}
/>
)
}
/** Findings zone and vertebral region: optional links of a point or a zone. */
function LinkSelects({ doc, form, onChange }: FieldsProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const zones = doc.finding_zones.map((z) => ({
value: z.id,
label: z.name[locale],
}))
const regions = doc.vertebral_config.regions.map((r) => ({
value: r.code,
label: r.name[locale],
}))
return (
<>
<OptionSelect
id="creation-zone"
label={t('editor.annotations.zone')}
value={form.zoneId}
options={zones}
blank
onChange={(zoneId) => onChange({ zoneId })}
/>
<OptionSelect
id="creation-region"
label={t('editor.annotations.region')}
value={form.regionCode}
options={regions}
blank
onChange={(regionCode) => onChange({ regionCode })}
/>
</>
)
}
@@ -3,7 +3,7 @@ import type {
AnatomicalSheetDocument,
Annotation,
} from '@faunosteo/core-wasm/types'
import { type CommitContext } from '@/editor/annotations/annotationCommit'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import { keyboardPending, type NewKind } from '@/editor/annotations/creation'
import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { isEditable } from '@/editor/annotations/geometryEdit'
@@ -15,9 +15,9 @@ import {
type UiAction,
type UiState,
} from '@/editor/annotations/uiState'
import type { RootAttributes } from '@/editor/annotations/useCanvasBuild'
import {
mainViewId,
useUndoShortcuts,
useViewModel,
type ViewModel,
} from '@/editor/annotations/useViewModel'
@@ -38,59 +38,75 @@ interface Props {
onSelectTab: EditorTabProps['onSelectTab']
}
export default function EditableAnnotations({ doc, onSelectTab }: Props) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
/** What both columns read: the tab's state, the view, its frame and its selection. */
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
onSelectTab: EditorTabProps['onSelectTab']
}
function useScene({ doc, onSelectTab }: Props): Scene {
const [ui, dispatch] = useReducer(uiReducer, initialUi)
const [viewBox, setViewBox] = useState<string | null>(null)
const [root, setRoot] = useState<RootAttributes | null>(null)
const viewId = ui.viewId ?? mainViewId(doc)
const model = useViewModel(doc, viewId)
const frame = model.measured ? parseFrame(viewBox) : null
const context: CommitContext = { t, locale }
const placement = usePlacement({ ui, dispatch, frame, doc, context })
useUndoShortcuts()
const selected = model.annotations.find((a) => a.id === ui.selectedId)
const scene = { doc, ui, dispatch, model, frame, selected, onSelectTab }
const own = model.measured && root?.viewId === viewId
return {
doc,
ui,
dispatch,
viewId,
model,
frame: own ? parseFrame(root.viewBox) : null,
selected: model.annotations.find((a) => a.id === ui.selectedId),
setRoot,
onSelectTab,
}
}
function useCommitContext(): CommitContext {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return { t, locale }
}
export default function EditableAnnotations(props: Props) {
const scene = useScene(props)
const context = useCommitContext()
const placement = usePlacement({ ...scene, context })
return (
<div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn {...scene} placement={placement} onRoot={setViewBox} />
<CanvasColumn scene={scene} placement={placement} />
<aside>
<SidePanel {...scene} viewId={viewId} context={context} />
<SidePanel scene={scene} context={context} />
</aside>
</div>
)
}
/** What both columns read: the document, the tab's state, the view and its frame. */
interface Scene extends Props {
ui: UiState
dispatch: Dispatch<UiAction>
model: ViewModel
frame: Frame | null
selected: Annotation | undefined
}
type Placement = ReturnType<typeof usePlacement>
function CanvasColumn({
scene,
placement,
onRoot,
...scene
}: Scene & {
placement: ReturnType<typeof usePlacement>
onRoot: (viewBox: string | null) => void
}: {
scene: Scene
placement: Placement
}) {
const locale = useLocaleStore((s) => s.locale)
const { doc, ui, dispatch, model, frame, selected } = scene
const viewId = ui.viewId ?? mainViewId(doc)
const view = doc.views.find((v) => v.id === viewId)
const { doc, ui, dispatch, model, selected } = scene
const noCategory = doc.categories.length === 0
const blocked = !model.measured || noCategory
const select = (id: string) => dispatch({ type: 'select', id })
if (!view) return null
return (
<div className="min-w-0 space-y-3" onKeyDown={placement.onKeyDown}>
<div className="min-w-0 space-y-3">
<ViewSwitcher
views={doc.views}
current={viewId}
current={scene.viewId}
onSelect={(id) => dispatch({ type: 'view', viewId: id })}
/>
<ToolNotes
@@ -100,30 +116,8 @@ function CanvasColumn({
noCategory={noCategory}
onSelectTab={scene.onSelectTab}
/>
{selected && (
<SelectionTag
kind={selected.kind}
name={annotationName(selected, doc.views, locale)}
/>
)}
<AnnotationCanvas
viewId={viewId}
viewName={view.name[locale]}
tool={ui.tool}
selectedId={ui.selectedId}
moveTarget={moveTargetOf(selected, model, ui.tool)}
overlay={overlayOf(ui, selected, frame)}
tools={{
tool: ui.tool,
onTool: (tool) => dispatch({ type: 'tool', tool }),
drawingDisabled: blocked,
linkDisabled: model.children.length === 0,
}}
onRoot={onRoot}
onSelect={select}
onPlace={placement.onPlace}
onDrop={placement.onDrop}
/>
{selected && <TagOf annotation={selected} doc={doc} />}
<CanvasStage scene={scene} placement={placement} />
{ui.tracing && (
<TracingBar
count={ui.tracing.points.length}
@@ -132,20 +126,71 @@ function CanvasColumn({
/>
)}
<KeyboardAdd
disabled={blocked || frame === null}
disabled={!model.measured || noCategory || scene.frame === null}
linkDisabled={model.children.length === 0}
onAdd={(kind) => addAtCentre(kind, frame, dispatch)}
onAdd={(kind) => addAtCentre(kind, scene.frame, dispatch)}
/>
<AnnotationList
annotations={model.annotations}
views={doc.views}
selectedId={ui.selectedId}
onSelect={select}
onSelect={(id) => dispatch({ type: 'select', id })}
/>
</div>
)
}
function TagOf({
annotation,
doc,
}: {
annotation: Annotation
doc: AnatomicalSheetDocument
}) {
const locale = useLocaleStore((s) => s.locale)
return (
<SelectionTag
kind={annotation.kind}
name={annotationName(annotation, doc.views, locale)}
/>
)
}
function CanvasStage({
scene,
placement,
}: {
scene: Scene
placement: Placement
}) {
const locale = useLocaleStore((s) => s.locale)
const { doc, ui, dispatch, model, frame, selected } = scene
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={moveTargetOf(selected, model, ui.tool)}
overlay={overlayOf(ui, selected, frame)}
tools={{
tool: ui.tool,
onTool: (tool) => dispatch({ type: 'tool', tool }),
drawingDisabled: blocked,
linkDisabled: model.children.length === 0,
}}
onRoot={scene.setRoot}
onSelect={(id) => dispatch({ type: 'select', id })}
onPlace={placement.onPlace}
onDrop={placement.onDrop}
onTraceKey={placement.onTraceKey}
/>
)
}
function addAtCentre(
kind: NewKind,
frame: Frame | null,
@@ -157,10 +202,12 @@ function addAtCentre(
/** The creation panel while an element is pending, else the selection's properties. */
function SidePanel({
viewId,
scene,
context,
...scene
}: Scene & { viewId: string; context: CommitContext }) {
}: {
scene: Scene
context: CommitContext
}) {
const t = useT()
const { doc, ui, dispatch, model, frame, selected } = scene
if (ui.pending) {
@@ -168,7 +215,7 @@ function SidePanel({
<CreationPanel
key={ui.serial}
pending={ui.pending}
viewId={viewId}
viewId={scene.viewId}
doc={doc}
frame={frame}
dispatch={dispatch}
@@ -30,6 +30,28 @@ export interface GeometryGroupProps {
type Fields = GroupFields
type PolygonFields = Extract<GroupFields, { type: 'polygon' }>
interface GroupState {
key: string
draft: Fields
messages: string[]
}
/** The typed fields, reset whenever the stored value changes (undo, restore, a move). */
function useGroupState(geometry: EditableGeometry) {
const key = JSON.stringify(fieldsOf(geometry))
const fresh = (): GroupState => ({
key,
draft: fieldsOf(geometry),
messages: [],
})
const [state, setState] = useState<GroupState>(fresh)
if (state.key !== key) setState(fresh())
return {
state,
set: (patch: Partial<GroupState>) => setState({ ...state, ...patch }),
}
}
/**
* The geometry fields as ONE group held in component state (plan « Repair through a
* temporary form »): Enter or leaving a field proposes the whole group as one update;
@@ -38,37 +60,26 @@ type PolygonFields = Extract<GroupFields, { type: 'polygon' }>
* never in the document and is dropped (no commit on unmount).
*/
export default function GeometryGroup(props: GeometryGroupProps) {
const stored = fieldsOf(props.geometry)
const storedKey = JSON.stringify(stored)
const [draft, setDraft] = useState<Fields>(stored)
const [seen, setSeen] = useState(storedKey)
const [messages, setMessages] = useState<string[]>([])
// A new stored value (undo, restore, an accepted move) replaces what was typed.
if (seen !== storedKey) {
setSeen(storedKey)
setDraft(stored)
setMessages([])
}
const apply = (next: Fields) => {
setDraft(next)
if (sameAsStored(next, props.geometry)) return setMessages([])
const { state, set } = useGroupState(props.geometry)
const propose = (next: Fields) => {
if (sameAsStored(next, props.geometry))
return set({ draft: next, messages: [] })
const parsed = parseFields(next)
if (!parsed.ok) return setMessages(['number'])
if (!parsed.ok) return set({ draft: next, messages: ['number'] })
const result = props.onApply(parsed.geometry)
setMessages(result.ok ? [] : result.messages)
set({ draft: next, messages: result.ok ? [] : result.messages })
}
const revert = () => {
setDraft(stored)
setMessages([])
}
const pending = changedFieldNames(draft, props.geometry)
const view = { ...props, draft, pending, messages }
return (
<GroupBody
{...view}
onChange={setDraft}
onPropose={apply}
onRevert={revert}
idPrefix={props.idPrefix}
locked={props.locked}
geometry={props.geometry}
draft={state.draft}
messages={state.messages}
pending={changedFieldNames(state.draft, props.geometry)}
onChange={(draft) => set({ draft })}
onPropose={propose}
onRevert={() => set({ draft: fieldsOf(props.geometry), messages: [] })}
/>
)
}
@@ -199,7 +210,7 @@ function CircleRows(props: RowsProps<Extract<Fields, { type: 'circle' }>>) {
function PolygonRows(props: RowsProps<PolygonFields>) {
const t = useT()
const [selected, setSelected] = useState(0)
const { fields, locked } = props
const { fields } = props
const change = (index: number, axis: 'x' | 'y', value: string) =>
props.onChange({
type: 'polygon',
@@ -207,39 +218,23 @@ function PolygonRows(props: RowsProps<PolygonFields>) {
i === index ? { ...row, [axis]: value } : row,
),
})
const count = String(fields.rows.length)
return (
<div className="space-y-2">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.geometry.vertices').replace(
'{count}',
String(fields.rows.length),
)}
{t('editor.annotations.geometry.vertices').replace('{count}', count)}
</p>
{fields.rows.map((row, index) => (
<div
<VertexRow
key={index}
className="grid grid-cols-[2rem_1fr_1fr] items-end gap-2"
index={index}
row={row}
group={props}
onType={(axis, value) => change(index, axis, value)}
onFocus={() => setSelected(index)}
>
<span className="pb-2 text-sm">{index + 1}</span>
{(['x', 'y'] as const).map((axis) => (
<NumberInput
key={axis}
id={`${props.idPrefix}-${axis}${index}`}
label={t(`editor.annotations.geometry.vertex_${axis}`).replace(
'{n}',
String(index + 1),
)}
value={row[axis]}
unapplied={props.pending.has(`${axis}${index}`)}
locked={locked}
onType={(value) => change(index, axis, value)}
onApply={() => props.onPropose(fields)}
/>
))}
</div>
/>
))}
{!locked && (
{!props.locked && (
<VertexButtons
fields={fields}
selected={selected}
@@ -250,6 +245,45 @@ function PolygonRows(props: RowsProps<PolygonFields>) {
)
}
function VertexRow({
index,
row,
group,
onType,
onFocus,
}: {
index: number
row: { x: string; y: string }
group: RowsProps<PolygonFields>
onType: (axis: 'x' | 'y', value: string) => void
onFocus: () => void
}) {
const t = useT()
return (
<div
className="grid grid-cols-[2rem_1fr_1fr] items-end gap-2"
onFocus={onFocus}
>
<span className="pb-2 text-sm">{index + 1}</span>
{(['x', 'y'] as const).map((axis) => (
<NumberInput
key={axis}
id={`${group.idPrefix}-${axis}${index}`}
label={t(`editor.annotations.geometry.vertex_${axis}`).replace(
'{n}',
String(index + 1),
)}
value={row[axis]}
unapplied={group.pending.has(`${axis}${index}`)}
locked={group.locked}
onType={(value) => onType(axis, value)}
onApply={() => group.onPropose(group.fields)}
/>
))}
</div>
)
}
function VertexButtons({
fields,
selected,
@@ -1,5 +1,9 @@
import { useT } from '@/i18n/useT'
const TAG =
'pointer-events-none inline-block rounded-md px-2 py-1 text-xs ' +
'bg-[var(--color-surface-strong)]'
/** Board 04's tag over the drawing: « Sélection : <type> « <nom> ». */
export default function SelectionTag({
kind,
@@ -10,10 +14,7 @@ export default function SelectionTag({
}) {
const t = useT()
return (
<p
data-testid="annotation-selection-tag"
className="pointer-events-none inline-block rounded-md bg-[var(--color-surface-strong)] px-2 py-1 text-xs"
>
<p data-testid="annotation-selection-tag" className={TAG}>
{t('editor.annotations.selection')
.replace(
'{kind}',
@@ -15,6 +15,12 @@ export interface ToolColumnProps {
onFit: () => void
}
const BUTTON =
'grid h-11 w-11 place-items-center rounded-lg border ' +
'border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 ' +
'focus-visible:outline-none focus-visible:ring-2 ' +
'focus-visible:ring-[var(--color-accent)]'
const GLYPHS: Record<string, string> = {
select: 'M5 3l12 7-5 1-3 5z',
point: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 3v3M12 18v3M3 12h3M18 12h3',
@@ -48,7 +54,7 @@ function ToolButton({
aria-pressed={pressed}
disabled={disabled}
onClick={onClick}
className={`grid h-11 w-11 place-items-center rounded-lg border border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
className={`${BUTTON} ${
pressed
? 'bg-[var(--color-ink)] text-white'
: 'bg-[var(--color-surface)] text-[var(--color-ink)]'
@@ -2,6 +2,11 @@ import type { SheetView } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
const CHIP =
'rounded-full border border-[var(--color-border)] px-3 py-1 text-sm ' +
'focus-visible:outline-none focus-visible:ring-2 ' +
'focus-visible:ring-[var(--color-accent)]'
/** One chip per view (board 04): the main view, then each detail view. */
export default function ViewSwitcher({
views,
@@ -26,7 +31,7 @@ export default function ViewSwitcher({
type="button"
aria-pressed={view.id === current}
onClick={() => onSelect(view.id)}
className={`rounded-full border border-[var(--color-border)] px-3 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
className={`${CHIP} ${
view.id === current
? 'bg-[var(--color-ink)] text-white'
: 'bg-[var(--color-surface)]'