refactor(editor): one press machine for clicks, drags and taps on the drawing

press.ts (pure: slop per pointer kind, nearest handle, press target, click
and drag actions, double click, stepPress) is now the editor canvas's only
decider; useCanvasGestures no longer uses clickHandler, useEmptyTap,
swallowClick nor useMoveGesture (deleted), and the box has no onClick.
canPan = dragAction(press target).type === 'pan' at pointer-down; framing
keys only when the box itself is the target. workStore.ts holds the U2
work with stale stamps: dropStale on every documentText change, reset on
a new session (editorStore subscription). The catalogue keeps useFraming
defaults and useEmptyTap, unchanged.

Named change (A13): a finger drag on a selected zone's (or circle link's)
interior moves nothing; the selected point is its own handle and still
moves by any pointer. Second observable change: touch and pen taps are
decided at the pointer-up from the press target, no longer from the
following click (no browser touch adjustment toward a marker).

tests/setup.ts: happy-dom has no elementsFromPoint; a shim answers the
pointerdown target and its ancestors.

Rewritten tests (editor-annotations-tab.test.tsx, D6b):
- "a touch tap deselects in its own click, not at the pointer-up" ->
  "a touch tap deselects at the pointer-up" (deselected after pointerup)
- "a touch tap whose click lands on a marker (adjustment) selects that
  marker" -> "a touch tap is decided by its press: a click adjusted toward
  a marker selects nothing" (deselected, announced, marker b not current)
- "a pen tap deselects in its own click, like a touch tap" -> "a pen tap
  deselects at the pointer-up, like a mouse tap"
- "a pen tap whose click lands on a marker selects that marker" -> "a pen
  tap is decided by its press: a click landing on a marker selects
  nothing"
Added: "a finger drags the selected point (its handle), never a selected
zone (A13)".
Drive-only changes, assertions unchanged: canvas fireEvent.click(x, y)
-> pressAt (pointerdown + pointerup) in the tab suite (C26, tracing,
paths, H3, H6, H8, filter reselect), editor-keep-alive and
editor-sections; drag moves carry buttons: 1 (C34, polygon block move,
H8 lostpointercapture and read-only, editor-no-loss drag in flight),
since a move without a button is a hover.
This commit is contained in:
bchanot committed 2026-11-17 16:56:35 +01:00
1 parent 5ca2b7e3ad
commit 08d266c89f
18 files changed
+1341 -311

No files matched your search

