diff --git a/apps/app/src/components/editor/annotations/AccessShapeChoice.tsx b/apps/app/src/components/editor/annotations/AccessShapeChoice.tsx new file mode 100644 index 00000000..00c63e68 --- /dev/null +++ b/apps/app/src/components/editor/annotations/AccessShapeChoice.tsx @@ -0,0 +1,45 @@ +import type { AccessShape } from '@/editor/annotations/accessShape' +import { useT } from '@/i18n/useT' + +const SHAPES: readonly AccessShape[] = ['rectangle', 'polygon', 'circle'] + +/** + * Board 07: the access tool's shape, a segmented choice in the strip (D5). The native radios + * give the arrow keys inside the group; the legend names it for a screen reader only. + */ +export default function AccessShapeChoice({ + shape, + onChange, +}: { + shape: AccessShape + onChange: (shape: AccessShape) => void +}) { + const t = useT() + return ( +
+ + {t('editor.annotations.shape.legend')} + + {SHAPES.map((value) => ( + + ))} +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx index b6b92dfe..41b18cac 100644 --- a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx @@ -6,7 +6,8 @@ import { type PointerEvent, type RefObject, } from 'react' -import type { Geometry } from '@faunosteo/core-wasm/types' +import type { Circle, Geometry, Polygon } from '@faunosteo/core-wasm/types' +import type { AccessShape } from '@/editor/annotations/accessShape' import { BAND_BACKGROUND, useBandResize } from '@/anatomy/frameBands' import Button from '@/components/ui/Button' import Notice from '@/components/ui/Notice' @@ -66,6 +67,9 @@ export interface AnnotationCanvasProps { onOpen: (id: string) => void /** A click with a drawing tool, in drawing units, and its closing reach (R-11). */ onPlace: (at: XY, reach: number) => void + /** D5: the access tool's shape; a rectangle or circle is drawn by a drag or a click. */ + accessShape: AccessShape + onShape: (geometry: Polygon | Circle) => void onDrop: Drop onHandle: (action: HandleAction) => void onDeselect: () => void @@ -115,6 +119,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) { transform: transformOf(gestures.framing.framing), overlay: { ...props.overlay, + pending: gestures.accessDraft ?? props.overlay.pending, svgRef: overlay, dragged: gestures.drag, hover: preview.hover, diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index fcad2e92..a887becb 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -9,6 +9,7 @@ import { useAnnotationRequest } from '@/editor/annotations/focusTarget' import { ordinaryCategories } from '@/editor/accessCategory' import type { NewKind } from '@/editor/annotations/creation' import { creationTracing } from '@/editor/annotations/creationWork' +import { useAccessTargetClear } from '@/editor/annotations/useAccessTargetClear' import { useCreationFollow } from '@/editor/annotations/useCreationFollow' import { PENDING_ID, @@ -169,6 +170,7 @@ function useScene(props: Props): Scene { const work = useAnnotationWork((s) => s.creation) const creation = work?.viewId === viewId ? work : null useSceneRequest(props, { ui, viewId, dispatch, creation }) + useAccessTargetClear(dispatch) return { doc, ui, @@ -312,6 +314,7 @@ function CanvasColumn({ noCategory={noCategory} linkDisabled={model.children.length === 0} armed={armedTool(scene.ui)} + accessShape={scene.ui.accessShape} centre={centreOf(scene)} onAdd={(kind) => guarded(() => addAtCentre(kind, scene))()} onArm={(kind, button) => armFromAdd(kind, button, scene)} @@ -439,6 +442,8 @@ function CanvasStage({ onSelect={(id) => free && dispatch({ type: 'select', id })} onOpen={(id) => free && scene.onOpen(id, 'drawing')} onPlace={work.placement.onPlace} + accessShape={ui.accessShape} + onShape={work.placement.onShape} onDrop={work.placement.onDrop} onHandle={work.zone.onHandle} onDeselect={() => free && onDeselect()} diff --git a/apps/app/src/components/editor/annotations/KeyboardAdd.tsx b/apps/app/src/components/editor/annotations/KeyboardAdd.tsx index c490c1a3..039ea689 100644 --- a/apps/app/src/components/editor/annotations/KeyboardAdd.tsx +++ b/apps/app/src/components/editor/annotations/KeyboardAdd.tsx @@ -1,5 +1,6 @@ import type { MouseEvent } from 'react' import Button from '@/components/ui/Button' +import type { AccessShape } from '@/editor/annotations/accessShape' import type { NewKind } from '@/editor/annotations/creation' import { TOOL_OF, type ToolId } from '@/editor/annotations/uiState' import { useT } from '@/i18n/useT' @@ -22,6 +23,7 @@ export default function KeyboardAdd({ noCategory, linkDisabled, armed, + accessShape, centre, onAdd, onArm, @@ -34,6 +36,8 @@ export default function KeyboardAdd({ linkDisabled: boolean /** The armed tool (`armedTool`): its button shows pressed. */ armed: ToolId + /** The access tool's chosen shape: the armed announcement says it (D5). */ + accessShape: AccessShape /** « Placer au centre » when it can be used now, else null: its slot stays reserved. */ centre: (() => void) | null onAdd: (kind: NewKind) => void @@ -44,7 +48,15 @@ export default function KeyboardAdd({ if (event.detail === 0) onAdd(kind) else if (event.detail === 1) onArm(kind, event.currentTarget) } + const announcement = (kind: NewKind) => + kind === 'detail_trigger' + ? t('editor.annotations.armed.detail_trigger_shape').replace( + '{shape}', + () => t(`editor.annotations.shape.${accessShape}`), + ) + : t(`editor.annotations.armed.${kind}`) const armedKind = centre ? KINDS.find((k) => TOOL_OF[k] === armed) : undefined + const announced = armedKind && announcement(armedKind) return (
{KINDS.map((kind) => ( @@ -76,7 +88,7 @@ export default function KeyboardAdd({ {/* Always mounted: the region exists before its text (M-3). */}

- {armedKind ? t(`editor.annotations.armed.${armedKind}`) : ''} + {announced ?? ''}

) diff --git a/apps/app/src/components/editor/annotations/SceneStrip.tsx b/apps/app/src/components/editor/annotations/SceneStrip.tsx index 55b68447..0ceb76d3 100644 --- a/apps/app/src/components/editor/annotations/SceneStrip.tsx +++ b/apps/app/src/components/editor/annotations/SceneStrip.tsx @@ -19,6 +19,7 @@ import { targetOfKey } from '@/editor/navigation' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' import type { Scene, Work } from './EditableAnnotations' +import AccessShapeChoice from './AccessShapeChoice' import CreationCommands from './CreationCommands' import EditStrip, { type StripNotice } from './EditStrip' import { @@ -63,6 +64,7 @@ export default function SceneStrip({ : stripLeadOf( { tool: ui.tool, + accessShape: ui.accessShape, tracing: scene.tracing, creation: scene.creation, frame, @@ -261,6 +263,14 @@ function SceneCommands({ /> ) } + if (ui.tool === 'link' && !creation) { + return ( + dispatch({ type: 'access_shape', shape })} + /> + ) + } if (ui.tool !== 'point' || creation || !frame) return null return ( + +export const isDrawn = (shape: AccessShape): shape is DrawnShape => + shape !== 'polygon' + +/** D5, D9: a rectangle access, stored as a polygon of four vertices clockwise from the + * top-left, so it reshapes by its vertices like a zone; rounded inward to 0.01, so an access + * held against the parent's edge stays inside it. */ +export function rectanglePolygon(box: Frame): Polygon { + const l = ceil2(box.x) + const t = ceil2(box.y) + const r = floor2(box.x + box.w) + const b = floor2(box.y + box.h) + return { + type: 'polygon', + points: [ + [l, t], + [r, t], + [r, b], + [l, b], + ], + } +} + +/** A1: the generated access, the frame's rectangle grown around its centre to `minSpan` on + * each side when needed (the core's smallest readable access on the parent), kept in `bounds`. */ +export function accessBox( + frame: Frame, + minSpan: number | null, + bounds: Frame, +): { box: Frame; grown: boolean } { + const span = minSpan ?? 0 + const w = Math.max(frame.w, span) + const h = Math.max(frame.h, span) + const grown = w > frame.w || h > frame.h + const box = clampInto( + { x: frame.x + (frame.w - w) / 2, y: frame.y + (frame.h - h) / 2, w, h }, + bounds, + ) + return { box, grown } +} + +/** D5: a circle dragged from its centre to its edge, kept inside `bounds`; a radius under + * `minR` counts as a click: `fallback()`. */ +export function circleFromDrag( + centre: XY, + edge: XY, + minR: number, + bounds: Frame, + fallback: () => Circle, +): Circle { + const r = Math.hypot(edge.x - centre.x, edge.y - centre.y) + if (r < minR) return fallback() + return circleInside({ type: 'circle', cx: centre.x, cy: centre.y, r }, bounds) +} + +/** D5: the default circle, a twelfth of the visible width in radius, centred on `at`. */ +export function defaultCircle(at: XY, visible: Frame, bounds: Frame): Circle { + return circleInside( + { type: 'circle', cx: at.x, cy: at.y, r: visible.w / 12 }, + bounds, + ) +} + +/** The circle moved (and shrunk only if larger) so it lies inside `bounds`, rounded inward to + * 0.01 so it stays inside them. */ +export function circleInside(circle: Circle, bounds: Frame): Circle { + const r = floor2(Math.min(circle.r, bounds.w / 2, bounds.h / 2)) + const inside = (v: number, lo: number, hi: number) => + Math.min(Math.max(round2(v), ceil2(lo)), floor2(hi)) + const cx = inside(circle.cx, bounds.x + r, bounds.x + bounds.w - r) + const cy = inside(circle.cy, bounds.y + r, bounds.y + bounds.h - r) + return { type: 'circle', cx, cy, r } +} + +/** D5: the access a click or « Placer au centre » places at `at`: the default frame as a + * polygon, or the default circle. */ +export function defaultAccess( + shape: DrawnShape, + at: XY, + visible: Frame, + bounds: Frame, +): Polygon | Circle { + if (shape === 'circle') return defaultCircle(at, visible, bounds) + return rectanglePolygon(defaultBox(at, visible, AREA_RATIO, bounds)) +} + +/** The view an access is preset to open (Tasks 10 and 12): `target` only while it is still + * a direct child of the view, else nothing. */ +export function presetTarget( + target: string | null, + children: readonly { id: string }[], +): string { + return children.some((child) => child.id === target) ? target! : '' +} diff --git a/apps/app/src/editor/annotations/creation.ts b/apps/app/src/editor/annotations/creation.ts index 071dcdba..c056395f 100644 --- a/apps/app/src/editor/annotations/creation.ts +++ b/apps/app/src/editor/annotations/creation.ts @@ -15,6 +15,7 @@ import { type XY, } from './frame' import { ACCESS_CATEGORY_ID, ordinaryCategories } from '../accessCategory' +import { defaultAccess, isDrawn, type AccessShape } from './accessShape' import type { Correction } from './correction' import type { EditableGeometry } from './geometryEdit' @@ -50,10 +51,14 @@ export const LATERALITIES: readonly Laterality[] = [ 'right', ] -/** An access starts in the internal category; a point or zone, in the first ordinary one. */ +/** + * An access starts in the internal category and, when given, on the view `opensViewId` + * (the preset); a point or zone, in the first ordinary category. + */ export function emptyForm( doc: AnatomicalSheetDocument, kind: NewKind = 'point', + opensViewId = '', ): CreationForm { const categoryId = kind === 'detail_trigger' @@ -64,7 +69,7 @@ export function emptyForm( en: '', categoryId, laterality: '', - opensViewId: '', + opensViewId, zoneId: '', regionCode: '', } @@ -80,15 +85,35 @@ export function directChildren( ) } +/** The access tool's chosen shape, and the part of F on screen its centre is read from. */ +export interface AccessPlacement { + shape: AccessShape + visible: Frame +} + +/** The access a keyboard placement holds: a drawn shape at the visible centre, else the triangle. */ +function accessPending(frame: Frame, access: AccessPlacement): PendingElement { + const { shape, visible } = access + if (!isDrawn(shape)) { + const points = centreTriangle(frame) + return { kind: 'detail_trigger', geometry: { type: 'polygon', points } } + } + const at = { x: visible.x + visible.w / 2, y: visible.y + visible.h / 2 } + const geometry = defaultAccess(shape, at, visible, frame) + return { kind: 'detail_trigger', geometry } +} + /** * The pending element a keyboard « Ajouter … » button holds at the centre of F; a point - * takes `radius`, the size of a new point (A5). + * takes `radius`, the size of a new point (A5); an access takes its chosen shape (D5). */ export function keyboardPending( kind: NewKind, frame: Frame, radius: number, + access: AccessPlacement | null = null, ): PendingElement { + if (kind === 'detail_trigger' && access) return accessPending(frame, access) if (kind === 'point') { const circle = centreCircle(frame, radius) return { diff --git a/apps/app/src/editor/annotations/frameBox.ts b/apps/app/src/editor/annotations/frameBox.ts index 0061eee2..2877cdc2 100644 --- a/apps/app/src/editor/annotations/frameBox.ts +++ b/apps/app/src/editor/annotations/frameBox.ts @@ -68,6 +68,9 @@ export function clampInto(box: Frame, bounds: Frame): Frame { return { x, y, w, h } } +/** The canvas box is 4:3: the ratio of the default frame (D4). */ +export const AREA_RATIO = 4 / 3 + /** D4: a third of the visible width at the drawing area's ratio (w / h), centred on `at`. */ export function defaultBox( at: XY, diff --git a/apps/app/src/editor/annotations/frameDraw.ts b/apps/app/src/editor/annotations/frameDraw.ts index 218241c2..a50d3ba8 100644 --- a/apps/app/src/editor/annotations/frameDraw.ts +++ b/apps/app/src/editor/annotations/frameDraw.ts @@ -1,14 +1,13 @@ import type { RefObject } from 'react' +import type { Circle } from '@faunosteo/core-wasm/types' +import { defaultCircle } from './accessShape' import { parseFrame, type Frame, type XY } from './frame' -import { boxFromCorners, defaultBox } from './frameBox' +import { AREA_RATIO, 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 @@ -48,6 +47,15 @@ export function defaultAt(surface: FrameSurface, at: XY, bounds: Frame): Frame { return defaultBox(at, visible, AREA_RATIO, bounds) } +/** D5: the default circle of a click, or of a drag too short, centred on `at`. */ +export function defaultCircleAt( + surface: FrameSurface, + at: XY, + bounds: Frame, +): Circle { + return defaultCircle(at, visibleDrawing(surface, bounds), bounds) +} + /** A click while drawing: the default frame where it fell. */ export function placeDefault(surface: FrameSurface, at: XY): void { const bounds = parentFrame(surface.overlay.current) diff --git a/apps/app/src/editor/annotations/stripLead.ts b/apps/app/src/editor/annotations/stripLead.ts index 86909c19..b08b9cae 100644 --- a/apps/app/src/editor/annotations/stripLead.ts +++ b/apps/app/src/editor/annotations/stripLead.ts @@ -8,6 +8,7 @@ import { annotationName } from '@/components/editor/annotations/AnnotationList' import type { GlyphName } from '@/components/editor/EditorGlyph' import type { Locale } from '@/i18n/types' import { pluralKey } from '../plural' +import type { AccessShape } from './accessShape' import type { PendingElement } from './creation' import { HANDLE_CAP } from './polygonEdit' import type { ToolId, Tracing } from './uiState' @@ -178,9 +179,18 @@ const TOOL_LEAD: Record< }, } +/** The access tool's detail: how the chosen shape is placed (D5). */ +const ACCESS_DETAIL: Record = { + rectangle: 'editor.annotations.strip.access_rectangle', + polygon: 'editor.annotations.strip.first_vertex', + circle: 'editor.annotations.strip.access_circle', +} + /** What the strip reads of the drawing: the tool, the tracing shown, the creation. */ export interface LeadState { tool: ToolId + /** The access tool's chosen shape; its detail says how to place it. */ + accessShape?: AccessShape tracing: Tracing | null creation?: Creation | null /** An open frame work: it leads before anything else. */ @@ -237,9 +247,13 @@ export function stripLeadOf( } if (selected) return selectionLead(selected, doc.views, ctx) const lead = TOOL_LEAD[ui.tool] + const detail = + ui.tool === 'link' && ui.accessShape + ? ACCESS_DETAIL[ui.accessShape] + : lead.detail return { title: ctx.t(lead.title), - detail: ctx.t(lead.detail), + detail: ctx.t(detail), icon: lead.icon, } } diff --git a/apps/app/src/editor/annotations/uiState.ts b/apps/app/src/editor/annotations/uiState.ts index 491cc850..d886a0b3 100644 --- a/apps/app/src/editor/annotations/uiState.ts +++ b/apps/app/src/editor/annotations/uiState.ts @@ -1,4 +1,5 @@ import type { Point } from '@faunosteo/core-wasm/types' +import type { AccessShape } from './accessShape' import type { NewKind } from './creation' import type { Creation } from './workStore' @@ -36,6 +37,14 @@ export interface UiState { filter: string /** The size the strip's slider chose for the next point (A5); null: the view's own. */ size: number | null + /** D5: the shape the access tool places; the last choice lasts the session. */ + accessShape: AccessShape + /** + * The detail view the next access opens (the preset « Vue ouverte »); read only while it + * is still a direct child of the view. Cleared by a view change, an undo or a redo, an + * access commit and the access tool being disarmed. + */ + accessTarget: string | null } export type UiAction = @@ -51,6 +60,8 @@ export type UiAction = | { type: 'hint'; hint: string | null } | { type: 'filter'; term: string } | { type: 'size'; size: number | null } + | { type: 'access_shape'; shape: AccessShape } + | { type: 'access_target'; viewId: string | null } export const initialUi: UiState = { viewId: null, @@ -61,6 +72,8 @@ export const initialUi: UiState = { hint: null, filter: '', size: null, + accessShape: 'rectangle', + accessTarget: null, } /** @@ -84,11 +97,16 @@ function retraced(state: UiState, points: Point[]): UiState { export function uiReducer(state: UiState, action: UiAction): UiState { switch (action.type) { case 'view': - return { ...initialUi, viewId: action.viewId } + return { + ...initialUi, + viewId: action.viewId, + accessShape: state.accessShape, + } case 'tool': return { ...state, tool: action.tool, + accessTarget: action.tool === 'link' ? state.accessTarget : null, armedFrom: action.from ?? 'tool', tracing: null, hint: null, @@ -143,5 +161,9 @@ export function uiReducer(state: UiState, action: UiAction): UiState { return { ...state, filter: action.term } case 'size': return { ...state, size: action.size } + case 'access_shape': + return { ...state, accessShape: action.shape } + case 'access_target': + return { ...state, accessTarget: action.viewId } } } diff --git a/apps/app/src/editor/annotations/useAccessTargetClear.ts b/apps/app/src/editor/annotations/useAccessTargetClear.ts new file mode 100644 index 00000000..97b93d85 --- /dev/null +++ b/apps/app/src/editor/annotations/useAccessTargetClear.ts @@ -0,0 +1,20 @@ +import { useEffect, type Dispatch } from 'react' +import { useEditorStore } from '../state/editorStore' +import type { UiAction } from './uiState' + +/** + * The preset « Vue ouverte » ends with an undo or a redo: either one takes an entry off a + * history stack, which a commit (one more undo entry) never does while a redo stays empty. + */ +export function useAccessTargetClear(dispatch: Dispatch): void { + useEffect( + () => + useEditorStore.subscribe((state, before) => { + const stepped = + state.undo.length < before.undo.length || + state.redo.length < before.redo.length + if (stepped) dispatch({ type: 'access_target', viewId: null }) + }), + [dispatch], + ) +} diff --git a/apps/app/src/editor/annotations/useCanvasGestures.ts b/apps/app/src/editor/annotations/useCanvasGestures.ts index fdba14d7..fe69250c 100644 --- a/apps/app/src/editor/annotations/useCanvasGestures.ts +++ b/apps/app/src/editor/annotations/useCanvasGestures.ts @@ -86,6 +86,7 @@ export function useCanvasGestures(input: GestureInput) { drag: press.preview, finger: press.finger, frameBox: press.frameBox, + accessDraft: press.accessDraft, boxProps: { ...composedPointer(framing, press), onKeyDown, diff --git a/apps/app/src/editor/annotations/useFrameDrag.ts b/apps/app/src/editor/annotations/useFrameDrag.ts index efbf3c2a..c6423424 100644 --- a/apps/app/src/editor/annotations/useFrameDrag.ts +++ b/apps/app/src/editor/annotations/useFrameDrag.ts @@ -1,4 +1,10 @@ import { useRef, useState } from 'react' +import type { Circle, Polygon } from '@faunosteo/core-wasm/types' +import { + circleFromDrag, + rectanglePolygon, + type DrawnShape, +} from './accessShape' import type { Frame, XY } from './frame' import { MIN_FRAME_PX, @@ -8,7 +14,12 @@ import { moveBox, resizeBox, } from './frameBox' -import { defaultAt, parentFrame, type FrameSurface } from './frameDraw' +import { + defaultCircleAt, + defaultAt, + parentFrame, + type FrameSurface, +} from './frameDraw' import { setFrameBox } from './frameWork' import { clientToDrawing, drawingPerClientPx } from './gesture' import type { FramePart } from './frameBox' @@ -28,8 +39,11 @@ interface Base { perPx: number kind: PointerKind } +/** What a `draw` draws: the detail view's frame, or an access (D5) of a drawn shape. */ +export type DrawTarget = 'frame' | DrawnShape + type Gesture = - | (Base & { type: 'draw' }) + | (Base & { type: 'draw'; target: DrawTarget }) | (Base & { type: 'drag_frame'; part: FramePart; start: Frame }) function begin( @@ -37,6 +51,7 @@ function begin( action: FrameDragAction, pressedAt: XY, kind: PointerKind, + target: DrawTarget, ): Gesture | null { const svg = surface.overlay.current const origin = clientToDrawing(svg, pressedAt) @@ -44,7 +59,7 @@ function begin( const perPx = drawingPerClientPx(svg) if (!origin || !bounds || perPx === null) return null const base = { origin, bounds, perPx, kind } - if (action.type === 'draw') return { ...base, type: 'draw' } + if (action.type === 'draw') return { ...base, type: 'draw', target } const start = useAnnotationWork.getState().frame?.box return start ? { ...base, type: 'drag_frame', part: action.part, start } @@ -73,6 +88,29 @@ function boxAt(g: Gesture, now: XY, shift: boolean): Frame { }) } +type Draw = Extract + +/** The access the drag shows (D5): what it spans so far, no minimum, nothing placed yet. */ +function accessAt(g: Draw, now: XY, shift: boolean): Polygon | Circle { + if (g.target !== 'circle') return rectanglePolygon(boxAt(g, now, shift)) + const none: Circle = { type: 'circle', cx: g.origin.x, cy: g.origin.y, r: 0 } + return circleFromDrag(g.origin, now, 0, g.bounds, () => none) +} + +/** What a drop places (D5): the drawn shape, or the default one for a drag too short. */ +function droppedAccess( + g: Draw, + surface: FrameSurface, + now: XY, +): Polygon | Circle { + if (g.target === 'circle') { + const fallback = () => defaultCircleAt(surface, g.origin, g.bounds) + return circleFromDrag(g.origin, now, minOf(g) / 2, g.bounds, fallback) + } + const box = droppedBox(g, surface, now, false) + return rectanglePolygon(box) +} + /** What a drop commits: a drawn box, or a click-sized one, the default frame (D4, D6). */ function droppedBox( g: Gesture, @@ -108,33 +146,47 @@ function useFinger() { return { finger, open, follow, close } } +/** What the gesture shows: the frame's box, or an access's shape (D5). */ +type Shown = { frame: Frame } | { access: Polygon | Circle } + +function shownAt(g: Gesture, now: XY, shift: boolean): Shown { + if (g.type === 'draw' && g.target !== 'frame') + return { access: accessAt(g, now, shift) } + return { frame: boxAt(g, now, shift) } +} + /** - * 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). + * A frame drag: `draw` (a box from two corners, or an access's rectangle or circle, D5) and + * `drag_frame` (a handle or the body). The shape shown is local to the canvas; the drop sets + * the work item's box once, or hands the access to `onAccess`, and nothing reaches the core + * (BDR-050). */ -export function useFrameDrag(surface: FrameSurface) { +export function useFrameDrag( + surface: FrameSurface, + onAccess: (access: Polygon | Circle) => void, +) { const gesture = useRef(null) - const [preview, setPreview] = useState(null) + const [shown, setShown] = useState(null) const finger = useFinger() const cancel = () => { gesture.current = null - setPreview(null) + setShown(null) finger.close() } const follow = (client: XY, shift: boolean) => { const now = clientToDrawing(surface.overlay.current, client) if (!gesture.current || !now) return finger.follow(client) - setPreview(boxAt(gesture.current, now, shift)) + setShown(shownAt(gesture.current, now, shift)) } const start = ( action: FrameDragAction, pressedAt: XY, client: XY, kind: PointerKind, + target: DrawTarget, ) => { - gesture.current = begin(surface, action, pressedAt, kind) + gesture.current = begin(surface, action, pressedAt, kind, target) if (kind === 'touch' && action.type === 'drag_frame' && gesture.current) finger.open(client) follow(client, false) @@ -144,8 +196,18 @@ export function useFrameDrag(surface: FrameSurface) { const now = clientToDrawing(surface.overlay.current, client) cancel() if (!g || !now) return + if (g.type === 'draw' && g.target !== 'frame') + return onAccess(droppedAccess(g, surface, now)) const box = droppedBox(g, surface, now, shift) if (!unchanged(g, box)) setFrameBox(box) } - return { preview, finger: finger.finger, start, follow, drop, cancel } + return { + preview: shown && 'frame' in shown ? shown.frame : null, + draft: shown && 'access' in shown ? shown.access : null, + finger: finger.finger, + start, + follow, + drop, + cancel, + } } diff --git a/apps/app/src/editor/annotations/usePlacement.ts b/apps/app/src/editor/annotations/usePlacement.ts index c45f8b44..42c5c6ac 100644 --- a/apps/app/src/editor/annotations/usePlacement.ts +++ b/apps/app/src/editor/annotations/usePlacement.ts @@ -2,8 +2,10 @@ import type { Dispatch, KeyboardEvent } from 'react' import type { Annotation, AnatomicalSheetDocument, + Circle, Geometry, Point, + Polygon, } from '@faunosteo/core-wasm/types' import { useT } from '@/i18n/useT' import { updateGeometry, type CommitContext } from './annotationCommit' @@ -22,11 +24,14 @@ import { type CreationStart, } from './creationWork' import { askCreation } from './creationAsk' +import { presetTarget } from './accessShape' import { round2, type Frame, type XY } from './frame' +import { canvasSurface, visibleDrawing } from './frameDraw' import { newPointSize } from './pointSize' import { endMode, PENDING_ID, useAnnotationWork } from './workStore' import type { ToolId, Tracing, UiAction, UiState } from './uiState' import type { GestureMessages } from './useGestureMessage' +import type { ViewModel } from './useViewModel' export const TOOL_TARGET: Record, NewKind> = { point: 'point', @@ -42,6 +47,8 @@ export interface PlacementInput { frame: Frame | null doc: AnatomicalSheetDocument viewId: string + /** Its direct child views: the preset of an access reads them. */ + model: Pick context: CommitContext /** The line under the drawing: a kept drop says so with « Défaire », a refused one in red. */ message: Pick @@ -80,12 +87,25 @@ function closeRedraw(input: PlacementInput, tracing: Tracing): void { input.message.show(text, { undo: true, tone: 'info' }) } +type StartScene = Pick< + PlacementInput, + 'viewId' | 'frame' | 'doc' | 'model' | 'ui' +> + +/** The view a new access is preset to open: the access target while it is a direct child. */ +const opensPreset = (kind: NewKind, { ui, model }: StartScene): string => + kind === 'detail_trigger' ? presetTarget(ui.accessTarget, model.children) : '' + /** Where a creation on this view starts: F, the origin, a fresh form (A4). */ const creationStart = ( - { viewId, frame, doc }: Pick, + scene: StartScene, origin: CreationStart['origin'], kind: NewKind, -): CreationStart => ({ viewId, frame, origin, form: emptyForm(doc, kind) }) +): CreationStart => { + const { viewId, frame, doc } = scene + const form = emptyForm(doc, kind, opensPreset(kind, scene)) + return { viewId, frame, origin, form } +} const isRedraw = (tracing: Tracing | null) => tracing?.target === 'replace' @@ -101,7 +121,7 @@ function popTrace({ tracing, dispatch }: PlacementInput): void { * keyboard path all end here; a stale strip hint goes first. */ export function placeAtCentre( - scene: Pick, + scene: StartScene & Pick, kind: NewKind, origin: CreationStart['origin'], ): void { @@ -109,12 +129,27 @@ export function placeAtCentre( if (!frame || useAnnotationWork.getState().creation) return dispatch({ type: 'hint', hint: null }) const size = newPointSize(doc.annotations, viewId, frame, ui.size) + const surface = canvasSurface() + const visible = surface ? visibleDrawing(surface, frame) : frame + const access = { shape: ui.accessShape, visible } placePending( creationStart(scene, origin, kind), - keyboardPending(kind, frame, size), + keyboardPending(kind, frame, size, access), ) } +/** + * An access drawn by a drag or a click (D5): its shape is pending, the dialog opens as it + * does for the keyboard's. The core judges it at « Créer ». + */ +function placeShape(input: PlacementInput, geometry: Polygon | Circle): void { + input.dispatch({ type: 'hint', hint: null }) + placePending(creationStart(input, input.ui.armedFrom, 'detail_trigger'), { + kind: 'detail_trigger', + geometry, + }) +} + /** * Enter on the drawing while an add tool is armed and nothing is started places the kind's * shape at the centre, as the C7 keyboard path does. @@ -270,6 +305,7 @@ export function usePlacement(input: PlacementInput) { } return { onPlace, + onShape: (geometry: Polygon | Circle) => placeShape(input, geometry), onDrop: dropAction(input), onTraceKey: tracing.onTraceKey, closeTracing: tracing.closeTracing, diff --git a/apps/app/src/editor/annotations/usePressGesture.ts b/apps/app/src/editor/annotations/usePressGesture.ts index b963c2fd..bb57b885 100644 --- a/apps/app/src/editor/annotations/usePressGesture.ts +++ b/apps/app/src/editor/annotations/usePressGesture.ts @@ -1,4 +1,11 @@ import { useEffect, useRef, type PointerEvent, type RefObject } from 'react' +import type { Circle, Polygon } from '@faunosteo/core-wasm/types' +import { + isDrawn, + rectanglePolygon, + type AccessShape, + type DrawnShape, +} from './accessShape' import type { XY } from './frame' import { clientToDrawing, drawingPerClientPx } from './gesture' import { HANDLE_CAP } from './polygonEdit' @@ -26,8 +33,18 @@ 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 { + defaultCircleAt, + defaultAt, + framePhase, + parentFrame, + placeDefault, +} from './frameDraw' +import { + useFrameDrag, + type DrawTarget, + type FrameDragAction, +} from './useFrameDrag' import { useAnnotationWork } from './workStore' export interface PressInput extends BlockDragInput { @@ -41,6 +58,10 @@ export interface PressInput extends BlockDragInput { onOpen: (id: string) => void /** A click with a drawing tool, in drawing units, with its closing reach (R-11). */ onPlace: (at: XY, reach: number) => void + /** D5: the access tool's chosen shape; a rectangle or circle is drawn by a drag or a click. */ + accessShape: AccessShape + /** D5: a rectangle or circle access was drawn, or placed by a click. */ + onShape: (geometry: Polygon | Circle) => void /** A click on a vertex handle, a « + » or the « − » bubble. */ onHandle: (action: HandleAction) => void /** A tap on the empty drawing with the select tool. */ @@ -204,6 +225,35 @@ function frameClick( if (at) placeDefault(input, at) } +/** + * The shape the access tool draws by a drag or a click (D5), while it is armed with a + * rectangle or a circle and nothing else is started; null for the polygon, traced by vertices. + */ +function drawnAccess(input: PressInput): DrawnShape | null { + if (input.tool !== 'link' || !isDrawn(input.accessShape)) return null + const { creation, frame } = useAnnotationWork.getState() + return creation === null && frame === null ? input.accessShape : null +} + +/** A click while the access tool draws: the default shape where it fell (D5). */ +function accessClick( + input: PressInput, + shape: DrawnShape, + target: PressTarget, + event: PointerEvent, +): void { + const action = clickAction(target, selectionOf(null), 'draw') + if (action.type !== 'place_default') return + const at = clientToDrawing(input.overlay.current, clientOf(event)) + const bounds = parentFrame(input.overlay.current) + if (!at || !bounds) return + input.onShape( + shape === 'circle' + ? defaultCircleAt(input, at, bounds) + : rectanglePolygon(defaultAt(input, at, bounds)), + ) +} + /** 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') { @@ -211,6 +261,8 @@ function onClick(f: Feed, target: PressTarget, event: PointerEvent): void { } const phase = framePhase(f.input.viewId) if (phase) return frameClick(f.input, target, event, phase) + const shape = drawnAccess(f.input) + if (shape) return accessClick(f.input, shape, target, event) if (f.input.tool !== 'select') return place(f.input, event) if (!inMoveMode()) selectClick(f, target, event) } @@ -241,6 +293,12 @@ function focusPressed(f: Feed, target: PressTarget): void { if (element instanceof SVGElement) element.focus({ preventScroll: true }) } +/** What a `draw` draws: the frame being drawn, else the access tool's shape. */ +const drawTargetOf = (input: PressInput): DrawTarget => + framePhase(input.viewId) === 'draw' + ? 'frame' + : (drawnAccess(input) ?? 'frame') + function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) { if (effect?.type === 'drag_cancel') { f.drag.cancel() @@ -261,7 +319,8 @@ function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) { const kind = pointerKindOf(event.pointerType) const { pressedAt } = f.machine.current const action = effect.action as FrameDragAction - f.frameDrag.start(action, pressedAt, clientOf(event), kind) + const target = drawTargetOf(f.input) + f.frameDrag.start(action, pressedAt, clientOf(event), kind, target) } if (effect.type === 'drag_start' && BLOCK_DRAGS.has(effect.action.type)) { const { action } = effect @@ -286,7 +345,7 @@ const contextOf = (input: PressInput) => { return { movable: movable(input), moveMode: inMoveMode(), - drawing: phase === 'draw', + drawing: phase === 'draw' || drawnAccess(input) !== null, adjusting: phase === 'adjust', } } @@ -423,7 +482,7 @@ const IDLE: Press = { phase: 'idle' } */ export function usePressGesture(input: PressInput) { const drag = useBlockDrag(input) - const frameDrag = useFrameDrag(input) + const frameDrag = useFrameDrag(input, input.onShape) const machine = useRef({ press: IDLE, target: { kind: 'empty' }, @@ -442,6 +501,7 @@ export function usePressGesture(input: PressInput) { return { preview: drag.preview, frameBox: frameDrag.preview, + accessDraft: frameDrag.draft, finger: drag.finger ?? frameDrag.finger, panning: () => { const press = machine.current.press diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 8a12c253..15fcd133 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1769,8 +1769,7 @@ export const en: Dict = { 'editor.annotations.correction_cancel': 'Cancel', 'editor.annotations.no_category': 'Create an annotation category first (Annotations, Categories section).', - 'editor.annotations.no_child_view': - 'No detail view opens from this view: create one in Annotations, Views section.', + 'editor.annotations.no_child_view': 'Create a detail view first.', 'editor.annotations.add.point': 'Add a point', 'editor.annotations.add.zone': 'Add a zone', 'editor.annotations.add.detail_trigger': 'Add a link', @@ -1779,8 +1778,16 @@ export const en: Dict = { 'Point tool on: tap or click the drawing where you want it, or choose “Place at the centre”, below the drawing (Enter on the drawing does the same).', 'editor.annotations.armed.zone': 'Zone tool on: place the vertices on the drawing, or choose “Place at the centre”, below the drawing (Enter on the drawing does the same).', - 'editor.annotations.armed.detail_trigger': - 'Link tool on: place the vertices on the drawing, or choose “Place at the centre”, below the drawing (Enter on the drawing does the same).', + 'editor.annotations.armed.detail_trigger_shape': + 'Access tool armed, {shape} shape.', + 'editor.annotations.shape.legend': 'Access shape', + 'editor.annotations.shape.rectangle': 'Rectangle', + 'editor.annotations.shape.polygon': 'Polygon', + 'editor.annotations.shape.circle': 'Circle', + 'editor.annotations.strip.access_rectangle': + 'Drag to draw the rectangle, or click for a default rectangle.', + 'editor.annotations.strip.access_circle': + 'Drag from the centre to the edge, or click for a default radius.', 'editor.annotations.new.point': 'New point', 'editor.annotations.new.zone': 'New zone', 'editor.annotations.new.detail_trigger': 'New link', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 46011d74..f40632e9 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1835,8 +1835,7 @@ export const fr: Dict = { 'editor.annotations.correction_cancel': 'Annuler', 'editor.annotations.no_category': "Créez d'abord une catégorie d'annotation (Annotations, section Catégories).", - 'editor.annotations.no_child_view': - "Aucune vue détaillée ne s'ouvre depuis cette vue : créez-en une dans Annotations, section Vues.", + 'editor.annotations.no_child_view': "Créez d'abord une vue de détail.", 'editor.annotations.add.point': 'Ajouter un point', 'editor.annotations.add.zone': 'Ajouter une zone', 'editor.annotations.add.detail_trigger': 'Ajouter un accès', @@ -1845,8 +1844,16 @@ export const fr: Dict = { "Outil Point actif : touchez ou cliquez sur le dessin à l'endroit voulu, ou choisissez « Placer au centre », sous le dessin (Entrée dans le dessin fait de même).", 'editor.annotations.armed.zone': 'Outil Zone actif : posez les sommets sur le dessin, ou choisissez « Placer au centre », sous le dessin (Entrée dans le dessin fait de même).', - 'editor.annotations.armed.detail_trigger': - 'Outil Accès actif : posez les sommets sur le dessin, ou choisissez « Placer au centre », sous le dessin (Entrée dans le dessin fait de même).', + 'editor.annotations.armed.detail_trigger_shape': + 'Outil Accès armé, forme {shape}.', + 'editor.annotations.shape.legend': "Forme de l'accès", + 'editor.annotations.shape.rectangle': 'Rectangle', + 'editor.annotations.shape.polygon': 'Polygone', + 'editor.annotations.shape.circle': 'Cercle', + 'editor.annotations.strip.access_rectangle': + 'Glissez pour tracer le rectangle, ou cliquez pour un rectangle par défaut.', + 'editor.annotations.strip.access_circle': + 'Glissez du centre vers le bord, ou cliquez pour un rayon par défaut.', 'editor.annotations.new.point': 'Nouveau point', 'editor.annotations.new.zone': 'Nouvelle zone', 'editor.annotations.new.detail_trigger': 'Nouvel accès', diff --git a/apps/app/tests/unit/annotations.accessShape.test.ts b/apps/app/tests/unit/annotations.accessShape.test.ts new file mode 100644 index 00000000..06152ec6 --- /dev/null +++ b/apps/app/tests/unit/annotations.accessShape.test.ts @@ -0,0 +1,151 @@ +/** U2 Task 14: the shapes of an access (D5): rectangle polygon, circle, and the shape state. */ +import { describe, expect, it } from 'vitest' +import { + accessBox, + circleFromDrag, + circleInside, + defaultCircle, + presetTarget, + rectanglePolygon, +} from '@/editor/annotations/accessShape' +import type { Frame } from '@/editor/annotations/frame' +import { initialUi, uiReducer } from '@/editor/annotations/uiState' + +const BOUNDS: Frame = { x: 0, y: 0, w: 100, h: 100 } + +describe('accessBox (A1)', () => { + it('grows a 10 x 10 frame to 29 x 29 around the same centre', () => { + const frame = { x: 50, y: 50, w: 10, h: 10 } + const { box, grown } = accessBox(frame, 29, BOUNDS) + expect(grown).toBe(true) + expect(box).toEqual({ x: 40.5, y: 40.5, w: 29, h: 29 }) + }) + + it('keeps the grown box inside the bounds near an edge', () => { + const { box } = accessBox({ x: 0, y: 95, w: 10, h: 5 }, 29, BOUNDS) + expect(box).toEqual({ x: 0, y: 71, w: 29, h: 29 }) + }) + + it('leaves a large frame unchanged, and one with no minimum', () => { + const frame = { x: 10, y: 10, w: 40, h: 40 } + expect(accessBox(frame, 29, BOUNDS)).toEqual({ box: frame, grown: false }) + expect(accessBox(frame, null, BOUNDS)).toEqual({ box: frame, grown: false }) + }) +}) + +describe('rectanglePolygon (D5, D9)', () => { + it('has four vertices clockwise from the top-left, rounded inward to 0.01', () => { + const polygon = rectanglePolygon({ x: 10.004, y: 20.006, w: 30, h: 40 }) + expect(polygon).toEqual({ + type: 'polygon', + points: [ + [10.01, 20.01], + [40, 20.01], + [40, 60], + [10.01, 60], + ], + }) + }) +}) + +describe('the circle (D5)', () => { + it('a drag from the centre to the edge sets the radius', () => { + const fallback = () => ({ type: 'circle' as const, cx: 0, cy: 0, r: 1 }) + const circle = circleFromDrag( + { x: 50, y: 50 }, + { x: 50, y: 60 }, + 5, + BOUNDS, + fallback, + ) + expect(circle).toEqual({ type: 'circle', cx: 50, cy: 50, r: 10 }) + }) + + it('a radius under the minimum counts as a click: the fallback', () => { + const fallback = () => ({ type: 'circle' as const, cx: 7, cy: 7, r: 7 }) + const circle = circleFromDrag( + { x: 50, y: 50 }, + { x: 52, y: 50 }, + 5, + BOUNDS, + fallback, + ) + expect(circle).toEqual({ type: 'circle', cx: 7, cy: 7, r: 7 }) + }) + + it('is moved inside the bounds at an edge', () => { + const circle = circleFromDrag( + { x: 95, y: 50 }, + { x: 95, y: 70 }, + 5, + BOUNDS, + () => ({ type: 'circle', cx: 0, cy: 0, r: 1 }), + ) + expect(circle).toEqual({ type: 'circle', cx: 80, cy: 50, r: 20 }) + }) + + it('is rounded inward to 0.01', () => { + const circle = circleInside( + { type: 'circle', cx: 50.004, cy: 50.006, r: 1.999 }, + BOUNDS, + ) + expect(circle).toEqual({ type: 'circle', cx: 50, cy: 50.01, r: 1.99 }) + }) + + it('shrinks only when larger than the bounds', () => { + const narrow = { x: 0, y: 0, w: 20, h: 10 } + const circle = circleInside( + { type: 'circle', cx: 10, cy: 5, r: 50 }, + narrow, + ) + expect(circle).toEqual({ type: 'circle', cx: 10, cy: 5, r: 5 }) + }) + + it('the default is a twelfth of the visible width, centred where asked', () => { + const visible = { x: 0, y: 0, w: 120, h: 90 } + expect(defaultCircle({ x: 50, y: 50 }, visible, BOUNDS)).toEqual({ + type: 'circle', + cx: 50, + cy: 50, + r: 10, + }) + expect(defaultCircle({ x: 2, y: 2 }, visible, BOUNDS)).toEqual({ + type: 'circle', + cx: 10, + cy: 10, + r: 10, + }) + }) +}) + +describe('the shape choice and the preset target', () => { + it('starts on Rectangle and survives a view change', () => { + expect(initialUi.accessShape).toBe('rectangle') + const chosen = uiReducer(initialUi, { + type: 'access_shape', + shape: 'circle', + }) + const moved = uiReducer(chosen, { type: 'view', viewId: 'view-det' }) + expect(moved.accessShape).toBe('circle') + expect(moved.viewId).toBe('view-det') + }) + + it('the preset target is cleared by a view change and by disarming the tool', () => { + const set = uiReducer(initialUi, { type: 'access_target', viewId: 'v1' }) + expect(set.accessTarget).toBe('v1') + expect( + uiReducer(set, { type: 'view', viewId: 'v2' }).accessTarget, + ).toBeNull() + const armed = uiReducer(set, { type: 'tool', tool: 'link' }) + expect(armed.accessTarget).toBe('v1') + const off = uiReducer(armed, { type: 'tool', tool: 'select' }) + expect(off.accessTarget).toBeNull() + }) + + it('names a direct child, else nothing (never a removed view)', () => { + const children = [{ id: 'view-det' }, { id: 'view-b' }] + expect(presetTarget('view-b', children)).toBe('view-b') + expect(presetTarget('view-gone', children)).toBe('') + expect(presetTarget(null, children)).toBe('') + }) +}) diff --git a/apps/app/tests/unit/editor-add-buttons.test.tsx b/apps/app/tests/unit/editor-add-buttons.test.tsx index 6a20d97f..67e8a460 100644 --- a/apps/app/tests/unit/editor-add-buttons.test.tsx +++ b/apps/app/tests/unit/editor-add-buttons.test.tsx @@ -11,6 +11,7 @@ import { } from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { Annotation, Point } from '@faunosteo/core-wasm/types' +import { dropCreation } from '@/editor/annotations/creationWork' import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore' import { en } from '@/i18n/en' import { fr } from '@/i18n/fr' @@ -510,10 +511,155 @@ describe('a redraw lends the zone tool', () => { }) }) +const mouse = { + pointerId: 1, + isPrimary: true, + button: 0, + pointerType: 'mouse', +} +const fire = (type: string, x: number, y: number) => + fireEvent( + canvas(), + new PointerEvent(type, { + bubbles: true, + clientX: x, + clientY: y, + buttons: type === 'pointerup' ? 0 : 1, + ...mouse, + }), + ) +const drag = (from: [number, number], to: [number, number]) => { + fire('pointerdown', ...from) + fire('pointermove', (from[0] + to[0]) / 2, (from[1] + to[1]) / 2) + fire('pointermove', ...to) + fire('pointerup', ...to) +} +const shapeRadio = (name: string) => screen.getByRole('radio', { name }) +const pendingGeometry = () => + useAnnotationWork.getState().creation!.pending.geometry + +describe('the access shapes (D5, panel 07)', () => { + async function armed() { + const user = await mount(withDetail()) + await user.click(add('un accès')) + return user + } + + it('the strip offers Rectangle, Polygone, Cercle, Rectangle first; arrows move inside', async () => { + const user = await armed() + const group = screen.getByRole('radiogroup', { name: "Forme de l'accès" }) + const names = within(group) + .getAllByRole('radio') + .map((r) => (r as HTMLInputElement).value) + expect(names).toEqual(['rectangle', 'polygon', 'circle']) + expect(shapeRadio('Rectangle')).toBeChecked() + shapeRadio('Rectangle').focus() + await user.keyboard('{ArrowRight}') + expect(shapeRadio('Polygone')).toBeChecked() + expect(status()).toHaveTextContent('Outil Accès armé, forme Polygone.') + }) + + it('shows the choice only with the access tool armed and no creation open', async () => { + const user = await armed() + expect(screen.getByTestId('access-shape')).toBeInTheDocument() + await user.click(tool('Sélectionner et déplacer')) + expect(screen.queryByTestId('access-shape')).toBeNull() + }) + + it('keeps the last choice when the tool is armed again', async () => { + const user = await armed() + await user.click(shapeRadio('Cercle')) + await user.click(tool('Sélectionner et déplacer')) + await user.click(add('un accès')) + expect(shapeRadio('Cercle')).toBeChecked() + }) + + it('a rectangle drag opens the dialog with a four-vertex polygon pending', async () => { + await armed() + drag([20, 20], [60, 50]) + await dialog('Nouvel accès') + expect(pendingGeometry()).toEqual({ + type: 'polygon', + points: [ + [20, 20], + [60, 20], + [60, 50], + [20, 50], + ], + }) + }) + + it('nothing reaches the document during the gesture', async () => { + await armed() + const before = store.getState().documentText + fire('pointerdown', 20, 20) + fire('pointermove', 40, 40) + fire('pointermove', 60, 50) + expect(store.getState().documentText).toBe(before) + expect(useAnnotationWork.getState().creation).toBeNull() + expect(screen.getByTestId('overlay-ghost')).toBeInTheDocument() + fire('pointerup', 60, 50) + await dialog('Nouvel accès') + expect(store.getState().documentText).toBe(before) + }) + + it('a circle drag from the centre to the edge opens it with a circle pending', async () => { + const user = await armed() + await user.click(shapeRadio('Cercle')) + drag([50, 50], [70, 50]) + await dialog('Nouvel accès') + expect(pendingGeometry()).toEqual({ type: 'circle', cx: 50, cy: 50, r: 20 }) + }) + + it('a click places the default shape where it fell', async () => { + const user = await armed() + pressAt(canvas(), 50, 50) + await dialog('Nouvel accès') + const rectangle = pendingGeometry() + expect(rectangle.type === 'polygon' && rectangle.points).toHaveLength(4) + act(() => dropCreation()) + await user.click(shapeRadio('Cercle')) + pressAt(canvas(), 50, 50) + await dialog('Nouvel accès') + expect(pendingGeometry()).toMatchObject({ type: 'circle', cx: 50, cy: 50 }) + }) + + it('a click with Polygone still places a vertex', async () => { + const user = await armed() + await user.click(shapeRadio('Polygone')) + pressAt(canvas(), 20, 20) + expect(useAnnotationWork.getState().creation).toMatchObject({ + closed: false, + }) + noDialog() + }) + + it('« Placer au centre » places the chosen shape', async () => { + const user = await armed() + const centre = () => + user.click(screen.getByRole('button', { name: 'Placer au centre' })) + await centre() + await dialog('Nouvel accès') + const rect = pendingGeometry() + expect(rect.type === 'polygon' && rect.points).toHaveLength(4) + act(() => dropCreation()) + await user.click(shapeRadio('Cercle')) + await centre() + await dialog('Nouvel accès') + expect(pendingGeometry()).toMatchObject({ type: 'circle', cx: 50, cy: 50 }) + act(() => dropCreation()) + await user.click(shapeRadio('Polygone')) + await centre() + await dialog('Nouvel accès') + const triangle = pendingGeometry() + expect(triangle.type === 'polygon' && triangle.points).toHaveLength(3) + }) +}) + describe('the dictionaries', () => { it('carry the three armed announcements in both languages', () => { for (const dict of [fr, en]) - for (const kind of ['point', 'zone', 'detail_trigger']) + for (const kind of ['point', 'zone', 'detail_trigger_shape']) expect(dict[`editor.annotations.armed.${kind}`]).toBeTruthy() }) @@ -526,8 +672,8 @@ describe('the dictionaries', () => { expect(fr['editor.annotations.armed.zone']).toBe( 'Outil Zone actif : posez les sommets sur le dessin, ou choisissez « Placer au centre », sous le dessin (Entrée dans le dessin fait de même).', ) - expect(fr['editor.annotations.armed.detail_trigger']).toBe( - 'Outil Accès actif : posez les sommets sur le dessin, ou choisissez « Placer au centre », sous le dessin (Entrée dans le dessin fait de même).', + expect(fr['editor.annotations.armed.detail_trigger_shape']).toBe( + 'Outil Accès armé, forme {shape}.', ) expect(en['editor.annotations.armed.point']).toBe( 'Point tool on: tap or click the drawing where you want it, or choose “Place at the centre”, below the drawing (Enter on the drawing does the same).', @@ -535,8 +681,8 @@ describe('the dictionaries', () => { expect(en['editor.annotations.armed.zone']).toBe( 'Zone tool on: place the vertices on the drawing, or choose “Place at the centre”, below the drawing (Enter on the drawing does the same).', ) - expect(en['editor.annotations.armed.detail_trigger']).toBe( - 'Link tool on: place the vertices on the drawing, or choose “Place at the centre”, below the drawing (Enter on the drawing does the same).', + expect(en['editor.annotations.armed.detail_trigger_shape']).toBe( + 'Access tool armed, {shape} shape.', ) }) }) diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx index a542585a..82f85770 100644 --- a/apps/app/tests/unit/editor-annotations-tab.test.tsx +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -2000,6 +2000,7 @@ describe('the strip', () => { frame: null, doc, viewId: 'main', + model: { children: [] }, context: { t: (key) => key, locale: 'fr' }, message: { show: vi.fn() }, }), diff --git a/apps/app/tests/unit/editor-creation-dialog.test.tsx b/apps/app/tests/unit/editor-creation-dialog.test.tsx index 05d3714b..ec442ac0 100644 --- a/apps/app/tests/unit/editor-creation-dialog.test.tsx +++ b/apps/app/tests/unit/editor-creation-dialog.test.tsx @@ -5,6 +5,7 @@ import { cleanup, fireEvent, render, + renderHook, screen, waitFor, within, @@ -19,7 +20,10 @@ import { useAnnotationWork, } from '@/editor/annotations/workStore' import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog' -import { emptyForm } from '@/editor/annotations/creation' +import { directChildren, emptyForm } from '@/editor/annotations/creation' +import { initialUi } from '@/editor/annotations/uiState' +import { useAccessTargetClear } from '@/editor/annotations/useAccessTargetClear' +import { placeAtCentre } from '@/editor/annotations/usePlacement' import { dropCreation, finishCreation, @@ -234,9 +238,98 @@ describe('placing and the form (A4, A5)', () => { const shown = await dialog('Nouvel accès') expect(within(shown).getByLabelText('Vue ouverte')).toBeInTheDocument() expect( - within(shown).getByText('Accès tracé, 3 sommets'), + within(shown).getByText('Accès tracé, 4 sommets'), ).toBeInTheDocument() }) + + it('an access dialog has no category: « Vue ouverte » and the laterality only', async () => { + const user = await mount(withDetail()) + await addByKeyboard( + user, + screen.getByRole('button', { name: 'Ajouter un accès' }), + ) + const shown = await dialog('Nouvel accès') + expect(within(shown).queryByLabelText('Catégorie')).toBeNull() + expect(within(shown).getByLabelText('Latéralité')).toBeInTheDocument() + expect(creation()!.form.categoryId).toBe('cat-access') + }) + + it('presets « Vue ouverte » from the access target while it is a direct child', async () => { + await mount(withDetail()) + const doc = store.getState().previewState!.document + const place = (children: ReturnType) => { + act(() => { + dropCreation() + placeAtCentre( + { + ui: { ...initialUi, accessTarget: 'view-det' }, + frame: { x: 0, y: 0, w: 100, h: 100 }, + doc, + viewId: 'view-main', + model: { children }, + dispatch: vi.fn(), + }, + 'detail_trigger', + 'add', + ) + }) + return creation()!.form.opensViewId + } + expect(place(directChildren(doc.views, 'view-main'))).toBe('view-det') + expect(place([])).toBe('') + }) + + it('an undo or a redo clears the access target, a commit does not', async () => { + const user = await mount(withDetail()) + const dispatch = vi.fn() + renderHook(() => useAccessTargetClear(dispatch)) + await addByKeyboard( + user, + screen.getByRole('button', { name: 'Ajouter un accès' }), + ) + const shown = await dialog('Nouvel accès') + await user.selectOptions( + within(shown).getByLabelText('Vue ouverte'), + 'view-det', + ) + await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left') + await user.click(within(shown).getByRole('button', { name: 'Créer' })) + await waitFor(() => expect(creation()).toBeNull()) + expect(dispatch).not.toHaveBeenCalled() + act(() => store.getState().undoStep()) + expect(dispatch).toHaveBeenCalledWith({ + type: 'access_target', + viewId: null, + }) + dispatch.mockClear() + act(() => store.getState().redoStep()) + expect(dispatch).toHaveBeenCalledTimes(1) + }) + + it('the committed access lands in the internal category', async () => { + const user = await mount(withDetail()) + await addByKeyboard( + user, + screen.getByRole('button', { name: 'Ajouter un accès' }), + ) + const shown = await dialog('Nouvel accès') + await user.selectOptions( + within(shown).getByLabelText('Vue ouverte'), + 'view-det', + ) + await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left') + await user.click(within(shown).getByRole('button', { name: 'Créer' })) + await waitFor(() => + expect(annotations().some((a) => a.kind === 'detail_trigger')).toBe(true), + ) + const access = annotations().find((a) => a.kind === 'detail_trigger')! + expect(access.category_id).toBe('cat-access') + expect( + store + .getState() + .previewState!.document.categories.some((c) => c.id === 'cat-access'), + ).toBe(true) + }) }) describe('Safari: a tracing started by a tap (no focus move)', () => {