feat(app): a click on the drawing deselects (R1, D6b)

The decision comes from the press (landed off a marker, moved <= 4 px, one
pointer), not the click target: mouse and pen act at pointerup, touch in the
tap's own click. The reader passes no onEmpty and is unchanged.
No existing assertion rewritten.
This commit is contained in:
bchanot committed 2026-11-12 12:51:59 +01:00
1 parent bbb1668406
commit bbdfd27311
9 files changed
+586 -21

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
import { useCallback, useEffect, useRef } from 'react'
import type { PointerEvent } from 'react'
/** Same 4 px as the framing's drag threshold: more is a drag, not a tap. */
const TAP_SLOP_PX = 4
const ANNOTATED = '[data-anno-id]'
type Point = { x: number; y: number }
/** What a pointer-up decides: act now (mouse, pen), at the click (touch), or not at all. */
export type TapVerdict = 'none' | 'now' | 'on_click'
/** What the click that follows must do: nothing, deselect, or its usual work. */
export type ClickAnswer = 'swallow' | 'deselect' | 'normal'
interface Press {
armed: boolean
onAnnotation: boolean
moved: number
multi: boolean
last: Point
touchPending: boolean
swallowClick: boolean
}
const idle = (): Press => ({
armed: false,
onAnnotation: false,
moved: 0,
multi: false,
last: { x: 0, y: 0 },
touchPending: false,
swallowClick: false,
})
const pointOf = (e: PointerEvent): Point => ({ x: e.clientX, y: e.clientY })
/**
* Tells a tap on the empty drawing from every other gesture. The decision is taken from
* the PRESS (where it landed, whether it moved, whether a second pointer joined), never
* from the click's target: the move gesture captures the pointer on the box, which
* retargets the click of a press on the selected marker; and on touch the browser builds
* the click after the lift, on the layout without the selection, and may adjust it toward
* a nearby marker. Mouse and pen act at the pointer-up (a blur commit at mousedown can
* rebuild the drawing and drop the click); touch acts in the tap's own click.
* Refs only: no render follows a press.
*/
export function useEmptyTap() {
const press = useRef<Press>(idle())
const pointerId = useRef<number | null>(null)
const stopListening = useRef<(() => void) | null>(null)
const release = useCallback(() => {
stopListening.current?.()
stopListening.current = null
}, [])
const disarm = useCallback(() => {
press.current.armed = false
release()
}, [release])
useEffect(() => release, [release])
const onPointerDown = useCallback(
(e: PointerEvent) => {
if (!e.isPrimary) {
press.current.multi = true
return
}
release()
pointerId.current = e.pointerId
const target = e.target instanceof Element ? e.target : null
press.current = {
...idle(),
armed: e.button === 0,
onAnnotation: target?.closest(ANNOTATED) != null,
last: pointOf(e),
}
if (!press.current.armed) return
// A second finger can land outside the box: only the document sees it.
const other = (ev: Event) => {
if ((ev as globalThis.PointerEvent).pointerId !== pointerId.current) {
press.current.multi = true
}
}
document.addEventListener('pointerdown', other, true)
stopListening.current = () =>
document.removeEventListener('pointerdown', other, true)
},
[release],
)
const onPointerMove = useCallback((e: PointerEvent) => {
const p = press.current
if (!e.isPrimary || !p.armed) return
const now = pointOf(e)
p.moved += Math.hypot(now.x - p.last.x, now.y - p.last.y)
p.last = now
}, [])
const verdict = useCallback(
(e: PointerEvent, enabled = true): TapVerdict => {
const p = press.current
const still = p.moved <= TAP_SLOP_PX && !p.multi
const tap = enabled && e.isPrimary && p.armed && still && !p.onAnnotation
if (e.isPrimary) disarm()
if (!tap) return 'none'
if (e.pointerType === 'touch') {
p.touchPending = true
return 'on_click'
}
p.swallowClick = true
return 'now'
},
[disarm],
)
const takeClick = useCallback((target: EventTarget | null): ClickAnswer => {
const p = press.current
if (p.swallowClick) {
p.swallowClick = false
return 'swallow'
}
if (!p.touchPending) return 'normal'
p.touchPending = false
const onMarker =
target instanceof Element && target.closest(ANNOTATED) !== null
return onMarker ? 'normal' : 'deselect'
}, [])
return {
onPointerDown,
onPointerMove,
onPointerCancel: disarm,
verdict,
takeClick,
}
}
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useRef, useState, type PointerEvent } from 'react'
import { usePlaceVisible } from '@/lib/placeVisibility'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
@@ -6,6 +6,7 @@ import { coreRuntime, useCoreStopped } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure'
import type { CataloguePreview } from '@/catalogue/preview'
import { transformOf } from '@/catalogue/framing'
import { useEmptyTap } from '@/catalogue/useEmptyTap'
import { useFraming } from '@/catalogue/useFraming'
import { useT } from '@/i18n/useT'
@@ -15,6 +16,8 @@ export interface CatalogueCanvasProps {
viewName: string
selectedId: string | null
onAnnotation: (annotationId: string) => void
/** A tap on the empty drawing; without it the canvas behaves as the reader always did. */
onEmpty?: () => void
}
type CanvasFailure = 'engine' | 'view'
@@ -54,6 +57,7 @@ export default function CatalogueCanvas({
viewName,
selectedId,
onAnnotation,
onEmpty,
}: CatalogueCanvasProps) {
const t = useT()
const viewport = useRef<HTMLDivElement | null>(null)
@@ -66,6 +70,29 @@ export default function CatalogueCanvas({
viewport,
viewId,
)
const tap = useEmptyTap()
const { takeClick } = tap
const emptyHandlers = onEmpty
? {
onPointerDown: (e: PointerEvent) => {
handlers.onPointerDown(e)
tap.onPointerDown(e)
},
onPointerMove: (e: PointerEvent) => {
handlers.onPointerMove(e)
tap.onPointerMove(e)
},
onPointerUp: (e: PointerEvent) => {
handlers.onPointerUp(e)
if (tap.verdict(e) === 'now') onEmpty()
},
onPointerCancel: (e: PointerEvent) => {
handlers.onPointerCancel(e)
tap.onPointerCancel()
},
onContextMenu: tap.onPointerCancel,
}
: handlers
const retryEngine = useCallback(() => {
void coreRuntime()
@@ -98,13 +125,16 @@ export default function CatalogueCanvas({
if (!element) return
const onClick = (event: Event) => {
if (swallowClick()) return
const answer = onEmpty ? takeClick(event.target) : 'normal'
if (answer === 'swallow') return
if (answer === 'deselect') return onEmpty?.()
const target = event.target instanceof Element ? event.target.closest(ANNOTATED) : null
const id = target?.getAttribute('data-anno-id')
if (id) onAnnotation(id)
}
element.addEventListener('click', onClick)
return () => element.removeEventListener('click', onClick)
}, [onAnnotation, swallowClick])
}, [onAnnotation, onEmpty, swallowClick, takeClick])
return (
<div className="space-y-2">
@@ -118,7 +148,7 @@ export default function CatalogueCanvas({
data-testid="catalogue-canvas"
className="svg-canvas aspect-[4/3] w-full cursor-grab select-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] sm:aspect-[3/2]"
style={{ touchAction: framing.scale === 1 ? 'pan-x pan-y' : 'none' }}
{...handlers}
{...emptyHandlers}
>
<div
ref={host}
@@ -38,6 +38,7 @@ export interface AnnotationCanvasProps {
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
onDrop: (id: string, geometry: Geometry) => void
onDeselect: () => void
onTraceKey: (event: KeyboardEvent) => void
}
@@ -133,14 +133,18 @@ export default function EditableAnnotations(props: Props) {
const placement = usePlacement({ ...scene, context })
const { ui, selected } = scene
const visible = usePlaceVisible()
const asideRef = useSelectionEscape(
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => scene.dispatch({ type: 'select', id: null }),
visible && selected !== undefined && ui.tracing === null && !ui.pending,
)
return (
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn scene={scene} placement={placement} />
<CanvasColumn
scene={scene}
placement={placement}
onDeselect={byDrawing}
/>
<aside ref={asideRef}>
<SidePanel scene={scene} context={context} />
</aside>
@@ -153,9 +157,11 @@ type Placement = ReturnType<typeof usePlacement>
function CanvasColumn({
scene,
placement,
onDeselect,
}: {
scene: Scene
placement: Placement
onDeselect: () => void
}) {
const { doc, ui, dispatch, model, selected } = scene
const noCategory = doc.categories.length === 0
@@ -175,7 +181,11 @@ function CanvasColumn({
navigate={scene.navigate}
/>
{selected && <TagOf annotation={selected} doc={doc} />}
<CanvasStage scene={scene} placement={placement} />
<CanvasStage
scene={scene}
placement={placement}
onDeselect={onDeselect}
/>
{ui.tracing && (
<TracingBar
count={ui.tracing.points.length}
@@ -211,9 +221,11 @@ function TagOf({
function CanvasStage({
scene,
placement,
onDeselect,
}: {
scene: Scene
placement: Placement
onDeselect: () => void
}) {
const locale = useLocaleStore((s) => s.locale)
// Hidden (the editor is read-only): no drag in flight survives, none is committed.
@@ -240,6 +252,7 @@ function CanvasStage({
onSelect={(id) => dispatch({ type: 'select', id })}
onPlace={placement.onPlace}
onDrop={placement.onDrop}
onDeselect={onDeselect}
onTraceKey={placement.onTraceKey}
/>
)
@@ -166,7 +166,7 @@ function ReadOnlyAnnotations({
const view = doc.views.find((v) => v.id === viewId)
const selected = model.annotations.find((a) => a.id === selectedId)
const visible = usePlaceVisible()
const asideRef = useSelectionEscape(
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => setSelectedId(null),
visible && selected !== undefined,
@@ -195,6 +195,7 @@ function ReadOnlyAnnotations({
viewName={view.name[locale]}
selectedId={selectedId}
onAnnotation={setSelectedId}
onEmpty={byDrawing}
/>
</div>
<aside ref={asideRef}>
+13 -6
View File
@@ -22,6 +22,11 @@ export function focusRowOrDrawing(id: string): boolean {
return focusRow({ kind: 'annotation', id }) || focusDrawing()
}
/** After a tap on the drawing: the box takes the focus, unless it already holds it. */
function drawingFocus(): void {
if (visibleElement(CANVAS_BOX) !== document.activeElement) focusDrawing()
}
/**
* Deselecting: `id` is the RESOLVED selection (never the raw id, which can name a removed
* annotation). The button always moves the focus to the row; Escape does only when it was
@@ -33,17 +38,18 @@ export function useDeselect(id: string | null, clear: () => void) {
const tRef = useRef(t)
tRef.current = t
const announce = useContext(AnnounceContext)
const run = (focus: boolean) => {
const run = (focus: ((id: string) => unknown) | null) => {
if (id === null) return false
commitFocusedField()
flushSync(clear)
if (focus) focusRowOrDrawing(id)
focus?.(id)
announce(tRef.current('editor.annotations.deselected'))
return true
}
return {
byButton: () => run(true),
byKey: (fromPanel: boolean) => run(fromPanel),
byButton: () => run(focusRowOrDrawing),
byKey: (fromPanel: boolean) => run(fromPanel ? focusRowOrDrawing : null),
byDrawing: () => run(drawingFocus),
}
}
@@ -82,7 +88,8 @@ export function useEscapeDeselect(
/**
* A body's Escape: deselects `id` while `active`. Returns the ref of the panel column, which
* tells a key pressed inside the panel (focus follows the row) from one pressed elsewhere.
* tells a key pressed inside the panel (focus follows the row) from one pressed elsewhere,
* and the tap-on-the-drawing deselect.
*/
export function useSelectionEscape(
id: string | null,
@@ -94,5 +101,5 @@ export function useSelectionEscape(
useEscapeDeselect(active, (event) =>
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
)
return asideRef
return { asideRef, byDrawing: deselect.byDrawing }
}
@@ -6,6 +6,7 @@ import type {
RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import { useEmptyTap } from '@/catalogue/useEmptyTap'
import { useFraming } from '@/catalogue/useFraming'
import type { XY } from './frame'
import { clientToDrawing } from './gesture'
@@ -23,15 +24,23 @@ export interface GestureInput {
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
onDrop: (id: string, geometry: Geometry) => void
/** A tap on the empty drawing with the select tool. */
onDeselect: () => 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>
type Tap = ReturnType<typeof useEmptyTap>
/** Each pointer handler of the framing and of the move gesture, one after the other. */
function composedPointer(framing: Framing, move: Move) {
function composedPointer(
framing: Framing,
move: Move,
tap: Tap,
input: GestureInput,
) {
const both =
(
name:
@@ -45,18 +54,38 @@ function composedPointer(framing: Framing, move: Move) {
move.handlers[name](event)
}
return {
onPointerDown: both('onPointerDown'),
onPointerMove: both('onPointerMove'),
onPointerUp: both('onPointerUp'),
onPointerCancel: both('onPointerCancel'),
onPointerDown: (event: PointerEvent) => {
both('onPointerDown')(event)
tap.onPointerDown(event)
},
onPointerMove: (event: PointerEvent) => {
both('onPointerMove')(event)
tap.onPointerMove(event)
},
onPointerUp: (event: PointerEvent) => {
both('onPointerUp')(event)
// Every press ends in a verdict, whatever the tool: it disarms the tracker.
if (tap.verdict(event, input.tool === 'select') === 'now')
input.onDeselect()
},
onPointerCancel: (event: PointerEvent) => {
both('onPointerCancel')(event)
tap.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) {
function clickHandler(input: GestureInput, framing: Framing, tap: Tap) {
return (event: MouseEvent) => {
if (framing.swallowClick()) return
const answer = tap.takeClick(event.target)
if (answer === 'swallow') return
if (answer === 'deselect') {
input.onDeselect()
return
}
if (input.tool === 'select') {
const id = annotationIdOf(event.target)
if (id) input.onSelect(id)
@@ -97,6 +126,7 @@ export function useCanvasGestures(input: GestureInput) {
const framing = useFraming(input.viewport, input.viewId, {
canPan: (event) => input.tool === 'select' && !move.claims(event),
})
const tap = useEmptyTap()
const onKeyDown = (event: KeyboardEvent) => {
framing.handlers.onKeyDown(event)
if (event.target === event.currentTarget) input.onTraceKey(event)
@@ -105,9 +135,10 @@ export function useCanvasGestures(input: GestureInput) {
framing,
drag: move.preview,
boxProps: {
...composedPointer(framing, move),
...composedPointer(framing, move, tap, input),
onContextMenu: tap.onPointerCancel,
onKeyDown,
onClick: clickHandler(input, framing),
onClick: clickHandler(input, framing, tap),
style: touchStyle(
input.tool,
move.armed,
@@ -1089,3 +1089,335 @@ describe('« Désélectionner » (R1, A6)', () => {
).toBeNull()
})
})
describe('a tap on the drawing (D6b)', () => {
const announce = vi.fn()
const DESELECTED = 'Aucune annotation sélectionnée.'
const drawing = (readOnly = false) =>
screen.getByTestId(
readOnly ? 'catalogue-canvas-drawing' : 'annotation-canvas-drawing',
)
const rect = (readOnly = false) => drawing(readOnly).querySelector('rect')!
const box = () => screen.getByTestId('annotation-canvas')
const snapshot = () => {
const state = store.getState()
return [
state.documentText,
state.handleVersion,
state.undo.length,
state.unsaved,
]
}
const init = (id = 1, type = 'mouse') => ({
pointerId: id,
isPrimary: true,
button: 0,
pointerType: type,
})
interface Tap {
dx?: number
upOn?: Element
type?: string
during?: () => void
}
/** pointerdown on `el`, an optional move, pointerup then click on `upOn`. */
function tap(el: Element, options: Tap = {}) {
const { dx = 0, upOn = el, type = 'mouse', during } = options
fireEvent.pointerDown(el, { ...init(1, type), clientX: 10, clientY: 10 })
if (dx !== 0) {
fireEvent.pointerMove(el, {
...init(1, type),
clientX: 10 + dx,
clientY: 10,
})
}
during?.()
fireEvent.pointerUp(upOn, {
...init(1, type),
clientX: 10 + dx,
clientY: 10,
})
fireEvent.click(upOn, { clientX: 10 + dx, clientY: 10 })
}
async function mountSpy(options: { text?: string; readOnly?: boolean } = {}) {
announce.mockReset()
await openReady({ text: options.text ?? text() })
const readOnly = options.readOnly ?? false
render(
<AnnounceContext value={announce}>
<AnnotationsTab {...props} readOnly={readOnly} />
</AnnounceContext>,
)
await waitFor(() =>
expect(drawing(readOnly).querySelector('svg')).not.toBeNull(),
)
}
const isDeselected = () =>
screen.queryByTestId('annotation-properties') === null
async function selected(options: { text?: string } = {}) {
await mountSpy(options)
await selectFromList()
}
it('deselects on the inner rect: focus on the box, announced, store unchanged', async () => {
await selected()
const before = snapshot()
tap(rect())
expect(isDeselected()).toBe(true)
expect(document.activeElement).toBe(box())
expect(announce).toHaveBeenCalledWith(DESELECTED)
expect(announce).toHaveBeenCalledTimes(1)
expect(snapshot()).toEqual(before)
})
it('deselects on the composed root svg and on the box margin', async () => {
await selected()
tap(drawing().querySelector('svg')!)
expect(isDeselected()).toBe(true)
await selectFromList()
tap(box())
expect(isDeselected()).toBe(true)
})
it('keeps the selection when the press began on the selected marker (click retargeted)', async () => {
await selected()
tap(marker('anno-a'), { upOn: box() })
expect(isDeselected()).toBe(false)
tap(marker('anno-a'), { dx: 2, upOn: box() })
expect(isDeselected()).toBe(false)
expect(announce).not.toHaveBeenCalled()
})
it('selects another marker and a zone polygon through the click', async () => {
const zone = zoneAnnotation({ type: 'polygon', points: triangle })
await selected({
text: insert(
insert(text(), { kind: 'annotation', value: zone }),
named('anno-b', 90, 90, 3),
),
})
tap(marker('anno-b'))
expect(screen.getByTestId('annotation-selection-tag')).toBeInTheDocument()
tap(marker('zone-a'))
expect(screen.getByTestId('annotation-selection-tag')).toHaveTextContent(
'zone',
)
expect(announce).not.toHaveBeenCalled()
})
it('keeps a pending keyboard creation with its typed name', async () => {
await mountSpy({ text: drawnText() })
const user = userEvent.setup()
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')
await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque')
tap(rect())
expect(screen.getByTestId('annotation-creation')).toBeInTheDocument()
expect(within(panel).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
})
it('tells a tap from a drag on the accumulated movement (4 px)', async () => {
await selected()
tap(rect(), { dx: 3 })
expect(isDeselected()).toBe(true)
await selectFromList()
tap(rect(), { dx: 6 })
expect(isDeselected()).toBe(false)
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerMove(rect(), { ...init(), clientX: 15, clientY: 10 })
fireEvent.pointerMove(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(false)
})
it('a second pointer, inside the box or not, makes it a gesture; the next tap deselects', async () => {
await selected()
tap(rect(), {
during: () =>
fireEvent.pointerDown(box(), {
pointerId: 2,
isPrimary: false,
button: 0,
pointerType: 'touch',
}),
})
expect(isDeselected()).toBe(false)
tap(rect(), {
during: () =>
fireEvent.pointerDown(document.body, {
pointerId: 2,
isPrimary: false,
button: 0,
pointerType: 'touch',
}),
})
expect(isDeselected()).toBe(false)
tap(rect())
expect(isDeselected()).toBe(true)
})
it('ignores a right-button press and a context menu during the press', async () => {
await selected()
fireEvent.pointerDown(rect(), { ...init(), button: 2 })
fireEvent.pointerUp(rect(), { ...init(), button: 2 })
fireEvent.click(rect())
expect(isDeselected()).toBe(false)
tap(rect(), { during: () => fireEvent.contextMenu(rect()) })
expect(isDeselected()).toBe(false)
})
it('removes its document listener once the press ends', async () => {
await selected()
const spy = vi.spyOn(document, 'removeEventListener')
tap(rect())
expect(spy).toHaveBeenCalledWith('pointerdown', expect.any(Function), true)
spy.mockRestore()
})
it('adds a vertex, selection kept, in a replace tracing', async () => {
const zone = zoneAnnotation({
type: 'path',
d: 'M 20 20 L 80 20 L 50 80 Z',
})
await mountSpy({
text: insert(drawnText(), { kind: 'annotation', value: zone }),
})
tap(marker('zone-a'))
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Remplacer par un polygone' }))
// The zone tool is active: the select-tool deselect never runs.
triangle.forEach(([x, y]) => {
fireEvent.pointerDown(box(), { ...init(), clientX: x, clientY: y })
fireEvent.pointerUp(box(), { ...init(), clientX: x, clientY: y })
fireEvent.click(box(), { clientX: x, clientY: y })
})
fireEvent.keyDown(box(), { key: 'Enter' })
await waitFor(() =>
expect(geometryOf('zone-a')).toEqual({
type: 'polygon',
points: triangle,
}),
)
expect(announce).not.toHaveBeenCalled()
})
it('a drag of the selected marker moves it and keeps the selection', async () => {
await selected()
const hit = marker('anno-a')
fireEvent.pointerDown(hit, { ...init(), clientX: 50, clientY: 50 })
fireEvent.pointerMove(hit, { ...init(), clientX: 58, clientY: 50 })
fireEvent.pointerUp(hit, { ...init(), clientX: 60, clientY: 40 })
fireEvent.click(box())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60, cy: 40 })
expect(isDeselected()).toBe(false)
})
it('a touch tap deselects in its own click, not at the pointer-up', async () => {
await selected()
const hit = rect()
fireEvent.pointerDown(hit, {
...init(1, 'touch'),
clientX: 10,
clientY: 10,
})
fireEvent.pointerUp(hit, { ...init(1, 'touch'), clientX: 10, clientY: 10 })
expect(isDeselected()).toBe(false)
fireEvent.click(hit)
expect(isDeselected()).toBe(true)
})
it('a touch tap whose click lands on a marker (adjustment) selects that marker', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { type: 'touch', upOn: marker('anno-b') })
expect(announce).not.toHaveBeenCalled()
expect(isDeselected()).toBe(false)
})
it('a mouse tap deselects at the pointer-up and swallows the click on a marker', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { upOn: rect() })
expect(isDeselected()).toBe(true)
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(marker('anno-b'))
expect(isDeselected()).toBe(true)
})
it('a press on a polygon vertex handle outside its fill deselects (documented)', async () => {
await mountSpy({
text: insert(drawnText(), {
kind: 'annotation',
value: zoneAnnotation({ type: 'polygon', points: triangle }),
}),
})
tap(marker('zone-a'))
const handle = screen
.getByTestId('annotation-overlay')
.querySelector('circle')!
tap(handle)
expect(isDeselected()).toBe(true)
})
it('read-only twin: deselects on the rect and focuses the catalogue canvas', async () => {
await mountSpy({ readOnly: true })
await selectFromList()
tap(rect(true))
expect(isDeselected()).toBe(true)
expect(document.activeElement).toBe(screen.getByTestId('catalogue-canvas'))
expect(announce).toHaveBeenCalledWith(DESELECTED)
})
it('undo after a tap deselect undoes the earlier edit, redo restores it', async () => {
await selected()
const user = userEvent.setup()
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60{Enter}')
tap(rect())
act(() => void store.getState().undoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
act(() => void store.getState().redoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
})
it('commits a typed valid value once and deselects when the press blurs the field', async () => {
await selected()
const user = userEvent.setup()
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60')
const depth = store.getState().undo.length
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
// What mousedown does: the focus moves to the box, the field commits, the drawing rebuilds.
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
expect(store.getState().undo.length).toBe(depth + 1)
expect(isDeselected()).toBe(true)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await selected({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const user = userEvent.setup()
const before = store.getState().documentText
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '1000000')
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(true)
expect(store.getState().documentText).toBe(before)
})
})
@@ -207,6 +207,20 @@ describe('/app/anatomy/:sheetId', () => {
expect(screen.queryByRole('link', { name: fr['catalogue.open_admin'] })).toBeNull()
})
it('keeps the zone panel when the empty drawing is tapped (reader: no deselect)', async () => {
mount(`/app/anatomy/${SHEET}`)
const canvas = await screen.findByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('[data-anno-id="thoracic"]')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="thoracic"]')!)
const empty = canvas.querySelector('svg')!
const init = { pointerId: 1, isPrimary: true, button: 0, pointerType: 'mouse' }
fireEvent.pointerDown(empty, init)
fireEvent.pointerUp(empty, init)
fireEvent.click(empty)
expect(screen.getByRole('heading', { name: 'Zone : Vertèbres thoraciques' })).toBeInTheDocument()
expect(canvas.querySelector('[data-anno-id="thoracic"]')).toHaveAttribute('data-state', 'current')
})
it('opens the detail view from its link on the drawing', async () => {
mount(`/app/anatomy/${SHEET}`)
const canvas = await screen.findByTestId('catalogue-canvas-drawing')