refactor(editor): tighten frame drag and cover its release

This commit is contained in:
bchanot committed 2026-11-23 13:42:31 +01:00
1 parent 64356e4b2c
commit e70d921ace
6 files changed
+166 -45

No files matched your search

@@ -207,7 +207,7 @@ function CanvasBox({
layer: Omit<LayerProps, 'host' | 'root' | 'detail'>
}) {
const root = build.root?.viewId === viewId ? build.root : null
const framed = useAnnotationWork((s) => s.frame !== null)
const framed = useAnnotationWork((s) => s.frame?.drawnOn === viewId)
const drawingFrame = useAnnotationWork(
(s) => s.frame?.drawnOn === viewId && s.frame.box === null,
)
+5 -7
View File
@@ -42,18 +42,16 @@ export function visibleDrawing(surface: FrameSurface, bounds: Frame): Frame {
return visible.w > 0 && visible.h > 0 ? visible : bounds
}
/** D4: the default frame centred on `at`. */
export function defaultAt(surface: FrameSurface, at: XY): Frame | null {
const bounds = parentFrame(surface.overlay.current)
if (!bounds) return null
/** D4: the default frame centred on `at`, in `bounds`. */
export function defaultAt(surface: FrameSurface, at: XY, bounds: Frame): Frame {
const visible = visibleDrawing(surface, bounds)
return defaultBox(at, visible, AREA_RATIO, bounds)
}
/** A click while drawing: the default frame where it fell. */
export function placeDefault(surface: FrameSurface, at: XY): void {
const box = defaultAt(surface, at)
if (box) setFrameBox(box)
const bounds = parentFrame(surface.overlay.current)
if (bounds) setFrameBox(defaultAt(surface, at, bounds))
}
/** The keyboard's placement: the default frame at the visible centre; false when unmeasured. */
@@ -62,6 +60,6 @@ export function placeAtCentre(surface: FrameSurface): boolean {
if (!bounds) return false
const visible = visibleDrawing(surface, bounds)
const at = { x: visible.x + visible.w / 2, y: visible.y + visible.h / 2 }
placeDefault(surface, at)
setFrameBox(defaultBox(at, visible, AREA_RATIO, bounds))
return true
}
@@ -70,7 +70,7 @@ export function useCanvasGestures(input: GestureInput) {
// R-1: a two-finger pan or zoom that worked; the visit never shows the hint again.
onPinch: markTwoFingers,
})
const framed = useAnnotationWork((s) => s.frame !== null)
const framed = useAnnotationWork((s) => s.frame?.drawnOn === input.viewId)
const onKeyDown = (event: KeyboardEvent) => {
if (event.target !== event.currentTarget) return
if (event.key === 'Enter' && framePhase(input.viewId) === 'draw') {
+51 -32
View File
@@ -11,6 +11,7 @@ import {
import { defaultAt, parentFrame, type FrameSurface } from './frameDraw'
import { setFrameBox } from './frameWork'
import { clientToDrawing, drawingPerClientPx } from './gesture'
import type { FramePart } from './frameBox'
import type { DragAction, PointerKind } from './press'
import { useAnnotationWork } from './workStore'
@@ -19,17 +20,17 @@ export type FrameDragAction = Extract<
{ type: 'draw' | 'drag_frame' }
>
interface Gesture {
action: FrameDragAction
interface Base {
/** The press point in drawing units. */
origin: XY
/** The box a `drag_frame` began with. */
start: Frame | null
bounds: Frame
/** Drawing units per CSS px: D6's minimum side is in screen px. */
perPx: number
kind: PointerKind
}
type Gesture =
| (Base & { type: 'draw' })
| (Base & { type: 'drag_frame'; part: FramePart; start: Frame })
function begin(
surface: FrameSurface,
@@ -41,23 +42,25 @@ function begin(
const origin = clientToDrawing(svg, pressedAt)
const bounds = parentFrame(svg)
const perPx = drawingPerClientPx(svg)
const start = useAnnotationWork.getState().frame?.box ?? null
if (!origin || !bounds || perPx === null) return null
if (action.type === 'drag_frame' && !start) return null
return { action, origin, start, bounds, perPx, kind }
const base = { origin, bounds, perPx, kind }
if (action.type === 'draw') return { ...base, type: 'draw' }
const start = useAnnotationWork.getState().frame?.box
return start
? { ...base, type: 'drag_frame', part: action.part, start }
: null
}
const minOf = (g: Gesture) => MIN_FRAME_PX[g.kind] * g.perPx
/** The box the gesture shows when the pointer is at `now`. */
function boxAt(g: Gesture, now: XY, shift: boolean): Frame {
if (g.action.type === 'draw') {
if (g.type === 'draw') {
const corners = boxFromCorners(g.origin, now)
return intersection(corners, g.bounds) ?? corners
}
const start = g.start!
const { start, part } = g
const delta = { x: now.x - g.origin.x, y: now.y - g.origin.y }
const { part } = g.action
if (part === 'body') return moveBox(start, delta, g.bounds)
const keepRatio = useAnnotationWork.getState().frame?.keepRatio ?? false
return resizeBox({
@@ -76,14 +79,34 @@ function droppedBox(
surface: FrameSurface,
now: XY,
shift: boolean,
) {
if (g.action.type === 'drag_frame') return boxAt(g, now, shift)
const fallback = () => defaultAt(surface, g.origin) ?? g.bounds
): Frame {
if (g.type === 'drag_frame') return boxAt(g, now, shift)
const fallback = () => defaultAt(surface, g.origin, g.bounds)
return drawnBox(g.origin, now, minOf(g), g.bounds, fallback)
}
const same = (a: Frame, b: Frame | null) =>
b !== null && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h
const same = (a: Frame, b: Frame) =>
a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h
/** A drop that moved nothing leaves the work as it was. */
const unchanged = (g: Gesture, box: Frame) =>
g.type === 'drag_frame' && same(box, g.start)
/** The finger's point, for the loupe (board 12: a handle's drag only, not a drawing). */
function useFinger() {
const [finger, setFinger] = useState<XY | null>(null)
const held = useRef(false)
const open = (client: XY) => {
held.current = true
setFinger(client)
}
const follow = (client: XY) => held.current && setFinger(client)
const close = () => {
if (held.current) setFinger(null)
held.current = false
}
return { finger, open, follow, close }
}
/**
* A frame drag: `draw` (a box from two corners) and `drag_frame` (a handle or the body).
@@ -93,21 +116,17 @@ const same = (a: Frame, b: Frame | null) =>
export function useFrameDrag(surface: FrameSurface) {
const gesture = useRef<Gesture | null>(null)
const [preview, setPreview] = useState<Frame | null>(null)
const [finger, setFinger] = useState<XY | null>(null)
const touch = useRef(false)
const clear = () => {
const finger = useFinger()
const cancel = () => {
gesture.current = null
setPreview(null)
if (touch.current) setFinger(null)
touch.current = false
finger.close()
}
const at = (client: XY) => clientToDrawing(surface.overlay.current, client)
const follow = (client: XY, shift: boolean) => {
const g = gesture.current
const now = at(client)
if (!g || !now) return
if (touch.current) setFinger(client)
setPreview(boxAt(g, now, shift))
const now = clientToDrawing(surface.overlay.current, client)
if (!gesture.current || !now) return
finger.follow(client)
setPreview(boxAt(gesture.current, now, shift))
}
const start = (
action: FrameDragAction,
@@ -116,17 +135,17 @@ export function useFrameDrag(surface: FrameSurface) {
kind: PointerKind,
) => {
gesture.current = begin(surface, action, pressedAt, kind)
touch.current = kind === 'touch' && gesture.current !== null
if (touch.current) setFinger(client)
if (kind === 'touch' && action.type === 'drag_frame' && gesture.current)
finger.open(client)
follow(client, false)
}
const drop = (client: XY, shift: boolean) => {
const g = gesture.current
const now = at(client)
clear()
const now = clientToDrawing(surface.overlay.current, client)
cancel()
if (!g || !now) return
const box = droppedBox(g, surface, now, shift)
if (g.action.type === 'draw' || !same(box, g.start)) setFrameBox(box)
if (!unchanged(g, box)) setFrameBox(box)
}
return { preview, finger, start, follow, drop, cancel: clear }
return { preview, finger: finger.finger, start, follow, drop, cancel }
}
@@ -75,10 +75,7 @@ describe('nearestHandle (R-9)', () => {
it('answers null without a handle', () => {
expect(
nearestHandle([{ kind: 'annotation', id: 'a', access: false }], {
x: 0,
y: 0,
}),
nearestHandle([{ kind: 'annotation', id: 'a', access: false }], { x: 0, y: 0 }),
).toBeNull()
})
})
@@ -209,3 +209,110 @@ describe('Escape over an open frame with nothing selected', () => {
expect(useAnnotationWork.getState().frame).not.toBeNull()
})
})
describe('releasing a frame handle', () => {
const START: Frame = { x: 10, y: 10, w: 40, h: 30 }
const fire = (type: string, x: number, y: number, over = {}) =>
fireEvent(
screen.getByTestId('annotation-canvas'),
new PointerEvent(type, {
bubbles: true,
clientX: x,
clientY: y,
button: 0,
buttons: type === 'pointerup' ? 0 : 1,
pointerId: 1,
isPrimary: true,
pointerType: 'mouse',
...over,
}),
)
/** The press lands on the handle's hit circle (the DOM gives no layout here). */
const onHandle = (part: string) => {
const hit = document.querySelector(
`[data-frame-part="${part}"] [data-handle]`,
)!
vi.spyOn(document, 'elementsFromPoint').mockReturnValue([hit])
}
const writes = () => {
const seen: unknown[] = []
useAnnotationWork.subscribe((s, before) => {
if (s.frame?.box !== before.frame?.box) seen.push(s.frame?.box)
})
return seen
}
it('sets the box once, on release, never during the move', async () => {
await mount()
open(START)
const seen = writes()
onHandle('se')
fire('pointerdown', 50, 40)
fire('pointermove', 60, 45)
fire('pointermove', 65, 48)
expect(seen).toHaveLength(0)
fire('pointerup', 70, 50)
expect(seen).toHaveLength(1)
expect(boxNow()).toEqual({ x: 10, y: 10, w: 60, h: 40 })
})
it('Shift keeps the ratio the box started with', async () => {
await mount()
open(START)
onHandle('se')
fire('pointerdown', 50, 40)
fire('pointermove', 80, 40, { shiftKey: true })
fire('pointerup', 80, 40, { shiftKey: true })
const box = boxNow()
expect(box.w).toBeCloseTo(70)
expect(box.w / box.h).toBeCloseTo(START.w / START.h)
})
it('the smallest side is 16 screen px, converted to drawing units', async () => {
await mount()
const twice = { a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }
// The overlay's own element answers, whatever class of the chain holds the getter.
const overlay = screen.getByTestId('annotation-overlay')
Object.defineProperty(overlay, 'getScreenCTM', {
configurable: true,
value: () => ({ ...twice, inverse: () => twice }),
})
open(START)
onHandle('se')
fire('pointerdown', 25, 20)
fire('pointermove', 20, 15)
fire('pointerup', -50, -50)
expect(boxNow()).toMatchObject({ w: 32, h: 32 })
})
it('the loupe follows a finger on a handle, not a finger drawing', async () => {
await mount()
const touch = { pointerType: 'touch' }
open(START)
onHandle('se')
fire('pointerdown', 50, 40, touch)
fire('pointermove', 60, 50, touch)
expect(screen.queryByTestId('loupe')).not.toBeNull()
fire('pointerup', 60, 50, touch)
expect(screen.queryByTestId('loupe')).toBeNull()
act(() => resetWork())
open(null)
vi.restoreAllMocks()
fire('pointerdown', 10, 10, touch)
fire('pointermove', 40, 40, touch)
expect(screen.queryByTestId('loupe')).toBeNull()
})
})
describe('a frame drawn on another view', () => {
it('leaves this canvas as it was', async () => {
const canvas = await mount()
open(null, 'view-other')
expect(canvas).not.toHaveAttribute('data-creating')
expect(canvas.style.touchAction).toBe('pan-x pan-y')
act(() => resetWork())
open(null)
expect(canvas).toHaveAttribute('data-creating')
expect(canvas.style.touchAction).toBe('none')
})
})