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,