diff --git a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx index 5e29763c..7d259def 100644 --- a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx @@ -13,7 +13,7 @@ import Notice from '@/components/ui/Notice' import { coreFailureMessage } from '@/core/failure' import { useCoreStopped } from '@/core/runtime' import { transformOf } from '@/catalogue/framing' -import type { XY } from '@/editor/annotations/frame' +import type { Frame, XY } from '@/editor/annotations/frame' import { clientToDrawing } from '@/editor/annotations/gesture' import { useCanvasBuild, @@ -25,6 +25,7 @@ import type { MoveTarget } from '@/editor/annotations/useBlockDrag' import type { Drop } from '@/editor/annotations/usePlacement' import type { HandleAction } from '@/editor/annotations/usePressGesture' import type { ToolId } from '@/editor/annotations/uiState' +import { useAnnotationWork } from '@/editor/annotations/workStore' import { useT } from '@/i18n/useT' import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay' import HandleLayer, { type HandleLayerProps } from './HandleLayer' @@ -33,7 +34,7 @@ import ToolColumn, { type ToolColumnProps } from './ToolColumn' type OverlayData = Omit< OverlayProps, - 'svgRef' | 'viewBox' | 'ratio' | 'dragged' | 'hover' + 'svgRef' | 'viewBox' | 'ratio' | 'dragged' | 'hover' | 'crop' > /** The handle layer's content: the handle and its keys (the layer measures itself). */ @@ -71,6 +72,8 @@ export interface AnnotationCanvasProps { /** A one-finger drag off the handles moved nothing (R-1). */ onFutileDrag: () => void onTraceKey: (event: KeyboardEvent) => void + /** Enter placed the default frame at the centre: announce it. */ + onFrameCentred: () => void } /** @@ -91,6 +94,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) { viewport, }) const preview = usePointPreview(props.previewRadius, overlay) + const crop = useCrop(props.viewId, gestures.frameBox) useSelectionMark(build.host, props.selectedId, build.root) useReportRoot(build.root, props.onRoot) return ( @@ -114,6 +118,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) { svgRef: overlay, dragged: gestures.drag, hover: preview.hover, + crop: crop.box, }, handles: { ...props.handles, @@ -123,6 +128,8 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) { y: gestures.framing.framing.y, }, dragged: gestures.drag, + crop: crop.box, + cropEdit: crop.editable, }, }} /> @@ -130,6 +137,18 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) { ) } +/** + * The frame drawn on this view: its box as shown (a drag's preview first), and whether it + * has handles (a box exists: not while the first drag draws it). + */ +function useCrop(viewId: string, dragged: Frame | null) { + const frame = useAnnotationWork((s) => + s.frame?.drawnOn === viewId ? s.frame : null, + ) + const box = dragged ?? frame?.box ?? null + return { box, editable: frame?.box != null } +} + type Build = ReturnType type BoxProps = ReturnType['boxProps'] type Preview = ReturnType @@ -188,7 +207,12 @@ function CanvasBox({ layer: Omit }) { const root = build.root?.viewId === viewId ? build.root : null - const cursor = tool === 'select' ? 'cursor-grab' : 'cursor-crosshair' + const framed = useAnnotationWork((s) => s.frame !== null) + const drawingFrame = useAnnotationWork( + (s) => s.frame?.drawnOn === viewId && s.frame.box === null, + ) + const cursor = + tool === 'select' && !drawingFrame ? 'cursor-grab' : 'cursor-crosshair' return (
@@ -217,6 +241,7 @@ function CanvasBox({ root={root} selectedId={selectedId} dragged={layer.overlay.dragged} + crop={layer.overlay.crop} /> )} @@ -242,6 +267,8 @@ interface LayerProps { scale: number pan: { x: number; y: number } dragged: Geometry | null + crop: Frame | null + cropEdit: boolean } } diff --git a/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx b/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx index 0609aa7d..6ac79e59 100644 --- a/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx @@ -23,6 +23,8 @@ export interface OverlayProps { hover: { x: number; y: number; r: number } | null tracing: Point[] | null correction: Correction | null + /** The detail view's frame as shown now (a drag's preview included); null: none. */ + crop: Frame | null /** A redraw runs: the stored outline stays as the old place until the close (06 C). */ redrawing: boolean } @@ -172,6 +174,33 @@ function HoverPreview({ ) } +/** + * Board 02, 03: the frame as a solid accent stroke, and the veil over the rest of the + * parent drawing (an even-odd path: the frame minus the box). + */ +function CropFrame({ crop, parent }: { crop: Frame; parent: Frame }) { + const rect = (f: Frame) => `M ${f.x} ${f.y} h ${f.w} v ${f.h} h ${-f.w} Z` + return ( + + + + + ) +} + function TracingPath({ points, size }: { points: Point[]; size: number }) { if (points.length === 0) return null const shape: Geometry = { type: 'polygon', points } @@ -254,6 +283,7 @@ export default function AnnotationOverlay(props: OverlayProps) { )} {tracing && } {props.hover && } + {props.crop && frame && } ) } diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index f92167c2..636cd5d3 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -257,12 +257,14 @@ export default function EditableAnnotations(props: Props) { const work = useWork(scene) const { ui, selected } = scene const visible = usePlaceVisible() + const framing = useAnnotationWork((s) => s.frame !== null) const { asideRef, byDrawing } = useSelectionEscape( selected?.id ?? null, () => scene.dispatch({ type: 'select', id: null }), - // A redraw's Escape cancels it at once (R-12); a creation asks (board 32 row 3). + // A redraw's Escape cancels it at once (R-12); a creation or an open frame asks + // (board 32 rows 3 and 4). visible && - (selected !== undefined || scene.creation !== null) && + (selected !== undefined || scene.creation !== null || framing) && (ui.tracing === null || ui.tracing.target === 'replace'), { editable: true, creating: scene.creation !== null }, ) @@ -453,6 +455,12 @@ function CanvasStage({ onDeselect={() => free && onDeselect()} onFutileDrag={() => hintTwoFingers(work.message, work.context.t)} onTraceKey={work.placement.onTraceKey} + onFrameCentred={() => + work.message.show(work.context.t('editor.annotations.frame.centred'), { + undo: false, + tone: 'info', + }) + } /> ) } diff --git a/apps/app/src/components/editor/annotations/FrameHandles.tsx b/apps/app/src/components/editor/annotations/FrameHandles.tsx new file mode 100644 index 00000000..8c999314 --- /dev/null +++ b/apps/app/src/components/editor/annotations/FrameHandles.tsx @@ -0,0 +1,177 @@ +import type { KeyboardEvent } from 'react' +import type { Frame, XY } from '@/editor/annotations/frame' +import { moveStep } from '@/editor/annotations/frame' +import { + MIN_FRAME_PX, + moveBox, + resizeBox, + shownHandles, + type FrameHandle, + type FramePart, +} from '@/editor/annotations/frameBox' +import { setFrameBox } from '@/editor/annotations/frameWork' +import type { HandleSizes } from '@/editor/annotations/handleSize' +import { useAnnotationWork } from '@/editor/annotations/workStore' +import { useT } from '@/i18n/useT' + +export interface FrameHandlesProps { + /** The box as shown now: the stored one, or the drag's preview. */ + box: Frame + /** The parent drawing's frame: the box never leaves it. */ + bounds: Frame + /** Drawing units per CSS px. */ + unit: number + sizes: HandleSizes +} + +const ARROWS: Record = { + ArrowLeft: { x: -1, y: 0 }, + ArrowRight: { x: 1, y: 0 }, + ArrowUp: { x: 0, y: -1 }, + ArrowDown: { x: 0, y: 1 }, +} + +const CURSOR: Record = { + nw: 'cursor-nwse-resize', + se: 'cursor-nwse-resize', + ne: 'cursor-nesw-resize', + sw: 'cursor-nesw-resize', + n: 'cursor-ns-resize', + s: 'cursor-ns-resize', + e: 'cursor-ew-resize', + w: 'cursor-ew-resize', +} + +function anchorOf(box: Frame, handle: FrameHandle): XY { + const x = handle.includes('w') + ? box.x + : handle.includes('e') + ? box.x + box.w + : box.x + box.w / 2 + const y = handle.includes('n') + ? box.y + : handle.includes('s') + ? box.y + box.h + : box.y + box.h / 2 + return { x, y } +} + +/** The box after one key step on `part`: the body moves, a handle resizes (D8). */ +function steppedBox(props: FrameHandlesProps, part: FramePart, delta: XY) { + const { box, bounds, unit } = props + if (part === 'body') return moveBox(box, delta, bounds) + const keepRatio = useAnnotationWork.getState().frame?.keepRatio ?? false + return resizeBox({ + start: box, + handle: part, + delta, + min: MIN_FRAME_PX.mouse * unit, + keepRatio, + bounds, + }) +} + +/** Arrows step by `moveStep` (ten with Shift); Escape reaches the document's listener. */ +function keyOf(props: FrameHandlesProps, part: FramePart) { + return (event: KeyboardEvent) => { + const arrow = ARROWS[event.key] + if (!arrow) return + event.preventDefault() + const size = moveStep(props.bounds, event.shiftKey) + setFrameBox( + steppedBox(props, part, { x: arrow.x * size, y: arrow.y * size }), + ) + } +} + +const RING = 'invisible group-focus-visible:visible' + +function Handle({ + handle, + props, +}: { + handle: FrameHandle + props: FrameHandlesProps +}) { + const t = useT() + const { box, unit, sizes } = props + const { x, y } = anchorOf(box, handle) + const half = (sizes.vertex * unit) / 2 + return ( + + + + + + ) +} + +/** + * The detail view's frame as handles (D8, board 03): the body, then the eight handles a + * box of this size on screen shows (D6), each focusable and named. The hit radius is + * constant on screen like the vertex handles; the pointer is the press machine's. + */ +export default function FrameHandles(props: FrameHandlesProps) { + const t = useT() + const { box, unit } = props + const shown = shownHandles(box.w / unit, box.h / unit) + return ( + + + {shown.map((handle) => ( + + ))} + + ) +} diff --git a/apps/app/src/components/editor/annotations/HandleLayer.tsx b/apps/app/src/components/editor/annotations/HandleLayer.tsx index 5c8f6904..a8a892bf 100644 --- a/apps/app/src/components/editor/annotations/HandleLayer.tsx +++ b/apps/app/src/components/editor/annotations/HandleLayer.tsx @@ -8,13 +8,14 @@ import { type RefObject, } from 'react' import type { Geometry } from '@faunosteo/core-wasm/types' -import { parseFrame } from '@/editor/annotations/frame' +import { parseFrame, type Frame } from '@/editor/annotations/frame' import { visibleBounds } from '@/editor/annotations/removeBubble' import { useHandleSizes, type HandleSizes, } from '@/editor/annotations/handleSize' import { useAnnotationWork } from '@/editor/annotations/workStore' +import FrameHandles from './FrameHandles' import ZoneHandles, { shownInserts, type Scale, @@ -45,6 +46,9 @@ export interface HandleLayerProps { zoneKeys: ZoneKeys /** The canvas-local drag preview: the handles follow it. */ dragged: Geometry | null + /** The frame's box as shown (the drag's preview included) and whether it has handles. */ + crop: Frame | null + cropEdit: boolean /** Whether a « + » is hidden for its short segment (R-18's hint). */ onInsertsHidden: (hidden: boolean) => void } @@ -120,6 +124,14 @@ export default function HandleLayer(props: HandleLayerProps) { unit={unit} /> )} + {props.crop && props.cropEdit && frame && ( + + )} {zone && ( - +
@@ -139,12 +141,14 @@ export default function Loupe(props: LoupeProps) { function LoupeOutline({ root, outline, + crop, }: { root: RootAttributes outline: Geometry | null + crop: Frame | null }) { const frame = parseFrame(root.viewBox) - if (!outline || !root.viewBox) return null + if ((!outline && !crop) || !root.viewBox) return null const size = frame ? Math.max(frame.w, frame.h) / 200 : 1 return ( - - + {outline && ( + <> + + + + )} + {crop && ( + + )} ) } diff --git a/apps/app/src/editor/annotations/frameDraw.ts b/apps/app/src/editor/annotations/frameDraw.ts new file mode 100644 index 00000000..25ac4a50 --- /dev/null +++ b/apps/app/src/editor/annotations/frameDraw.ts @@ -0,0 +1,67 @@ +import type { RefObject } from 'react' +import { parseFrame, type Frame, type XY } from './frame' +import { boxFromCorners, defaultBox } from './frameBox' +import { setFrameBox } from './frameWork' +import { clientToDrawing } from './gesture' +import type { FramePhase } from './press' +import { useAnnotationWork } from './workStore' + +/** The canvas box is 4:3: the ratio of the default frame (D4). */ +export const AREA_RATIO = 4 / 3 + +/** The two elements a frame gesture reads its coordinates from. */ +export interface FrameSurface { + overlay: RefObject + viewport: RefObject +} + +/** The phase of the frame drawn on `viewId`: nothing drawn yet, or a box to adjust. */ +export function framePhase(viewId: string): FramePhase | null { + const { frame } = useAnnotationWork.getState() + if (!frame || frame.drawnOn !== viewId) return null + return frame.box === null ? 'draw' : 'adjust' +} + +/** The parent drawing's frame: the composed root's `viewBox`, read from the overlay. */ +export function parentFrame(overlay: SVGSVGElement | null): Frame | null { + return parseFrame(overlay?.getAttribute('viewBox') ?? null) +} + +/** + * The part of the drawing on screen, in drawing units; the whole frame when the box has no + * layout (nothing measured, tests). + */ +export function visibleDrawing(surface: FrameSurface, bounds: Frame): Frame { + const rect = surface.viewport.current?.getBoundingClientRect() + const svg = surface.overlay.current + if (!rect) return bounds + const from = clientToDrawing(svg, { x: rect.left, y: rect.top }) + const to = clientToDrawing(svg, { x: rect.right, y: rect.bottom }) + if (!from || !to) return bounds + const visible = boxFromCorners(from, to) + 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 + 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) +} + +/** The keyboard's placement: the default frame at the visible centre; false when unmeasured. */ +export function placeAtCentre(surface: FrameSurface): boolean { + const bounds = parentFrame(surface.overlay.current) + 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) + return true +} diff --git a/apps/app/src/editor/annotations/press.ts b/apps/app/src/editor/annotations/press.ts index 25a8c930..ef098220 100644 --- a/apps/app/src/editor/annotations/press.ts +++ b/apps/app/src/editor/annotations/press.ts @@ -1,4 +1,5 @@ import type { XY } from './frame' +import type { FramePart } from './frameBox' 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. */ @@ -33,6 +34,7 @@ export type HandleRef = | { kind: 'vertex'; index: number } | { kind: 'remove'; index: number } | { kind: 'insert'; after: number } + | { kind: 'frame'; part: FramePart } /** One element under the press, top first (`elementsFromPoint`); handle centres in CSS px. */ export type Hit = @@ -44,14 +46,21 @@ const RANK: Record = { vertex: 0, remove: 1, insert: 2, + frame: 0, } +/** The frame's body answers only where no other handle is within reach. */ +const BODY_PENALTY = 1e6 + +const isBody = (handle: HandleRef) => + handle.kind === 'frame' && handle.part === 'body' + /** 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 d = distance(hit.centre, at) + (isBody(hit.handle) ? BODY_PENALTY : 0) const better = !best || d < best.d || @@ -99,9 +108,23 @@ export type ClickAction = | { type: 'unchoose' } | { type: 'open'; id: string } | { type: 'deselect' } + | { type: 'place_default' } + | { type: 'nothing' } -/** A press released within the slop (A1): select first, open on the selection itself. */ -export function clickAction(target: PressTarget, sel: Selection): ClickAction { +/** The phase of an open frame: nothing drawn yet, or a box to adjust. */ +export type FramePhase = 'draw' | 'adjust' + +/** + * A press released within the slop (A1): select first, open on the selection itself. An + * open frame takes the click: the default frame while drawing, nothing once adjusting. + */ +export function clickAction( + target: PressTarget, + sel: Selection, + phase: FramePhase | null = null, +): ClickAction { + if (phase === 'draw') return { type: 'place_default' } + if (phase === 'adjust') return { type: 'nothing' } if (target.kind === 'other') return { type: 'select', id: target.id } if (target.kind === 'empty') return { type: 'deselect' } if (target.kind === 'interior') { @@ -142,12 +165,18 @@ export interface DragContext { movable: boolean /** « Déplacer … » is on: a drag anywhere moves its target (board 06 B). */ moveMode: boolean + /** A frame without a box, or the access tool with a rectangle or circle shape: a drag draws. */ + drawing: boolean + /** A frame with a box: only its handles take a drag. */ + adjusting: boolean } export type DragAction = | { type: 'drag_mode' } | { type: 'drag_point' } | { type: 'drag_vertex'; index: number } + | { type: 'draw' } + | { type: 'drag_frame'; part: FramePart } | { type: 'drag_shape'; id: string } | { type: 'pan' } | { type: 'none'; futile: boolean } @@ -158,6 +187,14 @@ export type DragAction = */ export function dragAction(target: PressTarget, ctx: DragContext): DragAction { if (ctx.moveMode) return { type: 'drag_mode' } + if (ctx.drawing) return { type: 'draw' } + if (target.kind === 'handle' && target.handle.kind === 'frame') + return { type: 'drag_frame', part: target.handle.part } + if (ctx.adjusting) { + return ctx.kind === 'touch' + ? { type: 'none', futile: false } + : { type: 'pan' } + } if (target.kind === 'handle') { if (!ctx.movable) return { type: 'none', futile: false } if (target.handle.kind === 'point') return { type: 'drag_point' } diff --git a/apps/app/src/editor/annotations/useCanvasGestures.ts b/apps/app/src/editor/annotations/useCanvasGestures.ts index b2ef2657..07e2ade0 100644 --- a/apps/app/src/editor/annotations/useCanvasGestures.ts +++ b/apps/app/src/editor/annotations/useCanvasGestures.ts @@ -1,11 +1,13 @@ import type { CSSProperties, KeyboardEvent, PointerEvent } from 'react' import { useFraming } from '@/catalogue/useFraming' import type { ToolId } from './uiState' +import { framePhase, placeAtCentre } from './frameDraw' import { usePressGesture, type PressInput } from './usePressGesture' -import { markTwoFingers } from './workStore' +import { markTwoFingers, useAnnotationWork } from './workStore' export interface GestureInput extends PressInput { - viewId: string + /** The default frame was placed at the centre by the keyboard: say so. */ + onFrameCentred: () => void /** Enter and Escape while the canvas box itself has the focus (a tracing). */ onTraceKey: (event: KeyboardEvent) => void } @@ -46,8 +48,9 @@ function touchStyle( tool: ToolId, scale: number, movable: boolean, + framed: boolean, ): CSSProperties { - const none = tool !== 'select' || scale !== 1 || movable + const none = tool !== 'select' || scale !== 1 || movable || framed return { touchAction: none ? 'none' : 'pan-x pan-y' } } @@ -67,8 +70,14 @@ 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 onKeyDown = (event: KeyboardEvent) => { if (event.target !== event.currentTarget) return + if (event.key === 'Enter' && framePhase(input.viewId) === 'draw') { + event.preventDefault() + if (placeAtCentre(input)) input.onFrameCentred() + return + } framing.handlers.onKeyDown(event) input.onTraceKey(event) } @@ -76,6 +85,7 @@ export function useCanvasGestures(input: GestureInput) { framing, drag: press.preview, finger: press.finger, + frameBox: press.frameBox, boxProps: { ...composedPointer(framing, press), onKeyDown, @@ -83,6 +93,7 @@ export function useCanvasGestures(input: GestureInput) { input.tool, framing.framing.scale, input.target !== null, + framed, ), }, } diff --git a/apps/app/src/editor/annotations/useFrameDrag.ts b/apps/app/src/editor/annotations/useFrameDrag.ts new file mode 100644 index 00000000..a48407d8 --- /dev/null +++ b/apps/app/src/editor/annotations/useFrameDrag.ts @@ -0,0 +1,132 @@ +import { useRef, useState } from 'react' +import type { Frame, XY } from './frame' +import { + MIN_FRAME_PX, + boxFromCorners, + drawnBox, + intersection, + moveBox, + resizeBox, +} from './frameBox' +import { defaultAt, parentFrame, type FrameSurface } from './frameDraw' +import { setFrameBox } from './frameWork' +import { clientToDrawing, drawingPerClientPx } from './gesture' +import type { DragAction, PointerKind } from './press' +import { useAnnotationWork } from './workStore' + +export type FrameDragAction = Extract< + DragAction, + { type: 'draw' | 'drag_frame' } +> + +interface Gesture { + action: FrameDragAction + /** 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 +} + +function begin( + surface: FrameSurface, + action: FrameDragAction, + pressedAt: XY, + kind: PointerKind, +): Gesture | null { + const svg = surface.overlay.current + 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 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') { + const corners = boxFromCorners(g.origin, now) + return intersection(corners, g.bounds) ?? corners + } + const start = g.start! + 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({ + start, + handle: part, + delta, + min: minOf(g), + keepRatio: keepRatio || shift, + bounds: g.bounds, + }) +} + +/** What a drop commits: a drawn box, or a click-sized one, the default frame (D4, D6). */ +function droppedBox( + g: Gesture, + 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 + 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 + +/** + * A frame drag: `draw` (a box from two corners) and `drag_frame` (a handle or the body). + * The box shown is local to the canvas; the drop sets the work item's box once and nothing + * reaches the core (BDR-050). + */ +export function useFrameDrag(surface: FrameSurface) { + const gesture = useRef(null) + const [preview, setPreview] = useState(null) + const [finger, setFinger] = useState(null) + const touch = useRef(false) + const clear = () => { + gesture.current = null + setPreview(null) + if (touch.current) setFinger(null) + touch.current = false + } + 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 start = ( + action: FrameDragAction, + pressedAt: XY, + client: XY, + kind: PointerKind, + ) => { + gesture.current = begin(surface, action, pressedAt, kind) + touch.current = kind === 'touch' && gesture.current !== null + if (touch.current) setFinger(client) + follow(client, false) + } + const drop = (client: XY, shift: boolean) => { + const g = gesture.current + const now = at(client) + clear() + if (!g || !now) return + const box = droppedBox(g, surface, now, shift) + if (g.action.type === 'draw' || !same(box, g.start)) setFrameBox(box) + } + return { preview, finger, start, follow, drop, cancel: clear } +} diff --git a/apps/app/src/editor/annotations/usePressGesture.ts b/apps/app/src/editor/annotations/usePressGesture.ts index f5bff3da..b963c2fd 100644 --- a/apps/app/src/editor/annotations/usePressGesture.ts +++ b/apps/app/src/editor/annotations/usePressGesture.ts @@ -26,12 +26,16 @@ import type { ToolId } from './uiState' import { annotationIdOf } from './useCanvasBuild' import { useBlockDrag, type BlockDragInput } from './useBlockDrag' import { commitFocusedSeries } from './drawingGuard' +import { framePhase, placeDefault } from './frameDraw' +import { useFrameDrag, type FrameDragAction } from './useFrameDrag' import { useAnnotationWork } from './workStore' export interface PressInput extends BlockDragInput { tool: ToolId - selectedId: string | null + /** The view this canvas shows: a frame drawn on it takes the press. */ + viewId: string viewport: RefObject + selectedId: string | null onSelect: (id: string) => void /** A second click on the selection, or a double click: its properties dialog (A1). */ onOpen: (id: string) => void @@ -140,6 +144,7 @@ interface Feed { machine: RefObject input: PressInput drag: ReturnType + frameDrag: ReturnType } /** A click with a drawing tool places at the pointer-up, in drawing units. */ @@ -186,11 +191,26 @@ function absorbSynthesisedClick(at: XY): void { document.addEventListener('click', swallow, true) } +/** An open frame takes the click: the default frame while drawing, nothing once adjusting. */ +function frameClick( + input: PressInput, + target: PressTarget, + event: PointerEvent, + phase: NonNullable>, +): void { + const action = clickAction(target, selectionOf(null), phase) + if (action.type !== 'place_default') return + const at = clientToDrawing(input.overlay.current, clientOf(event)) + if (at) placeDefault(input, at) +} + /** A click with the select tool (none during the move mode, R-12), or with a drawing tool. */ function onClick(f: Feed, target: PressTarget, event: PointerEvent): void { if (pointerKindOf(event.pointerType) !== 'mouse') { absorbSynthesisedClick(clientOf(event)) } + const phase = framePhase(f.input.viewId) + if (phase) return frameClick(f.input, target, event, phase) if (f.input.tool !== 'select') return place(f.input, event) if (!inMoveMode()) selectClick(f, target, event) } @@ -202,27 +222,47 @@ const BLOCK_DRAGS = new Set([ 'drag_vertex', ]) -/** The vertex or point handle a press holds takes the focus a tap does not give it (Safari). */ +const FRAME_DRAGS = new Set(['draw', 'drag_frame']) + +/** The selector of the element a handle press focuses; null for the handles that take none. */ +function focusSelector(handle: HandleRef): string | null { + if (handle.kind === 'vertex') return `[data-vertex="${handle.index}"]` + if (handle.kind === 'point') return '[data-testid="point-handle"]' + if (handle.kind === 'frame') return `[data-frame-part="${handle.part}"]` + return null +} + +/** The vertex, point or frame handle a press holds takes the focus a tap does not give it (Safari). */ function focusPressed(f: Feed, target: PressTarget): void { if (target.kind !== 'handle') return - const { handle } = target - if (handle.kind !== 'vertex' && handle.kind !== 'point') return - const selector = - handle.kind === 'vertex' - ? `[data-vertex="${handle.index}"]` - : '[data-testid="point-handle"]' + const selector = focusSelector(target.handle) + if (selector === null) return const element = f.input.viewport.current?.querySelector(selector) if (element instanceof SVGElement) element.focus({ preventScroll: true }) } function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) { - if (effect?.type === 'drag_cancel') f.drag.cancel() + if (effect?.type === 'drag_cancel') { + f.drag.cancel() + f.frameDrag.cancel() + } if (!event || !effect) return if (effect.type === 'click') { onClick(f, effect.target, event) focusPressed(f, effect.target) } - if (effect.type === 'drag_end') f.drag.drop(clientOf(event)) + if (effect.type === 'drag_end') { + f.drag.drop(clientOf(event)) + f.frameDrag.drop(clientOf(event), event.shiftKey) + } + if (effect.type === 'drag_start' && FRAME_DRAGS.has(effect.action.type)) { + if (effect.action.type === 'drag_frame') + focusPressed(f, f.machine.current.target) + const kind = pointerKindOf(event.pointerType) + const { pressedAt } = f.machine.current + const action = effect.action as FrameDragAction + f.frameDrag.start(action, pressedAt, clientOf(event), kind) + } if (effect.type === 'drag_start' && BLOCK_DRAGS.has(effect.action.type)) { const { action } = effect const vertex = action.type === 'drag_vertex' ? action.index : null @@ -241,10 +281,15 @@ function movable(input: PressInput): boolean { return geometry.type !== 'polygon' || geometry.points.length <= HANDLE_CAP } -const contextOf = (input: PressInput) => ({ - movable: movable(input), - moveMode: inMoveMode(), -}) +const contextOf = (input: PressInput) => { + const phase = framePhase(input.viewId) + return { + movable: movable(input), + moveMode: inMoveMode(), + drawing: phase === 'draw', + adjusting: phase === 'adjust', + } +} /** A drag that ends having moved nothing (`none` with `futile`): a finger off the handles. */ const isFutile = (press: Press) => @@ -319,7 +364,8 @@ function startPress(latest: RefObject, event: PointerEvent): void { const kind = pointerKindOf(event.pointerType) const context = { kind, ...contextOf(f.input) } // The drag of the selection keeps its pointer even past the box's edge. - if (BLOCK_DRAGS.has(dragAction(m.target, context).type)) { + const dragType = dragAction(m.target, context).type + if (BLOCK_DRAGS.has(dragType) || FRAME_DRAGS.has(dragType)) { event.currentTarget.setPointerCapture?.(event.pointerId) } m.stop = watchOtherPointers(latest) @@ -356,7 +402,9 @@ function onPointerMove(f: Feed, event: PointerEvent): void { 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) + if (!dragging || pointerOf(m.press) !== event.pointerId) return + f.drag.follow(at) + f.frameDrag.follow(at, event.shiftKey) } function onPointerUp(f: Feed, event: PointerEvent): void { @@ -375,6 +423,7 @@ const IDLE: Press = { phase: 'idle' } */ export function usePressGesture(input: PressInput) { const drag = useBlockDrag(input) + const frameDrag = useFrameDrag(input) const machine = useRef({ press: IDLE, target: { kind: 'empty' }, @@ -383,8 +432,8 @@ export function usePressGesture(input: PressInput) { lastClick: null, stop: null, }) - const latest = useRef({ machine, input, drag }) - latest.current = { machine, input, drag } + const latest = useRef({ machine, input, drag, frameDrag }) + latest.current = { machine, input, drag, frameDrag } useEffect(() => { const m = machine.current return () => m.stop?.() @@ -392,7 +441,8 @@ export function usePressGesture(input: PressInput) { const cancel = () => feed(latest.current, { type: 'cancel' }, null) return { preview: drag.preview, - finger: drag.finger, + frameBox: frameDrag.preview, + finger: drag.finger ?? frameDrag.finger, panning: () => { const press = machine.current.press return press.phase === 'drag' && press.action.type === 'pan' diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 600d9f30..db396838 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1906,6 +1906,16 @@ export const en: Dict = { 'editor.annotations.guard.creation': 'Discard the creation?', 'editor.annotations.guard.frame_create': 'Abandon the creation?', 'editor.annotations.guard.frame_recrop': 'Abandon the recrop?', + 'editor.annotations.frame.body': 'Frame', + 'editor.annotations.frame.handle.nw': 'Top left corner', + 'editor.annotations.frame.handle.n': 'Top side', + 'editor.annotations.frame.handle.ne': 'Top right corner', + 'editor.annotations.frame.handle.e': 'Right side', + 'editor.annotations.frame.handle.se': 'Bottom right corner', + 'editor.annotations.frame.handle.s': 'Bottom side', + 'editor.annotations.frame.handle.sw': 'Bottom left corner', + 'editor.annotations.frame.handle.w': 'Left side', + 'editor.annotations.frame.centred': 'Frame placed at the centre.', 'editor.annotations.guard.continue': 'Continue', 'editor.annotations.guard.discard': 'Discard', 'editor.annotations.dropped.move': 'Move discarded: the sheet changed.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 1c746b67..2eebc00c 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1976,6 +1976,16 @@ export const fr: Dict = { 'editor.annotations.guard.creation': 'Abandonner la création ?', 'editor.annotations.guard.frame_create': 'Abandonner la création ?', 'editor.annotations.guard.frame_recrop': 'Abandonner le recadrage ?', + 'editor.annotations.frame.body': 'Cadre', + 'editor.annotations.frame.handle.nw': 'Coin haut gauche', + 'editor.annotations.frame.handle.n': 'Côté haut', + 'editor.annotations.frame.handle.ne': 'Coin haut droit', + 'editor.annotations.frame.handle.e': 'Côté droit', + 'editor.annotations.frame.handle.se': 'Coin bas droit', + 'editor.annotations.frame.handle.s': 'Côté bas', + 'editor.annotations.frame.handle.sw': 'Coin bas gauche', + 'editor.annotations.frame.handle.w': 'Côté gauche', + 'editor.annotations.frame.centred': 'Cadre posé au centre.', 'editor.annotations.guard.continue': 'Continuer', 'editor.annotations.guard.discard': 'Abandonner', 'editor.annotations.dropped.move': diff --git a/apps/app/tests/unit/annotations.press.test.ts b/apps/app/tests/unit/annotations.press.test.ts index fb4ee821..ec2a788f 100644 --- a/apps/app/tests/unit/annotations.press.test.ts +++ b/apps/app/tests/unit/annotations.press.test.ts @@ -75,7 +75,10 @@ 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() }) }) @@ -184,6 +187,8 @@ describe('dragAction (A13)', () => { kind: 'mouse', movable: true, moveMode: false, + drawing: false, + adjusting: false, ...over, }) const interior: PressTarget = { kind: 'interior', id: 'zone' } @@ -263,7 +268,12 @@ describe('dragAction (A13)', () => { }) describe('stepPress (R-8)', () => { - const ctx = { movable: true, moveMode: false } + const ctx = { + movable: true, + moveMode: false, + drawing: false, + adjusting: false, + } const target: PressTarget = { kind: 'interior', id: 'zone' } const down = ( pointerId: number, @@ -356,3 +366,131 @@ describe('stepPress (R-8)', () => { expect(press).toEqual({ phase: 'idle' }) }) }) + +describe('the frame, drawing phase (Task 8, D4)', () => { + const drawing = (kind: DragContext['kind']): DragContext => ({ + kind, + movable: true, + moveMode: false, + drawing: true, + adjusting: false, + }) + const targets: PressTarget[] = [ + { kind: 'empty' }, + { kind: 'other', id: 'a' }, + { kind: 'interior', id: 'a' }, + { kind: 'handle', handle: { kind: 'vertex', index: 0 } }, + ] + + it('a drag draws, mouse, pen and one finger alike, whatever it presses', () => { + for (const kind of ['mouse', 'pen', 'touch'] as const) + for (const target of targets) + expect(dragAction(target, drawing(kind))).toEqual({ type: 'draw' }) + }) + + it('a click places the default frame, whatever it presses', () => { + for (const target of targets) + expect(clickAction(target, NONE, 'draw')).toEqual({ + type: 'place_default', + }) + }) + + it('a second pointer cancels the drawing', () => { + const ctx = { + movable: true, + moveMode: false, + drawing: true, + adjusting: false, + } + const at = { x: 0, y: 0 } + const down = (pointerId: number, pointers: number): PressEvent => ({ + type: 'down', + pointerId, + kind: 'touch', + at, + target: { kind: 'empty' }, + pointers, + }) + let press: Press = { phase: 'idle' } + const run = (event: PressEvent) => { + const step = stepPress(press, event, ctx) + press = step.press + return step.effect + } + run(down(1, 1)) + expect(run({ type: 'move', pointerId: 1, at: { x: 30, y: 0 } })).toEqual({ + type: 'drag_start', + action: { type: 'draw' }, + }) + expect(run(down(2, 2))).toEqual({ type: 'drag_cancel' }) + expect(press).toEqual({ phase: 'multi' }) + }) +}) + +describe('the frame, adjust phase (Task 8, D8)', () => { + const adjusting = (kind: DragContext['kind']): DragContext => ({ + kind, + movable: true, + moveMode: false, + drawing: false, + adjusting: true, + }) + const frameHandle = (part: 'se' | 'body'): PressTarget => ({ + kind: 'handle', + handle: { kind: 'frame', part }, + }) + + it('a press on a frame handle drags that part, the body moves the box', () => { + for (const kind of ['mouse', 'touch'] as const) { + expect(dragAction(frameHandle('se'), adjusting(kind))).toEqual({ + type: 'drag_frame', + part: 'se', + }) + expect(dragAction(frameHandle('body'), adjusting(kind))).toEqual({ + type: 'drag_frame', + part: 'body', + }) + } + }) + + it('a press on an annotation starts no drag and selects nothing', () => { + const other: PressTarget = { kind: 'other', id: 'a' } + expect(dragAction(other, adjusting('touch'))).toEqual({ + type: 'none', + futile: false, + }) + expect(clickAction(other, NONE, 'adjust')).toEqual({ type: 'nothing' }) + expect(clickAction(frameHandle('se'), NONE, 'adjust')).toEqual({ + type: 'nothing', + }) + }) + + it('with the mouse a press off the frame pans the framing', () => { + expect(dragAction({ kind: 'empty' }, adjusting('mouse'))).toEqual({ + type: 'pan', + }) + }) + + it('a frame handle outranks the others only by distance, the body last', () => { + const hits: Hit[] = [ + { + kind: 'handle', + handle: { kind: 'frame', part: 'body' }, + centre: { x: 0, y: 0 }, + }, + { + kind: 'handle', + handle: { kind: 'frame', part: 'nw' }, + centre: { x: 8, y: 0 }, + }, + ] + expect(nearestHandle(hits, { x: 1, y: 0 })).toEqual({ + kind: 'frame', + part: 'nw', + }) + expect(nearestHandle(hits.slice(0, 1), { x: 1, y: 0 })).toEqual({ + kind: 'frame', + part: 'body', + }) + }) +}) diff --git a/apps/app/tests/unit/editor-frame-draw.test.tsx b/apps/app/tests/unit/editor-frame-draw.test.tsx new file mode 100644 index 00000000..cdf5702d --- /dev/null +++ b/apps/app/tests/unit/editor-frame-draw.test.tsx @@ -0,0 +1,211 @@ +/** U2 Task 8: drawing and adjusting a detail view's frame (handles, keys, Enter, Escape). */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import FrameHandles from '@/components/editor/annotations/FrameHandles' +import { parseFrame, type Frame } from '@/editor/annotations/frame' +import { setFrameBox, startFrame } from '@/editor/annotations/frameWork' +import { deviceSizes } from '@/editor/annotations/handleSize' +import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore' +import { useLocaleStore } from '@/state/localeStore' +import { drawnText } from '../helpers/editorFixtures' +import { resetStore, serverHas } from '../helpers/editorHarness' +import { mountDraft, setWidth } from '../helpers/editorRoute' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } + Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', { + configurable: true, + value: () => ({ ...identity, inverse: () => identity }), + }) +}) +afterEach(() => { + cleanup() + act(() => resetWork()) + resetStore() + setWidth(1024) +}) + +const BOUNDS: Frame = { x: 0, y: 0, w: 1000, h: 800 } +const NAMES = [ + 'Cadre', + 'Coin haut gauche', + 'Côté haut', + 'Coin haut droit', + 'Côté droit', + 'Coin bas droit', + 'Côté bas', + 'Coin bas gauche', + 'Côté gauche', +] + +function open(box: Frame | null, drawnOn = 'view-main') { + act(() => { + startFrame({ + purpose: 'create', + viewId: 'view-main', + drawnOn, + box: null, + returnTo: 'view-main', + }) + if (box) setFrameBox(box) + }) +} +const boxNow = () => useAnnotationWork.getState().frame!.box! + +/** The handle layer's job: the box shown is the work item's, re-read after each change. */ +function Shown() { + const box = useAnnotationWork((s) => s.frame!.box!) + return ( + + + + ) +} + +function handles(box: Frame) { + open(box) + render() +} + +describe('the frame handles (D8, D6)', () => { + it('a 300 × 200 px box has its body and eight named handles, in order', () => { + handles({ x: 100, y: 100, w: 300, h: 200 }) + const names = screen + .getAllByRole('button') + .map((b) => b.getAttribute('aria-label')) + expect(names).toEqual(NAMES) + }) + + it('a 40 px wide box hides the two side handles on top and bottom', () => { + handles({ x: 100, y: 100, w: 40, h: 200 }) + const names = screen + .getAllByRole('button') + .map((b) => b.getAttribute('aria-label')) + expect(names).toHaveLength(7) + expect(names).not.toContain('Côté haut') + expect(names).not.toContain('Côté bas') + }) + + it('ArrowRight on « Côté droit » widens by one step, ten with Shift', () => { + handles({ x: 100, y: 100, w: 300, h: 200 }) + const side = screen.getByRole('button', { name: 'Côté droit' }) + fireEvent.keyDown(side, { key: 'ArrowRight' }) + expect(boxNow()).toMatchObject({ x: 100, w: 305, h: 200 }) + fireEvent.keyDown(side, { key: 'ArrowRight', shiftKey: true }) + expect(boxNow()).toMatchObject({ x: 100, w: 355, h: 200 }) + }) + + it('arrows on the body move the whole box', () => { + handles({ x: 100, y: 100, w: 300, h: 200 }) + fireEvent.keyDown(screen.getByRole('button', { name: 'Cadre' }), { + key: 'ArrowDown', + }) + expect(boxNow()).toMatchObject({ x: 100, y: 105, w: 300, h: 200 }) + }) +}) + +async function mount() { + serverHas(drawnText(), 3) + mountDraft({ width: 1280 }) + await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) + await waitFor(() => + expect( + document.querySelector('[data-testid$="canvas-drawing"] svg'), + ).not.toBeNull(), + ) + return screen.getByTestId('annotation-canvas') +} + +describe('Enter on the drawing while drawing', () => { + it('places the default frame at the centre and announces it', async () => { + const canvas = await mount() + open(null) + canvas.focus() + fireEvent.keyDown(canvas, { key: 'Enter' }) + const box = boxNow() + expect(box.w).toBeGreaterThan(0) + const parent = parseFrame( + screen.getByTestId('annotation-overlay').getAttribute('viewBox'), + )! + expect(box.w).toBeCloseTo(parent.w / 3) + expect(box.x + box.w / 2).toBeCloseTo(parent.x + parent.w / 2) + expect(box.y + box.h / 2).toBeCloseTo(parent.y + parent.h / 2) + expect(await screen.findByText('Cadre posé au centre.')).toBeVisible() + expect(canvas).toHaveAttribute('data-creating') + }) +}) + +describe('drawing with the pointer', () => { + const press = (type: string, x: number, y: number, over = {}) => + fireEvent( + screen.getByTestId('annotation-canvas'), + new MouseEvent(type, { + bubbles: true, + clientX: x, + clientY: y, + button: 0, + buttons: type === 'pointerup' ? 0 : 1, + ...over, + }), + ) + + it('a mouse drag past the slop draws the box it spans, once, on release', async () => { + await mount() + open(null) + press('pointerdown', 10, 10) + press('pointermove', 30, 25) + expect(useAnnotationWork.getState().frame!.box).toBeNull() + press('pointerup', 60, 50) + expect(boxNow()).toEqual({ x: 10, y: 10, w: 50, h: 40 }) + expect(useAnnotationWork.getState().frame!.started).toBe(true) + }) + + it('a click places the default frame there', async () => { + await mount() + open(null) + press('pointerdown', 50, 50) + press('pointerup', 50, 50) + expect(boxNow().w).toBeGreaterThan(0) + }) +}) + +describe('Escape over an open frame with nothing selected', () => { + it('ends an unstarted frame silently', async () => { + await mount() + open(null) + expect(screen.getByTestId('annotation-canvas')).toHaveAttribute( + 'data-creating', + ) + fireEvent.keyDown(document.body, { key: 'Escape' }) + expect(useAnnotationWork.getState().frame).toBeNull() + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('asks about a started one', async () => { + await mount() + open({ x: 10, y: 10, w: 50, h: 40 }) + fireEvent.keyDown(document.body, { key: 'Escape' }) + expect( + await screen.findByRole('dialog', { name: 'Abandonner la création ?' }), + ).toBeVisible() + expect(useAnnotationWork.getState().frame).not.toBeNull() + }) +})