feat(app): editor Annotations tab, core-decided placement, repair rules
This commit is contained in:
1 parent
92c595caa1
commit
26097852ff
37 files changed
+5001
-6
No files matched your search
@@ -0,0 +1,208 @@
|
||||
import { useEffect, useRef, type PointerEvent } 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 type { ToolId } from '@/editor/annotations/uiState'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
|
||||
import ToolColumn, { type ToolColumnProps } from './ToolColumn'
|
||||
|
||||
type OverlayData = Omit<
|
||||
OverlayProps,
|
||||
'svgRef' | 'viewBox' | 'ratio' | 'dragged'
|
||||
>
|
||||
|
||||
export interface AnnotationCanvasProps {
|
||||
viewId: string
|
||||
viewName: string
|
||||
tool: ToolId
|
||||
selectedId: string | null
|
||||
/** The selected annotation when it can be moved now. */
|
||||
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
|
||||
onSelect: (id: string) => void
|
||||
/** A click with a drawing tool, in drawing units. */
|
||||
onPlace: (at: XY) => void
|
||||
onDrop: (id: string, geometry: Geometry) => 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.
|
||||
*/
|
||||
export default function AnnotationCanvas(props: AnnotationCanvasProps) {
|
||||
const overlayRef = 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),
|
||||
})
|
||||
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
|
||||
return (
|
||||
<div className="flex flex-col gap-2 lg:flex-row">
|
||||
<ToolColumn
|
||||
{...props.tools}
|
||||
onZoomIn={framing.zoomIn}
|
||||
onZoomOut={framing.zoomOut}
|
||||
onFit={framing.reset}
|
||||
/>
|
||||
<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>
|
||||
root: RootAttributes | null
|
||||
transform: string
|
||||
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="relative h-full w-full origin-top-left"
|
||||
style={{ transform }}
|
||||
>
|
||||
<div
|
||||
ref={host}
|
||||
data-testid="annotation-canvas-drawing"
|
||||
className="h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
|
||||
/>
|
||||
{root?.viewBox && (
|
||||
<AnnotationOverlay
|
||||
{...overlay}
|
||||
viewBox={root.viewBox}
|
||||
ratio={root.ratio}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function useReportRoot(
|
||||
viewBox: string | null,
|
||||
onRoot: (v: string | 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,
|
||||
}
|
||||
}
|
||||
|
||||
function CanvasFailure({
|
||||
failure,
|
||||
retry,
|
||||
}: {
|
||||
failure: 'engine' | 'view' | null
|
||||
retry: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const stopped = useCoreStopped()
|
||||
if (!failure) return null
|
||||
return (
|
||||
<div className="absolute inset-0 grid place-items-center bg-[var(--color-surface)] p-4">
|
||||
<div className="max-w-sm space-y-3">
|
||||
<Notice tone="error">
|
||||
{failure === 'view'
|
||||
? t('catalogue.failure.view')
|
||||
: coreFailureMessage(t, 'sheet.core_unavailable')}
|
||||
</Notice>
|
||||
{failure === 'engine' && !stopped && (
|
||||
<Button onClick={retry}>{t('sheet.core_retry')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
Laterality,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import TextField from '@/components/editor/fields/TextField'
|
||||
import { LATERALITIES, directChildren } from '@/editor/annotations/creation'
|
||||
import { isBlank, nullable } from '@/editor/sheetDocument'
|
||||
import type { EditCommandApi } from '@/editor/useEditCommand'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
interface Props {
|
||||
annotation: Annotation
|
||||
doc: AnatomicalSheetDocument
|
||||
readOnly: boolean
|
||||
edit: EditCommandApi
|
||||
}
|
||||
|
||||
/** One `update` carrying the whole annotation with `patch` applied. */
|
||||
function useSend({ annotation, edit }: Props) {
|
||||
return (field: string, patch: Record<string, unknown>) =>
|
||||
edit.run(field, {
|
||||
op: 'update',
|
||||
key: { kind: 'annotation', id: annotation.id },
|
||||
element: {
|
||||
kind: 'annotation',
|
||||
value: { ...annotation, ...patch } as Annotation,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const noneOption = (label: string) => ({ value: '', label })
|
||||
|
||||
/** Names: both or none for a link (its name is optional), both required otherwise. */
|
||||
function NameFields(props: Props) {
|
||||
const t = useT()
|
||||
const send = useSend(props)
|
||||
const { annotation, edit, readOnly } = props
|
||||
const isLink = annotation.kind === 'detail_trigger'
|
||||
const rename = (locale: 'fr' | 'en') => (value: string) => {
|
||||
const name = {
|
||||
fr: annotation.name?.fr ?? '',
|
||||
en: annotation.name?.en ?? '',
|
||||
[locale]: value,
|
||||
}
|
||||
const blanks = [name.fr, name.en].filter(isBlank).length
|
||||
if (isLink && blanks === 2) return send(locale, { name: null })
|
||||
if (blanks > 0) return edit.reject(locale, 'editor.field.required_names')
|
||||
return send(locale, { name })
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{(['fr', 'en'] as const).map((locale) => (
|
||||
<TextField
|
||||
key={locale}
|
||||
id={`annotation-name-${locale}`}
|
||||
label={t(`editor.annotations.name_${locale}`)}
|
||||
value={annotation.name?.[locale] ?? ''}
|
||||
onCommit={rename(locale)}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError(locale)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AnnotationFields(props: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const send = useSend(props)
|
||||
const { annotation, doc, readOnly, edit } = props
|
||||
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">
|
||||
<NameFields {...props} />
|
||||
<SelectField
|
||||
id="annotation-category"
|
||||
label={t('editor.annotations.category')}
|
||||
value={annotation.category_id}
|
||||
options={categories}
|
||||
onCommit={(value) => send('category', { category_id: value })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('category')}
|
||||
/>
|
||||
<TextField
|
||||
id="annotation-color"
|
||||
label={t('editor.annotations.color')}
|
||||
value={annotation.color ?? ''}
|
||||
onCommit={(value) => send('color', { color: nullable(value) })}
|
||||
readOnly={readOnly}
|
||||
hint={t('editor.annotations.color_hint')}
|
||||
error={edit.fieldError('color')}
|
||||
/>
|
||||
<SelectField
|
||||
id="annotation-laterality"
|
||||
label={t('editor.annotations.laterality')}
|
||||
value={annotation.laterality}
|
||||
options={sides}
|
||||
onCommit={(value) => send('laterality', { laterality: value })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('laterality')}
|
||||
/>
|
||||
{annotation.kind === 'detail_trigger' ? (
|
||||
<OpensField {...props} />
|
||||
) : (
|
||||
<LinkFields {...props} annotation={annotation} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OpensField({ annotation, doc, readOnly, edit }: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const send = useSend({ annotation, doc, readOnly, edit })
|
||||
if (annotation.kind !== 'detail_trigger') return null
|
||||
const options = directChildren(doc.views, annotation.view_id).map((v) => ({
|
||||
value: v.id,
|
||||
label: v.name[locale],
|
||||
}))
|
||||
const current = doc.views.find((v) => v.id === annotation.opens_view_id)
|
||||
if (current && !options.some((o) => o.value === current.id)) {
|
||||
options.push({ value: current.id, label: current.name[locale] })
|
||||
}
|
||||
return (
|
||||
<SelectField
|
||||
id="annotation-opens"
|
||||
label={t('editor.annotations.opens')}
|
||||
value={annotation.opens_view_id}
|
||||
options={options}
|
||||
onCommit={(value) => send('opens', { opens_view_id: value })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('opens')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function LinkFields(props: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const send = useSend(props)
|
||||
const { annotation, doc, readOnly, edit } = props
|
||||
if (annotation.kind === 'detail_trigger') return null
|
||||
const regions = [
|
||||
noneOption(t('editor.annotations.none')),
|
||||
...doc.vertebral_config.regions.map((r) => ({
|
||||
value: r.code,
|
||||
label: r.name[locale],
|
||||
})),
|
||||
]
|
||||
const zones = [
|
||||
noneOption(t('editor.annotations.none')),
|
||||
...doc.finding_zones.map((z) => ({ value: z.id, label: z.name[locale] })),
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<SelectField
|
||||
id="annotation-region"
|
||||
label={t('editor.annotations.region')}
|
||||
value={annotation.vertebral_region_code ?? ''}
|
||||
options={regions}
|
||||
onCommit={(value) =>
|
||||
send('region', { vertebral_region_code: nullable(value) })
|
||||
}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('region')}
|
||||
/>
|
||||
<SelectField
|
||||
id="annotation-zone"
|
||||
label={t('editor.annotations.zone')}
|
||||
value={annotation.finding_zone_id ?? ''}
|
||||
options={zones}
|
||||
onCommit={(value) => send('zone', { finding_zone_id: nullable(value) })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('zone')}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Annotation, SheetView } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import ReviewBadge from './ReviewBadge'
|
||||
|
||||
/** The name an annotation shows: its own, else (an unnamed link) the view it opens. */
|
||||
export function annotationName(
|
||||
annotation: Annotation,
|
||||
views: readonly SheetView[],
|
||||
locale: 'fr' | 'en',
|
||||
): string {
|
||||
if (annotation.name) return annotation.name[locale]
|
||||
if (annotation.kind !== 'detail_trigger') return annotation.id
|
||||
const opened = views.find((view) => view.id === annotation.opens_view_id)
|
||||
return opened?.name[locale] ?? annotation.id
|
||||
}
|
||||
|
||||
/**
|
||||
* The annotations of the view: name, kind, review badge; each row a button, reachable
|
||||
* from the keyboard. Selection works in every mode, so a read-only draft is browsable.
|
||||
*/
|
||||
export default function AnnotationList({
|
||||
annotations,
|
||||
views,
|
||||
selectedId,
|
||||
onSelect,
|
||||
}: {
|
||||
annotations: readonly Annotation[]
|
||||
views: readonly SheetView[]
|
||||
selectedId: string | null
|
||||
onSelect: (id: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
if (annotations.length === 0) {
|
||||
return (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.annotations.list_empty')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
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)]"
|
||||
>
|
||||
{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)] ${
|
||||
annotation.id === selectedId
|
||||
? 'bg-[var(--color-surface-strong)]'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 truncate">
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
{t(`editor.annotations.kind.${annotation.kind}`)}
|
||||
</span>{' '}
|
||||
{annotationName(annotation, views, locale)}
|
||||
</span>
|
||||
<ReviewBadge status={annotation.review_status} />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { Ref } from 'react'
|
||||
import type { Geometry, Point } from '@faunosteo/core-wasm/types'
|
||||
import type { Correction } from '@/editor/annotations/correction'
|
||||
import type { Frame } from '@/editor/annotations/frame'
|
||||
import { isEditable } from '@/editor/annotations/geometryEdit'
|
||||
|
||||
export interface OverlayProps {
|
||||
svgRef: Ref<SVGSVGElement>
|
||||
/** The composed root's own attributes: the overlay shares its coordinates. */
|
||||
viewBox: string
|
||||
ratio: string
|
||||
frame: Frame | null
|
||||
selected: Geometry | null
|
||||
dragged: Geometry | null
|
||||
pending: Geometry | null
|
||||
tracing: Point[] | null
|
||||
correction: Correction | null
|
||||
}
|
||||
|
||||
const STROKE = { fill: 'none', vectorEffect: 'non-scaling-stroke' } as const
|
||||
|
||||
function Outline({
|
||||
geometry,
|
||||
dashed,
|
||||
colour,
|
||||
}: {
|
||||
geometry: Geometry
|
||||
dashed: boolean
|
||||
colour: string
|
||||
}) {
|
||||
const style = {
|
||||
...STROKE,
|
||||
stroke: colour,
|
||||
strokeWidth: 2,
|
||||
strokeDasharray: dashed ? '6 4' : undefined,
|
||||
}
|
||||
if (geometry.type === 'circle') {
|
||||
return (
|
||||
<circle cx={geometry.cx} cy={geometry.cy} r={geometry.r} {...style} />
|
||||
)
|
||||
}
|
||||
if (geometry.type === 'polygon') {
|
||||
return <polygon points={geometry.points.join(' ')} {...style} />
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function Vertices({ geometry, size }: { geometry: Geometry; size: number }) {
|
||||
if (geometry.type !== 'polygon') return null
|
||||
return (
|
||||
<>
|
||||
{geometry.points.map(([x, y], index) => (
|
||||
<circle
|
||||
key={index}
|
||||
cx={x}
|
||||
cy={y}
|
||||
r={size}
|
||||
fill="white"
|
||||
stroke="var(--color-ink)"
|
||||
strokeWidth={1.5}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The hollow cross of the position the user chose, drawn apart from the proposal. */
|
||||
function HollowCross({
|
||||
at,
|
||||
size,
|
||||
}: {
|
||||
at: { x: number; y: number }
|
||||
size: number
|
||||
}) {
|
||||
const style = { ...STROKE, stroke: 'var(--color-ink)', strokeWidth: 2 }
|
||||
return (
|
||||
<g data-testid="overlay-click-cross">
|
||||
<path
|
||||
d={`M ${at.x - size} ${at.y - size} L ${at.x + size} ${at.y + size}`}
|
||||
{...style}
|
||||
/>
|
||||
<path
|
||||
d={`M ${at.x - size} ${at.y + size} L ${at.x + size} ${at.y - size}`}
|
||||
{...style}
|
||||
/>
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
function TracingPath({ points, size }: { points: Point[]; size: number }) {
|
||||
if (points.length === 0) return null
|
||||
const shape: Geometry = { type: 'polygon', points }
|
||||
return (
|
||||
<>
|
||||
<polyline
|
||||
points={points.join(' ')}
|
||||
{...STROKE}
|
||||
stroke="var(--color-accent)"
|
||||
strokeWidth={2}
|
||||
strokeDasharray="6 4"
|
||||
/>
|
||||
<Vertices geometry={shape} size={size} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The page-drawn overlay (docs/ANNOTATION-RENDERING.md « Editor overlay »): numbers only,
|
||||
* no annotation. Selection outline, vertex circles, the tracing in progress, the pending
|
||||
* or dragged outline, a corrected position with the click marked apart. It never takes
|
||||
* the pointer: the canvas box does.
|
||||
*/
|
||||
export default function AnnotationOverlay(props: OverlayProps) {
|
||||
const { frame, selected, dragged, pending, tracing, correction } = props
|
||||
const size = frame ? Math.max(frame.w, frame.h) / 200 : 1
|
||||
const shown = dragged ?? selected
|
||||
return (
|
||||
<svg
|
||||
ref={props.svgRef}
|
||||
aria-hidden="true"
|
||||
data-testid="annotation-overlay"
|
||||
viewBox={props.viewBox}
|
||||
preserveAspectRatio={props.ratio}
|
||||
className="pointer-events-none absolute inset-0 h-full w-full"
|
||||
>
|
||||
{shown && isEditable(shown) && (
|
||||
<>
|
||||
<Outline geometry={shown} dashed colour="var(--color-ink)" />
|
||||
<Vertices geometry={shown} size={size} />
|
||||
</>
|
||||
)}
|
||||
{pending && (
|
||||
<Outline
|
||||
geometry={pending}
|
||||
dashed={false}
|
||||
colour="var(--color-accent)"
|
||||
/>
|
||||
)}
|
||||
{correction && (
|
||||
<>
|
||||
<Outline
|
||||
geometry={{ type: 'circle', ...correction.circle }}
|
||||
dashed
|
||||
colour="var(--color-accent)"
|
||||
/>
|
||||
<HollowCross at={correction.click} size={size * 1.5} />
|
||||
</>
|
||||
)}
|
||||
{tracing && <TracingPath points={tracing} size={size} />}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import type { Correction } from '@/editor/annotations/correction'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/**
|
||||
* The corrected position is never taken silently: the page says where the point would
|
||||
* sit, the overlay shows it with the click marked apart, and only « Utiliser cette
|
||||
* position » inserts it.
|
||||
*/
|
||||
export default function CorrectionNotice({
|
||||
correction,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
correction: Correction
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const message = t('editor.annotations.correction')
|
||||
.replace('{x}', String(correction.circle.cx))
|
||||
.replace('{y}', String(correction.circle.cy))
|
||||
return (
|
||||
<Notice tone="info">
|
||||
<div className="space-y-2" data-testid="correction-notice">
|
||||
<p>{message}</p>
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" size="sm" onClick={onConfirm}>
|
||||
{t('editor.annotations.correction_use')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={onCancel}
|
||||
>
|
||||
{t('editor.annotations.correction_cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Notice>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
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 Button from '@/components/ui/Button'
|
||||
import Select from '@/components/ui/Select'
|
||||
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,
|
||||
type CreationForm,
|
||||
type PendingElement,
|
||||
} from '@/editor/annotations/creation'
|
||||
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 GeometryGroup from './GeometryGroup'
|
||||
|
||||
export interface CreationPanelProps {
|
||||
pending: PendingElement
|
||||
viewId: string
|
||||
doc: AnatomicalSheetDocument
|
||||
/** F of the current view; null while it is not measured. */
|
||||
frame: Frame | null
|
||||
dispatch: Dispatch<UiAction>
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/** « 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 }),
|
||||
)
|
||||
}
|
||||
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 }))
|
||||
}
|
||||
|
||||
/**
|
||||
* « Nouveau point / Nouvelle zone / Nouvel accès »: the fields the core requires are
|
||||
* collected first, then « Créer » inserts once through `accept` (no default labels).
|
||||
* The geometry stays here, outside the document, until then.
|
||||
*/
|
||||
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 }
|
||||
}
|
||||
return (
|
||||
<section
|
||||
aria-label={t(`editor.annotations.new.${pending.kind}`)}
|
||||
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>
|
||||
<CreationFields
|
||||
kind={pending.kind}
|
||||
viewId={props.viewId}
|
||||
form={form}
|
||||
doc={doc}
|
||||
onChange={(patch) => setForm({ ...form, ...patch })}
|
||||
/>
|
||||
<GeometryGroup
|
||||
idPrefix="creation"
|
||||
geometry={pending.geometry}
|
||||
onApply={setGeometry}
|
||||
locked={false}
|
||||
/>
|
||||
{pending.correction && (
|
||||
<CorrectionNotice
|
||||
correction={pending.correction}
|
||||
onConfirm={() =>
|
||||
settle(confirmAttempt(props, form, pending.correction!))
|
||||
}
|
||||
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>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Messages({ messages }: { messages: string[] }) {
|
||||
if (messages.length === 0) return null
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="space-y-1 text-sm text-[var(--color-danger-strong)]"
|
||||
>
|
||||
{messages.map((message) => (
|
||||
<p key={message}>{message}</p>
|
||||
))}
|
||||
</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 })}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import { useReducer, useState, type Dispatch } from 'react'
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
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'
|
||||
import { usePlacement } from '@/editor/annotations/usePlacement'
|
||||
import {
|
||||
initialUi,
|
||||
uiReducer,
|
||||
type ToolId,
|
||||
type UiAction,
|
||||
type UiState,
|
||||
} from '@/editor/annotations/uiState'
|
||||
import {
|
||||
mainViewId,
|
||||
useUndoShortcuts,
|
||||
useViewModel,
|
||||
type ViewModel,
|
||||
} from '@/editor/annotations/useViewModel'
|
||||
import type { EditorTabProps } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import AnnotationCanvas from './AnnotationCanvas'
|
||||
import AnnotationList, { annotationName } from './AnnotationList'
|
||||
import CreationPanel from './CreationPanel'
|
||||
import KeyboardAdd from './KeyboardAdd'
|
||||
import PropertiesPanel, { UnmeasuredHint } from './PropertiesPanel'
|
||||
import SelectionTag from './SelectionTag'
|
||||
import TracingBar from './TracingBar'
|
||||
import ViewSwitcher from './ViewSwitcher'
|
||||
|
||||
interface Props {
|
||||
doc: AnatomicalSheetDocument
|
||||
onSelectTab: EditorTabProps['onSelectTab']
|
||||
}
|
||||
|
||||
export default function EditableAnnotations({ doc, onSelectTab }: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const [ui, dispatch] = useReducer(uiReducer, initialUi)
|
||||
const [viewBox, setViewBox] = useState<string | 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 }
|
||||
return (
|
||||
<div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
|
||||
<CanvasColumn {...scene} placement={placement} onRoot={setViewBox} />
|
||||
<aside>
|
||||
<SidePanel {...scene} viewId={viewId} 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
|
||||
}
|
||||
|
||||
function CanvasColumn({
|
||||
placement,
|
||||
onRoot,
|
||||
...scene
|
||||
}: Scene & {
|
||||
placement: ReturnType<typeof usePlacement>
|
||||
onRoot: (viewBox: string | null) => void
|
||||
}) {
|
||||
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 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}>
|
||||
<ViewSwitcher
|
||||
views={doc.views}
|
||||
current={viewId}
|
||||
onSelect={(id) => dispatch({ type: 'view', viewId: id })}
|
||||
/>
|
||||
<ToolNotes
|
||||
tool={ui.tool}
|
||||
hint={ui.hint}
|
||||
model={model}
|
||||
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}
|
||||
/>
|
||||
{ui.tracing && (
|
||||
<TracingBar
|
||||
count={ui.tracing.points.length}
|
||||
onClose={placement.closeTracing}
|
||||
onCancel={() => dispatch({ type: 'trace_cancel' })}
|
||||
/>
|
||||
)}
|
||||
<KeyboardAdd
|
||||
disabled={blocked || frame === null}
|
||||
linkDisabled={model.children.length === 0}
|
||||
onAdd={(kind) => addAtCentre(kind, frame, dispatch)}
|
||||
/>
|
||||
<AnnotationList
|
||||
annotations={model.annotations}
|
||||
views={doc.views}
|
||||
selectedId={ui.selectedId}
|
||||
onSelect={select}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function addAtCentre(
|
||||
kind: NewKind,
|
||||
frame: Frame | null,
|
||||
dispatch: Dispatch<UiAction>,
|
||||
) {
|
||||
if (!frame) return
|
||||
dispatch({ type: 'pending_new', pending: keyboardPending(kind, frame) })
|
||||
}
|
||||
|
||||
/** The creation panel while an element is pending, else the selection's properties. */
|
||||
function SidePanel({
|
||||
viewId,
|
||||
context,
|
||||
...scene
|
||||
}: Scene & { viewId: string; context: CommitContext }) {
|
||||
const t = useT()
|
||||
const { doc, ui, dispatch, model, frame, selected } = scene
|
||||
if (ui.pending) {
|
||||
return (
|
||||
<CreationPanel
|
||||
key={ui.serial}
|
||||
pending={ui.pending}
|
||||
viewId={viewId}
|
||||
doc={doc}
|
||||
frame={frame}
|
||||
dispatch={dispatch}
|
||||
context={context}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (!selected) {
|
||||
return (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.annotations.select_hint')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<PropertiesPanel
|
||||
key={selected.id}
|
||||
annotation={selected}
|
||||
doc={doc}
|
||||
readOnly={false}
|
||||
geometryLocked={!model.measured}
|
||||
dispatch={dispatch}
|
||||
context={context}
|
||||
onSelectTab={scene.onSelectTab}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function moveTargetOf(
|
||||
selected: Annotation | undefined,
|
||||
model: ViewModel,
|
||||
tool: ToolId,
|
||||
) {
|
||||
if (!selected || !model.measured || tool !== 'select') return null
|
||||
return isEditable(selected.geometry)
|
||||
? { id: selected.id, geometry: selected.geometry }
|
||||
: null
|
||||
}
|
||||
|
||||
function overlayOf(
|
||||
ui: UiState,
|
||||
selected: Annotation | undefined,
|
||||
frame: Frame | null,
|
||||
) {
|
||||
return {
|
||||
frame,
|
||||
selected: selected?.geometry ?? null,
|
||||
pending: ui.pending?.geometry ?? null,
|
||||
tracing: ui.tracing?.points ?? null,
|
||||
correction: ui.pending?.correction ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool line and the reasons a tool cannot be used now. */
|
||||
function ToolNotes({
|
||||
tool,
|
||||
hint,
|
||||
model,
|
||||
noCategory,
|
||||
onSelectTab,
|
||||
}: {
|
||||
tool: ToolId
|
||||
hint: string | null
|
||||
model: ViewModel
|
||||
noCategory: boolean
|
||||
onSelectTab: EditorTabProps['onSelectTab']
|
||||
}) {
|
||||
const t = useT()
|
||||
const linkBlocked = tool === 'link' && model.children.length === 0
|
||||
return (
|
||||
<div className="space-y-1 text-sm text-[var(--color-ink-muted)]">
|
||||
<p>{t(`editor.annotations.tool_hint.${tool}`)}</p>
|
||||
{!model.measured && <UnmeasuredHint onSelectTab={onSelectTab} />}
|
||||
{noCategory && <p>{t('editor.annotations.no_category')}</p>}
|
||||
{linkBlocked && <p>{t('editor.annotations.no_child_view')}</p>}
|
||||
{hint && (
|
||||
<p role="alert" className="text-[var(--color-danger-strong)]">
|
||||
{hint}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import { useState } from 'react'
|
||||
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Input from '@/components/ui/Input'
|
||||
import {
|
||||
changedFieldNames,
|
||||
fieldsOf,
|
||||
parseFields,
|
||||
sameAsStored,
|
||||
withVertexAfter,
|
||||
withoutVertex,
|
||||
type EditableGeometry,
|
||||
type GroupFields,
|
||||
} from '@/editor/annotations/geometryEdit'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** What applying the group answers: kept, or the words that say why not. */
|
||||
export type ApplyResult = { ok: true } | { ok: false; messages: string[] }
|
||||
|
||||
export interface GeometryGroupProps {
|
||||
idPrefix: string
|
||||
/** The stored (or pending) geometry the fields start from. */
|
||||
geometry: EditableGeometry
|
||||
/** Proposes the WHOLE group; the core's verdict comes back as the result. */
|
||||
onApply: (geometry: EditableGeometry) => ApplyResult
|
||||
/** Fields shown as text: read-only mode or an unmeasured view. */
|
||||
locked: boolean
|
||||
}
|
||||
|
||||
type Fields = GroupFields
|
||||
type PolygonFields = Extract<GroupFields, { type: 'polygon' }>
|
||||
|
||||
/**
|
||||
* 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;
|
||||
* a refusal keeps the typed values marked « non appliqué » with the core's message and
|
||||
* the document unchanged. Selecting another element unmounts it: an unapplied group was
|
||||
* 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 parsed = parseFields(next)
|
||||
if (!parsed.ok) return setMessages(['number'])
|
||||
const result = props.onApply(parsed.geometry)
|
||||
setMessages(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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
interface BodyProps extends Omit<GeometryGroupProps, 'onApply'> {
|
||||
draft: Fields
|
||||
pending: Set<string>
|
||||
messages: string[]
|
||||
onChange: (fields: Fields) => void
|
||||
onPropose: (fields: Fields) => void
|
||||
onRevert: () => void
|
||||
}
|
||||
|
||||
function GroupBody(props: BodyProps) {
|
||||
const t = useT()
|
||||
const { draft, pending, messages } = props
|
||||
const unapplied = pending.size > 0 && messages.length > 0
|
||||
return (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">
|
||||
{t(
|
||||
draft.type === 'circle'
|
||||
? 'editor.annotations.geometry.circle'
|
||||
: 'editor.annotations.geometry.polygon',
|
||||
)}
|
||||
</legend>
|
||||
{draft.type === 'circle' ? (
|
||||
<CircleRows {...props} fields={draft} />
|
||||
) : (
|
||||
<PolygonRows {...props} fields={draft} />
|
||||
)}
|
||||
{unapplied && <Unapplied {...props} />}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
function Unapplied({ messages, onRevert }: BodyProps) {
|
||||
const t = useT()
|
||||
const words = messages.map((m) =>
|
||||
m === 'number' ? t('editor.annotations.geometry.number') : m,
|
||||
)
|
||||
return (
|
||||
<div role="alert" className="space-y-1 text-sm">
|
||||
<p className="font-medium text-[var(--color-danger-strong)]">
|
||||
{t('editor.annotations.geometry.unapplied')}
|
||||
</p>
|
||||
{words.map((word) => (
|
||||
<p key={word} className="text-[var(--color-danger-strong)]">
|
||||
{word}
|
||||
</p>
|
||||
))}
|
||||
<Button type="button" variant="secondary" size="sm" onClick={onRevert}>
|
||||
{t('editor.annotations.geometry.revert')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NumberInput({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
unapplied,
|
||||
locked,
|
||||
onType,
|
||||
onApply,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
unapplied: boolean
|
||||
locked: boolean
|
||||
onType: (value: string) => void
|
||||
onApply: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
if (locked) {
|
||||
return (
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{label}</span> {value}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
const hint = unapplied
|
||||
? t('editor.annotations.geometry.unapplied_tag')
|
||||
: undefined
|
||||
return (
|
||||
<FormField id={id} label={label} hint={hint}>
|
||||
<Input
|
||||
id={id}
|
||||
inputMode="decimal"
|
||||
value={value}
|
||||
aria-invalid={unapplied}
|
||||
aria-describedby={fieldDescribedBy(id, hint)}
|
||||
onChange={(e) => onType(e.target.value)}
|
||||
onBlur={onApply}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.nativeEvent.isComposing) onApply()
|
||||
}}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
type RowsProps<F extends Fields> = BodyProps & { fields: F }
|
||||
|
||||
function CircleRows(props: RowsProps<Extract<Fields, { type: 'circle' }>>) {
|
||||
const t = useT()
|
||||
const { fields, pending, locked, idPrefix } = props
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{(['cx', 'cy', 'r'] as const).map((key) => (
|
||||
<NumberInput
|
||||
key={key}
|
||||
id={`${idPrefix}-${key}`}
|
||||
label={t(`editor.annotations.geometry.${key}`)}
|
||||
value={fields[key]}
|
||||
unapplied={pending.has(key)}
|
||||
locked={locked}
|
||||
onType={(value) => props.onChange({ ...fields, [key]: value })}
|
||||
onApply={() => props.onPropose(fields)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PolygonRows(props: RowsProps<PolygonFields>) {
|
||||
const t = useT()
|
||||
const [selected, setSelected] = useState(0)
|
||||
const { fields, locked } = props
|
||||
const change = (index: number, axis: 'x' | 'y', value: string) =>
|
||||
props.onChange({
|
||||
type: 'polygon',
|
||||
rows: fields.rows.map((row, i) =>
|
||||
i === index ? { ...row, [axis]: value } : row,
|
||||
),
|
||||
})
|
||||
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),
|
||||
)}
|
||||
</p>
|
||||
{fields.rows.map((row, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="grid grid-cols-[2rem_1fr_1fr] items-end gap-2"
|
||||
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 && (
|
||||
<VertexButtons
|
||||
fields={fields}
|
||||
selected={selected}
|
||||
onApply={props.onPropose}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function VertexButtons({
|
||||
fields,
|
||||
selected,
|
||||
onApply,
|
||||
}: {
|
||||
fields: PolygonFields
|
||||
selected: number
|
||||
onApply: (fields: Fields) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onApply(withVertexAfter(fields, selected))}
|
||||
>
|
||||
{t('editor.annotations.geometry.add_vertex')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={fields.rows.length <= 3}
|
||||
onClick={() => onApply(withoutVertex(fields, selected))}
|
||||
>
|
||||
{t('editor.action.remove')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { NewKind } from '@/editor/annotations/creation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
const KINDS: readonly NewKind[] = ['point', 'zone', 'detail_trigger']
|
||||
|
||||
/**
|
||||
* The keyboard creation path (C7): each button holds a pending element at the centre of
|
||||
* the frame and opens the creation panel; every coordinate is then typed in the fields.
|
||||
*/
|
||||
export default function KeyboardAdd({
|
||||
disabled,
|
||||
linkDisabled,
|
||||
onAdd,
|
||||
}: {
|
||||
/** No measured frame, or no category: nothing can be placed. */
|
||||
disabled: boolean
|
||||
/** No detail view directly under this view: no link can be placed. */
|
||||
linkDisabled: boolean
|
||||
onAdd: (kind: NewKind) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{KINDS.map((kind) => (
|
||||
<Button
|
||||
key={kind}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={disabled || (kind === 'detail_trigger' && linkDisabled)}
|
||||
onClick={() => onAdd(kind)}
|
||||
>
|
||||
{t(`editor.annotations.add.${kind}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { useState, type Dispatch } from 'react'
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
Geometry,
|
||||
Marking,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import DeleteDialog from '@/components/editor/DeleteDialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import {
|
||||
updateGeometry,
|
||||
type CommitContext,
|
||||
} from '@/editor/annotations/annotationCommit'
|
||||
import { isEditable } from '@/editor/annotations/geometryEdit'
|
||||
import type { UiAction } from '@/editor/annotations/uiState'
|
||||
import { geometryErrorsById } from '@/editor/issues'
|
||||
import type { EditorTabId } from '@/editor/tabs'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import { useEditorStore } from '@/editor/state/editorStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import AnnotationFields from './AnnotationFields'
|
||||
import type { ApplyResult } from './GeometryGroup'
|
||||
import { annotationName } from './AnnotationList'
|
||||
import GeometryGroup from './GeometryGroup'
|
||||
import ReviewBadge from './ReviewBadge'
|
||||
|
||||
export interface PropertiesPanelProps {
|
||||
annotation: Annotation
|
||||
doc: AnatomicalSheetDocument
|
||||
/** Not editable now: every field shows as text and no action is offered. */
|
||||
readOnly: boolean
|
||||
/** The view is not measured: geometry is shown as text only, the rest stays editable. */
|
||||
geometryLocked: boolean
|
||||
dispatch: Dispatch<UiAction>
|
||||
context: CommitContext
|
||||
onSelectTab: (tab: EditorTabId) => void
|
||||
}
|
||||
|
||||
/** What still names this annotation as invalid: never hidden, never shown as valid. */
|
||||
function useGeometryIssues(id: string): string[] {
|
||||
const state = useEditorStore((s) => s.previewState)
|
||||
const issues = state ? geometryErrorsById(state).get(id) : undefined
|
||||
return [...new Set((issues ?? []).map((issue) => issue.message))]
|
||||
}
|
||||
|
||||
export default function PropertiesPanel(props: PropertiesPanelProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { annotation, doc, readOnly } = props
|
||||
const edit = useEditCommand()
|
||||
const name = annotationName(annotation, doc.views, locale)
|
||||
return (
|
||||
<section
|
||||
aria-label={t('editor.annotations.properties')}
|
||||
data-testid="annotation-properties"
|
||||
className="space-y-4 rounded-xl border border-[var(--color-border)] p-4"
|
||||
>
|
||||
<header className="flex items-start justify-between gap-2">
|
||||
<h3 className="text-base font-semibold">
|
||||
{t(`editor.annotations.kind.${annotation.kind}`)}
|
||||
</h3>
|
||||
<ReviewBadge status={annotation.review_status} />
|
||||
</header>
|
||||
<AnnotationFields
|
||||
annotation={annotation}
|
||||
doc={doc}
|
||||
readOnly={readOnly}
|
||||
edit={edit}
|
||||
/>
|
||||
<GeometrySection {...props} />
|
||||
<StatusActions annotation={annotation} readOnly={readOnly} edit={edit} />
|
||||
<Deletion id={annotation.id} name={name} readOnly={readOnly} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function GeometrySection(props: PropertiesPanelProps) {
|
||||
const t = useT()
|
||||
const { annotation, readOnly, geometryLocked } = props
|
||||
const locked = readOnly || geometryLocked
|
||||
const { geometry } = annotation
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{geometryLocked && !readOnly && <UnmeasuredHint {...props} />}
|
||||
{isEditable(geometry) ? (
|
||||
<GeometryGroup
|
||||
key={annotation.id}
|
||||
idPrefix="annotation"
|
||||
geometry={geometry}
|
||||
locked={locked}
|
||||
onApply={(next) => applyGeometry(annotation, next, props.context)}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t(
|
||||
geometry === null
|
||||
? 'editor.annotations.no_geometry'
|
||||
: 'editor.annotations.path',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{!locked && !isEditable(geometry) && (
|
||||
<TraceReplacement id={annotation.id} dispatch={props.dispatch} />
|
||||
)}
|
||||
<GeometryIssues id={annotation.id} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function applyGeometry(
|
||||
annotation: Annotation,
|
||||
next: Geometry,
|
||||
context: CommitContext,
|
||||
): ApplyResult {
|
||||
const result = updateGeometry(annotation, next, context)
|
||||
return result.ok ? { ok: true } : { ok: false, messages: result.messages }
|
||||
}
|
||||
|
||||
function TraceReplacement({
|
||||
id,
|
||||
dispatch,
|
||||
}: {
|
||||
id: string
|
||||
dispatch: Dispatch<UiAction>
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
dispatch({ type: 'trace_start', target: 'replace', annotationId: id })
|
||||
}
|
||||
>
|
||||
{t('editor.annotations.replace_polygon')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function GeometryIssues({ id }: { id: string }) {
|
||||
const issues = useGeometryIssues(id)
|
||||
if (issues.length === 0) return null
|
||||
return (
|
||||
<ul
|
||||
role="alert"
|
||||
data-testid="annotation-geometry-issues"
|
||||
className="list-disc pl-5 text-sm text-[var(--color-danger-strong)]"
|
||||
>
|
||||
{issues.map((issue) => (
|
||||
<li key={issue}>{issue}</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
export function UnmeasuredHint({
|
||||
onSelectTab,
|
||||
}: Pick<PropertiesPanelProps, 'onSelectTab'>) {
|
||||
const t = useT()
|
||||
return (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.annotations.unmeasured.hint')}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => onSelectTab('views')}
|
||||
>
|
||||
{t('editor.tab.views')}
|
||||
</button>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
function StatusActions({
|
||||
annotation,
|
||||
readOnly,
|
||||
edit,
|
||||
}: {
|
||||
annotation: Annotation
|
||||
readOnly: boolean
|
||||
edit: ReturnType<typeof useEditCommand>
|
||||
}) {
|
||||
const t = useT()
|
||||
const mark = (status: Marking) =>
|
||||
edit.run('status', {
|
||||
op: 'set_status',
|
||||
key: { kind: 'annotation', id: annotation.id },
|
||||
status,
|
||||
})
|
||||
const reviewed = annotation.review_status === 'reviewed'
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<ActionButton
|
||||
readOnly={readOnly}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => mark(reviewed ? 'to_confirm' : 'reviewed')}
|
||||
>
|
||||
{t(
|
||||
reviewed
|
||||
? 'editor.annotations.to_confirm'
|
||||
: 'editor.annotations.mark_reviewed',
|
||||
)}
|
||||
</ActionButton>
|
||||
{edit.fieldError('status') && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{edit.fieldError('status')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Deletion({
|
||||
id,
|
||||
name,
|
||||
readOnly,
|
||||
}: {
|
||||
id: string
|
||||
name: string
|
||||
readOnly: boolean
|
||||
}) {
|
||||
const t = useT()
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<ActionButton
|
||||
readOnly={readOnly}
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
{t('editor.action.delete')}
|
||||
</ActionButton>
|
||||
<DeleteDialog
|
||||
target={open ? { key: { kind: 'annotation', id }, label: name } : null}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { ReviewStatus } from '@faunosteo/core-wasm/types'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
const TONES = {
|
||||
to_confirm: 'warn',
|
||||
reviewed: 'accent',
|
||||
inherited: 'neutral',
|
||||
} as const
|
||||
|
||||
export default function ReviewBadge({ status }: { status: ReviewStatus }) {
|
||||
const t = useT()
|
||||
return (
|
||||
<Badge tone={TONES[status]}>
|
||||
{t(`editor.annotations.status.${status}`)}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** Board 04's tag over the drawing: « Sélection : <type> « <nom> ». */
|
||||
export default function SelectionTag({
|
||||
kind,
|
||||
name,
|
||||
}: {
|
||||
kind: string
|
||||
name: string
|
||||
}) {
|
||||
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"
|
||||
>
|
||||
{t('editor.annotations.selection')
|
||||
.replace(
|
||||
'{kind}',
|
||||
t(`editor.annotations.kind.${kind}`).toLocaleLowerCase(),
|
||||
)
|
||||
.replace('{name}', name)}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
|
||||
import type { ToolId } from '@/editor/annotations/uiState'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface ToolColumnProps {
|
||||
tool: ToolId
|
||||
onTool: (tool: ToolId) => void
|
||||
/** Point, zone and link need a measured view and a category. */
|
||||
drawingDisabled: boolean
|
||||
/** The link tool needs a detail view directly under the current one. */
|
||||
linkDisabled: boolean
|
||||
onZoomIn: () => void
|
||||
onZoomOut: () => void
|
||||
onFit: () => void
|
||||
}
|
||||
|
||||
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',
|
||||
zone: 'M12 3l8 6-3 10H7L4 9z',
|
||||
link: 'M4 4h8v8H4zM12 12h8v8h-8z',
|
||||
in: 'M11 5v12M5 11h12M20 20l-4-4',
|
||||
out: 'M5 11h12M20 20l-4-4',
|
||||
fit: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5',
|
||||
undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10',
|
||||
redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10',
|
||||
}
|
||||
|
||||
function ToolButton({
|
||||
glyph,
|
||||
label,
|
||||
pressed,
|
||||
disabled,
|
||||
onClick,
|
||||
}: {
|
||||
glyph: string
|
||||
label: string
|
||||
pressed?: boolean
|
||||
disabled?: boolean
|
||||
onClick: () => void
|
||||
}): ReactNode {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={label}
|
||||
title={label}
|
||||
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)] ${
|
||||
pressed
|
||||
? 'bg-[var(--color-ink)] text-white'
|
||||
: 'bg-[var(--color-surface)] text-[var(--color-ink)]'
|
||||
}`}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width="20"
|
||||
height="20"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d={GLYPHS[glyph]} />
|
||||
</svg>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** Board 04's tool column: tools, zoom, then undo and redo (icon buttons). */
|
||||
export default function ToolColumn(props: ToolColumnProps) {
|
||||
const t = useT()
|
||||
const undoable = useEditorStore(canUndo)
|
||||
const redoable = useEditorStore(canRedo)
|
||||
const tool = (id: ToolId, disabled: boolean) => (
|
||||
<ToolButton
|
||||
glyph={id}
|
||||
label={t(`editor.annotations.tool.${id}`)}
|
||||
pressed={props.tool === id}
|
||||
disabled={disabled}
|
||||
onClick={() => props.onTool(id)}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
role="toolbar"
|
||||
aria-orientation="vertical"
|
||||
aria-label={t('editor.annotations.tools')}
|
||||
className="flex flex-row gap-2 lg:flex-col"
|
||||
>
|
||||
{tool('select', false)}
|
||||
{tool('point', props.drawingDisabled)}
|
||||
{tool('zone', props.drawingDisabled)}
|
||||
{tool('link', props.drawingDisabled || props.linkDisabled)}
|
||||
<hr className="hidden border-[var(--color-border)] lg:block" />
|
||||
<ToolButton
|
||||
glyph="out"
|
||||
label={t('catalogue.zoom.out')}
|
||||
onClick={props.onZoomOut}
|
||||
/>
|
||||
<ToolButton
|
||||
glyph="in"
|
||||
label={t('catalogue.zoom.in')}
|
||||
onClick={props.onZoomIn}
|
||||
/>
|
||||
<ToolButton
|
||||
glyph="fit"
|
||||
label={t('catalogue.zoom.fit')}
|
||||
onClick={props.onFit}
|
||||
/>
|
||||
<hr className="hidden border-[var(--color-border)] lg:block" />
|
||||
<ToolButton
|
||||
glyph="undo"
|
||||
label={t('editor.annotations.undo')}
|
||||
disabled={!undoable}
|
||||
onClick={() => useEditorStore.getState().undoStep()}
|
||||
/>
|
||||
<ToolButton
|
||||
glyph="redo"
|
||||
label={t('editor.annotations.redo')}
|
||||
disabled={!redoable}
|
||||
onClick={() => useEditorStore.getState().redoStep()}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** While a zone or link is being traced: close (3 vertices at least) or drop it. */
|
||||
export default function TracingBar({
|
||||
count,
|
||||
onClose,
|
||||
onCancel,
|
||||
}: {
|
||||
count: number
|
||||
onClose: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.annotations.tracing').replace('{count}', String(count))}
|
||||
</p>
|
||||
<Button type="button" size="sm" disabled={count < 3} onClick={onClose}>
|
||||
{t('editor.annotations.trace_close')}
|
||||
</Button>
|
||||
<Button type="button" size="sm" variant="ghost" onClick={onCancel}>
|
||||
{t('editor.annotations.trace_cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { SheetView } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
/** One chip per view (board 04): the main view, then each detail view. */
|
||||
export default function ViewSwitcher({
|
||||
views,
|
||||
current,
|
||||
onSelect,
|
||||
}: {
|
||||
views: readonly SheetView[]
|
||||
current: string
|
||||
onSelect: (viewId: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('editor.annotations.views')}
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
{views.map((view) => (
|
||||
<button
|
||||
key={view.id}
|
||||
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)] ${
|
||||
view.id === current
|
||||
? 'bg-[var(--color-ink)] text-white'
|
||||
: 'bg-[var(--color-surface)]'
|
||||
}`}
|
||||
>
|
||||
{view.name[locale]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,14 +1,105 @@
|
||||
import { useState } from 'react'
|
||||
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
|
||||
import CatalogueCanvas from '@/components/catalogue/CatalogueCanvas'
|
||||
import AnnotationList, {
|
||||
annotationName,
|
||||
} from '@/components/editor/annotations/AnnotationList'
|
||||
import EditableAnnotations from '@/components/editor/annotations/EditableAnnotations'
|
||||
import PropertiesPanel from '@/components/editor/annotations/PropertiesPanel'
|
||||
import ViewSwitcher from '@/components/editor/annotations/ViewSwitcher'
|
||||
import SelectionTag from '@/components/editor/annotations/SelectionTag'
|
||||
import { mainViewId, useViewModel } from '@/editor/annotations/useViewModel'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useEditorStore } from '@/editor/state/editorStore'
|
||||
import type { EditorTabProps } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
/** Placeholder: Lot H replaces the body and keeps the props contract (`EditorTabProps`). */
|
||||
export default function AnnotationsTab(_props: EditorTabProps) {
|
||||
/**
|
||||
* Annotations: the canvas with its tools, the list of the view, the creation and
|
||||
* properties panels. Read-only, the same view is browsable (canvas, list, properties as
|
||||
* text) with no tool and no action.
|
||||
*/
|
||||
export default function AnnotationsTab(props: EditorTabProps) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const preview = useEditorStore((s) => s.preview)
|
||||
return (
|
||||
<section
|
||||
data-testid="editor-tab-annotations"
|
||||
aria-label={t('editor.tab.annotations')}
|
||||
className="min-h-24"
|
||||
/>
|
||||
className="min-h-24 space-y-3"
|
||||
>
|
||||
{doc && preview && props.readOnly && (
|
||||
<ReadOnlyAnnotations doc={doc} onSelectTab={props.onSelectTab} />
|
||||
)}
|
||||
{doc && preview && !props.readOnly && (
|
||||
<EditableAnnotations doc={doc} onSelectTab={props.onSelectTab} />
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function ReadOnlyAnnotations({
|
||||
doc,
|
||||
onSelectTab,
|
||||
}: {
|
||||
doc: AnatomicalSheetDocument
|
||||
onSelectTab: EditorTabProps['onSelectTab']
|
||||
}) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const preview = useEditorStore((s) => s.preview)
|
||||
const handleVersion = useEditorStore((s) => s.handleVersion)
|
||||
const [viewId, setViewId] = useState(mainViewId(doc))
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const model = useViewModel(doc, viewId)
|
||||
const view = doc.views.find((v) => v.id === viewId)
|
||||
const selected = model.annotations.find((a) => a.id === selectedId)
|
||||
if (!preview || !view) return null
|
||||
return (
|
||||
<div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
|
||||
<div className="min-w-0 space-y-3">
|
||||
<ViewSwitcher
|
||||
views={doc.views}
|
||||
current={viewId}
|
||||
onSelect={(id) => {
|
||||
setViewId(id)
|
||||
setSelectedId(null)
|
||||
}}
|
||||
/>
|
||||
{selected && (
|
||||
<SelectionTag
|
||||
kind={selected.kind}
|
||||
name={annotationName(selected, doc.views, locale)}
|
||||
/>
|
||||
)}
|
||||
<CatalogueCanvas
|
||||
key={handleVersion}
|
||||
preview={preview}
|
||||
viewId={viewId}
|
||||
viewName={view.name[locale]}
|
||||
selectedId={selectedId}
|
||||
onAnnotation={setSelectedId}
|
||||
/>
|
||||
<AnnotationList
|
||||
annotations={model.annotations}
|
||||
views={doc.views}
|
||||
selectedId={selectedId}
|
||||
onSelect={setSelectedId}
|
||||
/>
|
||||
</div>
|
||||
{selected && (
|
||||
<PropertiesPanel
|
||||
key={selected.id}
|
||||
annotation={selected}
|
||||
doc={doc}
|
||||
readOnly
|
||||
geometryLocked={!model.measured}
|
||||
dispatch={() => undefined}
|
||||
context={{ t: (key) => key, locale }}
|
||||
onSelectTab={onSelectTab}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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 } }
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}, [])
|
||||
}
|
||||
@@ -1434,4 +1434,79 @@ export const en: Dict = {
|
||||
'editor.findings.empty': 'No findings zone yet.',
|
||||
'editor.findings.mark_reviewed': 'Mark as reviewed',
|
||||
'editor.findings.reset_to_confirm': 'Reset to confirm',
|
||||
'editor.annotations.tools': 'Tools',
|
||||
'editor.annotations.tool.select': 'Select and move',
|
||||
'editor.annotations.tool.point': 'Point',
|
||||
'editor.annotations.tool.zone': 'Zone',
|
||||
'editor.annotations.tool.link': 'Link to a detail view',
|
||||
'editor.annotations.undo': 'Undo',
|
||||
'editor.annotations.redo': 'Redo',
|
||||
'editor.annotations.tool_hint.select': 'Tool: select and move · Esc cancels a tracing',
|
||||
'editor.annotations.tool_hint.point': 'Tool: point · click in the drawing to place a point.',
|
||||
'editor.annotations.tool_hint.zone': 'Tool: zone · click to place the vertices; Enter or « Close the tracing » finishes, Esc cancels.',
|
||||
'editor.annotations.tool_hint.link': 'Tool: link to a detail view · trace the outline that opens the view; Enter finishes, Esc cancels.',
|
||||
'editor.annotations.views': 'Views',
|
||||
'editor.annotations.unmeasured.hint': 'This drawing cannot be measured: add or fix its illustration (tab Views and illustrations) before placing or moving elements.',
|
||||
'editor.annotations.outside': 'Click inside the drawing.',
|
||||
'editor.annotations.correction': 'The point does not fit where you clicked. Corrected position proposed: x = {x}, y = {y}.',
|
||||
'editor.annotations.correction_use': 'Use this position',
|
||||
'editor.annotations.correction_cancel': 'Cancel',
|
||||
'editor.annotations.no_category': 'Create an annotation category first (tab General).',
|
||||
'editor.annotations.no_child_view': 'No detail view opens from this view: create one in the Views and illustrations tab.',
|
||||
'editor.annotations.add.point': 'Add a point',
|
||||
'editor.annotations.add.zone': 'Add a zone',
|
||||
'editor.annotations.add.detail_trigger': 'Add a link',
|
||||
'editor.annotations.new.point': 'New point',
|
||||
'editor.annotations.new.zone': 'New zone',
|
||||
'editor.annotations.new.detail_trigger': 'New link',
|
||||
'editor.annotations.create': 'Create',
|
||||
'editor.annotations.create_cancel': 'Cancel',
|
||||
'editor.annotations.name_fr': 'Name (FR)',
|
||||
'editor.annotations.name_en': 'Name (EN)',
|
||||
'editor.annotations.category': 'Category',
|
||||
'editor.annotations.color': 'Colour',
|
||||
'editor.annotations.color_hint': 'Leave empty for the category colour, or enter a hexadecimal value (#rrggbb).',
|
||||
'editor.annotations.laterality': 'Laterality',
|
||||
'editor.annotations.laterality.unpaired': 'Unpaired',
|
||||
'editor.annotations.laterality.bilateral': 'Bilateral',
|
||||
'editor.annotations.laterality.left': 'Left',
|
||||
'editor.annotations.laterality.right': 'Right',
|
||||
'editor.annotations.region': 'Vertebral region',
|
||||
'editor.annotations.zone': 'Findings zone',
|
||||
'editor.annotations.opens': 'Opened view',
|
||||
'editor.annotations.none': 'None',
|
||||
'editor.annotations.required.fields': 'Choose the category and the laterality (and the opened view for a link).',
|
||||
'editor.annotations.required.names': 'Enter the name in French and in English.',
|
||||
'editor.annotations.kind.point': 'Point',
|
||||
'editor.annotations.kind.zone': 'Zone',
|
||||
'editor.annotations.kind.detail_trigger': 'Link',
|
||||
'editor.annotations.status.to_confirm': 'To confirm',
|
||||
'editor.annotations.status.reviewed': 'Reviewed',
|
||||
'editor.annotations.status.inherited': 'Inherited, not reviewed',
|
||||
'editor.annotations.mark_reviewed': 'Mark as reviewed',
|
||||
'editor.annotations.to_confirm': 'Reset to confirm',
|
||||
'editor.annotations.list': 'Annotations of the view',
|
||||
'editor.annotations.list_empty': 'No annotation in this view.',
|
||||
'editor.annotations.selection': 'Selection: {kind} « {name} »',
|
||||
'editor.annotations.select_hint': 'Select an annotation on the drawing or in the list to see its properties.',
|
||||
'editor.annotations.properties': 'Annotation properties',
|
||||
'editor.annotations.tracing': '{count} vertex(es) placed.',
|
||||
'editor.annotations.trace_close': 'Close the tracing',
|
||||
'editor.annotations.trace_cancel': 'Cancel the tracing',
|
||||
'editor.annotations.replace_polygon': 'Replace with a polygon',
|
||||
'editor.annotations.no_geometry': 'This annotation has no geometry: trace a polygon to give it one.',
|
||||
'editor.annotations.path': 'This annotation is a free path: its data cannot be edited here.',
|
||||
'editor.annotations.geometry.circle': 'Position and radius',
|
||||
'editor.annotations.geometry.polygon': 'Vertices',
|
||||
'editor.annotations.geometry.cx': 'Centre x',
|
||||
'editor.annotations.geometry.cy': 'Centre y',
|
||||
'editor.annotations.geometry.r': 'Radius',
|
||||
'editor.annotations.geometry.vertex_x': 'x of vertex {n}',
|
||||
'editor.annotations.geometry.vertex_y': 'y of vertex {n}',
|
||||
'editor.annotations.geometry.vertices': '{count} vertices',
|
||||
'editor.annotations.geometry.add_vertex': 'Add a vertex',
|
||||
'editor.annotations.geometry.unapplied': 'Values not applied: the draft is unchanged.',
|
||||
'editor.annotations.geometry.unapplied_tag': 'not applied',
|
||||
'editor.annotations.geometry.revert': 'Back to the saved values',
|
||||
'editor.annotations.geometry.number': 'Each field must hold a number.',
|
||||
}
|
||||
@@ -1465,4 +1465,79 @@ export const fr: Dict = {
|
||||
'editor.findings.empty': "Aucune zone de constats pour l'instant.",
|
||||
'editor.findings.mark_reviewed': 'Marquer comme relu',
|
||||
'editor.findings.reset_to_confirm': 'Remettre à confirmer',
|
||||
'editor.annotations.tools': 'Outils',
|
||||
'editor.annotations.tool.select': 'Sélectionner et déplacer',
|
||||
'editor.annotations.tool.point': 'Point',
|
||||
'editor.annotations.tool.zone': 'Zone',
|
||||
'editor.annotations.tool.link': 'Accès à une vue détaillée',
|
||||
'editor.annotations.undo': 'Annuler',
|
||||
'editor.annotations.redo': 'Rétablir',
|
||||
'editor.annotations.tool_hint.select': 'Outil : sélectionner et déplacer · Échap annule un tracé',
|
||||
'editor.annotations.tool_hint.point': 'Outil : point · cliquez dans le dessin pour placer un point.',
|
||||
'editor.annotations.tool_hint.zone': 'Outil : zone · cliquez pour poser les sommets ; Entrée ou « Fermer le tracé » termine, Échap annule.',
|
||||
'editor.annotations.tool_hint.link': 'Outil : accès à une vue détaillée · tracez le contour qui ouvre la vue ; Entrée termine, Échap annule.',
|
||||
'editor.annotations.views': 'Vues',
|
||||
'editor.annotations.unmeasured.hint': "Ce dessin n'est pas mesurable : ajoutez ou corrigez son illustration (onglet Vues et illustrations) avant de placer ou de déplacer des éléments.",
|
||||
'editor.annotations.outside': "Cliquez à l'intérieur du dessin.",
|
||||
'editor.annotations.correction': "Le point ne tient pas à l'endroit choisi. Position corrigée proposée : x = {x}, y = {y}.",
|
||||
'editor.annotations.correction_use': 'Utiliser cette position',
|
||||
'editor.annotations.correction_cancel': 'Annuler',
|
||||
'editor.annotations.no_category': "Créez d'abord une catégorie d'annotation (onglet Général).",
|
||||
'editor.annotations.no_child_view': "Aucune vue détaillée ne s'ouvre depuis cette vue : créez-en une dans l'onglet Vues et illustrations.",
|
||||
'editor.annotations.add.point': 'Ajouter un point',
|
||||
'editor.annotations.add.zone': 'Ajouter une zone',
|
||||
'editor.annotations.add.detail_trigger': 'Ajouter un accès',
|
||||
'editor.annotations.new.point': 'Nouveau point',
|
||||
'editor.annotations.new.zone': 'Nouvelle zone',
|
||||
'editor.annotations.new.detail_trigger': 'Nouvel accès',
|
||||
'editor.annotations.create': 'Créer',
|
||||
'editor.annotations.create_cancel': 'Annuler',
|
||||
'editor.annotations.name_fr': 'Nom (FR)',
|
||||
'editor.annotations.name_en': 'Nom (EN)',
|
||||
'editor.annotations.category': 'Catégorie',
|
||||
'editor.annotations.color': 'Couleur',
|
||||
'editor.annotations.color_hint': 'Laissez vide pour la couleur de la catégorie, ou indiquez une valeur hexadécimale (#rrggbb).',
|
||||
'editor.annotations.laterality': 'Latéralité',
|
||||
'editor.annotations.laterality.unpaired': 'Non latéralisée',
|
||||
'editor.annotations.laterality.bilateral': 'Bilatérale',
|
||||
'editor.annotations.laterality.left': 'Gauche',
|
||||
'editor.annotations.laterality.right': 'Droite',
|
||||
'editor.annotations.region': 'Région vertébrale',
|
||||
'editor.annotations.zone': 'Zone de constats',
|
||||
'editor.annotations.opens': 'Vue ouverte',
|
||||
'editor.annotations.none': 'Aucune',
|
||||
'editor.annotations.required.fields': 'Choisissez la catégorie et la latéralité (et la vue ouverte pour un accès).',
|
||||
'editor.annotations.required.names': 'Renseignez le nom en français et en anglais.',
|
||||
'editor.annotations.kind.point': 'Point',
|
||||
'editor.annotations.kind.zone': 'Zone',
|
||||
'editor.annotations.kind.detail_trigger': 'Accès',
|
||||
'editor.annotations.status.to_confirm': 'À confirmer',
|
||||
'editor.annotations.status.reviewed': 'Relu',
|
||||
'editor.annotations.status.inherited': 'Hérité, non relu',
|
||||
'editor.annotations.mark_reviewed': 'Marquer comme relu',
|
||||
'editor.annotations.to_confirm': 'Remettre à confirmer',
|
||||
'editor.annotations.list': 'Annotations de la vue',
|
||||
'editor.annotations.list_empty': 'Aucune annotation dans cette vue.',
|
||||
'editor.annotations.selection': 'Sélection : {kind} « {name} »',
|
||||
'editor.annotations.select_hint': 'Sélectionnez une annotation sur le dessin ou dans la liste pour voir ses propriétés.',
|
||||
'editor.annotations.properties': "Propriétés de l'annotation",
|
||||
'editor.annotations.tracing': '{count} sommet(s) posé(s).',
|
||||
'editor.annotations.trace_close': 'Fermer le tracé',
|
||||
'editor.annotations.trace_cancel': 'Annuler le tracé',
|
||||
'editor.annotations.replace_polygon': 'Remplacer par un polygone',
|
||||
'editor.annotations.no_geometry': "Cette annotation n'a pas de géométrie : tracez un polygone pour lui en donner une.",
|
||||
'editor.annotations.path': 'Cette annotation est un tracé libre (path) : ses données ne se modifient pas ici.',
|
||||
'editor.annotations.geometry.circle': 'Position et rayon',
|
||||
'editor.annotations.geometry.polygon': 'Sommets',
|
||||
'editor.annotations.geometry.cx': 'Centre x',
|
||||
'editor.annotations.geometry.cy': 'Centre y',
|
||||
'editor.annotations.geometry.r': 'Rayon',
|
||||
'editor.annotations.geometry.vertex_x': 'x du sommet {n}',
|
||||
'editor.annotations.geometry.vertex_y': 'y du sommet {n}',
|
||||
'editor.annotations.geometry.vertices': '{count} sommets',
|
||||
'editor.annotations.geometry.add_vertex': 'Ajouter un sommet',
|
||||
'editor.annotations.geometry.unapplied': 'Valeurs non appliquées : le brouillon est inchangé.',
|
||||
'editor.annotations.geometry.unapplied_tag': 'non appliqué',
|
||||
'editor.annotations.geometry.revert': 'Revenir aux valeurs enregistrées',
|
||||
'editor.annotations.geometry.number': 'Chaque champ doit contenir un nombre.',
|
||||
}
|
||||
Reference in new issue
Block a user