@@ -12,7 +12,7 @@ import {
useSelectionMark,
} from '@/editor/annotations/useCanvasBuild'
import { useCanvasGestures } from '@/editor/annotations/useCanvasGestures'
import type { MoveTarget } from '@/editor/annotations/useMoveGesture'
import type { MoveTarget } from '@/editor/annotations/useBlockDrag'
import type { ToolId } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
@@ -44,15 +44,20 @@ export interface AnnotationCanvasProps {
/**
* 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.
* same transformed box, the tool column beside it. Select and place work on a press
* released within the slop (the press machine, R-8); a drag past it moves the selection
* as a block: the selected point by any pointer, a shape's interior by mouse or pen (A13).
*/
export default function AnnotationCanvas(props: AnnotationCanvasProps) {
const overlay = useRef<SVGSVGElement | null>(null)
const viewport = useRef<HTMLDivElement | null>(null)
const build = useCanvasBuild(props.viewId)
const gestures = useCanvasGestures({ ...props, overlay, viewport })
const gestures = useCanvasGestures({
...props,
target: props.moveTarget,
overlay,
viewport,
})
useSelectionMark(build.host, props.selectedId, build.root)
useReportRoot(build.root, props.onRoot)
return (
@@ -326,7 +326,7 @@ function moveTargetOf(
) {
if (!selected || !model.measured || tool !== 'select') return null
return isEditable(selected.geometry)
? { id: selected.id, geometry: selected.geometry }
? { id: selected.id, kind: selected.kind, geometry: selected.geometry }
: null
}
@@ -1,13 +1,6 @@
import type { Geometry } from '@faunosteo/core-wasm/types'
import { round2, type XY } from './frame'
/** CSS px a press must travel before it is a drag (a click with jitter never moves). */
export const DRAG_START_PX = 4
export function pastDragThreshold(from: XY, to: XY): boolean {
return Math.hypot(to.x - from.x, to.y - from.y) > DRAG_START_PX
}
/** A circle or polygon translated as a block by a drawing-unit delta, rounded to 0.01. */
export function translatedGeometry(
geometry: Geometry,
+267
View File
@@ -0,0 +1,267 @@
import type { XY } from './frame'
export type PointerKind = 'mouse' | 'pen' | 'touch'
/** CSS px a press travels before it is a drag (R-8): a finger jitters more than a mouse. */
export const SLOP_PX: Readonly<Record<PointerKind, number>> = {
mouse: 4,
pen: 6,
touch: 10,
}
export const DOUBLE_MS = 400
export const DOUBLE_PX = 8
export function pointerKindOf(pointerType: string): PointerKind {
return pointerType === 'touch' || pointerType === 'pen'
? pointerType
: 'mouse'
}
const distance = (a: XY, b: XY) => Math.hypot(a.x - b.x, a.y - b.y)
export function pastSlop(kind: PointerKind, from: XY, to: XY): boolean {
return distance(from, to) > SLOP_PX[kind]
}
export type HandleRef =
| { kind: 'point' }
| { kind: 'vertex'; index: number }
| { kind: 'remove'; index: number }
| { kind: 'insert'; after: number }
/** One element under the press, top first (`elementsFromPoint`); handle centres in CSS px. */
export type Hit =
| { kind: 'handle'; handle: HandleRef; centre: XY }
| { kind: 'annotation'; id: string }
const RANK: Record<HandleRef['kind'], number> = {
point: 0,
vertex: 0,
remove: 1,
insert: 2,
}
/** R-9: the nearest handle; at equal distance a vertex, then « − », then « + ». */
export function nearestHandle(hits: readonly Hit[], at: XY): HandleRef | null {
let best: { handle: HandleRef; d: number } | null = null
for (const hit of hits) {
if (hit.kind !== 'handle') continue
const d = distance(hit.centre, at)
const better =
!best ||
d < best.d ||
(d === best.d && RANK[hit.handle.kind] < RANK[best.handle.kind])
if (better) best = { handle: hit.handle, d }
}
return best?.handle ?? null
}
export interface Selection {
selectedId: string | null
chosenVertex: number | null
}
export type PressTarget =
| { kind: 'handle'; handle: HandleRef }
| { kind: 'other'; id: string }
| { kind: 'interior'; id: string }
| { kind: 'empty' }
/**
* Board 32: the selection's handles, then the TOPMOST annotation (the visible wins), else
* nothing.
*/
export function pressTarget(
hits: readonly Hit[],
at: XY,
sel: Selection,
): PressTarget {
const handle = nearestHandle(hits, at)
if (handle) return { kind: 'handle', handle }
const top = hits.find((hit) => hit.kind === 'annotation')
if (top?.kind !== 'annotation') return { kind: 'empty' }
return top.id === sel.selectedId
? { kind: 'interior', id: top.id }
: { kind: 'other', id: top.id }
}
export type ClickAction =
| { type: 'choose_vertex'; index: number }
| { type: 'insert'; after: number }
| { type: 'remove'; index: number }
| { type: 'select'; id: string }
| { type: 'unchoose' }
| { type: 'open'; id: string }
| { type: 'deselect' }
/** A press released within the slop (A1): select first, open on the selection itself. */
export function clickAction(target: PressTarget, sel: Selection): ClickAction {
if (target.kind === 'other') return { type: 'select', id: target.id }
if (target.kind === 'empty') return { type: 'deselect' }
if (target.kind === 'interior') {
return sel.chosenVertex === null
? { type: 'open', id: target.id }
: { type: 'unchoose' }
}
const { handle } = target
if (handle.kind === 'vertex')
return { type: 'choose_vertex', index: handle.index }
if (handle.kind === 'insert') return { type: 'insert', after: handle.after }
if (handle.kind === 'remove') return { type: 'remove', index: handle.index }
return sel.selectedId
? { type: 'open', id: sel.selectedId }
: { type: 'deselect' }
}
/** R-8: the second of two clicks close in time and place opens; it never acts on a handle. */
export interface LastClick {
at: XY
time: number
}
export function isDoubleClick(
last: LastClick | null,
at: XY,
time: number,
): boolean {
return (
last !== null &&
time - last.time <= DOUBLE_MS &&
distance(last.at, at) <= DOUBLE_PX
)
}
export interface DragContext {
kind: PointerKind
/** The selection can move now (editable, measured, circle or polygon, under the cap). */
movable: boolean
/** « Déplacer … » is on: a drag anywhere moves its target (board 06 B). */
moveMode: boolean
}
export type DragAction =
| { type: 'drag_mode' }
| { type: 'drag_point' }
| { type: 'drag_vertex'; index: number }
| { type: 'drag_shape'; id: string }
| { type: 'pan' }
| { type: 'none'; futile: boolean }
/**
* A press past the slop: a finger moves only what it holds (A13); a mouse or pen drags the
* interior.
*/
export function dragAction(target: PressTarget, ctx: DragContext): DragAction {
if (ctx.moveMode) return { type: 'drag_mode' }
if (target.kind === 'handle') {
if (!ctx.movable) return { type: 'none', futile: false }
if (target.handle.kind === 'point') return { type: 'drag_point' }
if (target.handle.kind === 'vertex')
return { type: 'drag_vertex', index: target.handle.index }
return { type: 'none', futile: false }
}
if (ctx.kind === 'touch') return { type: 'none', futile: true }
if (target.kind === 'interior' && ctx.movable)
return { type: 'drag_shape', id: target.id }
return { type: 'pan' }
}
/** The press in flight: one pointer, or a multi-pointer gesture that never clicks nor commits. */
export type Press =
| { phase: 'idle' }
| {
phase: 'down'
pointerId: number
kind: PointerKind
start: XY
target: PressTarget
}
| { phase: 'drag'; pointerId: number; action: DragAction }
| { phase: 'multi' }
/** `pointers`: how many pointers are down after the event. */
export type PressEvent =
| {
type: 'down'
pointerId: number
kind: PointerKind
at: XY
target: PressTarget
pointers: number
}
| { type: 'move'; pointerId: number; at: XY }
| { type: 'up'; pointerId: number; pointers: number }
| { type: 'cancel' }
export type PressEffect =
| { type: 'click'; target: PressTarget }
| { type: 'drag_start'; action: DragAction }
| { type: 'drag_end' }
| { type: 'drag_cancel' }
| null
type Step = { press: Press; effect: PressEffect }
type MoveContext = Omit<DragContext, 'kind'>
const IDLE: Press = { phase: 'idle' }
/** A first pointer starts a press; any other turns it into a gesture that never clicks. */
function stepDown(
press: Press,
event: Extract<PressEvent, { type: 'down' }>,
): Step {
if (press.phase === 'idle' && event.pointers === 1) {
const { pointerId, kind, at, target } = event
return {
press: { phase: 'down', pointerId, kind, start: at, target },
effect: null,
}
}
return {
press: { phase: 'multi' },
effect: press.phase === 'drag' ? { type: 'drag_cancel' } : null,
}
}
function stepMove(
press: Press,
event: Extract<PressEvent, { type: 'move' }>,
ctx: MoveContext,
): Step {
if (press.phase !== 'down' || event.pointerId !== press.pointerId)
return { press, effect: null }
if (!pastSlop(press.kind, press.start, event.at))
return { press, effect: null }
const action = dragAction(press.target, { ...ctx, kind: press.kind })
return {
press: { phase: 'drag', pointerId: press.pointerId, action },
effect: { type: 'drag_start', action },
}
}
function stepUp(
press: Press,
event: Extract<PressEvent, { type: 'up' }>,
): Step {
if (press.phase === 'multi')
return { press: event.pointers === 0 ? IDLE : press, effect: null }
if (press.phase === 'down')
return { press: IDLE, effect: { type: 'click', target: press.target } }
if (press.phase === 'drag')
return { press: IDLE, effect: { type: 'drag_end' } }
return { press, effect: null }
}
export function stepPress(
press: Press,
event: PressEvent,
ctx: MoveContext,
): Step {
if (event.type === 'cancel') {
return {
press: IDLE,
effect: press.phase === 'drag' ? { type: 'drag_cancel' } : null,
}
}
if (event.type === 'down') return stepDown(press, event)
if (event.type === 'move') return stepMove(press, event, ctx)
return stepUp(press, event)
}
@@ -0,0 +1,81 @@
import { useEffect, useRef, useState, type RefObject } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import type { XY } from './frame'
import { clientToDrawing, translatedGeometry } from './gesture'
import type { EditableGeometry } from './geometryEdit'
export interface MoveTarget {
id: string
kind: Annotation['kind']
geometry: EditableGeometry
}
export interface BlockDragInput {
overlay: RefObject<SVGSVGElement | null>
/** The selected annotation, when it can be moved (editable, measured, circle or polygon). */
target: MoveTarget | null
/** One `update` on the drop; the verdict and the message are the caller's. */
onDrop: (id: string, geometry: Geometry) => void
}
interface Drag {
target: MoveTarget
/** The press point in drawing units: the block moves by the pointer's delta from it. */
origin: XY
}
function translatedAt(
overlay: BlockDragInput['overlay'],
drag: Drag,
client: XY,
): Geometry | null {
const now = clientToDrawing(overlay.current, client)
if (!now) return null
return translatedGeometry(drag.target.geometry, {
x: now.x - drag.origin.x,
y: now.y - drag.origin.y,
})
}
/** Losing the target (read-only, another selection) or a document change drops the drag. */
function useDropOnChange(target: MoveTarget | null, drop: () => void) {
const text = useEditorStore((s) => s.documentText)
const dropRef = useRef(drop)
dropRef.current = drop
const id = target?.id ?? null
useEffect(() => dropRef.current(), [id, text])
}
/**
* The selection moved as a block (`drag_shape`, `drag_point`): the overlay previews the
* translated outline, kept local to the canvas for speed; the drop commits once.
*/
export function useBlockDrag(input: BlockDragInput) {
const drag = useRef<Drag | null>(null)
const [preview, setPreview] = useState<Geometry | null>(null)
const cancel = () => {
drag.current = null
setPreview(null)
}
useDropOnChange(input.target, cancel)
const start = (pressedAt: XY, client: XY) => {
const origin = clientToDrawing(input.overlay.current, pressedAt)
if (!input.target || !origin) return
drag.current = { target: input.target, origin }
setPreview(translatedAt(input.overlay, drag.current, client))
}
const follow = (client: XY) => {
if (drag.current)
setPreview(translatedAt(input.overlay, drag.current, client))
}
const drop = (client: XY) => {
const gesture = drag.current
const dropped = gesture
? translatedAt(input.overlay, gesture, client)
: null
cancel()
if (gesture && dropped) input.onDrop(gesture.target.id, dropped)
}
return { preview, start, follow, drop, cancel }
}
@@ -1,46 +1,20 @@
import type {
CSSProperties,
KeyboardEvent,
MouseEvent,
PointerEvent,
RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import { useEmptyTap } from '@/catalogue/useEmptyTap'
import type { CSSProperties, KeyboardEvent, PointerEvent } from 'react'
import { useFraming } from '@/catalogue/useFraming'
import type { XY } from './frame'
import { clientToDrawing } from './gesture'
import { dragAction, pointerKindOf } from './press'
import type { ToolId } from './uiState'
import { annotationIdOf } from './useCanvasBuild'
import { useMoveGesture, type MoveTarget } from './useMoveGesture'
import { usePressGesture, type PressInput } from './usePressGesture'
export interface GestureInput {
export interface GestureInput extends PressInput {
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
/** 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>
type Press = ReturnType<typeof usePressGesture>
/** Each pointer handler of the framing and of the move gesture, one after the other. */
function composedPointer(
framing: Framing,
move: Move,
tap: Tap,
input: GestureInput,
) {
/** The press machine first (it decides the press's target), then the framing. */
function composedPointer(framing: Framing, press: Press) {
const both =
(
name:
@@ -50,100 +24,67 @@ function composedPointer(
| 'onPointerCancel',
) =>
(event: PointerEvent) => {
press.handlers[name](event)
framing.handlers[name](event)
move.handlers[name](event)
}
return {
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, 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)
return
}
const client = { x: event.clientX, y: event.clientY }
const at = clientToDrawing(input.overlay.current, client)
if (at) input.onPlace(at)
onPointerDown: both('onPointerDown'),
onPointerMove: both('onPointerMove'),
onPointerUp: both('onPointerUp'),
onPointerCancel: both('onPointerCancel'),
onLostPointerCapture: press.handlers.onLostPointerCapture,
onContextMenu: press.handlers.onContextMenu,
}
}
/**
* `touch-action: none` while a drawing tool, a drag, a zoom or a movable selection is
* active: the browser reads it at touchstart, so a touch drag of the selected marker
* would otherwise be taken as a pan and cancelled before the drag is armed.
* `touch-action: none` while a drawing tool, a zoom or a movable selection (a drag in
* flight implies one) is active: the browser reads it at touchstart, so a touch drag of
* the selected marker would otherwise be taken as a pan and cancelled before it starts.
*/
function touchStyle(
tool: ToolId,
armed: boolean,
scale: number,
movable: boolean,
): CSSProperties {
const none = tool !== 'select' || armed || scale !== 1 || movable
const none = tool !== 'select' || scale !== 1 || movable
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.
* Everything the canvas box listens to: zoom and pan, the press machine (click, drag,
* tap), and the keys. Keys only count when the box itself is the target: Enter on
* « Annuler le tracé » (or a list row) is that button's, never a close of the tracing, and
* an arrow on an element inside the box never pans the drawing.
*/
export function useCanvasGestures(input: GestureInput) {
const move = useMoveGesture({
overlay: input.overlay,
target: input.moveTarget,
onDrop: input.onDrop,
})
const press = usePressGesture(input)
const framing = useFraming(input.viewport, input.viewId, {
canPan: (event) => input.tool === 'select' && !move.claims(event),
// A one-pointer pan only where the press machine would pan (a mouse or pen off the
// movable selection), decided once at pointer-down.
canPan: (event) =>
input.tool === 'select' &&
dragAction(press.target(), {
kind: pointerKindOf(event.pointerType),
movable: input.target !== null,
moveMode: false,
}).type === 'pan',
})
const tap = useEmptyTap()
const onKeyDown = (event: KeyboardEvent) => {
if (event.target !== event.currentTarget) return
framing.handlers.onKeyDown(event)
if (event.target === event.currentTarget) input.onTraceKey(event)
input.onTraceKey(event)
}
return {
framing,
drag: move.preview,
drag: press.preview,
boxProps: {
...composedPointer(framing, move, tap, input),
onContextMenu: tap.onPointerCancel,
...composedPointer(framing, press),
onKeyDown,
onClick: clickHandler(input, framing, tap),
style: touchStyle(
input.tool,
move.armed,
framing.framing.scale,
input.moveTarget !== null,
input.target !== null,
),
},
}
@@ -1,128 +0,0 @@
import {
useEffect,
useRef,
useState,
type PointerEvent,
type RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import type { XY } from './frame'
import {
clientToDrawing,
pastDragThreshold,
translatedGeometry,
} from './gesture'
import type { EditableGeometry } from './geometryEdit'
import { annotationIdOf } from './useCanvasBuild'
export interface MoveTarget {
id: string
geometry: EditableGeometry
}
export interface MoveOptions {
overlay: RefObject<SVGSVGElement | null>
/** The selected annotation, when it can be moved (editable, measured, circle or polygon). */
target: MoveTarget | null
/** One `update` on pointer-up; the verdict and the message are the caller's. */
onDrop: (id: string, geometry: Geometry) => void
}
interface Drag {
start: XY
origin: XY
started: boolean
}
const clientOf = (event: PointerEvent): XY => ({
x: event.clientX,
y: event.clientY,
})
/** 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)
const stop = () => {
drag.current = null
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) stopRef.current()
}, [target])
return { drag, preview, setPreview, armed, setArmed, stop }
}
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
state.drag.current = { start: clientOf(event), origin, started: false }
event.currentTarget.setPointerCapture?.(event.pointerId)
state.setArmed(true)
}
const onPointerMove = (event: PointerEvent) => {
const gesture = state.drag.current
if (!gesture) return
if (!gesture.started && !pastDragThreshold(gesture.start, clientOf(event)))
return
gesture.started = true
state.setPreview(translatedAt(overlay, gesture, target, event))
}
const onPointerUp = (event: PointerEvent) => {
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 {
claims,
handlers: {
onPointerDown,
onPointerMove,
onPointerUp,
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 }
}
@@ -0,0 +1,310 @@
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, read by the framing's pan 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>
}
/** The click effect: a drawing tool places, the select tool selects or deselects. */
function onClick(f: Feed, target: PressTarget, event: PointerEvent): void {
const { input } = f
const at = clientOf(event)
if (input.tool !== 'select') {
const drawn = clientToDrawing(input.overlay.current, at)
if (drawn) input.onPlace(drawn)
return
}
const m = f.machine.current
const sel = selectionOf(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, input)
}
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)
}
function onPointerDown(latest: RefObject<Feed>, event: PointerEvent): void {
const f = latest.current
const m = f.machine.current
const at = clientOf(event)
const hits = hitsAt(f.input.viewport.current, at, pointIdOf(f.input.target))
m.target = pressTarget(hits, at, selectionOf(f.input.selectedId))
if (event.button !== 0) return
if (isFresh(m, event)) startPress(latest, event)
m.pointers.add(event.pointerId)
const { pointerId } = event
const kind = pointerKindOf(event.pointerType)
const pointers = m.pointers.size
feed(
f,
{ type: 'down', pointerId, kind, at, target: m.target, pointers },
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. `target()` is the press's target, for the framing's pan decision.
*/
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,
target: () => machine.current.target,
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,
},
}
}
@@ -0,0 +1,68 @@
import { create } from 'zustand'
import type { Geometry } from '@faunosteo/core-wasm/types'
import type { CreationForm, PendingElement } from './creation'
/** A geometry shown but not committed, stamped with the document text it was computed on. */
export interface Preview {
annotationId: string
geometry: Geometry
base: string
source: 'move' | 'size' | 'keys'
}
export interface Chosen {
annotationId: string
vertex: number
base: string
}
export interface Creation {
/** A new zone or link being traced lives here from its first vertex (`closed` false). */
pending: PendingElement
closed: boolean
form: CreationForm
/** The dialog is shown; false while the shape is replaced or the trace resumed. */
dialog: boolean
}
/** A move mode or a redraw; `started` once the position differs or a vertex is placed (R-12). */
export interface ModeWork {
kind: 'move' | 'redraw'
annotationId: string
started: boolean
}
interface Work {
creation: Creation | null
mode: ModeWork | null
preview: Preview | null
chosen: Chosen | null
}
const NO_WORK: Work = {
creation: null,
mode: null,
preview: null,
chosen: null,
}
export const useAnnotationWork = create<Work>(() => NO_WORK)
export type GuardWork = 'creation' | 'move' | 'redraw' | null
/** R-12: what a navigation must ask about; an unstarted mode asks nothing and simply ends. */
export function guardWork(work: Work): GuardWork {
if (work.creation !== null) return 'creation'
return work.mode?.started ? work.mode.kind : null
}
/** The end of a mode without a question (unstarted, or « Abandonner » answered). */
export function endMode(): void {
useAnnotationWork.setState({ mode: null, preview: null })
}
/** R-13: drop what was computed on another document text; the caller passes the current text. */
export function dropStale(text: string): void {
useAnnotationWork.setState((work) => ({
preview: work.preview && work.preview.base !== text ? null : work.preview,
chosen: work.chosen && work.chosen.base !== text ? null : work.chosen,
}))
}
/** Another sheet opened, or the editor closed: nothing of the previous one survives. */
export function resetWork(): void {
useAnnotationWork.setState(NO_WORK)
}
+9
View File
@@ -1,4 +1,5 @@
import { create } from 'zustand'
import { dropStale, resetWork } from '../annotations/workStore'
import { addDrawing, commit, commitBatch, stepHistory } from './editorEdit'
import { initialData } from './editorBase'
import { close, discardChanges, open, reloadServerDraft } from './editorLoad'
@@ -57,4 +58,12 @@ useEditorStore.subscribe((state, previous) => {
if (copyInputsChanged(state, previous)) syncCopy(storeApi)
})
// The annotation work follows the document: a new session (another sheet, the editor
// closed) drops it all; a document change drops what was computed on the old text (R-13).
useEditorStore.subscribe((state, previous) => {
if (state.session !== previous.session) resetWork()
else if (state.documentText !== previous.documentText)
dropStale(state.documentText)
})
export { canRedo, canUndo, leaveGuardArmed } from './editorBase'
+38 -5
View File
@@ -1,4 +1,5 @@
import { expect, vi } from 'vitest'
import { fireEvent } from '@testing-library/react'
import type { EditCommand } from '@faunosteo/core-wasm/types'
import * as supabase from '@faunosteo/supabase'
import { useEditorStore } from '@/editor/state/editorStore'
@@ -22,8 +23,14 @@ export function baseText(): string {
return insert(drawnText(), point('anno-a', 50, 50, 5))
}
export function versionAnswer(text: string, revision: number, withDrawing = true) {
const drawings = withDrawing ? [{ asset_id: ASSET, sha256: svgBytes().sha256 }] : []
export function versionAnswer(
text: string,
revision: number,
withDrawing = true,
) {
const drawings = withDrawing
? [{ asset_id: ASSET, sha256: svgBytes().sha256 }]
: []
return {
sheet_id: SHEET,
version_id: VERSION,
@@ -37,8 +44,14 @@ export function versionAnswer(text: string, revision: number, withDrawing = true
}
}
export function serverHas(text: string, revision: number, withDrawing = true): void {
sb.getSheetVersion.mockResolvedValue(versionAnswer(text, revision, withDrawing) as never)
export function serverHas(
text: string,
revision: number,
withDrawing = true,
): void {
sb.getSheetVersion.mockResolvedValue(
versionAnswer(text, revision, withDrawing) as never,
)
sb.downloadSheetDrawing.mockResolvedValue(svgBytes().bytes)
}
@@ -46,7 +59,9 @@ export async function openReady(
options: { text?: string; revision?: number; canEdit?: boolean } = {},
): Promise<number> {
serverHas(options.text ?? baseText(), options.revision ?? 3)
const token = store.getState().open(VERSION, USER, { canEdit: options.canEdit ?? true })
const token = store
.getState()
.open(VERSION, USER, { canEdit: options.canEdit ?? true })
await vi.waitFor(() => expect(store.getState().status).not.toBe('loading'))
return token
}
@@ -78,3 +93,21 @@ export function storedCopy(version = VERSION, user = USER) {
const raw = sessionStorage.getItem(copyKeyOf(version, user))
return raw === null ? null : JSON.parse(raw)
}
/**
* A mouse press released in place on `el`: the editor's click on the drawing (the press
* machine decides at the pointer-up; the box has no `click` listener).
*/
export function pressAt(el: Element, x = 0, y = 0): void {
const init = {
clientX: x,
clientY: y,
pointerId: 1,
isPrimary: true,
button: 0,
buttons: 1,
pointerType: 'mouse',
}
fireEvent.pointerDown(el, init)
fireEvent.pointerUp(el, { ...init, buttons: 0 })
}
+24
View File
@@ -4,3 +4,27 @@ import { testCoreRuntime } from './helpers/core'
// The application runs on the real core (R2): the shipped wasm build, loaded from disk.
setCoreRuntime(await testCoreRuntime())
// happy-dom has no hit testing: `elementsFromPoint` answers the element the pointerdown
// being dispatched targets, then its ancestors (top first, as a browser would), whatever
// the coordinates. The editor's press machine reads the press's target through it.
function stubHitTesting(doc: Document): void {
let pressed: Element | null = null
doc.addEventListener(
'pointerdown',
(event) => {
pressed = event.target instanceof Element ? event.target : null
},
true,
)
Object.defineProperty(doc, 'elementsFromPoint', {
configurable: true,
value: () => {
const chain: Element[] = []
for (let el = pressed; el; el = el.parentElement) chain.push(el)
return chain
},
})
}
// Node-environment suites have no document.
if (typeof document !== 'undefined') stubHitTesting(document)
@@ -0,0 +1,345 @@
/** U2 Task 2: the press machine, the editor's one decider for clicks, drags and taps. */
import { describe, expect, it } from 'vitest'
import {
clickAction,
dragAction,
isDoubleClick,
nearestHandle,
pressTarget,
stepPress,
type DragContext,
type Hit,
type Press,
type PressEvent,
type PressTarget,
type Selection,
} from '@/editor/annotations/press'
const NONE: Selection = { selectedId: null, chosenVertex: null }
const ZONE: Selection = { selectedId: 'zone', chosenVertex: null }
describe('nearestHandle (R-9)', () => {
it('takes the nearest of three overlapping hit circles (an 11 px segment)', () => {
const hits: Hit[] = [
{
kind: 'handle',
handle: { kind: 'vertex', index: 0 },
centre: { x: 0, y: 0 },
},
{
kind: 'handle',
handle: { kind: 'insert', after: 0 },
centre: { x: 5.5, y: 0 },
},
{
kind: 'handle',
handle: { kind: 'vertex', index: 1 },
centre: { x: 11, y: 0 },
},
]
expect(nearestHandle(hits, { x: 9, y: 0 })).toEqual({
kind: 'vertex',
index: 1,
})
expect(nearestHandle(hits, { x: 5, y: 1 })).toEqual({
kind: 'insert',
after: 0,
})
expect(nearestHandle(hits, { x: 1, y: 0 })).toEqual({
kind: 'vertex',
index: 0,
})
})
it('at a tie a vertex beats « − », which beats « + »', () => {
const at = { x: 0, y: 0 }
const remove: Hit = {
kind: 'handle',
handle: { kind: 'remove', index: 2 },
centre: { x: 3, y: 0 },
}
const insert: Hit = {
kind: 'handle',
handle: { kind: 'insert', after: 2 },
centre: { x: -3, y: 0 },
}
const vertex: Hit = {
kind: 'handle',
handle: { kind: 'vertex', index: 2 },
centre: { x: 0, y: 3 },
}
expect(nearestHandle([insert, remove, vertex], at)).toEqual(vertex.handle)
expect(nearestHandle([insert, remove], at)).toEqual(remove.handle)
expect(nearestHandle([remove, insert], at)).toEqual(remove.handle)
})
it('answers null without a handle', () => {
expect(
nearestHandle([{ kind: 'annotation', id: 'a' }], { x: 0, y: 0 }),
).toBeNull()
})
})
describe('pressTarget (board 32)', () => {
const at = { x: 0, y: 0 }
it('a selected zone hit first, a point hitbox under it: the interior', () => {
const hits: Hit[] = [
{ kind: 'annotation', id: 'zone' },
{ kind: 'annotation', id: 'point' },
]
expect(pressTarget(hits, at, ZONE)).toEqual({
kind: 'interior',
id: 'zone',
})
})
it('a point twin hit first, the selected zone under it: the other one', () => {
const hits: Hit[] = [
{ kind: 'annotation', id: 'point' },
{ kind: 'annotation', id: 'zone' },
]
expect(pressTarget(hits, at, ZONE)).toEqual({ kind: 'other', id: 'point' })
})
it('a handle wins over every annotation; nothing is empty', () => {
const hits: Hit[] = [
{ kind: 'annotation', id: 'point' },
{ kind: 'handle', handle: { kind: 'vertex', index: 1 }, centre: at },
]
expect(pressTarget(hits, at, ZONE)).toEqual({
kind: 'handle',
handle: { kind: 'vertex', index: 1 },
})
expect(pressTarget([], at, ZONE)).toEqual({ kind: 'empty' })
})
})
describe('clickAction (A1)', () => {
const handle = (h: PressTarget & { kind: 'handle' }) => h
it('selects another, deselects on empty', () => {
expect(clickAction({ kind: 'other', id: 'b' }, ZONE)).toEqual({
type: 'select',
id: 'b',
})
expect(clickAction({ kind: 'empty' }, ZONE)).toEqual({ type: 'deselect' })
})
it('the interior opens without a chosen vertex, unchooses with one', () => {
const interior: PressTarget = { kind: 'interior', id: 'zone' }
expect(clickAction(interior, ZONE)).toEqual({ type: 'open', id: 'zone' })
expect(clickAction(interior, { ...ZONE, chosenVertex: 2 })).toEqual({
type: 'unchoose',
})
})
it('maps each handle, and a point handle opens the selection', () => {
const on = (h: Parameters<typeof handle>[0]['handle']) =>
clickAction(handle({ kind: 'handle', handle: h }), ZONE)
expect(on({ kind: 'vertex', index: 3 })).toEqual({
type: 'choose_vertex',
index: 3,
})
expect(on({ kind: 'insert', after: 1 })).toEqual({
type: 'insert',
after: 1,
})
expect(on({ kind: 'remove', index: 2 })).toEqual({
type: 'remove',
index: 2,
})
expect(on({ kind: 'point' })).toEqual({ type: 'open', id: 'zone' })
expect(
clickAction({ kind: 'handle', handle: { kind: 'point' } }, NONE),
).toEqual({
type: 'deselect',
})
})
})
describe('isDoubleClick (R-8)', () => {
const last = { at: { x: 0, y: 0 }, time: 1000 }
it('holds within 400 ms and 8 px, edges included', () => {
expect(isDoubleClick(last, { x: 8, y: 0 }, 1400)).toBe(true)
expect(isDoubleClick(last, { x: 8.01, y: 0 }, 1400)).toBe(false)
expect(isDoubleClick(last, { x: 0, y: 0 }, 1400.5)).toBe(false)
expect(isDoubleClick(null, { x: 0, y: 0 }, 1000)).toBe(false)
})
})
describe('dragAction (A13)', () => {
const ctx = (over: Partial<DragContext> = {}): DragContext => ({
kind: 'mouse',
movable: true,
moveMode: false,
...over,
})
const interior: PressTarget = { kind: 'interior', id: 'zone' }
const point: PressTarget = { kind: 'handle', handle: { kind: 'point' } }
it('a move mode drags whatever the target or the pointer', () => {
for (const kind of ['mouse', 'pen', 'touch'] as const) {
for (const target of [
interior,
point,
{ kind: 'empty' } as PressTarget,
]) {
expect(dragAction(target, ctx({ kind, moveMode: true }))).toEqual({
type: 'drag_mode',
})
}
}
})
it('a finger moves only what it holds: off a handle it is futile', () => {
const touch = ctx({ kind: 'touch' })
expect(dragAction(point, touch)).toEqual({ type: 'drag_point' })
expect(
dragAction(
{ kind: 'handle', handle: { kind: 'vertex', index: 4 } },
touch,
),
).toEqual({
type: 'drag_vertex',
index: 4,
})
expect(dragAction(interior, touch)).toEqual({ type: 'none', futile: true })
expect(dragAction({ kind: 'empty' }, touch)).toEqual({
type: 'none',
futile: true,
})
})
it('a mouse or pen drags the movable interior, pans otherwise', () => {
expect(dragAction(interior, ctx())).toEqual({
type: 'drag_shape',
id: 'zone',
})
expect(dragAction(interior, ctx({ kind: 'pen' }))).toEqual({
type: 'drag_shape',
id: 'zone',
})
expect(dragAction(interior, ctx({ movable: false }))).toEqual({
type: 'pan',
})
expect(dragAction({ kind: 'other', id: 'b' }, ctx())).toEqual({
type: 'pan',
})
expect(dragAction({ kind: 'empty' }, ctx())).toEqual({ type: 'pan' })
})
it('« + » and « − » never drag; an unmovable handle moves nothing', () => {
for (const kind of ['mouse', 'touch'] as const) {
expect(
dragAction(
{ kind: 'handle', handle: { kind: 'insert', after: 0 } },
ctx({ kind }),
),
).toEqual({ type: 'none', futile: false })
expect(
dragAction(
{ kind: 'handle', handle: { kind: 'remove', index: 0 } },
ctx({ kind }),
),
).toEqual({ type: 'none', futile: false })
}
expect(dragAction(point, ctx({ movable: false }))).toEqual({
type: 'none',
futile: false,
})
})
})
describe('stepPress (R-8)', () => {
const ctx = { movable: true, moveMode: false }
const target: PressTarget = { kind: 'interior', id: 'zone' }
const down = (
pointerId: number,
pointers: number,
kind = 'mouse' as const,
): PressEvent => ({
type: 'down',
pointerId,
kind,
at: { x: 0, y: 0 },
target,
pointers,
})
const move = (pointerId: number, x: number): PressEvent => ({
type: 'move',
pointerId,
at: { x, y: 0 },
})
const up = (pointerId: number, pointers: number): PressEvent => ({
type: 'up',
pointerId,
pointers,
})
/** Runs the events from idle; answers the effects and the last press. */
function run(events: PressEvent[]) {
let press: Press = { phase: 'idle' }
const effects = events.map((event) => {
const step = stepPress(press, event, ctx)
press = step.press
return step.effect
})
return { press, effects }
}
it('a single press within the slop is a click', () => {
const { press, effects } = run([down(1, 1), move(1, 4), up(1, 0)])
expect(effects).toEqual([null, null, { type: 'click', target }])
expect(press).toEqual({ phase: 'idle' })
})
it('past the slop it starts a drag, then ends it', () => {
const action = { type: 'drag_shape', id: 'zone' }
const { press, effects } = run([
down(1, 1),
move(1, 5),
move(1, 30),
up(1, 0),
])
expect(effects).toEqual([
null,
{ type: 'drag_start', action },
null,
{ type: 'drag_end' },
])
expect(press).toEqual({ phase: 'idle' })
})
it('the slop follows the pointer kind', () => {
const finger = run([down(1, 1, 'touch' as never), move(1, 10), up(1, 0)])
expect(finger.effects[2]).toEqual({ type: 'click', target })
})
it('a second down while down is a gesture: no click on any up, idle at zero pointers', () => {
const { press, effects } = run([down(1, 1), down(2, 2), up(1, 1), up(2, 0)])
expect(effects).toEqual([null, null, null, null])
expect(press).toEqual({ phase: 'idle' })
const held = run([down(1, 1), down(2, 2), up(2, 1)])
expect(held.press).toEqual({ phase: 'multi' })
})
it('a second down while dragging cancels the drag', () => {
const { press, effects } = run([down(1, 1), move(1, 20), down(2, 2)])
expect(effects[2]).toEqual({ type: 'drag_cancel' })
expect(press).toEqual({ phase: 'multi' })
})
it('cancel while dragging cancels the drag; while down it is silent', () => {
expect(
run([down(1, 1), move(1, 20), { type: 'cancel' }]).effects[2],
).toEqual({
type: 'drag_cancel',
})
const quiet = run([down(1, 1), { type: 'cancel' }, up(1, 0)])
expect(quiet.effects).toEqual([null, null, null])
})
it('ignores a move from another pointer id', () => {
const { press, effects } = run([down(1, 1), move(2, 50), up(1, 0)])
expect(effects).toEqual([null, null, { type: 'click', target }])
expect(press).toEqual({ phase: 'idle' })
})
})
@@ -0,0 +1,52 @@
/** U2 Task 2: the annotation work store and its stale stamp (R-13). */
import { afterEach, describe, expect, it } from 'vitest'
import {
dropStale,
resetWork,
useAnnotationWork,
type Preview,
} from '@/editor/annotations/workStore'
import { useEditorStore } from '@/editor/state/editorStore'
const preview = (base: string): Preview => ({
annotationId: 'a',
geometry: { type: 'circle', cx: 1, cy: 2, r: 3 },
base,
source: 'move',
})
afterEach(() => {
resetWork()
useEditorStore.setState({ documentText: '', session: 0 })
})
describe('dropStale (R-13)', () => {
it('drops what was computed on another text, keeps what was computed on this one', () => {
useAnnotationWork.setState({
preview: preview('one'),
chosen: { annotationId: 'a', vertex: 1, base: 'one' },
})
dropStale('one')
expect(useAnnotationWork.getState().preview).toEqual(preview('one'))
expect(useAnnotationWork.getState().chosen).not.toBeNull()
dropStale('two')
expect(useAnnotationWork.getState().preview).toBeNull()
expect(useAnnotationWork.getState().chosen).toBeNull()
})
it('runs on every document change of the editor store', () => {
useAnnotationWork.setState({ preview: preview('one') })
useEditorStore.setState({ documentText: 'one' })
expect(useAnnotationWork.getState().preview).not.toBeNull()
useEditorStore.setState({ documentText: 'two' })
expect(useAnnotationWork.getState().preview).toBeNull()
})
it('a new session (another sheet, the editor closed) resets the work', () => {
useAnnotationWork.setState({
mode: { kind: 'move', annotationId: 'a', started: true },
})
useEditorStore.setState({ session: useEditorStore.getState().session + 1 })
expect(useAnnotationWork.getState().mode).toBeNull()
})
})
@@ -27,6 +27,7 @@ import {
commitMove,
openReady,
resetStore,
pressAt,
sb,
store,
versionAnswer,
@@ -274,10 +275,7 @@ describe('the point tool and the corrected position (C26)', () => {
async function clickCorner() {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 0,
clientY: 0,
})
pressAt(screen.getByTestId('annotation-canvas'), 0, 0)
return user
}
@@ -351,10 +349,7 @@ describe('the point tool and the corrected position (C26)', () => {
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: -5,
clientY: 50,
})
pressAt(screen.getByTestId('annotation-canvas'), -5, 50)
expect(
await screen.findByText("Cliquez à l'intérieur du dessin."),
).toBeInTheDocument()
@@ -379,7 +374,12 @@ describe('select and move gestures (C34)', () => {
pointerId: 1,
})
const moveTo = (el: Element, x: number, y: number) =>
fireEvent.pointerMove(el, { clientX: x, clientY: y, pointerId: 1 })
fireEvent.pointerMove(el, {
clientX: x,
clientY: y,
pointerId: 1,
buttons: 1,
})
const up = (el: Element, x: number, y: number) =>
fireEvent.pointerUp(el, { clientX: x, clientY: y, pointerId: 1 })
@@ -555,10 +555,7 @@ const zoneAnnotation = (geometry: object): Annotation =>
describe('tracing a zone or a link', () => {
const clickAt = (x: number, y: number) =>
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: x,
clientY: y,
})
pressAt(screen.getByTestId('annotation-canvas'), x, y)
it('closes on Enter, holds the polygon pending, inserts it on « Créer »', async () => {
await mount({ text: drawnText() })
@@ -689,7 +686,12 @@ describe('polygons and paths', () => {
button: 0,
pointerId: 1,
})
fireEvent.pointerMove(hit, { clientX: 55, clientY: 40, pointerId: 1 })
fireEvent.pointerMove(hit, {
clientX: 55,
clientY: 40,
pointerId: 1,
buttons: 1,
})
fireEvent.pointerUp(hit, { clientX: 60, clientY: 45, pointerId: 1 })
expect(geometryOf('zone-a')).toMatchObject({
points: [
@@ -712,9 +714,7 @@ describe('polygons and paths', () => {
}),
)
const canvas = screen.getByTestId('annotation-canvas')
triangle.forEach(([x, y]) =>
fireEvent.click(canvas, { clientX: x, clientY: y }),
)
triangle.forEach(([x, y]) => pressAt(canvas, x, y))
fireEvent.keyDown(canvas, { key: 'Enter' })
await waitFor(() =>
expect(geometryOf('zone-a')).toEqual({
@@ -727,10 +727,7 @@ describe('polygons and paths', () => {
describe('keys while tracing (H3)', () => {
const clickAt = (x: number, y: number) =>
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: x,
clientY: y,
})
pressAt(screen.getByTestId('annotation-canvas'), x, y)
async function traced() {
await mount({ text: drawnText() })
@@ -774,15 +771,9 @@ describe('a second click with the point tool (H6)', () => {
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 50,
clientY: 50,
})
pressAt(screen.getByTestId('annotation-canvas'), 50, 50)
const panel = await fillCreation(user)
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 60,
clientY: 40,
})
pressAt(screen.getByTestId('annotation-canvas'), 60, 40)
await waitFor(() =>
expect(within(panel).getByLabelText('Centre x')).toHaveValue('60'),
)
@@ -867,7 +858,7 @@ describe('refusals through the tab (H8)', () => {
[20, 20],
[500, 20],
[50, 80],
].forEach(([x, y]) => fireEvent.click(canvas, { clientX: x, clientY: y }))
].forEach(([x, y]) => pressAt(canvas, x, y))
fireEvent.keyDown(canvas, { key: 'Enter' })
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(
@@ -917,7 +908,12 @@ describe('the drag and the canvas follow the handle (H8)', () => {
const hit = marker('anno-a')
const version = store.getState().handleVersion
down(hit, 50, 50)
fireEvent.pointerMove(hit, { clientX: 70, clientY: 50, pointerId: 1 })
fireEvent.pointerMove(hit, {
clientX: 70,
clientY: 50,
pointerId: 1,
buttons: 1,
})
fireEvent.lostPointerCapture(hit, { pointerId: 1 })
fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 })
expect(store.getState().handleVersion).toBe(version)
@@ -935,7 +931,12 @@ describe('the drag and the canvas follow the handle (H8)', () => {
const hit = marker('anno-a')
const version = store.getState().handleVersion
down(hit, 50, 50)
fireEvent.pointerMove(hit, { clientX: 70, clientY: 50, pointerId: 1 })
fireEvent.pointerMove(hit, {
clientX: 70,
clientY: 50,
pointerId: 1,
buttons: 1,
})
view.rerender(<AnnotationsTab {...props} readOnly />)
fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 })
expect(store.getState().handleVersion).toBe(version)
@@ -1009,10 +1010,10 @@ describe('« Désélectionner » (R1, A6)', () => {
await userEvent.setup().click(button(panel))
const filter = screen.getByLabelText('Filtrer par nom')
fireEvent.change(filter, { target: { value: 'zzz-no-match' } })
fireEvent.click(
screen.getByTestId('annotation-canvas-drawing').querySelector(
'[data-anno-id="anno-a"]',
)!,
pressAt(
screen
.getByTestId('annotation-canvas-drawing')
.querySelector('[data-anno-id="anno-a"]')!,
)
const reopened = await screen.findByTestId('annotation-properties')
await userEvent.setup().click(button(reopened))
@@ -1035,7 +1036,9 @@ describe('« Désélectionner » (R1, A6)', () => {
it('read-only: no « Supprimer », it deselects and focuses the ro- row', async () => {
await mountSpy({ readOnly: true })
const panel = await selectFromList()
expect(within(panel).queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(
within(panel).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
await userEvent.setup().click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
const row = document.querySelector(
@@ -1089,9 +1092,13 @@ describe('« Désélectionner » (R1, A6)', () => {
}),
})
const panel = await selectFromList()
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 open = await screen.findByTestId('annotation-properties')
expect(
within(open).queryByRole('button', { name: 'Désélectionner' }),
@@ -1275,23 +1282,21 @@ describe('a tap on the drawing (D6b)', () => {
expect(fireEvent.keyDown(canvas, { key: 'ArrowLeft' })).toBe(false)
})
it('a pen tap deselects in its own click, like a touch tap', async () => {
it('a pen tap deselects at the pointer-up, like a mouse tap', async () => {
await selected()
const hit = rect()
fireEvent.pointerDown(hit, { ...init(1, 'pen'), clientX: 10, clientY: 10 })
fireEvent.pointerUp(hit, { ...init(1, 'pen'), clientX: 10, clientY: 10 })
expect(isDeselected()).toBe(false)
fireEvent.click(hit)
expect(isDeselected()).toBe(true)
expect(announce).toHaveBeenCalledWith(DESELECTED)
})
it('a pen tap whose click lands on a marker selects that marker', async () => {
it('a pen tap is decided by its press: a click landing on a marker selects nothing', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { type: 'pen', upOn: marker('anno-b') })
expect(announce).not.toHaveBeenCalled()
expect(marker('anno-b')).toHaveAttribute('data-state', 'current')
expect(marker('anno-a')).not.toHaveAttribute('data-state')
expect(announce).toHaveBeenCalledWith(DESELECTED)
expect(marker('anno-b')).not.toHaveAttribute('data-state')
expect(isDeselected()).toBe(true)
})
it('a hover move after the press does not count as a drag', async () => {
@@ -1312,7 +1317,11 @@ describe('a tap on the drawing (D6b)', () => {
await selected()
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerUp(document.body, { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerDown(document.body, { ...init(), clientX: 300, clientY: 10 })
fireEvent.pointerDown(document.body, {
...init(),
clientX: 300,
clientY: 10,
})
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(false)
@@ -1432,7 +1441,7 @@ describe('a tap on the drawing (D6b)', () => {
expect(isDeselected()).toBe(false)
})
it('a touch tap deselects in its own click, not at the pointer-up', async () => {
it('a touch tap deselects at the pointer-up', async () => {
await selected()
const hit = rect()
fireEvent.pointerDown(hit, {
@@ -1441,18 +1450,42 @@ describe('a tap on the drawing (D6b)', () => {
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 () => {
it('a touch tap is decided by its press: a click adjusted toward a marker selects nothing', 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(announce).toHaveBeenCalledWith(DESELECTED)
expect(isDeselected()).toBe(true)
expect(marker('anno-b')).not.toHaveAttribute('data-state')
})
it('a finger drags the selected point (its handle), never a selected zone (A13)', async () => {
const zone = zoneAnnotation({ type: 'polygon', points: triangle })
await selected({
text: insert(text(), { kind: 'annotation', value: zone }),
})
const drag = (el: Element) => {
fireEvent.pointerDown(el, {
...init(1, 'touch'),
clientX: 50,
clientY: 50,
})
fireEvent.pointerMove(el, {
...init(1, 'touch'),
clientX: 70,
clientY: 50,
})
fireEvent.pointerUp(el, { ...init(1, 'touch'), clientX: 70, clientY: 40 })
}
drag(marker('anno-a'))
expect(geometryOf('anno-a')).toMatchObject({ cx: 70, cy: 40 })
tap(marker('zone-a'))
const before = store.getState().documentText
drag(marker('zone-a'))
expect(store.getState().documentText).toBe(before)
expect(isDeselected()).toBe(false)
expect(marker('anno-b')).toHaveAttribute('data-state', 'current')
expect(marker('anno-a')).not.toHaveAttribute('data-state')
})
it('a mouse tap deselects at the pointer-up and swallows the click on a marker', async () => {
@@ -33,6 +33,7 @@ import {
serverHas,
store,
versionAnswer,
pressAt,
} from '../helpers/editorHarness'
import { testLayer } from '../helpers/findingsHost'
import { mountDraft, setWidth } from '../helpers/editorRoute'
@@ -500,10 +501,7 @@ describe('« Aller à » while a creation or a tracing is in progress', () => {
await user.click(
inPlace('annotations.drawing').getByRole('button', { name: 'Zone' }),
)
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 20,
clientY: 20,
})
pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
})
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
const bar = within(place('annotations.drawing')).getByTestId('tracing-bar')
+6 -1
View File
@@ -348,7 +348,12 @@ describe('the guards of a width change', () => {
button: 0,
pointerId: 1,
})
fireEvent.pointerMove(marker(), { clientX: 70, clientY: 50, pointerId: 1 })
fireEvent.pointerMove(marker(), {
clientX: 70,
clientY: 50,
pointerId: 1,
buttons: 1,
})
const version = store.getState().handleVersion
cross(800)
cross(1280)
+3 -9
View File
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
@@ -25,6 +24,7 @@ import {
resetStore,
serverHas,
store,
pressAt,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
@@ -227,10 +227,7 @@ describe('the shown view disappears (undo)', () => {
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Zone' }))
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 20,
clientY: 30,
})
pressAt(screen.getByTestId('annotation-canvas'), 20, 30)
expect(screen.getByTestId('tracing-bar')).toBeInTheDocument()
act(() => void store.getState().undoStep())
await waitFor(() => expect(screen.queryByTestId('tracing-bar')).toBeNull())
@@ -277,10 +274,7 @@ describe('« Aller à » an annotation while something is in progress', () => {
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Zone' }))
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 20,
clientY: 20,
})
pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
})
await waitFor(() => expect(consumed).toHaveBeenCalledWith(7, 'kept'))
expect(document.activeElement).toBe(screen.getByTestId('tracing-bar'))