Files
faunosteo/apps/app/src/editor/annotations/usePressGesture.ts
T
bchanot b2d78f9621 fix(editor): one press is either a pan or a click
useFraming takes an optional panning gate read on each one-pointer move;
the editor passes the press machine's drag-with-pan phase, so a zoomed
pen within its 6 px slop or a mouse wiggle no longer pans and clicks.
Catalogue: no options, behaviour unchanged.

Test added: « a press is either a pan or a click, never both (R-8) »
(pen 5 px clicks without pan, pen 8 px pans without click, mouse wiggle
clicks without pan). No assertion removed.
2026-11-17 17:10:45 +01:00

324 lines
11 KiB
TypeScript

import { useEffect, useRef, type PointerEvent, type RefObject } from 'react'
import type { XY } from './frame'
import { clientToDrawing } from './gesture'
import {
clickAction,
dragAction,
isDoubleClick,
pointerKindOf,
pressTarget,
stepPress,
type ClickAction,
type HandleRef,
type Hit,
type LastClick,
type Press,
type PressEffect,
type PressEvent,
type PressTarget,
type Selection,
} from './press'
import type { ToolId } from './uiState'
import { annotationIdOf } from './useCanvasBuild'
import {
useBlockDrag,
type BlockDragInput,
type MoveTarget,
} from './useBlockDrag'
import { useAnnotationWork } from './workStore'
export interface PressInput extends BlockDragInput {
tool: ToolId
selectedId: string | null
viewport: RefObject<HTMLDivElement | null>
onSelect: (id: string) => void
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
/** A tap on the empty drawing with the select tool. */
onDeselect: () => void
}
const clientOf = (event: { clientX: number; clientY: number }): XY => ({
x: event.clientX,
y: event.clientY,
})
function centreOf(element: Element): XY {
const box = element.getBoundingClientRect()
return { x: box.left + box.width / 2, y: box.top + box.height / 2 }
}
/**
* One element under the press as a hit: a handle by its `data-handle`, else an annotation.
* Until the handle layer exists, the selected point's own marker stands for its handle.
*/
function hitOf(element: Element, pointId: string | null): Hit | null {
const handle = element.getAttribute('data-handle')
if (handle !== null) {
const ref = JSON.parse(handle) as HandleRef
return { kind: 'handle', handle: ref, centre: centreOf(element) }
}
const id = annotationIdOf(element)
if (id === null) return null
if (id !== pointId) return { kind: 'annotation', id }
const marker = element.closest('[data-anno-id]') ?? element
const centre = centreOf(marker)
return { kind: 'handle', handle: { kind: 'point' }, centre }
}
/** Everything under the client point inside the canvas box, top first. */
function hitsAt(
viewport: Element | null,
at: XY,
pointId: string | null,
): Hit[] {
if (!viewport) return []
return document
.elementsFromPoint(at.x, at.y)
.filter((element) => viewport.contains(element))
.flatMap((element) => hitOf(element, pointId) ?? [])
}
function selectionOf(selectedId: string | null): Selection {
const chosen = useAnnotationWork.getState().chosen
const own = selectedId !== null && chosen?.annotationId === selectedId
return { selectedId, chosenVertex: own ? chosen.vertex : null }
}
const pointIdOf = (target: MoveTarget | null) =>
target?.kind === 'point' ? target.id : null
const HANDLE_ACTIONS = new Set<ClickAction['type']>([
'choose_vertex',
'insert',
'remove',
'unchoose',
])
/** R-8: the second click of a double click opens; it never runs a handle action. */
function doubled(
action: ClickAction,
target: PressTarget,
sel: Selection,
): ClickAction {
if (!HANDLE_ACTIONS.has(action.type)) return action
const id = target.kind === 'interior' ? target.id : sel.selectedId
return id === null ? action : { type: 'open', id }
}
/**
* What a click does with the select tool. `open` (the properties dialog) and the vertex
* handles (`choose_vertex`, `insert`, `remove`) have nothing to act on yet.
*/
function runClick(action: ClickAction, input: PressInput): void {
if (action.type === 'select') input.onSelect(action.id)
else if (action.type === 'deselect') input.onDeselect()
else if (action.type === 'unchoose') {
useAnnotationWork.setState({ chosen: null })
}
}
interface Machine {
press: Press
/** The press's target, kept for the capture decision at pointer-down. */
target: PressTarget
/** The pointers pressed on the box; one pressed outside it is never counted (no release). */
pointers: Set<number>
pressedAt: XY
lastClick: LastClick | null
/** Removes the document listener of the press in flight. */
stop: (() => void) | null
}
interface Feed {
machine: RefObject<Machine>
input: PressInput
drag: ReturnType<typeof useBlockDrag>
}
/** A click with a drawing tool places at the pointer-up, in drawing units. */
function place(input: PressInput, event: PointerEvent): void {
const drawn = clientToDrawing(input.overlay.current, clientOf(event))
if (drawn) input.onPlace(drawn)
}
/** A click with the select tool: its action, or `open` as the second of a double click. */
function selectClick(f: Feed, target: PressTarget, event: PointerEvent): void {
const m = f.machine.current
const at = clientOf(event)
const sel = selectionOf(f.input.selectedId)
const double = isDoubleClick(m.lastClick, at, event.timeStamp)
m.lastClick = double ? null : { at, time: event.timeStamp }
const action = clickAction(target, sel)
runClick(double ? doubled(action, target, sel) : action, f.input)
}
function onClick(f: Feed, target: PressTarget, event: PointerEvent): void {
if (f.input.tool === 'select') selectClick(f, target, event)
else place(f.input, event)
}
const BLOCK_DRAGS = new Set(['drag_shape', 'drag_point'])
function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) {
if (effect?.type === 'drag_cancel') f.drag.cancel()
if (!event || !effect) return
if (effect.type === 'click') onClick(f, effect.target, event)
if (effect.type === 'drag_end') f.drag.drop(clientOf(event))
if (effect.type === 'drag_start' && BLOCK_DRAGS.has(effect.action.type)) {
f.drag.start(f.machine.current.pressedAt, clientOf(event))
}
}
/** One event through the machine and its effect; at idle the press is over. */
function feed(f: Feed, event: PressEvent, pointer: PointerEvent | null) {
const m = f.machine.current
const context = { movable: f.input.target !== null, moveMode: false }
const step = stepPress(m.press, event, context)
m.press = step.press
applyEffect(f, step.effect, pointer)
if (m.press.phase !== 'idle') return
m.pointers.clear()
m.stop?.()
m.stop = null
}
const pointerOf = (press: Press) =>
press.phase === 'down' || press.phase === 'drag' ? press.pointerId : null
/**
* A second finger can land outside the box: only the document sees it, and it makes the
* press a gesture. The same pointer pressing again means the press lost its release (it
* ended outside the box): it is cancelled.
*/
function watchOtherPointers(latest: RefObject<Feed>): () => void {
const other = (ev: Event) => {
const event = ev as globalThis.PointerEvent
const f = latest.current
const box = f.input.viewport.current
if (event.target instanceof Node && box?.contains(event.target)) return
if (pointerOf(f.machine.current.press) === event.pointerId) {
return feed(f, { type: 'cancel' }, null)
}
feed(f, outsideDown(event.pointerId, f.machine.current), null)
}
document.addEventListener('pointerdown', other, true)
return () => document.removeEventListener('pointerdown', other, true)
}
function outsideDown(pointerId: number, m: Machine): PressEvent {
const at = m.pressedAt
const pointers = m.pointers.size + 1
return {
type: 'down',
pointerId,
kind: 'touch',
at,
target: m.target,
pointers,
}
}
/** A new press: the first pointer, a primary one (the others are up), or the same again. */
function isFresh(m: Machine, event: PointerEvent): boolean {
const same = pointerOf(m.press) === event.pointerId
return m.press.phase === 'idle' || event.isPrimary || same
}
function startPress(latest: RefObject<Feed>, event: PointerEvent): void {
const f = latest.current
const m = f.machine.current
if (m.press.phase !== 'idle') feed(f, { type: 'cancel' }, null)
m.pressedAt = clientOf(event)
const kind = pointerKindOf(event.pointerType)
const context = { kind, movable: f.input.target !== null, moveMode: false }
// The drag of the selection keeps its pointer even past the box's edge.
if (BLOCK_DRAGS.has(dragAction(m.target, context).type)) {
event.currentTarget.setPointerCapture?.(event.pointerId)
}
m.stop = watchOtherPointers(latest)
}
/** The press's target: the selection's handles, then the topmost annotation. */
function targetAt(input: PressInput, at: XY): PressTarget {
const hits = hitsAt(input.viewport.current, at, pointIdOf(input.target))
return pressTarget(hits, at, selectionOf(input.selectedId))
}
function onPointerDown(latest: RefObject<Feed>, event: PointerEvent): void {
const m = latest.current.machine.current
const at = clientOf(event)
m.target = targetAt(latest.current.input, at)
if (event.button !== 0) return
if (isFresh(m, event)) startPress(latest, event)
m.pointers.add(event.pointerId)
const down: PressEvent = {
type: 'down',
pointerId: event.pointerId,
kind: pointerKindOf(event.pointerType),
at,
target: m.target,
pointers: m.pointers.size,
}
feed(latest.current, down, event)
}
function onPointerMove(f: Feed, event: PointerEvent): void {
// A hover (no button, no contact) is not part of the press.
if (event.buttons === 0) return
const m = f.machine.current
const dragging = m.press.phase === 'drag'
const at = clientOf(event)
feed(f, { type: 'move', pointerId: event.pointerId, at }, event)
if (dragging && pointerOf(m.press) === event.pointerId) f.drag.follow(at)
}
function onPointerUp(f: Feed, event: PointerEvent): void {
const m = f.machine.current
if (!m.pointers.delete(event.pointerId)) return
const pointers = m.pointers.size
feed(f, { type: 'up', pointerId: event.pointerId, pointers }, event)
}
const IDLE: Press = { phase: 'idle' }
/**
* The editor's one decider for the drawing (U2 R-8): every pointer event goes through the
* press machine, whose effects select, deselect, place with a drawing tool, or move the
* selection as a block. `panning()` gates the framing's one-pointer pan.
*/
export function usePressGesture(input: PressInput) {
const drag = useBlockDrag(input)
const machine = useRef<Machine>({
press: IDLE,
target: { kind: 'empty' },
pointers: new Set(),
pressedAt: { x: 0, y: 0 },
lastClick: null,
stop: null,
})
const latest = useRef<Feed>({ machine, input, drag })
latest.current = { machine, input, drag }
useEffect(() => {
const m = machine.current
return () => m.stop?.()
}, [])
const cancel = () => feed(latest.current, { type: 'cancel' }, null)
return {
preview: drag.preview,
panning: () => {
const press = machine.current.press
return press.phase === 'drag' && press.action.type === 'pan'
},
handlers: {
onPointerDown: (event: PointerEvent) => onPointerDown(latest, event),
onPointerMove: (event: PointerEvent) =>
onPointerMove(latest.current, event),
onPointerUp: (event: PointerEvent) => onPointerUp(latest.current, event),
onPointerCancel: cancel,
onLostPointerCapture: cancel,
onContextMenu: cancel,
},
}
}