fix(app): annotations tab split, editor-wide undo keys, keyboard point fits, typed radius message
This commit is contained in:
1 parent
447d0a4272
commit
3f15762d95
25 files changed
+1398
-653
No files matched your search
@@ -31,6 +31,7 @@ import {
|
||||
} from '@/editor/mode'
|
||||
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
|
||||
import type { EditorTabId } from '@/editor/tabs'
|
||||
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
|
||||
import { useTabTier } from '@/editor/useViewport'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
@@ -97,6 +98,7 @@ function DraftEditor({
|
||||
}, [versionId, userId])
|
||||
useEffect(() => useEditorStore.getState().setCanEdit(canEdit), [canEdit])
|
||||
useLeaveGuard(useEditorStore(leaveGuardArmed))
|
||||
useUndoShortcuts(canEdit && recovery === 'none')
|
||||
|
||||
if (status === 'failed' && failure !== null) {
|
||||
if (failure === 'denied') return <AccessDenied />
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
import { useEffect, useRef, type PointerEvent } from 'react'
|
||||
import { useEffect, useRef, type KeyboardEvent, type RefObject } from 'react'
|
||||
import type { Geometry } from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { coreFailureMessage } from '@/core/failure'
|
||||
import { useCoreStopped } from '@/core/runtime'
|
||||
import { transformOf } from '@/catalogue/framing'
|
||||
import { useFraming } from '@/catalogue/useFraming'
|
||||
import { clientToDrawing } from '@/editor/annotations/gesture'
|
||||
import type { XY } from '@/editor/annotations/frame'
|
||||
import {
|
||||
annotationIdOf,
|
||||
useCanvasBuild,
|
||||
type RootAttributes,
|
||||
useSelectionMark,
|
||||
} from '@/editor/annotations/useCanvasBuild'
|
||||
import {
|
||||
useMoveGesture,
|
||||
type MoveTarget,
|
||||
} from '@/editor/annotations/useMoveGesture'
|
||||
import { useCanvasGestures } from '@/editor/annotations/useCanvasGestures'
|
||||
import type { MoveTarget } from '@/editor/annotations/useMoveGesture'
|
||||
import type { ToolId } from '@/editor/annotations/uiState'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
|
||||
@@ -37,101 +32,107 @@ export interface AnnotationCanvasProps {
|
||||
moveTarget: MoveTarget | null
|
||||
overlay: OverlayData
|
||||
tools: Omit<ToolColumnProps, 'onZoomIn' | 'onZoomOut' | 'onFit'>
|
||||
/** The composed root's `viewBox` text, as rebuilt; null on failure. */
|
||||
onRoot: (viewBox: string | null) => void
|
||||
/** The composed root as rebuilt (with its view); null on failure. */
|
||||
onRoot: (root: RootAttributes | null) => void
|
||||
onSelect: (id: string) => void
|
||||
/** A click with a drawing tool, in drawing units. */
|
||||
onPlace: (at: XY) => void
|
||||
onDrop: (id: string, geometry: Geometry) => void
|
||||
onTraceKey: (event: KeyboardEvent) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The edit canvas: the core's composed view, the numbers-only overlay above it in the
|
||||
* same transformed box, the tool column beside it. Select and place work on `click`
|
||||
* (a press that moved is a drag and swallows it); a drag from the selected marker moves
|
||||
* it after 4 CSS px. `touch-action: none` only while a drawing tool or a drag is active.
|
||||
* it after 4 CSS px.
|
||||
*/
|
||||
export default function AnnotationCanvas(props: AnnotationCanvasProps) {
|
||||
const overlayRef = useRef<SVGSVGElement | null>(null)
|
||||
const overlay = useRef<SVGSVGElement | null>(null)
|
||||
const viewport = useRef<HTMLDivElement | null>(null)
|
||||
const build = useCanvasBuild(props.viewId)
|
||||
const move = useMoveGesture({
|
||||
overlay: overlayRef,
|
||||
target: props.moveTarget,
|
||||
onDrop: props.onDrop,
|
||||
})
|
||||
const framing = useFraming(viewport, props.viewId, {
|
||||
canPan: (event) => props.tool === 'select' && !move.claims(event),
|
||||
})
|
||||
const gestures = useCanvasGestures({ ...props, overlay, viewport })
|
||||
useSelectionMark(build.host, props.selectedId, build.root)
|
||||
const { onRoot } = props
|
||||
const viewBox = build.root?.viewBox ?? null
|
||||
useReportRoot(viewBox, onRoot)
|
||||
|
||||
const onClick = (event: React.MouseEvent) => {
|
||||
if (framing.swallowClick()) return
|
||||
const id = annotationIdOf(event.target)
|
||||
if (props.tool === 'select') return id ? props.onSelect(id) : undefined
|
||||
const at = clientToDrawing(overlayRef.current, {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
})
|
||||
if (at) props.onPlace(at)
|
||||
}
|
||||
const handlers = composed(framing.handlers, move.handlers)
|
||||
const touchNone =
|
||||
props.tool !== 'select' || move.armed || framing.framing.scale !== 1
|
||||
useReportRoot(build.root, props.onRoot)
|
||||
return (
|
||||
<div className="flex flex-col gap-2 lg:flex-row">
|
||||
<ToolColumn
|
||||
{...props.tools}
|
||||
onZoomIn={framing.zoomIn}
|
||||
onZoomOut={framing.zoomOut}
|
||||
onFit={framing.reset}
|
||||
onZoomIn={gestures.framing.zoomIn}
|
||||
onZoomOut={gestures.framing.zoomOut}
|
||||
onFit={gestures.framing.reset}
|
||||
/>
|
||||
<CanvasBox
|
||||
{...props}
|
||||
build={build}
|
||||
viewport={viewport}
|
||||
boxProps={gestures.boxProps}
|
||||
layer={{
|
||||
transform: transformOf(gestures.framing.framing),
|
||||
overlay: {
|
||||
...props.overlay,
|
||||
svgRef: overlay,
|
||||
dragged: gestures.drag,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<div className="relative min-w-0 flex-1 overflow-hidden rounded-xl border border-[var(--color-border)] bg-white">
|
||||
<div
|
||||
ref={viewport}
|
||||
tabIndex={0}
|
||||
role="group"
|
||||
aria-label={props.viewName}
|
||||
data-testid="annotation-canvas"
|
||||
className={`svg-canvas aspect-[4/3] w-full select-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] ${
|
||||
props.tool === 'select' ? 'cursor-grab' : 'cursor-crosshair'
|
||||
}`}
|
||||
style={{ touchAction: touchNone ? 'none' : 'pan-x pan-y' }}
|
||||
onClick={onClick}
|
||||
{...handlers}
|
||||
>
|
||||
<DrawingLayer
|
||||
host={build.host}
|
||||
root={build.root}
|
||||
transform={transformOf(framing.framing)}
|
||||
overlay={{
|
||||
...props.overlay,
|
||||
svgRef: overlayRef,
|
||||
dragged: move.preview,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<CanvasFailure failure={build.failure} retry={build.retry} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */
|
||||
function DrawingLayer({
|
||||
host,
|
||||
root,
|
||||
transform,
|
||||
overlay,
|
||||
}: {
|
||||
host: React.RefObject<HTMLDivElement | null>
|
||||
type Build = ReturnType<typeof useCanvasBuild>
|
||||
|
||||
function CanvasBox({
|
||||
viewId,
|
||||
viewName,
|
||||
tool,
|
||||
build,
|
||||
viewport,
|
||||
boxProps,
|
||||
layer,
|
||||
}: AnnotationCanvasProps & {
|
||||
build: Build
|
||||
viewport: RefObject<HTMLDivElement | null>
|
||||
boxProps: ReturnType<typeof useCanvasGestures>['boxProps']
|
||||
layer: Omit<LayerProps, 'host' | 'root'>
|
||||
}) {
|
||||
const root = build.root?.viewId === viewId ? build.root : null
|
||||
const cursor = tool === 'select' ? 'cursor-grab' : 'cursor-crosshair'
|
||||
return (
|
||||
<div className={BOX}>
|
||||
<div
|
||||
ref={viewport}
|
||||
tabIndex={0}
|
||||
role="group"
|
||||
aria-label={viewName}
|
||||
data-testid="annotation-canvas"
|
||||
className={`svg-canvas aspect-[4/3] w-full select-none ${cursor} ${FOCUS_RING}`}
|
||||
{...boxProps}
|
||||
>
|
||||
<DrawingLayer host={build.host} root={root} {...layer} />
|
||||
</div>
|
||||
<CanvasFailure failure={build.failure} retry={build.retry} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const BOX =
|
||||
'relative min-w-0 flex-1 overflow-hidden rounded-xl border ' +
|
||||
'border-[var(--color-border)] bg-white'
|
||||
|
||||
const FOCUS_RING =
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' +
|
||||
'focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
interface LayerProps {
|
||||
host: RefObject<HTMLDivElement | null>
|
||||
root: RootAttributes | null
|
||||
transform: string
|
||||
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
|
||||
}) {
|
||||
}
|
||||
|
||||
/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */
|
||||
function DrawingLayer({ host, root, transform, overlay }: LayerProps) {
|
||||
return (
|
||||
<div
|
||||
className="relative h-full w-full origin-top-left"
|
||||
@@ -154,31 +155,10 @@ function DrawingLayer({
|
||||
}
|
||||
|
||||
function useReportRoot(
|
||||
viewBox: string | null,
|
||||
onRoot: (v: string | null) => void,
|
||||
root: RootAttributes | null,
|
||||
onRoot: (root: RootAttributes | null) => void,
|
||||
) {
|
||||
useEffect(() => onRoot(viewBox), [viewBox, onRoot])
|
||||
}
|
||||
|
||||
/** Each pointer handler of the framing and of the move gesture, one after the other. */
|
||||
function composed(
|
||||
a: ReturnType<typeof useFraming>['handlers'],
|
||||
b: ReturnType<typeof useMoveGesture>['handlers'],
|
||||
) {
|
||||
const both =
|
||||
(first: (e: PointerEvent) => void, second: (e: PointerEvent) => void) =>
|
||||
(event: PointerEvent) => {
|
||||
first(event)
|
||||
second(event)
|
||||
}
|
||||
return {
|
||||
onPointerDown: both(a.onPointerDown, b.onPointerDown),
|
||||
onPointerMove: both(a.onPointerMove, b.onPointerMove),
|
||||
onPointerUp: both(a.onPointerUp, b.onPointerUp),
|
||||
onPointerCancel: both(a.onPointerCancel, b.onPointerCancel),
|
||||
onLostPointerCapture: b.onLostPointerCapture,
|
||||
onKeyDown: a.onKeyDown,
|
||||
}
|
||||
useEffect(() => onRoot(root), [root, onRoot])
|
||||
}
|
||||
|
||||
function CanvasFailure({
|
||||
|
||||
@@ -3,6 +3,15 @@ import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import ReviewBadge from './ReviewBadge'
|
||||
|
||||
const LIST =
|
||||
'max-h-64 divide-y divide-[var(--color-border)] overflow-y-auto rounded-lg ' +
|
||||
'border border-[var(--color-border)]'
|
||||
|
||||
const ROW =
|
||||
'flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm ' +
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' +
|
||||
'focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
/** The name an annotation shows: its own, else (an unnamed link) the view it opens. */
|
||||
export function annotationName(
|
||||
annotation: Annotation,
|
||||
@@ -40,17 +49,14 @@ export default function AnnotationList({
|
||||
)
|
||||
}
|
||||
return (
|
||||
<ul
|
||||
aria-label={t('editor.annotations.list')}
|
||||
className="max-h-64 divide-y divide-[var(--color-border)] overflow-y-auto rounded-lg border border-[var(--color-border)]"
|
||||
>
|
||||
<ul aria-label={t('editor.annotations.list')} className={LIST}>
|
||||
{annotations.map((annotation) => (
|
||||
<li key={annotation.id}>
|
||||
<button
|
||||
type="button"
|
||||
aria-current={annotation.id === selectedId}
|
||||
onClick={() => onSelect(annotation.id)}
|
||||
className={`flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] ${
|
||||
className={`${ROW} ${
|
||||
annotation.id === selectedId
|
||||
? 'bg-[var(--color-surface-strong)]'
|
||||
: ''
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Laterality,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import Select from '@/components/ui/Select'
|
||||
import {
|
||||
LATERALITIES,
|
||||
directChildren,
|
||||
type CreationForm,
|
||||
type PendingElement,
|
||||
} from '@/editor/annotations/creation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
interface FieldsProps {
|
||||
doc: AnatomicalSheetDocument
|
||||
form: CreationForm
|
||||
onChange: (patch: Partial<CreationForm>) => void
|
||||
}
|
||||
|
||||
interface Option {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
function OptionSelect({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
blank,
|
||||
onChange,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
options: Option[]
|
||||
/** A « Choisir… » entry: the choice is required and has no default. */
|
||||
blank: boolean
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<FormField id={id} label={label}>
|
||||
<Select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
|
||||
{blank && <option value="">{t('editor.field.choose')}</option>}
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
/** The fields the core requires, collected before the insert. */
|
||||
export default function CreationFields({
|
||||
kind,
|
||||
viewId,
|
||||
...fields
|
||||
}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { doc, form, onChange } = fields
|
||||
const categories = doc.categories.map((c) => ({
|
||||
value: c.id,
|
||||
label: c.name[locale],
|
||||
}))
|
||||
const sides = LATERALITIES.map((l: Laterality) => ({
|
||||
value: l,
|
||||
label: t(`editor.annotations.laterality.${l}`),
|
||||
}))
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<DraftField
|
||||
id="creation-fr"
|
||||
label={t('editor.annotations.name_fr')}
|
||||
value={form.fr}
|
||||
onChange={(fr) => onChange({ fr })}
|
||||
/>
|
||||
<DraftField
|
||||
id="creation-en"
|
||||
label={t('editor.annotations.name_en')}
|
||||
value={form.en}
|
||||
onChange={(en) => onChange({ en })}
|
||||
/>
|
||||
<OptionSelect
|
||||
id="creation-category"
|
||||
label={t('editor.annotations.category')}
|
||||
value={form.categoryId}
|
||||
options={categories}
|
||||
blank={false}
|
||||
onChange={(categoryId) => onChange({ categoryId })}
|
||||
/>
|
||||
<OptionSelect
|
||||
id="creation-laterality"
|
||||
label={t('editor.annotations.laterality')}
|
||||
value={form.laterality}
|
||||
options={sides}
|
||||
blank
|
||||
onChange={(laterality) =>
|
||||
onChange({ laterality: laterality as CreationForm['laterality'] })
|
||||
}
|
||||
/>
|
||||
{kind === 'detail_trigger' ? (
|
||||
<OpensSelect {...fields} viewId={viewId} />
|
||||
) : (
|
||||
<LinkSelects {...fields} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OpensSelect({
|
||||
doc,
|
||||
form,
|
||||
onChange,
|
||||
viewId,
|
||||
}: FieldsProps & { viewId: string }) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const options = directChildren(doc.views, viewId).map((v) => ({
|
||||
value: v.id,
|
||||
label: v.name[locale],
|
||||
}))
|
||||
return (
|
||||
<OptionSelect
|
||||
id="creation-opens"
|
||||
label={t('editor.annotations.opens')}
|
||||
value={form.opensViewId}
|
||||
options={options}
|
||||
blank
|
||||
onChange={(opensViewId) => onChange({ opensViewId })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Findings zone and vertebral region: optional links of a point or a zone. */
|
||||
function LinkSelects({ doc, form, onChange }: FieldsProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const zones = doc.finding_zones.map((z) => ({
|
||||
value: z.id,
|
||||
label: z.name[locale],
|
||||
}))
|
||||
const regions = doc.vertebral_config.regions.map((r) => ({
|
||||
value: r.code,
|
||||
label: r.name[locale],
|
||||
}))
|
||||
return (
|
||||
<>
|
||||
<OptionSelect
|
||||
id="creation-zone"
|
||||
label={t('editor.annotations.zone')}
|
||||
value={form.zoneId}
|
||||
options={zones}
|
||||
blank
|
||||
onChange={(zoneId) => onChange({ zoneId })}
|
||||
/>
|
||||
<OptionSelect
|
||||
id="creation-region"
|
||||
label={t('editor.annotations.region')}
|
||||
value={form.regionCode}
|
||||
options={regions}
|
||||
blank
|
||||
onChange={(regionCode) => onChange({ regionCode })}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,38 +1,24 @@
|
||||
import { useState, type Dispatch } from 'react'
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Laterality,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Select from '@/components/ui/Select'
|
||||
import type { CommitContext } from '@/editor/annotations/annotationCommit'
|
||||
import {
|
||||
insertAnnotation,
|
||||
type CommitContext,
|
||||
type CommitResult,
|
||||
} from '@/editor/annotations/annotationCommit'
|
||||
import {
|
||||
attemptPoint,
|
||||
confirmCorrection,
|
||||
type Correction,
|
||||
type PointAttempt,
|
||||
} from '@/editor/annotations/correction'
|
||||
import {
|
||||
LATERALITIES,
|
||||
annotationOf,
|
||||
directChildren,
|
||||
emptyForm,
|
||||
formProblem,
|
||||
withGeometry,
|
||||
type CreationForm,
|
||||
type PendingElement,
|
||||
} from '@/editor/annotations/creation'
|
||||
import {
|
||||
confirmAttempt,
|
||||
createAttempt,
|
||||
type Attempt,
|
||||
type CreationInput,
|
||||
} from '@/editor/annotations/creationAttempt'
|
||||
import type { Frame } from '@/editor/annotations/frame'
|
||||
import type { EditableGeometry } from '@/editor/annotations/geometryEdit'
|
||||
import type { UiAction } from '@/editor/annotations/uiState'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import CorrectionNotice from './CorrectionNotice'
|
||||
import CreationFields from './CreationFields'
|
||||
import GeometryGroup from './GeometryGroup'
|
||||
|
||||
export interface CreationPanelProps {
|
||||
@@ -45,47 +31,44 @@ export interface CreationPanelProps {
|
||||
context: CommitContext
|
||||
}
|
||||
|
||||
type Attempt = PointAttempt | { status: 'invalid'; messages: string[] }
|
||||
|
||||
/** The insert of this panel's element under a given geometry, through `accept`. */
|
||||
function inserterOf(props: CreationPanelProps, form: CreationForm) {
|
||||
return (geometry: EditableGeometry): CommitResult =>
|
||||
insertAnnotation(
|
||||
(id) =>
|
||||
annotationOf(id, props.viewId, { ...props.pending, geometry }, form),
|
||||
props.context,
|
||||
)
|
||||
/** What an attempt leaves on screen: the core's words, or the form's own. */
|
||||
function messagesOf(attempt: Attempt, words: (problem: string) => string) {
|
||||
if (attempt.status === 'refused') return attempt.messages
|
||||
return attempt.status === 'invalid' ? [words(attempt.problem)] : []
|
||||
}
|
||||
|
||||
/** « Créer »: a point lets the core's verdict offer C; nothing else is ever invented. */
|
||||
function createAttempt(
|
||||
props: CreationPanelProps,
|
||||
form: CreationForm,
|
||||
words: (problem: string) => string,
|
||||
): Attempt {
|
||||
const { pending, frame } = props
|
||||
const problem = formProblem(pending.kind, form)
|
||||
if (problem) return { status: 'invalid', messages: [words(problem)] }
|
||||
const insert = inserterOf(props, form)
|
||||
const { geometry } = pending
|
||||
if (pending.kind === 'point' && geometry.type === 'circle' && frame) {
|
||||
return attemptPoint(frame, geometry, (c) =>
|
||||
insert({ type: 'circle', ...c }),
|
||||
/**
|
||||
* The typed fields and the outcome of « Créer » / « Utiliser cette position ». The form
|
||||
* survives a change of the pending geometry (a second click): the panel is not remounted.
|
||||
*/
|
||||
function useCreation(props: CreationPanelProps) {
|
||||
const t = useT()
|
||||
const [form, setForm] = useState<CreationForm>(() => emptyForm(props.doc))
|
||||
const [messages, setMessages] = useState<string[]>([])
|
||||
const settle = (attempt: Attempt) => {
|
||||
const { dispatch, pending } = props
|
||||
setMessages(
|
||||
messagesOf(attempt, (p) => t(`editor.annotations.required.${p}`)),
|
||||
)
|
||||
if (attempt.status === 'created') {
|
||||
dispatch({ type: 'select', id: attempt.id ?? null })
|
||||
}
|
||||
if (attempt.status === 'correction') {
|
||||
const next = { ...pending, correction: attempt.correction }
|
||||
dispatch({ type: 'pending_update', pending: next })
|
||||
}
|
||||
}
|
||||
const input: CreationInput = props
|
||||
return {
|
||||
form,
|
||||
messages,
|
||||
patch: (change: Partial<CreationForm>) => setForm({ ...form, ...change }),
|
||||
create: () => settle(createAttempt(input, form)),
|
||||
confirm: () => {
|
||||
const { correction } = props.pending
|
||||
if (correction) settle(confirmAttempt(input, form, correction))
|
||||
},
|
||||
}
|
||||
const result = insert(geometry)
|
||||
return result.ok
|
||||
? { status: 'created', id: result.id }
|
||||
: { status: 'refused', messages: result.messages }
|
||||
}
|
||||
|
||||
function confirmAttempt(
|
||||
props: CreationPanelProps,
|
||||
form: CreationForm,
|
||||
correction: Correction,
|
||||
): Attempt {
|
||||
const insert = inserterOf(props, form)
|
||||
return confirmCorrection(correction, (c) => insert({ type: 'circle', ...c }))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,80 +78,74 @@ function confirmAttempt(
|
||||
*/
|
||||
export default function CreationPanel(props: CreationPanelProps) {
|
||||
const t = useT()
|
||||
const { pending, doc, dispatch } = props
|
||||
const [form, setForm] = useState<CreationForm>(() => emptyForm(doc))
|
||||
const [messages, setMessages] = useState<string[]>([])
|
||||
const update = (next: PendingElement) =>
|
||||
dispatch({ type: 'pending_update', pending: next })
|
||||
const settle = (attempt: Attempt) => {
|
||||
setMessages(
|
||||
attempt.status === 'refused' || attempt.status === 'invalid'
|
||||
? attempt.messages
|
||||
: [],
|
||||
)
|
||||
if (attempt.status === 'created') {
|
||||
dispatch({ type: 'select', id: attempt.id ?? null })
|
||||
}
|
||||
if (attempt.status === 'correction') {
|
||||
update({ ...pending, correction: attempt.correction })
|
||||
}
|
||||
}
|
||||
const words = (problem: string) => t(`editor.annotations.required.${problem}`)
|
||||
const setGeometry = (geometry: EditableGeometry) => {
|
||||
update({ ...pending, geometry, correction: null })
|
||||
return { ok: true as const }
|
||||
}
|
||||
const creation = useCreation(props)
|
||||
const { pending, dispatch } = props
|
||||
const title = t(`editor.annotations.new.${pending.kind}`)
|
||||
return (
|
||||
<section
|
||||
aria-label={t(`editor.annotations.new.${pending.kind}`)}
|
||||
aria-label={title}
|
||||
data-testid="annotation-creation"
|
||||
className="space-y-3 rounded-xl border border-[var(--color-border)] p-4"
|
||||
>
|
||||
<h3 className="text-base font-semibold">
|
||||
{t(`editor.annotations.new.${pending.kind}`)}
|
||||
</h3>
|
||||
<h3 className="text-base font-semibold">{title}</h3>
|
||||
<CreationFields
|
||||
kind={pending.kind}
|
||||
viewId={props.viewId}
|
||||
form={form}
|
||||
doc={doc}
|
||||
onChange={(patch) => setForm({ ...form, ...patch })}
|
||||
form={creation.form}
|
||||
doc={props.doc}
|
||||
onChange={creation.patch}
|
||||
/>
|
||||
<GeometryGroup
|
||||
idPrefix="creation"
|
||||
geometry={pending.geometry}
|
||||
onApply={setGeometry}
|
||||
locked={false}
|
||||
onApply={(geometry) => {
|
||||
const next = withGeometry(pending, geometry)
|
||||
dispatch({ type: 'pending_update', pending: next })
|
||||
return { ok: true }
|
||||
}}
|
||||
/>
|
||||
{pending.correction && (
|
||||
<CorrectionNotice
|
||||
correction={pending.correction}
|
||||
onConfirm={() =>
|
||||
settle(confirmAttempt(props, form, pending.correction!))
|
||||
onConfirm={creation.confirm}
|
||||
onCancel={() =>
|
||||
dispatch({
|
||||
type: 'pending_update',
|
||||
pending: { ...pending, correction: null },
|
||||
})
|
||||
}
|
||||
onCancel={() => update({ ...pending, correction: null })}
|
||||
/>
|
||||
)}
|
||||
<Messages messages={messages} />
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => settle(createAttempt(props, form, words))}
|
||||
>
|
||||
{t('editor.annotations.create')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => dispatch({ type: 'pending_drop' })}
|
||||
>
|
||||
{t('editor.annotations.create_cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
<Messages messages={creation.messages} />
|
||||
<CreationActions
|
||||
onCreate={creation.create}
|
||||
onCancel={() => dispatch({ type: 'pending_drop' })}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function CreationActions({
|
||||
onCreate,
|
||||
onCancel,
|
||||
}: {
|
||||
onCreate: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" onClick={onCreate}>
|
||||
{t('editor.annotations.create')}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={onCancel}>
|
||||
{t('editor.annotations.create_cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Messages({ messages }: { messages: string[] }) {
|
||||
if (messages.length === 0) return null
|
||||
return (
|
||||
@@ -182,161 +159,3 @@ function Messages({ messages }: { messages: string[] }) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface FieldsProps {
|
||||
doc: AnatomicalSheetDocument
|
||||
form: CreationForm
|
||||
onChange: (patch: Partial<CreationForm>) => void
|
||||
}
|
||||
|
||||
interface Option {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
function OptionSelect({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
blank,
|
||||
onChange,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
options: Option[]
|
||||
/** A « Choisir… » entry: the choice is required and has no default. */
|
||||
blank: boolean
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<FormField id={id} label={label}>
|
||||
<Select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
|
||||
{blank && <option value="">{t('editor.field.choose')}</option>}
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
/** The fields the core requires, collected before the insert. */
|
||||
function CreationFields({
|
||||
kind,
|
||||
viewId,
|
||||
...fields
|
||||
}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { doc, form, onChange } = fields
|
||||
const categories = doc.categories.map((c) => ({
|
||||
value: c.id,
|
||||
label: c.name[locale],
|
||||
}))
|
||||
const sides = LATERALITIES.map((l: Laterality) => ({
|
||||
value: l,
|
||||
label: t(`editor.annotations.laterality.${l}`),
|
||||
}))
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<DraftField
|
||||
id="creation-fr"
|
||||
label={t('editor.annotations.name_fr')}
|
||||
value={form.fr}
|
||||
onChange={(fr) => onChange({ fr })}
|
||||
/>
|
||||
<DraftField
|
||||
id="creation-en"
|
||||
label={t('editor.annotations.name_en')}
|
||||
value={form.en}
|
||||
onChange={(en) => onChange({ en })}
|
||||
/>
|
||||
<OptionSelect
|
||||
id="creation-category"
|
||||
label={t('editor.annotations.category')}
|
||||
value={form.categoryId}
|
||||
options={categories}
|
||||
blank={false}
|
||||
onChange={(categoryId) => onChange({ categoryId })}
|
||||
/>
|
||||
<OptionSelect
|
||||
id="creation-laterality"
|
||||
label={t('editor.annotations.laterality')}
|
||||
value={form.laterality}
|
||||
options={sides}
|
||||
blank
|
||||
onChange={(laterality) =>
|
||||
onChange({ laterality: laterality as CreationForm['laterality'] })
|
||||
}
|
||||
/>
|
||||
{kind === 'detail_trigger' ? (
|
||||
<OpensSelect {...fields} viewId={viewId} />
|
||||
) : (
|
||||
<LinkSelects {...fields} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OpensSelect({
|
||||
doc,
|
||||
form,
|
||||
onChange,
|
||||
viewId,
|
||||
}: FieldsProps & { viewId: string }) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const options = directChildren(doc.views, viewId).map((v) => ({
|
||||
value: v.id,
|
||||
label: v.name[locale],
|
||||
}))
|
||||
return (
|
||||
<OptionSelect
|
||||
id="creation-opens"
|
||||
label={t('editor.annotations.opens')}
|
||||
value={form.opensViewId}
|
||||
options={options}
|
||||
blank
|
||||
onChange={(opensViewId) => onChange({ opensViewId })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Findings zone and vertebral region: optional links of a point or a zone. */
|
||||
function LinkSelects({ doc, form, onChange }: FieldsProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const zones = doc.finding_zones.map((z) => ({
|
||||
value: z.id,
|
||||
label: z.name[locale],
|
||||
}))
|
||||
const regions = doc.vertebral_config.regions.map((r) => ({
|
||||
value: r.code,
|
||||
label: r.name[locale],
|
||||
}))
|
||||
return (
|
||||
<>
|
||||
<OptionSelect
|
||||
id="creation-zone"
|
||||
label={t('editor.annotations.zone')}
|
||||
value={form.zoneId}
|
||||
options={zones}
|
||||
blank
|
||||
onChange={(zoneId) => onChange({ zoneId })}
|
||||
/>
|
||||
<OptionSelect
|
||||
id="creation-region"
|
||||
label={t('editor.annotations.region')}
|
||||
value={form.regionCode}
|
||||
options={regions}
|
||||
blank
|
||||
onChange={(regionCode) => onChange({ regionCode })}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { type CommitContext } from '@/editor/annotations/annotationCommit'
|
||||
import type { CommitContext } from '@/editor/annotations/annotationCommit'
|
||||
import { keyboardPending, type NewKind } from '@/editor/annotations/creation'
|
||||
import { parseFrame, type Frame } from '@/editor/annotations/frame'
|
||||
import { isEditable } from '@/editor/annotations/geometryEdit'
|
||||
@@ -15,9 +15,9 @@ import {
|
||||
type UiAction,
|
||||
type UiState,
|
||||
} from '@/editor/annotations/uiState'
|
||||
import type { RootAttributes } from '@/editor/annotations/useCanvasBuild'
|
||||
import {
|
||||
mainViewId,
|
||||
useUndoShortcuts,
|
||||
useViewModel,
|
||||
type ViewModel,
|
||||
} from '@/editor/annotations/useViewModel'
|
||||
@@ -38,59 +38,75 @@ interface Props {
|
||||
onSelectTab: EditorTabProps['onSelectTab']
|
||||
}
|
||||
|
||||
export default function EditableAnnotations({ doc, onSelectTab }: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
/** What both columns read: the tab's state, the view, its frame and its selection. */
|
||||
interface Scene {
|
||||
doc: AnatomicalSheetDocument
|
||||
ui: UiState
|
||||
dispatch: Dispatch<UiAction>
|
||||
viewId: string
|
||||
model: ViewModel
|
||||
/** F of the current view, only while the core measures it and the build is its own. */
|
||||
frame: Frame | null
|
||||
selected: Annotation | undefined
|
||||
setRoot: (root: RootAttributes | null) => void
|
||||
onSelectTab: EditorTabProps['onSelectTab']
|
||||
}
|
||||
|
||||
function useScene({ doc, onSelectTab }: Props): Scene {
|
||||
const [ui, dispatch] = useReducer(uiReducer, initialUi)
|
||||
const [viewBox, setViewBox] = useState<string | null>(null)
|
||||
const [root, setRoot] = useState<RootAttributes | null>(null)
|
||||
const viewId = ui.viewId ?? mainViewId(doc)
|
||||
const model = useViewModel(doc, viewId)
|
||||
const frame = model.measured ? parseFrame(viewBox) : null
|
||||
const context: CommitContext = { t, locale }
|
||||
const placement = usePlacement({ ui, dispatch, frame, doc, context })
|
||||
useUndoShortcuts()
|
||||
const selected = model.annotations.find((a) => a.id === ui.selectedId)
|
||||
const scene = { doc, ui, dispatch, model, frame, selected, onSelectTab }
|
||||
const own = model.measured && root?.viewId === viewId
|
||||
return {
|
||||
doc,
|
||||
ui,
|
||||
dispatch,
|
||||
viewId,
|
||||
model,
|
||||
frame: own ? parseFrame(root.viewBox) : null,
|
||||
selected: model.annotations.find((a) => a.id === ui.selectedId),
|
||||
setRoot,
|
||||
onSelectTab,
|
||||
}
|
||||
}
|
||||
|
||||
function useCommitContext(): CommitContext {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
return { t, locale }
|
||||
}
|
||||
|
||||
export default function EditableAnnotations(props: Props) {
|
||||
const scene = useScene(props)
|
||||
const context = useCommitContext()
|
||||
const placement = usePlacement({ ...scene, context })
|
||||
return (
|
||||
<div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
|
||||
<CanvasColumn {...scene} placement={placement} onRoot={setViewBox} />
|
||||
<CanvasColumn scene={scene} placement={placement} />
|
||||
<aside>
|
||||
<SidePanel {...scene} viewId={viewId} context={context} />
|
||||
<SidePanel scene={scene} context={context} />
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** What both columns read: the document, the tab's state, the view and its frame. */
|
||||
interface Scene extends Props {
|
||||
ui: UiState
|
||||
dispatch: Dispatch<UiAction>
|
||||
model: ViewModel
|
||||
frame: Frame | null
|
||||
selected: Annotation | undefined
|
||||
}
|
||||
type Placement = ReturnType<typeof usePlacement>
|
||||
|
||||
function CanvasColumn({
|
||||
scene,
|
||||
placement,
|
||||
onRoot,
|
||||
...scene
|
||||
}: Scene & {
|
||||
placement: ReturnType<typeof usePlacement>
|
||||
onRoot: (viewBox: string | null) => void
|
||||
}: {
|
||||
scene: Scene
|
||||
placement: Placement
|
||||
}) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { doc, ui, dispatch, model, frame, selected } = scene
|
||||
const viewId = ui.viewId ?? mainViewId(doc)
|
||||
const view = doc.views.find((v) => v.id === viewId)
|
||||
const { doc, ui, dispatch, model, selected } = scene
|
||||
const noCategory = doc.categories.length === 0
|
||||
const blocked = !model.measured || noCategory
|
||||
const select = (id: string) => dispatch({ type: 'select', id })
|
||||
if (!view) return null
|
||||
return (
|
||||
<div className="min-w-0 space-y-3" onKeyDown={placement.onKeyDown}>
|
||||
<div className="min-w-0 space-y-3">
|
||||
<ViewSwitcher
|
||||
views={doc.views}
|
||||
current={viewId}
|
||||
current={scene.viewId}
|
||||
onSelect={(id) => dispatch({ type: 'view', viewId: id })}
|
||||
/>
|
||||
<ToolNotes
|
||||
@@ -100,30 +116,8 @@ function CanvasColumn({
|
||||
noCategory={noCategory}
|
||||
onSelectTab={scene.onSelectTab}
|
||||
/>
|
||||
{selected && (
|
||||
<SelectionTag
|
||||
kind={selected.kind}
|
||||
name={annotationName(selected, doc.views, locale)}
|
||||
/>
|
||||
)}
|
||||
<AnnotationCanvas
|
||||
viewId={viewId}
|
||||
viewName={view.name[locale]}
|
||||
tool={ui.tool}
|
||||
selectedId={ui.selectedId}
|
||||
moveTarget={moveTargetOf(selected, model, ui.tool)}
|
||||
overlay={overlayOf(ui, selected, frame)}
|
||||
tools={{
|
||||
tool: ui.tool,
|
||||
onTool: (tool) => dispatch({ type: 'tool', tool }),
|
||||
drawingDisabled: blocked,
|
||||
linkDisabled: model.children.length === 0,
|
||||
}}
|
||||
onRoot={onRoot}
|
||||
onSelect={select}
|
||||
onPlace={placement.onPlace}
|
||||
onDrop={placement.onDrop}
|
||||
/>
|
||||
{selected && <TagOf annotation={selected} doc={doc} />}
|
||||
<CanvasStage scene={scene} placement={placement} />
|
||||
{ui.tracing && (
|
||||
<TracingBar
|
||||
count={ui.tracing.points.length}
|
||||
@@ -132,20 +126,71 @@ function CanvasColumn({
|
||||
/>
|
||||
)}
|
||||
<KeyboardAdd
|
||||
disabled={blocked || frame === null}
|
||||
disabled={!model.measured || noCategory || scene.frame === null}
|
||||
linkDisabled={model.children.length === 0}
|
||||
onAdd={(kind) => addAtCentre(kind, frame, dispatch)}
|
||||
onAdd={(kind) => addAtCentre(kind, scene.frame, dispatch)}
|
||||
/>
|
||||
<AnnotationList
|
||||
annotations={model.annotations}
|
||||
views={doc.views}
|
||||
selectedId={ui.selectedId}
|
||||
onSelect={select}
|
||||
onSelect={(id) => dispatch({ type: 'select', id })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TagOf({
|
||||
annotation,
|
||||
doc,
|
||||
}: {
|
||||
annotation: Annotation
|
||||
doc: AnatomicalSheetDocument
|
||||
}) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
return (
|
||||
<SelectionTag
|
||||
kind={annotation.kind}
|
||||
name={annotationName(annotation, doc.views, locale)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CanvasStage({
|
||||
scene,
|
||||
placement,
|
||||
}: {
|
||||
scene: Scene
|
||||
placement: Placement
|
||||
}) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { doc, ui, dispatch, model, frame, selected } = scene
|
||||
const view = doc.views.find((v) => v.id === scene.viewId)
|
||||
const blocked = !model.measured || doc.categories.length === 0
|
||||
if (!view) return null
|
||||
return (
|
||||
<AnnotationCanvas
|
||||
viewId={scene.viewId}
|
||||
viewName={view.name[locale]}
|
||||
tool={ui.tool}
|
||||
selectedId={ui.selectedId}
|
||||
moveTarget={moveTargetOf(selected, model, ui.tool)}
|
||||
overlay={overlayOf(ui, selected, frame)}
|
||||
tools={{
|
||||
tool: ui.tool,
|
||||
onTool: (tool) => dispatch({ type: 'tool', tool }),
|
||||
drawingDisabled: blocked,
|
||||
linkDisabled: model.children.length === 0,
|
||||
}}
|
||||
onRoot={scene.setRoot}
|
||||
onSelect={(id) => dispatch({ type: 'select', id })}
|
||||
onPlace={placement.onPlace}
|
||||
onDrop={placement.onDrop}
|
||||
onTraceKey={placement.onTraceKey}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function addAtCentre(
|
||||
kind: NewKind,
|
||||
frame: Frame | null,
|
||||
@@ -157,10 +202,12 @@ function addAtCentre(
|
||||
|
||||
/** The creation panel while an element is pending, else the selection's properties. */
|
||||
function SidePanel({
|
||||
viewId,
|
||||
scene,
|
||||
context,
|
||||
...scene
|
||||
}: Scene & { viewId: string; context: CommitContext }) {
|
||||
}: {
|
||||
scene: Scene
|
||||
context: CommitContext
|
||||
}) {
|
||||
const t = useT()
|
||||
const { doc, ui, dispatch, model, frame, selected } = scene
|
||||
if (ui.pending) {
|
||||
@@ -168,7 +215,7 @@ function SidePanel({
|
||||
<CreationPanel
|
||||
key={ui.serial}
|
||||
pending={ui.pending}
|
||||
viewId={viewId}
|
||||
viewId={scene.viewId}
|
||||
doc={doc}
|
||||
frame={frame}
|
||||
dispatch={dispatch}
|
||||
|
||||
@@ -30,6 +30,28 @@ export interface GeometryGroupProps {
|
||||
type Fields = GroupFields
|
||||
type PolygonFields = Extract<GroupFields, { type: 'polygon' }>
|
||||
|
||||
interface GroupState {
|
||||
key: string
|
||||
draft: Fields
|
||||
messages: string[]
|
||||
}
|
||||
|
||||
/** The typed fields, reset whenever the stored value changes (undo, restore, a move). */
|
||||
function useGroupState(geometry: EditableGeometry) {
|
||||
const key = JSON.stringify(fieldsOf(geometry))
|
||||
const fresh = (): GroupState => ({
|
||||
key,
|
||||
draft: fieldsOf(geometry),
|
||||
messages: [],
|
||||
})
|
||||
const [state, setState] = useState<GroupState>(fresh)
|
||||
if (state.key !== key) setState(fresh())
|
||||
return {
|
||||
state,
|
||||
set: (patch: Partial<GroupState>) => setState({ ...state, ...patch }),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The geometry fields as ONE group held in component state (plan « Repair through a
|
||||
* temporary form »): Enter or leaving a field proposes the whole group as one update;
|
||||
@@ -38,37 +60,26 @@ type PolygonFields = Extract<GroupFields, { type: 'polygon' }>
|
||||
* never in the document and is dropped (no commit on unmount).
|
||||
*/
|
||||
export default function GeometryGroup(props: GeometryGroupProps) {
|
||||
const stored = fieldsOf(props.geometry)
|
||||
const storedKey = JSON.stringify(stored)
|
||||
const [draft, setDraft] = useState<Fields>(stored)
|
||||
const [seen, setSeen] = useState(storedKey)
|
||||
const [messages, setMessages] = useState<string[]>([])
|
||||
// A new stored value (undo, restore, an accepted move) replaces what was typed.
|
||||
if (seen !== storedKey) {
|
||||
setSeen(storedKey)
|
||||
setDraft(stored)
|
||||
setMessages([])
|
||||
}
|
||||
const apply = (next: Fields) => {
|
||||
setDraft(next)
|
||||
if (sameAsStored(next, props.geometry)) return setMessages([])
|
||||
const { state, set } = useGroupState(props.geometry)
|
||||
const propose = (next: Fields) => {
|
||||
if (sameAsStored(next, props.geometry))
|
||||
return set({ draft: next, messages: [] })
|
||||
const parsed = parseFields(next)
|
||||
if (!parsed.ok) return setMessages(['number'])
|
||||
if (!parsed.ok) return set({ draft: next, messages: ['number'] })
|
||||
const result = props.onApply(parsed.geometry)
|
||||
setMessages(result.ok ? [] : result.messages)
|
||||
set({ draft: next, messages: result.ok ? [] : result.messages })
|
||||
}
|
||||
const revert = () => {
|
||||
setDraft(stored)
|
||||
setMessages([])
|
||||
}
|
||||
const pending = changedFieldNames(draft, props.geometry)
|
||||
const view = { ...props, draft, pending, messages }
|
||||
return (
|
||||
<GroupBody
|
||||
{...view}
|
||||
onChange={setDraft}
|
||||
onPropose={apply}
|
||||
onRevert={revert}
|
||||
idPrefix={props.idPrefix}
|
||||
locked={props.locked}
|
||||
geometry={props.geometry}
|
||||
draft={state.draft}
|
||||
messages={state.messages}
|
||||
pending={changedFieldNames(state.draft, props.geometry)}
|
||||
onChange={(draft) => set({ draft })}
|
||||
onPropose={propose}
|
||||
onRevert={() => set({ draft: fieldsOf(props.geometry), messages: [] })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -199,7 +210,7 @@ function CircleRows(props: RowsProps<Extract<Fields, { type: 'circle' }>>) {
|
||||
function PolygonRows(props: RowsProps<PolygonFields>) {
|
||||
const t = useT()
|
||||
const [selected, setSelected] = useState(0)
|
||||
const { fields, locked } = props
|
||||
const { fields } = props
|
||||
const change = (index: number, axis: 'x' | 'y', value: string) =>
|
||||
props.onChange({
|
||||
type: 'polygon',
|
||||
@@ -207,39 +218,23 @@ function PolygonRows(props: RowsProps<PolygonFields>) {
|
||||
i === index ? { ...row, [axis]: value } : row,
|
||||
),
|
||||
})
|
||||
const count = String(fields.rows.length)
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.annotations.geometry.vertices').replace(
|
||||
'{count}',
|
||||
String(fields.rows.length),
|
||||
)}
|
||||
{t('editor.annotations.geometry.vertices').replace('{count}', count)}
|
||||
</p>
|
||||
{fields.rows.map((row, index) => (
|
||||
<div
|
||||
<VertexRow
|
||||
key={index}
|
||||
className="grid grid-cols-[2rem_1fr_1fr] items-end gap-2"
|
||||
index={index}
|
||||
row={row}
|
||||
group={props}
|
||||
onType={(axis, value) => change(index, axis, value)}
|
||||
onFocus={() => setSelected(index)}
|
||||
>
|
||||
<span className="pb-2 text-sm">{index + 1}</span>
|
||||
{(['x', 'y'] as const).map((axis) => (
|
||||
<NumberInput
|
||||
key={axis}
|
||||
id={`${props.idPrefix}-${axis}${index}`}
|
||||
label={t(`editor.annotations.geometry.vertex_${axis}`).replace(
|
||||
'{n}',
|
||||
String(index + 1),
|
||||
)}
|
||||
value={row[axis]}
|
||||
unapplied={props.pending.has(`${axis}${index}`)}
|
||||
locked={locked}
|
||||
onType={(value) => change(index, axis, value)}
|
||||
onApply={() => props.onPropose(fields)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
/>
|
||||
))}
|
||||
{!locked && (
|
||||
{!props.locked && (
|
||||
<VertexButtons
|
||||
fields={fields}
|
||||
selected={selected}
|
||||
@@ -250,6 +245,45 @@ function PolygonRows(props: RowsProps<PolygonFields>) {
|
||||
)
|
||||
}
|
||||
|
||||
function VertexRow({
|
||||
index,
|
||||
row,
|
||||
group,
|
||||
onType,
|
||||
onFocus,
|
||||
}: {
|
||||
index: number
|
||||
row: { x: string; y: string }
|
||||
group: RowsProps<PolygonFields>
|
||||
onType: (axis: 'x' | 'y', value: string) => void
|
||||
onFocus: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div
|
||||
className="grid grid-cols-[2rem_1fr_1fr] items-end gap-2"
|
||||
onFocus={onFocus}
|
||||
>
|
||||
<span className="pb-2 text-sm">{index + 1}</span>
|
||||
{(['x', 'y'] as const).map((axis) => (
|
||||
<NumberInput
|
||||
key={axis}
|
||||
id={`${group.idPrefix}-${axis}${index}`}
|
||||
label={t(`editor.annotations.geometry.vertex_${axis}`).replace(
|
||||
'{n}',
|
||||
String(index + 1),
|
||||
)}
|
||||
value={row[axis]}
|
||||
unapplied={group.pending.has(`${axis}${index}`)}
|
||||
locked={group.locked}
|
||||
onType={(value) => onType(axis, value)}
|
||||
onApply={() => group.onPropose(group.fields)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function VertexButtons({
|
||||
fields,
|
||||
selected,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
const TAG =
|
||||
'pointer-events-none inline-block rounded-md px-2 py-1 text-xs ' +
|
||||
'bg-[var(--color-surface-strong)]'
|
||||
|
||||
/** Board 04's tag over the drawing: « Sélection : <type> « <nom> ». */
|
||||
export default function SelectionTag({
|
||||
kind,
|
||||
@@ -10,10 +14,7 @@ export default function SelectionTag({
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<p
|
||||
data-testid="annotation-selection-tag"
|
||||
className="pointer-events-none inline-block rounded-md bg-[var(--color-surface-strong)] px-2 py-1 text-xs"
|
||||
>
|
||||
<p data-testid="annotation-selection-tag" className={TAG}>
|
||||
{t('editor.annotations.selection')
|
||||
.replace(
|
||||
'{kind}',
|
||||
|
||||
@@ -15,6 +15,12 @@ export interface ToolColumnProps {
|
||||
onFit: () => void
|
||||
}
|
||||
|
||||
const BUTTON =
|
||||
'grid h-11 w-11 place-items-center rounded-lg border ' +
|
||||
'border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 ' +
|
||||
'focus-visible:outline-none focus-visible:ring-2 ' +
|
||||
'focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
const GLYPHS: Record<string, string> = {
|
||||
select: 'M5 3l12 7-5 1-3 5z',
|
||||
point: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 3v3M12 18v3M3 12h3M18 12h3',
|
||||
@@ -48,7 +54,7 @@ function ToolButton({
|
||||
aria-pressed={pressed}
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className={`grid h-11 w-11 place-items-center rounded-lg border border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
|
||||
className={`${BUTTON} ${
|
||||
pressed
|
||||
? 'bg-[var(--color-ink)] text-white'
|
||||
: 'bg-[var(--color-surface)] text-[var(--color-ink)]'
|
||||
|
||||
@@ -2,6 +2,11 @@ import type { SheetView } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
const CHIP =
|
||||
'rounded-full border border-[var(--color-border)] px-3 py-1 text-sm ' +
|
||||
'focus-visible:outline-none focus-visible:ring-2 ' +
|
||||
'focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
/** One chip per view (board 04): the main view, then each detail view. */
|
||||
export default function ViewSwitcher({
|
||||
views,
|
||||
@@ -26,7 +31,7 @@ export default function ViewSwitcher({
|
||||
type="button"
|
||||
aria-pressed={view.id === current}
|
||||
onClick={() => onSelect(view.id)}
|
||||
className={`rounded-full border border-[var(--color-border)] px-3 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
|
||||
className={`${CHIP} ${
|
||||
view.id === current
|
||||
? 'bg-[var(--color-ink)] text-white'
|
||||
: 'bg-[var(--color-surface)]'
|
||||
|
||||
@@ -18,15 +18,19 @@ export interface Correction {
|
||||
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.
|
||||
* Candidate C is offered when the core refused the page's own proposal (its radius still
|
||||
* `proposedRadius`) and that proposal was either a reduced radius (B) or refused
|
||||
* `out_of_frame` (A at a float edge). A radius the user typed is an explicit value, and
|
||||
* an A refused `too_small` (r0 already capped) offers nothing: the core's issue is shown.
|
||||
*/
|
||||
export function correctionFor(
|
||||
frame: Frame,
|
||||
attempted: CircleShape,
|
||||
refusedCodes: readonly string[],
|
||||
proposedRadius: number | undefined,
|
||||
): Correction | null {
|
||||
if (proposedRadius === undefined || attempted.r !== proposedRadius)
|
||||
return null
|
||||
const reduced = attempted.r < defaultRadius(frame)
|
||||
if (!reduced && !refusedCodes.includes(OUT_OF_FRAME)) return null
|
||||
const click = { x: attempted.cx, y: attempted.cy }
|
||||
@@ -47,10 +51,11 @@ export function attemptPoint(
|
||||
frame: Frame,
|
||||
circle: CircleShape,
|
||||
insert: InsertCircle,
|
||||
proposedRadius: number | undefined,
|
||||
): PointAttempt {
|
||||
const result = insert(circle)
|
||||
if (result.ok) return { status: 'created', id: result.id }
|
||||
const correction = correctionFor(frame, circle, result.codes)
|
||||
const correction = correctionFor(frame, circle, result.codes, proposedRadius)
|
||||
return correction
|
||||
? { status: 'correction', correction }
|
||||
: { status: 'refused', messages: result.messages }
|
||||
|
||||
@@ -25,6 +25,23 @@ export interface PendingElement {
|
||||
geometry: EditableGeometry
|
||||
/** Candidate C awaiting the user's confirmation (a point only). */
|
||||
correction?: Correction | null
|
||||
/** The radius the page proposed; a radius typed since is the user's own value. */
|
||||
proposedRadius?: number
|
||||
}
|
||||
|
||||
/** The pending element with a geometry the user typed: C and the proposal lapse with it. */
|
||||
export function withGeometry(
|
||||
pending: PendingElement,
|
||||
geometry: EditableGeometry,
|
||||
): PendingElement {
|
||||
const kept =
|
||||
geometry.type === 'circle' && geometry.r === pending.proposedRadius
|
||||
return {
|
||||
...pending,
|
||||
geometry,
|
||||
correction: null,
|
||||
proposedRadius: kept ? pending.proposedRadius : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** What the creation panel collects (no default labels: names and laterality are typed). */
|
||||
@@ -70,7 +87,12 @@ export function directChildren(
|
||||
/** 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) } }
|
||||
const circle = centreCircle(frame)
|
||||
return {
|
||||
kind,
|
||||
geometry: { type: 'circle', ...circle },
|
||||
proposedRadius: circle.r,
|
||||
}
|
||||
}
|
||||
return { kind, geometry: { type: 'polygon', points: centreTriangle(frame) } }
|
||||
}
|
||||
@@ -141,7 +163,12 @@ export function pendingForClick(frame: Frame, click: XY): ClickOutcome {
|
||||
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 pending = {
|
||||
kind: 'point' as const,
|
||||
geometry,
|
||||
proposedRadius: proposal.circle.r,
|
||||
}
|
||||
return { kind: 'pending', pending }
|
||||
}
|
||||
const at = { x: round2(click.x), y: round2(click.y) }
|
||||
const geometry = {
|
||||
@@ -151,5 +178,9 @@ export function pendingForClick(frame: Frame, click: XY): ClickOutcome {
|
||||
r: defaultRadius(frame),
|
||||
}
|
||||
const correction = { click: at, circle: proposal.circle }
|
||||
return { kind: 'pending', pending: { kind: 'point', geometry, correction } }
|
||||
const pending = { kind: 'point' as const, geometry, correction }
|
||||
return {
|
||||
kind: 'pending',
|
||||
pending: { ...pending, proposedRadius: geometry.r },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { Annotation } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
insertAnnotation,
|
||||
type CommitContext,
|
||||
type CommitResult,
|
||||
} from './annotationCommit'
|
||||
import {
|
||||
attemptPoint,
|
||||
confirmCorrection,
|
||||
type Correction,
|
||||
type PointAttempt,
|
||||
} from './correction'
|
||||
import {
|
||||
annotationOf,
|
||||
formProblem,
|
||||
type CreationForm,
|
||||
type PendingElement,
|
||||
} from './creation'
|
||||
import type { Frame } from './frame'
|
||||
import type { EditableGeometry } from './geometryEdit'
|
||||
|
||||
/** What « Créer » or the confirmation of C works from. */
|
||||
export interface CreationInput {
|
||||
pending: PendingElement
|
||||
viewId: string
|
||||
/** F of the current view; null while it is not measured. */
|
||||
frame: Frame | null
|
||||
context: CommitContext
|
||||
}
|
||||
|
||||
export type Attempt = PointAttempt | { status: 'invalid'; problem: string }
|
||||
|
||||
/** The insert of the pending element under a given geometry, through `accept`. */
|
||||
function inserterOf(input: CreationInput, form: CreationForm) {
|
||||
return (geometry: EditableGeometry): CommitResult =>
|
||||
insertAnnotation(
|
||||
(id): Annotation =>
|
||||
annotationOf(id, input.viewId, { ...input.pending, geometry }, form),
|
||||
input.context,
|
||||
)
|
||||
}
|
||||
|
||||
/** « Créer »: a point lets the core's verdict offer C; nothing else is ever invented. */
|
||||
export function createAttempt(
|
||||
input: CreationInput,
|
||||
form: CreationForm,
|
||||
): Attempt {
|
||||
const { pending, frame } = input
|
||||
const problem = formProblem(pending.kind, form)
|
||||
if (problem) return { status: 'invalid', problem }
|
||||
const insert = inserterOf(input, form)
|
||||
const { geometry } = pending
|
||||
if (pending.kind === 'point' && geometry.type === 'circle' && frame) {
|
||||
return attemptPoint(
|
||||
frame,
|
||||
geometry,
|
||||
(c) => insert({ type: 'circle', ...c }),
|
||||
pending.proposedRadius,
|
||||
)
|
||||
}
|
||||
const result = insert(geometry)
|
||||
return result.ok
|
||||
? { status: 'created', id: result.id }
|
||||
: { status: 'refused', messages: result.messages }
|
||||
}
|
||||
|
||||
export function confirmAttempt(
|
||||
input: CreationInput,
|
||||
form: CreationForm,
|
||||
correction: Correction,
|
||||
): Attempt {
|
||||
const insert = inserterOf(input, form)
|
||||
return confirmCorrection(correction, (c) => insert({ type: 'circle', ...c }))
|
||||
}
|
||||
@@ -58,15 +58,6 @@ export function defaultRadius(frame: Frame): number {
|
||||
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,
|
||||
@@ -143,5 +134,16 @@ export function centreTriangle(frame: Frame): [number, number][] {
|
||||
return corners.map(([x, y]) => [round2(x), round2(y)])
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a keyboard-created point sits: the centre of F with r0. Clamped as candidate C is,
|
||||
* so it fits even with an origin off the 0.01 grid and r0 = min(w, h) / 2.
|
||||
*/
|
||||
export function centreCircle(frame: Frame): CircleShape {
|
||||
return correctedCircle(frame, {
|
||||
x: frame.x + frame.w / 2,
|
||||
y: frame.y + frame.h / 2,
|
||||
})
|
||||
}
|
||||
|
||||
export const sameCircle = (a: CircleShape, b: CircleShape): boolean =>
|
||||
a.cx === b.cx && a.cy === b.cy && a.r === b.r
|
||||
@@ -69,7 +69,11 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
|
||||
return {
|
||||
...state,
|
||||
pending: action.pending,
|
||||
serial: state.serial + 1,
|
||||
// A second click with the same kind keeps the typed fields (same panel).
|
||||
serial:
|
||||
state.pending?.kind === action.pending.kind
|
||||
? state.serial
|
||||
: state.serial + 1,
|
||||
selectedId: null,
|
||||
tracing: null,
|
||||
hint: null,
|
||||
|
||||
@@ -3,52 +3,68 @@ 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`). */
|
||||
/** The composed root's own attributes, read as text (never `baseVal`), and its view. */
|
||||
export interface RootAttributes {
|
||||
/** The view this build was made for: a frame is never paired with another view's. */
|
||||
viewId: string
|
||||
viewBox: string | null
|
||||
ratio: string
|
||||
}
|
||||
|
||||
export type CanvasFailure = 'engine' | 'view'
|
||||
|
||||
interface Built {
|
||||
root: RootAttributes | null
|
||||
failure: CanvasFailure | null
|
||||
}
|
||||
|
||||
const ANNOTATED = '[data-anno-id]'
|
||||
|
||||
function rootOf(viewId: string, svg: Element): RootAttributes {
|
||||
return {
|
||||
viewId,
|
||||
viewBox: svg.getAttribute('viewBox'),
|
||||
ratio: svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet',
|
||||
}
|
||||
}
|
||||
|
||||
/** What the canvas rebuilds on: the handle and its version counter. */
|
||||
function useHandle() {
|
||||
const preview = useEditorStore((s) => s.preview)
|
||||
const version = useEditorStore((s) => s.handleVersion)
|
||||
return { preview, version }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* retry (plan « Rendering and canvas »): the edit canvas follows the handle. Root and
|
||||
* failure come from the same build; 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 handle = useHandle()
|
||||
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)
|
||||
const [built, setBuilt] = useState<Built>({ root: null, failure: 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,
|
||||
if (!element || !handle.preview) return
|
||||
const result = buildView(handle.preview, viewId)
|
||||
element.replaceChildren(...(result.ok ? [result.svg] : []))
|
||||
setBuilt(
|
||||
result.ok
|
||||
? { root: rootOf(viewId, result.svg), failure: null }
|
||||
: { root: null, failure: result.failure },
|
||||
)
|
||||
}, [preview, viewId, handleVersion, attempt])
|
||||
}, [handle.preview, viewId, handle.version, attempt])
|
||||
|
||||
const retry = useCallback(() => {
|
||||
void coreRuntime()
|
||||
.retry()
|
||||
.finally(() => setAttempt((n) => n + 1))
|
||||
}, [])
|
||||
return { host, root, failure, retry, handleVersion }
|
||||
return { host, ...built, retry }
|
||||
}
|
||||
|
||||
/** The selected annotation's markers wear `data-state="current"`, restyled in place. */
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type {
|
||||
CSSProperties,
|
||||
KeyboardEvent,
|
||||
MouseEvent,
|
||||
PointerEvent,
|
||||
RefObject,
|
||||
} from 'react'
|
||||
import type { Geometry } from '@faunosteo/core-wasm/types'
|
||||
import { useFraming } from '@/catalogue/useFraming'
|
||||
import type { XY } from './frame'
|
||||
import { clientToDrawing } from './gesture'
|
||||
import type { ToolId } from './uiState'
|
||||
import { annotationIdOf } from './useCanvasBuild'
|
||||
import { useMoveGesture, type MoveTarget } from './useMoveGesture'
|
||||
|
||||
export interface GestureInput {
|
||||
viewId: string
|
||||
tool: ToolId
|
||||
moveTarget: MoveTarget | null
|
||||
overlay: RefObject<SVGSVGElement | null>
|
||||
viewport: RefObject<HTMLDivElement | null>
|
||||
onSelect: (id: string) => void
|
||||
/** A click with a drawing tool, in drawing units. */
|
||||
onPlace: (at: XY) => void
|
||||
onDrop: (id: string, geometry: Geometry) => void
|
||||
/** Enter and Escape while the canvas box itself has the focus (a tracing). */
|
||||
onTraceKey: (event: KeyboardEvent) => void
|
||||
}
|
||||
|
||||
type Framing = ReturnType<typeof useFraming>
|
||||
type Move = ReturnType<typeof useMoveGesture>
|
||||
|
||||
/** Each pointer handler of the framing and of the move gesture, one after the other. */
|
||||
function composedPointer(framing: Framing, move: Move) {
|
||||
const both =
|
||||
(
|
||||
name:
|
||||
| 'onPointerDown'
|
||||
| 'onPointerMove'
|
||||
| 'onPointerUp'
|
||||
| 'onPointerCancel',
|
||||
) =>
|
||||
(event: PointerEvent) => {
|
||||
framing.handlers[name](event)
|
||||
move.handlers[name](event)
|
||||
}
|
||||
return {
|
||||
onPointerDown: both('onPointerDown'),
|
||||
onPointerMove: both('onPointerMove'),
|
||||
onPointerUp: both('onPointerUp'),
|
||||
onPointerCancel: both('onPointerCancel'),
|
||||
onLostPointerCapture: move.handlers.onLostPointerCapture,
|
||||
}
|
||||
}
|
||||
|
||||
/** A click selects with the select tool, places with a drawing tool; a drag swallows it. */
|
||||
function clickHandler(input: GestureInput, framing: Framing) {
|
||||
return (event: MouseEvent) => {
|
||||
if (framing.swallowClick()) return
|
||||
if (input.tool === 'select') {
|
||||
const id = annotationIdOf(event.target)
|
||||
if (id) input.onSelect(id)
|
||||
return
|
||||
}
|
||||
const client = { x: event.clientX, y: event.clientY }
|
||||
const at = clientToDrawing(input.overlay.current, client)
|
||||
if (at) input.onPlace(at)
|
||||
}
|
||||
}
|
||||
|
||||
/** `touch-action: none` only while a drawing tool, a drag or a zoom is active. */
|
||||
function touchStyle(
|
||||
tool: ToolId,
|
||||
armed: boolean,
|
||||
scale: number,
|
||||
): CSSProperties {
|
||||
const none = tool !== 'select' || armed || scale !== 1
|
||||
return { touchAction: none ? 'none' : 'pan-x pan-y' }
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the canvas box listens to: zoom and pan, the move gesture, the click, and
|
||||
* the keys. Enter and Escape only count when the box itself is the target, so Enter on
|
||||
* « Annuler le tracé » (or a list row) is that button's, never a close of the tracing.
|
||||
*/
|
||||
export function useCanvasGestures(input: GestureInput) {
|
||||
const move = useMoveGesture({
|
||||
overlay: input.overlay,
|
||||
target: input.moveTarget,
|
||||
onDrop: input.onDrop,
|
||||
})
|
||||
const framing = useFraming(input.viewport, input.viewId, {
|
||||
canPan: (event) => input.tool === 'select' && !move.claims(event),
|
||||
})
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
framing.handlers.onKeyDown(event)
|
||||
if (event.target === event.currentTarget) input.onTraceKey(event)
|
||||
}
|
||||
return {
|
||||
framing,
|
||||
drag: move.preview,
|
||||
boxProps: {
|
||||
...composedPointer(framing, move),
|
||||
onKeyDown,
|
||||
onClick: clickHandler(input, framing),
|
||||
style: touchStyle(input.tool, move.armed, framing.framing.scale),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -39,13 +39,8 @@ const clientOf = (event: PointerEvent): XY => ({
|
||||
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) {
|
||||
/** The drag in flight (a ref, read by the handlers) and what the page shows of it. */
|
||||
function useDragState(target: MoveTarget | null) {
|
||||
const drag = useRef<Drag | null>(null)
|
||||
const [preview, setPreview] = useState<Geometry | null>(null)
|
||||
const [armed, setArmed] = useState(false)
|
||||
@@ -54,54 +49,80 @@ export function useMoveGesture({ overlay, target, onDrop }: MoveOptions) {
|
||||
setPreview(null)
|
||||
setArmed(false)
|
||||
}
|
||||
const stopRef = useRef(stop)
|
||||
stopRef.current = stop
|
||||
// Losing the target (a switch to read-only, another selection) drops the drag.
|
||||
useEffect(() => {
|
||||
if (target === null) stop()
|
||||
if (target === null) stopRef.current()
|
||||
}, [target])
|
||||
return { drag, preview, setPreview, armed, setArmed, stop }
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
type DragState = ReturnType<typeof useDragState>
|
||||
|
||||
/** The geometry the pointer's position gives the target, translated as a block. */
|
||||
function translatedAt(
|
||||
overlay: MoveOptions['overlay'],
|
||||
gesture: Drag | null,
|
||||
target: MoveTarget | null,
|
||||
event: PointerEvent,
|
||||
): Geometry | null {
|
||||
const now = clientToDrawing(overlay.current, clientOf(event))
|
||||
if (!now || !gesture || !target) return null
|
||||
return translatedGeometry(target.geometry, {
|
||||
x: now.x - gesture.origin.x,
|
||||
y: now.y - gesture.origin.y,
|
||||
})
|
||||
}
|
||||
|
||||
function pointerHandlers(options: MoveOptions, state: DragState) {
|
||||
const { overlay, target, onDrop } = options
|
||||
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 }
|
||||
state.drag.current = { start: clientOf(event), origin, started: false }
|
||||
event.currentTarget.setPointerCapture?.(event.pointerId)
|
||||
setArmed(true)
|
||||
state.setArmed(true)
|
||||
}
|
||||
const onPointerMove = (event: PointerEvent) => {
|
||||
const gesture = drag.current
|
||||
const gesture = state.drag.current
|
||||
if (!gesture) return
|
||||
if (!gesture.started && !pastDragThreshold(gesture.start, clientOf(event)))
|
||||
return
|
||||
gesture.started = true
|
||||
setPreview(translated(event))
|
||||
state.setPreview(translatedAt(overlay, gesture, target, event))
|
||||
}
|
||||
const onPointerUp = (event: PointerEvent) => {
|
||||
const gesture = drag.current
|
||||
const dropped = gesture?.started ? translated(event) : null
|
||||
stop()
|
||||
const gesture = state.drag.current
|
||||
const dropped = gesture?.started
|
||||
? translatedAt(overlay, gesture, target, event)
|
||||
: null
|
||||
state.stop()
|
||||
if (dropped && target) onDrop(target.id, dropped)
|
||||
}
|
||||
return {
|
||||
preview,
|
||||
armed,
|
||||
claims,
|
||||
handlers: {
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel: stop,
|
||||
onLostPointerCapture: stop,
|
||||
onPointerCancel: state.stop,
|
||||
onLostPointerCapture: state.stop,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(options: MoveOptions) {
|
||||
const state = useDragState(options.target)
|
||||
const { claims, handlers } = pointerHandlers(options, state)
|
||||
return { preview: state.preview, armed: state.armed, claims, handlers }
|
||||
}
|
||||
@@ -62,24 +62,11 @@ export function closingActions(
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* 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') })
|
||||
}
|
||||
/** Tracing with the zone and link tools: vertices, closing, Enter and Escape. */
|
||||
function tracingActions(input: PlacementInput) {
|
||||
const { ui, dispatch, frame } = input
|
||||
const closeTracing = () =>
|
||||
closingActions(ui.tracing, doc, context).forEach(dispatch)
|
||||
|
||||
closingActions(ui.tracing, input.doc, input.context).forEach(dispatch)
|
||||
const trace = (tool: Exclude<ToolId, 'select' | 'point'>, at: XY) => {
|
||||
if (!frame) return
|
||||
if (ui.tracing && nearFirstVertex(ui.tracing, at, frame)) {
|
||||
@@ -89,21 +76,48 @@ export function usePlacement(input: PlacementInput) {
|
||||
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) => {
|
||||
const onTraceKey = (event: KeyboardEvent) => {
|
||||
if (!ui.tracing) return
|
||||
if (event.key === 'Enter') closeTracing()
|
||||
if (event.key === 'Escape') dispatch({ type: 'trace_cancel' })
|
||||
}
|
||||
return { onPlace, onDrop, onKeyDown, closeTracing }
|
||||
return { closeTracing, trace, onTraceKey }
|
||||
}
|
||||
|
||||
/** A drop commits one update; the hint holds the core's words on a refusal. */
|
||||
function dropAction(input: PlacementInput) {
|
||||
return (id: string, geometry: Geometry) => {
|
||||
const annotation = input.doc.annotations.find((a) => a.id === id)
|
||||
if (!annotation) return
|
||||
const result = updateGeometry(annotation, geometry, input.context)
|
||||
const hint = result.ok ? null : result.messages.join(' ')
|
||||
input.dispatch({ type: 'hint', hint })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* `onTraceKey` is for the canvas viewport only (a key from a button is the button's).
|
||||
*/
|
||||
export function usePlacement(input: PlacementInput) {
|
||||
const t = useT()
|
||||
const tracing = tracingActions(input)
|
||||
const { ui, dispatch, frame } = input
|
||||
const onPlace = (at: XY) => {
|
||||
if (ui.tool === 'zone' || ui.tool === 'link')
|
||||
return tracing.trace(ui.tool, at)
|
||||
if (ui.tool !== 'point' || !frame) return
|
||||
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') })
|
||||
}
|
||||
return {
|
||||
onPlace,
|
||||
onDrop: dropAction(input),
|
||||
onTraceKey: tracing.onTraceKey,
|
||||
closeTracing: tracing.closeTracing,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Annotation,
|
||||
@@ -32,23 +32,3 @@ export function useViewModel(
|
||||
}
|
||||
}, [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)
|
||||
}, [])
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useEditorStore } from './state/editorStore'
|
||||
|
||||
const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]'
|
||||
const MODAL_OPEN = 'dialog[open]'
|
||||
|
||||
/**
|
||||
* Ctrl+Z undoes and Ctrl+Shift+Z redoes, editor-wide (plan « Store and sessions », no
|
||||
* Ctrl+Y): active only while the draft is writable, ignored in text fields and while a
|
||||
* modal dialog is open (its own focus and keys come first).
|
||||
*/
|
||||
export function useUndoShortcuts(writable: boolean): void {
|
||||
useEffect(() => {
|
||||
if (!writable) return
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
const { target } = event
|
||||
if (target instanceof Element && target.closest(TEXT_TARGET)) return
|
||||
if (document.querySelector(MODAL_OPEN)) 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)
|
||||
}, [writable])
|
||||
}
|
||||
@@ -277,6 +277,22 @@ describe('a frame change (rule 7)', () => {
|
||||
expect(store.getState().documentText).toBe(before)
|
||||
})
|
||||
|
||||
it('is refused when it makes a point too_small, nothing kept', async () => {
|
||||
await openWith(
|
||||
insert(drawnText(), point('anno-a', 2500, 2500, 400)),
|
||||
'0 0 5000 5000',
|
||||
)
|
||||
const before = store.getState().documentText
|
||||
const outcome = crop({ min_x: 0, min_y: 0, width: 200000, height: 200000 })
|
||||
expect(outcome).toMatchObject({ ok: false, reason: 'refused' })
|
||||
if (outcome.ok || outcome.reason !== 'refused')
|
||||
throw new Error('not refused')
|
||||
expect(outcome.refusal.issues.map((i) => i.code)).toContain(
|
||||
'annotation.geometry.too_small',
|
||||
)
|
||||
expect(store.getState().documentText).toBe(before)
|
||||
})
|
||||
|
||||
it('is accepted when only an already-invalid point is affected', async () => {
|
||||
await openReady({ text: insert(drawnText(), point('anno-a', 150, 50, 5)) })
|
||||
expect(crop({ min_x: 0, min_y: 0, width: 80, height: 80 }).ok).toBe(true)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Lot H: the Annotations tab (creation, corrected position, gestures, read-only, repair). */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
import {
|
||||
USER,
|
||||
VERSION,
|
||||
commitMove,
|
||||
openReady,
|
||||
resetStore,
|
||||
sb,
|
||||
@@ -693,13 +695,11 @@ describe('polygons and paths', () => {
|
||||
})
|
||||
const panel = await selectFromList()
|
||||
expect(within(panel).queryByText(/M 20 20/)).toBeNull()
|
||||
await userEvent
|
||||
.setup()
|
||||
.click(
|
||||
within(panel).getByRole('button', {
|
||||
name: 'Remplacer par un polygone',
|
||||
}),
|
||||
)
|
||||
await userEvent.setup().click(
|
||||
within(panel).getByRole('button', {
|
||||
name: 'Remplacer par un polygone',
|
||||
}),
|
||||
)
|
||||
const canvas = screen.getByTestId('annotation-canvas')
|
||||
triangle.forEach(([x, y]) =>
|
||||
fireEvent.click(canvas, { clientX: x, clientY: y }),
|
||||
@@ -714,25 +714,232 @@ describe('polygons and paths', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('keyboard shortcuts', () => {
|
||||
it('undoes with Ctrl+Z outside a text field and not inside one', async () => {
|
||||
await mount()
|
||||
await selectFromList()
|
||||
const user = userEvent.setup()
|
||||
const cx = within(
|
||||
screen.getByTestId('annotation-properties'),
|
||||
).getByLabelText('Centre x')
|
||||
await user.clear(cx)
|
||||
await user.type(cx, '60{Enter}')
|
||||
fireEvent.keyDown(cx, { key: 'z', ctrlKey: true })
|
||||
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
|
||||
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
|
||||
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
|
||||
fireEvent.keyDown(document.body, {
|
||||
key: 'z',
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
describe('keys while tracing (H3)', () => {
|
||||
const clickAt = (x: number, y: number) =>
|
||||
fireEvent.click(screen.getByTestId('annotation-canvas'), {
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
})
|
||||
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
|
||||
|
||||
async function traced() {
|
||||
await mount({ text: drawnText() })
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'Zone' }))
|
||||
triangle.forEach(([x, y]) => clickAt(x, y))
|
||||
return user
|
||||
}
|
||||
|
||||
it('Enter on « Annuler le tracé » cancels the tracing instead of closing it', async () => {
|
||||
const user = await traced()
|
||||
screen.getByRole('button', { name: 'Annuler le tracé' }).focus()
|
||||
await user.keyboard('{Enter}')
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Annuler le tracé' }),
|
||||
).toBeNull()
|
||||
expect(screen.queryByTestId('annotation-creation')).toBeNull()
|
||||
})
|
||||
|
||||
it('Enter on a view chip or a list row never closes the tracing', async () => {
|
||||
await traced()
|
||||
const views = screen.getByRole('group', { name: 'Vues' })
|
||||
fireEvent.keyDown(within(views).getAllByRole('button')[0], {
|
||||
key: 'Enter',
|
||||
})
|
||||
expect(screen.queryByTestId('annotation-creation')).toBeNull()
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Annuler le tracé' }),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('a second click with the point tool (H6)', () => {
|
||||
it('moves the pending point and keeps what was typed', async () => {
|
||||
await mount({ text: drawnText() })
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'Point' }))
|
||||
fireEvent.click(screen.getByTestId('annotation-canvas'), {
|
||||
clientX: 50,
|
||||
clientY: 50,
|
||||
})
|
||||
const panel = await fillCreation(user)
|
||||
fireEvent.click(screen.getByTestId('annotation-canvas'), {
|
||||
clientX: 60,
|
||||
clientY: 40,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(within(panel).getByLabelText('Centre x')).toHaveValue('60'),
|
||||
)
|
||||
expect(within(panel).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
|
||||
expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired')
|
||||
expect(screen.getByTestId('annotation-creation')).toBe(panel)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a typed radius (H5)', () => {
|
||||
it('shows the core issue, not a corrected position', async () => {
|
||||
const drawing = svgBytes('0 0 5000 5000')
|
||||
sb.getSheetVersion.mockResolvedValue({
|
||||
...versionAnswer(drawnText(), 3),
|
||||
drawings: [{ asset_id: ASSET, sha256: drawing.sha256 }],
|
||||
} as never)
|
||||
sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes)
|
||||
store.getState().open(VERSION, USER, { canEdit: true })
|
||||
await waitFor(() => expect(store.getState().status).toBe('ready'))
|
||||
render(<AnnotationsTab {...props} />)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Ajouter un point' }),
|
||||
).toBeEnabled(),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
|
||||
const panel = await fillCreation(user)
|
||||
const r = within(panel).getByLabelText('Rayon')
|
||||
await user.clear(r)
|
||||
await user.type(r, '1{Enter}')
|
||||
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
|
||||
expect(screen.queryByTestId('correction-notice')).toBeNull()
|
||||
expect(within(panel).getByRole('alert')).toBeInTheDocument()
|
||||
expect(annotations()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the frame follows the view (H7)', () => {
|
||||
it('holds the keyboard point at the centre of the view shown, after a switch', async () => {
|
||||
const withView = insert(drawnText(), {
|
||||
kind: 'view',
|
||||
value: {
|
||||
kind: 'detail',
|
||||
id: 'view-det',
|
||||
name: { fr: 'Tête', en: 'Head' },
|
||||
svg_asset_id: null,
|
||||
view_box: { min_x: 10, min_y: 20, width: 40, height: 60 },
|
||||
parent_view_id: 'view-main',
|
||||
},
|
||||
})
|
||||
await mount({ text: withView })
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'Tête' }))
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Ajouter un point' }),
|
||||
).toBeEnabled(),
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
|
||||
const panel = await screen.findByTestId('annotation-creation')
|
||||
expect(within(panel).getByLabelText('Centre x')).toHaveValue('30')
|
||||
expect(within(panel).getByLabelText('Centre y')).toHaveValue('50')
|
||||
})
|
||||
})
|
||||
|
||||
describe('refusals through the tab (H8)', () => {
|
||||
const zoneText = (geometry: object) =>
|
||||
insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) })
|
||||
|
||||
it('a refused « Remplacer par un polygone » drops the tracing, shows the core message', async () => {
|
||||
const path = { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }
|
||||
await mount({ text: zoneText(path) })
|
||||
const panel = await selectFromList()
|
||||
await userEvent.setup().click(
|
||||
within(panel).getByRole('button', {
|
||||
name: 'Remplacer par un polygone',
|
||||
}),
|
||||
)
|
||||
const canvas = screen.getByTestId('annotation-canvas')
|
||||
;[
|
||||
[20, 20],
|
||||
[500, 20],
|
||||
[50, 80],
|
||||
].forEach(([x, y]) => fireEvent.click(canvas, { clientX: x, clientY: y }))
|
||||
fireEvent.keyDown(canvas, { key: 'Enter' })
|
||||
expect(await screen.findByRole('alert')).toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Annuler le tracé' }),
|
||||
).toBeNull()
|
||||
expect(geometryOf('zone-a')).toEqual(path)
|
||||
})
|
||||
|
||||
it('a refused vertex add and a refused remove stay « non appliqué », document unchanged', async () => {
|
||||
await mount({
|
||||
text: zoneText({ type: 'polygon', points: [...triangle, [20, 60]] }),
|
||||
})
|
||||
const panel = await selectFromList()
|
||||
const user = userEvent.setup()
|
||||
const before = store.getState().documentText
|
||||
const x = within(panel).getByLabelText('x du sommet 1')
|
||||
await user.clear(x)
|
||||
await user.type(x, '500{Enter}')
|
||||
await user.click(
|
||||
within(panel).getByRole('button', { name: 'Ajouter un sommet' }),
|
||||
)
|
||||
expect(store.getState().documentText).toBe(before)
|
||||
expect(within(panel).getAllByLabelText(/^x du sommet/)).toHaveLength(5)
|
||||
expect(
|
||||
within(panel).getByText(/Valeurs non appliquées/),
|
||||
).toBeInTheDocument()
|
||||
await user.click(within(panel).getByRole('button', { name: 'Retirer' }))
|
||||
expect(store.getState().documentText).toBe(before)
|
||||
expect(
|
||||
within(panel).getByText(/Valeurs non appliquées/),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the drag and the canvas follow the handle (H8)', () => {
|
||||
const down = (el: Element, x: number, y: number) =>
|
||||
fireEvent.pointerDown(el, {
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
button: 0,
|
||||
pointerId: 1,
|
||||
})
|
||||
|
||||
it('lostpointercapture drops the drag with no command', async () => {
|
||||
await mount()
|
||||
await selectFromList()
|
||||
const hit = marker('anno-a')
|
||||
const version = store.getState().handleVersion
|
||||
down(hit, 50, 50)
|
||||
fireEvent.pointerMove(hit, { clientX: 70, clientY: 50, pointerId: 1 })
|
||||
fireEvent.lostPointerCapture(hit, { pointerId: 1 })
|
||||
fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 })
|
||||
expect(store.getState().handleVersion).toBe(version)
|
||||
})
|
||||
|
||||
it('a switch to read-only mid-drag drops it', async () => {
|
||||
await openReady({ text: text() })
|
||||
const view = render(<AnnotationsTab {...props} />)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
|
||||
).not.toBeNull(),
|
||||
)
|
||||
await selectFromList()
|
||||
const hit = marker('anno-a')
|
||||
const version = store.getState().handleVersion
|
||||
down(hit, 50, 50)
|
||||
fireEvent.pointerMove(hit, { clientX: 70, clientY: 50, pointerId: 1 })
|
||||
view.rerender(<AnnotationsTab {...props} readOnly />)
|
||||
fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 })
|
||||
expect(store.getState().handleVersion).toBe(version)
|
||||
expect(geometryOf('anno-a')).toEqual({
|
||||
type: 'circle',
|
||||
cx: 50,
|
||||
cy: 50,
|
||||
r: 5,
|
||||
})
|
||||
})
|
||||
|
||||
it('rebuilds the drawing when the handle changes under it', async () => {
|
||||
await mount()
|
||||
const first = marker('anno-a')
|
||||
act(() => void commitMove(60))
|
||||
await waitFor(() => expect(marker('anno-a')).not.toBe(first))
|
||||
})
|
||||
})
|
||||
@@ -147,24 +147,27 @@ describe('correctionFor', () => {
|
||||
it('offers C for a refused B or an A refused out_of_frame, never for A too_small', () => {
|
||||
const reduced = { cx: 13.19, cy: 15, r: 13.19 }
|
||||
expect(
|
||||
correctionFor(frame, reduced, ['annotation.geometry.too_small']),
|
||||
correctionFor(frame, reduced, ['annotation.geometry.too_small'], 13.19),
|
||||
).not.toBeNull()
|
||||
const edge = { cx: 5, cy: 15, r: 13.2 }
|
||||
expect(
|
||||
correctionFor(frame, edge, ['annotation.geometry.out_of_frame'])?.circle
|
||||
.cx,
|
||||
correctionFor(frame, edge, ['annotation.geometry.out_of_frame'], 13.2)
|
||||
?.circle.cx,
|
||||
).toBe(13.2)
|
||||
expect(
|
||||
correctionFor(frame, { cx: 20, cy: 15, r: 13.2 }, [
|
||||
'annotation.geometry.too_small',
|
||||
]),
|
||||
correctionFor(
|
||||
frame,
|
||||
{ cx: 20, cy: 15, r: 13.2 },
|
||||
['annotation.geometry.too_small'],
|
||||
13.2,
|
||||
),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('offers nothing when C is the circle that was just refused', () => {
|
||||
const circle = { cx: 13.2, cy: 13.2, r: 13.2 }
|
||||
expect(
|
||||
correctionFor(frame, circle, ['annotation.geometry.out_of_frame']),
|
||||
correctionFor(frame, circle, ['annotation.geometry.out_of_frame'], 13.2),
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -211,7 +214,12 @@ describe.each(FRAMES)('a point placed in the frame %s', (viewBox) => {
|
||||
expect(proposal.kind).not.toBe('outside')
|
||||
if (proposal.kind === 'outside') continue
|
||||
const insert = circleInserter(b)
|
||||
const attempt = attemptPoint(frame, proposal.circle, insert)
|
||||
const attempt = attemptPoint(
|
||||
frame,
|
||||
proposal.circle,
|
||||
insert,
|
||||
proposal.circle.r,
|
||||
)
|
||||
expect(attempt).toMatchObject({ status: 'created' })
|
||||
expect(currentErrors(b).size).toBe(0)
|
||||
}
|
||||
@@ -247,7 +255,12 @@ describe('a very elongated frame', () => {
|
||||
const frame = frameOf(b)!
|
||||
const proposal = proposePoint(frame, { x: 500, y: 15 })
|
||||
if (proposal.kind !== 'circle') throw new Error('proposal')
|
||||
const attempt = attemptPoint(frame, proposal.circle, circleInserter(b))
|
||||
const attempt = attemptPoint(
|
||||
frame,
|
||||
proposal.circle,
|
||||
circleInserter(b),
|
||||
proposal.circle.r,
|
||||
)
|
||||
expect(attempt.status).toBe('refused')
|
||||
expect(b.preview.document).toBe(b.text)
|
||||
})
|
||||
@@ -267,7 +280,9 @@ describe('a detail crop', () => {
|
||||
const inside = proposePoint(frame, { x: 150, y: 350 })
|
||||
if (inside.kind !== 'circle') throw new Error('proposal')
|
||||
const insert = circleInserter(b, 'view-det')
|
||||
expect(attemptPoint(frame, inside.circle, insert)).toMatchObject({
|
||||
expect(
|
||||
attemptPoint(frame, inside.circle, insert, inside.circle.r),
|
||||
).toMatchObject({
|
||||
status: 'created',
|
||||
})
|
||||
expect(proposePoint(frame, { x: 99, y: 350 })).toEqual({ kind: 'outside' })
|
||||
@@ -276,3 +291,73 @@ describe('a detail crop', () => {
|
||||
expect(currentErrors(b).size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a radius the user typed (H5)', () => {
|
||||
const frame = f(0, 0, 40, 30)
|
||||
|
||||
it('is never replaced by a corrected position: the core issue is shown', () => {
|
||||
const typed = { cx: 20, cy: 15, r: 1 }
|
||||
const codes = ['annotation.geometry.too_small']
|
||||
expect(correctionFor(frame, typed, codes, 13.2)).toBeNull()
|
||||
expect(correctionFor(frame, typed, codes, undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('on the core: a typed too-small radius creates nothing and keeps the message', () => {
|
||||
const b = bed('0 0 5000 5000')
|
||||
const big = frameOf(b)!
|
||||
const attempt = attemptPoint(
|
||||
big,
|
||||
{ cx: 2500, cy: 2500, r: 1 },
|
||||
circleInserter(b),
|
||||
defaultRadius(big),
|
||||
)
|
||||
expect(attempt).toMatchObject({ status: 'refused' })
|
||||
expect(b.preview.document).toBe(b.text)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the keyboard point (H4)', () => {
|
||||
it.each([
|
||||
'0.003 0.004 20 20',
|
||||
'0 0 20 20',
|
||||
'-50 20 40 30',
|
||||
'0.003 0.004 1000 30',
|
||||
])('fits the frame %s by construction, with no correction', (viewBox) => {
|
||||
const b = bed(viewBox)
|
||||
const frame = frameOf(b)!
|
||||
const circle = centreCircle(frame)
|
||||
const slack = 1e-9 // float noise of x + w / 2 − r only; the core decides below
|
||||
expect(circle.cx - circle.r).toBeGreaterThanOrEqual(frame.x - slack)
|
||||
expect(circle.cy - circle.r).toBeGreaterThanOrEqual(frame.y - slack)
|
||||
expect(circle.cx + circle.r).toBeLessThanOrEqual(frame.x + frame.w + slack)
|
||||
expect(circle.cy + circle.r).toBeLessThanOrEqual(frame.y + frame.h + slack)
|
||||
const attempt = attemptPoint(frame, circle, circleInserter(b), circle.r)
|
||||
expect(attempt.status).not.toBe('correction')
|
||||
if (viewBox.endsWith('1000 30')) return
|
||||
expect(attempt).toMatchObject({ status: 'created' })
|
||||
})
|
||||
})
|
||||
|
||||
describe.each(['0 0 1000 30', '0 0 4000 200'])(
|
||||
'the elongated frame %s (H8)',
|
||||
(viewBox) => {
|
||||
it('gives the core the verdict on every edge and corner click, keeping nothing invalid', () => {
|
||||
const frame = frameOf(bed(viewBox))!
|
||||
for (const click of clicksOf(frame)) {
|
||||
const b = bed(viewBox)
|
||||
const proposal = proposePoint(frame, click)
|
||||
if (proposal.kind === 'outside') continue
|
||||
const attempt = attemptPoint(
|
||||
frame,
|
||||
proposal.circle,
|
||||
circleInserter(b),
|
||||
proposal.circle.r,
|
||||
)
|
||||
expect(['created', 'refused', 'correction']).toContain(attempt.status)
|
||||
expect(currentErrors(b).size).toBe(0)
|
||||
if (attempt.status !== 'created')
|
||||
expect(b.preview.document).toBe(b.text)
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Lot H fix H2: Ctrl+Z and Ctrl+Shift+Z are editor-wide, writable only, not in a dialog. */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import {
|
||||
baseText,
|
||||
commitMove,
|
||||
resetStore,
|
||||
serverHas,
|
||||
store,
|
||||
} from '../helpers/editorHarness'
|
||||
import { mountDraft, setWidth } from '../helpers/editorRoute'
|
||||
|
||||
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
||||
vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
...(await orig<typeof import('@faunosteo/supabase')>()),
|
||||
getSheetVersion: vi.fn(),
|
||||
downloadSheetDrawing: vi.fn(),
|
||||
saveSheetDraft: vi.fn(),
|
||||
getOfficialSheetAdmin: vi.fn(),
|
||||
submitSheetReview: vi.fn(),
|
||||
}))
|
||||
|
||||
beforeEach(() => serverHas(baseText(), 3))
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetStore()
|
||||
setWidth(1024)
|
||||
})
|
||||
|
||||
const ready = () =>
|
||||
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
|
||||
const cx = () => store.getState().previewState?.document.annotations[0].geometry
|
||||
const ctrlZ = (target: Element, shift = false) =>
|
||||
fireEvent.keyDown(target, { key: 'z', ctrlKey: true, shiftKey: shift })
|
||||
|
||||
describe('editor-wide undo', () => {
|
||||
it('undoes and redoes from another tab', async () => {
|
||||
mountDraft()
|
||||
await ready()
|
||||
act(() => void commitMove(40))
|
||||
await userEvent.setup().click(screen.getByRole('tab', { name: 'Général' }))
|
||||
ctrlZ(document.body)
|
||||
expect(cx()).toMatchObject({ cx: 50 })
|
||||
ctrlZ(document.body, true)
|
||||
expect(cx()).toMatchObject({ cx: 40 })
|
||||
})
|
||||
|
||||
it('does nothing in a text field', async () => {
|
||||
mountDraft()
|
||||
await ready()
|
||||
act(() => void commitMove(40))
|
||||
await userEvent.setup().click(screen.getByRole('tab', { name: 'Général' }))
|
||||
ctrlZ(document.querySelector('input') as Element)
|
||||
expect(cx()).toMatchObject({ cx: 40 })
|
||||
})
|
||||
|
||||
it('does nothing while a modal dialog is open', async () => {
|
||||
mountDraft()
|
||||
await ready()
|
||||
act(() => void commitMove(40))
|
||||
const dialog = document.createElement('dialog')
|
||||
dialog.setAttribute('open', '')
|
||||
document.body.append(dialog)
|
||||
ctrlZ(document.body)
|
||||
expect(cx()).toMatchObject({ cx: 40 })
|
||||
dialog.remove()
|
||||
})
|
||||
|
||||
it('is off in a read-only mode', async () => {
|
||||
mountDraft({ width: 800 })
|
||||
await ready()
|
||||
store.getState().setCanEdit(true)
|
||||
act(() => void commitMove(40))
|
||||
store.getState().setCanEdit(false)
|
||||
ctrlZ(document.body)
|
||||
expect(cx()).toMatchObject({ cx: 40 })
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user