diff --git a/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx index a0cbbfe4..e1aed3dd 100644 --- a/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx @@ -31,6 +31,7 @@ import { } from '@/editor/mode' import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore' import type { EditorTabId } from '@/editor/tabs' +import { useUndoShortcuts } from '@/editor/useUndoShortcuts' import { useTabTier } from '@/editor/useViewport' import { useAuthStore } from '@/state/authStore' import { useT } from '@/i18n/useT' @@ -97,6 +98,7 @@ function DraftEditor({ }, [versionId, userId]) useEffect(() => useEditorStore.getState().setCanEdit(canEdit), [canEdit]) useLeaveGuard(useEditorStore(leaveGuardArmed)) + useUndoShortcuts(canEdit && recovery === 'none') if (status === 'failed' && failure !== null) { if (failure === 'denied') return diff --git a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx index 55430e55..2e1b07a8 100644 --- a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx @@ -1,23 +1,18 @@ -import { useEffect, useRef, type PointerEvent } from 'react' +import { useEffect, useRef, type KeyboardEvent, type RefObject } from 'react' import type { Geometry } from '@faunosteo/core-wasm/types' import Button from '@/components/ui/Button' import Notice from '@/components/ui/Notice' import { coreFailureMessage } from '@/core/failure' import { useCoreStopped } from '@/core/runtime' import { transformOf } from '@/catalogue/framing' -import { useFraming } from '@/catalogue/useFraming' -import { clientToDrawing } from '@/editor/annotations/gesture' import type { XY } from '@/editor/annotations/frame' import { - annotationIdOf, useCanvasBuild, type RootAttributes, useSelectionMark, } from '@/editor/annotations/useCanvasBuild' -import { - useMoveGesture, - type MoveTarget, -} from '@/editor/annotations/useMoveGesture' +import { useCanvasGestures } from '@/editor/annotations/useCanvasGestures' +import type { MoveTarget } from '@/editor/annotations/useMoveGesture' import type { ToolId } from '@/editor/annotations/uiState' import { useT } from '@/i18n/useT' import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay' @@ -37,101 +32,107 @@ export interface AnnotationCanvasProps { moveTarget: MoveTarget | null overlay: OverlayData tools: Omit - /** The composed root's `viewBox` text, as rebuilt; null on failure. */ - onRoot: (viewBox: string | null) => void + /** The composed root as rebuilt (with its view); null on failure. */ + onRoot: (root: RootAttributes | null) => void onSelect: (id: string) => void /** A click with a drawing tool, in drawing units. */ onPlace: (at: XY) => void onDrop: (id: string, geometry: Geometry) => void + onTraceKey: (event: KeyboardEvent) => void } /** * The edit canvas: the core's composed view, the numbers-only overlay above it in the * same transformed box, the tool column beside it. Select and place work on `click` * (a press that moved is a drag and swallows it); a drag from the selected marker moves - * it after 4 CSS px. `touch-action: none` only while a drawing tool or a drag is active. + * it after 4 CSS px. */ export default function AnnotationCanvas(props: AnnotationCanvasProps) { - const overlayRef = useRef(null) + const overlay = useRef(null) const viewport = useRef(null) const build = useCanvasBuild(props.viewId) - const move = useMoveGesture({ - overlay: overlayRef, - target: props.moveTarget, - onDrop: props.onDrop, - }) - const framing = useFraming(viewport, props.viewId, { - canPan: (event) => props.tool === 'select' && !move.claims(event), - }) + const gestures = useCanvasGestures({ ...props, overlay, viewport }) useSelectionMark(build.host, props.selectedId, build.root) - const { onRoot } = props - const viewBox = build.root?.viewBox ?? null - useReportRoot(viewBox, onRoot) - - const onClick = (event: React.MouseEvent) => { - if (framing.swallowClick()) return - const id = annotationIdOf(event.target) - if (props.tool === 'select') return id ? props.onSelect(id) : undefined - const at = clientToDrawing(overlayRef.current, { - x: event.clientX, - y: event.clientY, - }) - if (at) props.onPlace(at) - } - const handlers = composed(framing.handlers, move.handlers) - const touchNone = - props.tool !== 'select' || move.armed || framing.framing.scale !== 1 + useReportRoot(build.root, props.onRoot) return (
+ -
-
- -
- -
) } -/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */ -function DrawingLayer({ - host, - root, - transform, - overlay, -}: { - host: React.RefObject +type Build = ReturnType + +function CanvasBox({ + viewId, + viewName, + tool, + build, + viewport, + boxProps, + layer, +}: AnnotationCanvasProps & { + build: Build + viewport: RefObject + boxProps: ReturnType['boxProps'] + layer: Omit +}) { + const root = build.root?.viewId === viewId ? build.root : null + const cursor = tool === 'select' ? 'cursor-grab' : 'cursor-crosshair' + return ( +
+
+ +
+ +
+ ) +} + +const BOX = + 'relative min-w-0 flex-1 overflow-hidden rounded-xl border ' + + 'border-[var(--color-border)] bg-white' + +const FOCUS_RING = + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' + + 'focus-visible:ring-[var(--color-accent)]' + +interface LayerProps { + host: RefObject root: RootAttributes | null transform: string overlay: Omit -}) { +} + +/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */ +function DrawingLayer({ host, root, transform, overlay }: LayerProps) { return (
void, + root: RootAttributes | null, + onRoot: (root: RootAttributes | null) => void, ) { - useEffect(() => onRoot(viewBox), [viewBox, onRoot]) -} - -/** Each pointer handler of the framing and of the move gesture, one after the other. */ -function composed( - a: ReturnType['handlers'], - b: ReturnType['handlers'], -) { - const both = - (first: (e: PointerEvent) => void, second: (e: PointerEvent) => void) => - (event: PointerEvent) => { - first(event) - second(event) - } - return { - onPointerDown: both(a.onPointerDown, b.onPointerDown), - onPointerMove: both(a.onPointerMove, b.onPointerMove), - onPointerUp: both(a.onPointerUp, b.onPointerUp), - onPointerCancel: both(a.onPointerCancel, b.onPointerCancel), - onLostPointerCapture: b.onLostPointerCapture, - onKeyDown: a.onKeyDown, - } + useEffect(() => onRoot(root), [root, onRoot]) } function CanvasFailure({ diff --git a/apps/app/src/components/editor/annotations/AnnotationList.tsx b/apps/app/src/components/editor/annotations/AnnotationList.tsx index 75a15021..3acf75e0 100644 --- a/apps/app/src/components/editor/annotations/AnnotationList.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationList.tsx @@ -3,6 +3,15 @@ import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' import ReviewBadge from './ReviewBadge' +const LIST = + 'max-h-64 divide-y divide-[var(--color-border)] overflow-y-auto rounded-lg ' + + 'border border-[var(--color-border)]' + +const ROW = + 'flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm ' + + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' + + 'focus-visible:ring-[var(--color-accent)]' + /** The name an annotation shows: its own, else (an unnamed link) the view it opens. */ export function annotationName( annotation: Annotation, @@ -40,17 +49,14 @@ export default function AnnotationList({ ) } return ( -
    +
      {annotations.map((annotation) => (
    • - -
+ + dispatch({ type: 'pending_drop' })} + /> ) } +function CreationActions({ + onCreate, + onCancel, +}: { + onCreate: () => void + onCancel: () => void +}) { + const t = useT() + return ( +
+ + +
+ ) +} + function Messages({ messages }: { messages: string[] }) { if (messages.length === 0) return null return ( @@ -182,161 +159,3 @@ function Messages({ messages }: { messages: string[] }) { ) } - -interface FieldsProps { - doc: AnatomicalSheetDocument - form: CreationForm - onChange: (patch: Partial) => void -} - -interface Option { - value: string - label: string -} - -function OptionSelect({ - id, - label, - value, - options, - blank, - onChange, -}: { - id: string - label: string - value: string - options: Option[] - /** A « Choisir… » entry: the choice is required and has no default. */ - blank: boolean - onChange: (value: string) => void -}) { - const t = useT() - return ( - - - - ) -} - -/** The fields the core requires, collected before the insert. */ -function CreationFields({ - kind, - viewId, - ...fields -}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) { - const t = useT() - const locale = useLocaleStore((s) => s.locale) - const { doc, form, onChange } = fields - const categories = doc.categories.map((c) => ({ - value: c.id, - label: c.name[locale], - })) - const sides = LATERALITIES.map((l: Laterality) => ({ - value: l, - label: t(`editor.annotations.laterality.${l}`), - })) - return ( -
- onChange({ fr })} - /> - onChange({ en })} - /> - onChange({ categoryId })} - /> - - onChange({ laterality: laterality as CreationForm['laterality'] }) - } - /> - {kind === 'detail_trigger' ? ( - - ) : ( - - )} -
- ) -} - -function OpensSelect({ - doc, - form, - onChange, - viewId, -}: FieldsProps & { viewId: string }) { - const t = useT() - const locale = useLocaleStore((s) => s.locale) - const options = directChildren(doc.views, viewId).map((v) => ({ - value: v.id, - label: v.name[locale], - })) - return ( - onChange({ opensViewId })} - /> - ) -} - -/** Findings zone and vertebral region: optional links of a point or a zone. */ -function LinkSelects({ doc, form, onChange }: FieldsProps) { - const t = useT() - const locale = useLocaleStore((s) => s.locale) - const zones = doc.finding_zones.map((z) => ({ - value: z.id, - label: z.name[locale], - })) - const regions = doc.vertebral_config.regions.map((r) => ({ - value: r.code, - label: r.name[locale], - })) - return ( - <> - onChange({ zoneId })} - /> - onChange({ regionCode })} - /> - - ) -} diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index 928a7a12..78cced80 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -3,7 +3,7 @@ import type { AnatomicalSheetDocument, Annotation, } from '@faunosteo/core-wasm/types' -import { type CommitContext } from '@/editor/annotations/annotationCommit' +import type { CommitContext } from '@/editor/annotations/annotationCommit' import { keyboardPending, type NewKind } from '@/editor/annotations/creation' import { parseFrame, type Frame } from '@/editor/annotations/frame' import { isEditable } from '@/editor/annotations/geometryEdit' @@ -15,9 +15,9 @@ import { type UiAction, type UiState, } from '@/editor/annotations/uiState' +import type { RootAttributes } from '@/editor/annotations/useCanvasBuild' import { mainViewId, - useUndoShortcuts, useViewModel, type ViewModel, } from '@/editor/annotations/useViewModel' @@ -38,59 +38,75 @@ interface Props { onSelectTab: EditorTabProps['onSelectTab'] } -export default function EditableAnnotations({ doc, onSelectTab }: Props) { - const t = useT() - const locale = useLocaleStore((s) => s.locale) +/** What both columns read: the tab's state, the view, its frame and its selection. */ +interface Scene { + doc: AnatomicalSheetDocument + ui: UiState + dispatch: Dispatch + viewId: string + model: ViewModel + /** F of the current view, only while the core measures it and the build is its own. */ + frame: Frame | null + selected: Annotation | undefined + setRoot: (root: RootAttributes | null) => void + onSelectTab: EditorTabProps['onSelectTab'] +} + +function useScene({ doc, onSelectTab }: Props): Scene { const [ui, dispatch] = useReducer(uiReducer, initialUi) - const [viewBox, setViewBox] = useState(null) + const [root, setRoot] = useState(null) const viewId = ui.viewId ?? mainViewId(doc) const model = useViewModel(doc, viewId) - const frame = model.measured ? parseFrame(viewBox) : null - const context: CommitContext = { t, locale } - const placement = usePlacement({ ui, dispatch, frame, doc, context }) - useUndoShortcuts() - const selected = model.annotations.find((a) => a.id === ui.selectedId) - const scene = { doc, ui, dispatch, model, frame, selected, onSelectTab } + const own = model.measured && root?.viewId === viewId + return { + doc, + ui, + dispatch, + viewId, + model, + frame: own ? parseFrame(root.viewBox) : null, + selected: model.annotations.find((a) => a.id === ui.selectedId), + setRoot, + onSelectTab, + } +} + +function useCommitContext(): CommitContext { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + return { t, locale } +} + +export default function EditableAnnotations(props: Props) { + const scene = useScene(props) + const context = useCommitContext() + const placement = usePlacement({ ...scene, context }) return (
- +
) } -/** What both columns read: the document, the tab's state, the view and its frame. */ -interface Scene extends Props { - ui: UiState - dispatch: Dispatch - model: ViewModel - frame: Frame | null - selected: Annotation | undefined -} +type Placement = ReturnType function CanvasColumn({ + scene, placement, - onRoot, - ...scene -}: Scene & { - placement: ReturnType - onRoot: (viewBox: string | null) => void +}: { + scene: Scene + placement: Placement }) { - const locale = useLocaleStore((s) => s.locale) - const { doc, ui, dispatch, model, frame, selected } = scene - const viewId = ui.viewId ?? mainViewId(doc) - const view = doc.views.find((v) => v.id === viewId) + const { doc, ui, dispatch, model, selected } = scene const noCategory = doc.categories.length === 0 - const blocked = !model.measured || noCategory - const select = (id: string) => dispatch({ type: 'select', id }) - if (!view) return null return ( -
+
dispatch({ type: 'view', viewId: id })} /> - {selected && ( - - )} - dispatch({ type: 'tool', tool }), - drawingDisabled: blocked, - linkDisabled: model.children.length === 0, - }} - onRoot={onRoot} - onSelect={select} - onPlace={placement.onPlace} - onDrop={placement.onDrop} - /> + {selected && } + {ui.tracing && ( )} addAtCentre(kind, frame, dispatch)} + onAdd={(kind) => addAtCentre(kind, scene.frame, dispatch)} /> dispatch({ type: 'select', id })} />
) } +function TagOf({ + annotation, + doc, +}: { + annotation: Annotation + doc: AnatomicalSheetDocument +}) { + const locale = useLocaleStore((s) => s.locale) + return ( + + ) +} + +function CanvasStage({ + scene, + placement, +}: { + scene: Scene + placement: Placement +}) { + const locale = useLocaleStore((s) => s.locale) + const { doc, ui, dispatch, model, frame, selected } = scene + const view = doc.views.find((v) => v.id === scene.viewId) + const blocked = !model.measured || doc.categories.length === 0 + if (!view) return null + return ( + dispatch({ type: 'tool', tool }), + drawingDisabled: blocked, + linkDisabled: model.children.length === 0, + }} + onRoot={scene.setRoot} + onSelect={(id) => dispatch({ type: 'select', id })} + onPlace={placement.onPlace} + onDrop={placement.onDrop} + onTraceKey={placement.onTraceKey} + /> + ) +} + function addAtCentre( kind: NewKind, frame: Frame | null, @@ -157,10 +202,12 @@ function addAtCentre( /** The creation panel while an element is pending, else the selection's properties. */ function SidePanel({ - viewId, + scene, context, - ...scene -}: Scene & { viewId: string; context: CommitContext }) { +}: { + scene: Scene + context: CommitContext +}) { const t = useT() const { doc, ui, dispatch, model, frame, selected } = scene if (ui.pending) { @@ -168,7 +215,7 @@ function SidePanel({ +interface GroupState { + key: string + draft: Fields + messages: string[] +} + +/** The typed fields, reset whenever the stored value changes (undo, restore, a move). */ +function useGroupState(geometry: EditableGeometry) { + const key = JSON.stringify(fieldsOf(geometry)) + const fresh = (): GroupState => ({ + key, + draft: fieldsOf(geometry), + messages: [], + }) + const [state, setState] = useState(fresh) + if (state.key !== key) setState(fresh()) + return { + state, + set: (patch: Partial) => setState({ ...state, ...patch }), + } +} + /** * The geometry fields as ONE group held in component state (plan « Repair through a * temporary form »): Enter or leaving a field proposes the whole group as one update; @@ -38,37 +60,26 @@ type PolygonFields = Extract * never in the document and is dropped (no commit on unmount). */ export default function GeometryGroup(props: GeometryGroupProps) { - const stored = fieldsOf(props.geometry) - const storedKey = JSON.stringify(stored) - const [draft, setDraft] = useState(stored) - const [seen, setSeen] = useState(storedKey) - const [messages, setMessages] = useState([]) - // A new stored value (undo, restore, an accepted move) replaces what was typed. - if (seen !== storedKey) { - setSeen(storedKey) - setDraft(stored) - setMessages([]) - } - const apply = (next: Fields) => { - setDraft(next) - if (sameAsStored(next, props.geometry)) return setMessages([]) + const { state, set } = useGroupState(props.geometry) + const propose = (next: Fields) => { + if (sameAsStored(next, props.geometry)) + return set({ draft: next, messages: [] }) const parsed = parseFields(next) - if (!parsed.ok) return setMessages(['number']) + if (!parsed.ok) return set({ draft: next, messages: ['number'] }) const result = props.onApply(parsed.geometry) - setMessages(result.ok ? [] : result.messages) + set({ draft: next, messages: result.ok ? [] : result.messages }) } - const revert = () => { - setDraft(stored) - setMessages([]) - } - const pending = changedFieldNames(draft, props.geometry) - const view = { ...props, draft, pending, messages } return ( set({ draft })} + onPropose={propose} + onRevert={() => set({ draft: fieldsOf(props.geometry), messages: [] })} /> ) } @@ -199,7 +210,7 @@ function CircleRows(props: RowsProps>) { function PolygonRows(props: RowsProps) { const t = useT() const [selected, setSelected] = useState(0) - const { fields, locked } = props + const { fields } = props const change = (index: number, axis: 'x' | 'y', value: string) => props.onChange({ type: 'polygon', @@ -207,39 +218,23 @@ function PolygonRows(props: RowsProps) { i === index ? { ...row, [axis]: value } : row, ), }) + const count = String(fields.rows.length) return (

- {t('editor.annotations.geometry.vertices').replace( - '{count}', - String(fields.rows.length), - )} + {t('editor.annotations.geometry.vertices').replace('{count}', count)}

{fields.rows.map((row, index) => ( -
change(index, axis, value)} onFocus={() => setSelected(index)} - > - {index + 1} - {(['x', 'y'] as const).map((axis) => ( - change(index, axis, value)} - onApply={() => props.onPropose(fields)} - /> - ))} -
+ /> ))} - {!locked && ( + {!props.locked && ( ) { ) } +function VertexRow({ + index, + row, + group, + onType, + onFocus, +}: { + index: number + row: { x: string; y: string } + group: RowsProps + onType: (axis: 'x' | 'y', value: string) => void + onFocus: () => void +}) { + const t = useT() + return ( +
+ {index + 1} + {(['x', 'y'] as const).map((axis) => ( + onType(axis, value)} + onApply={() => group.onPropose(group.fields)} + /> + ))} +
+ ) +} + function VertexButtons({ fields, selected, diff --git a/apps/app/src/components/editor/annotations/SelectionTag.tsx b/apps/app/src/components/editor/annotations/SelectionTag.tsx index 8882b0fe..bb47a857 100644 --- a/apps/app/src/components/editor/annotations/SelectionTag.tsx +++ b/apps/app/src/components/editor/annotations/SelectionTag.tsx @@ -1,5 +1,9 @@ import { useT } from '@/i18n/useT' +const TAG = + 'pointer-events-none inline-block rounded-md px-2 py-1 text-xs ' + + 'bg-[var(--color-surface-strong)]' + /** Board 04's tag over the drawing: « Sélection : « ». */ export default function SelectionTag({ kind, @@ -10,10 +14,7 @@ export default function SelectionTag({ }) { const t = useT() return ( -

+

{t('editor.annotations.selection') .replace( '{kind}', diff --git a/apps/app/src/components/editor/annotations/ToolColumn.tsx b/apps/app/src/components/editor/annotations/ToolColumn.tsx index b6b2145d..752154c5 100644 --- a/apps/app/src/components/editor/annotations/ToolColumn.tsx +++ b/apps/app/src/components/editor/annotations/ToolColumn.tsx @@ -15,6 +15,12 @@ export interface ToolColumnProps { onFit: () => void } +const BUTTON = + 'grid h-11 w-11 place-items-center rounded-lg border ' + + 'border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 ' + + 'focus-visible:outline-none focus-visible:ring-2 ' + + 'focus-visible:ring-[var(--color-accent)]' + const GLYPHS: Record = { select: 'M5 3l12 7-5 1-3 5z', point: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 3v3M12 18v3M3 12h3M18 12h3', @@ -48,7 +54,7 @@ function ToolButton({ aria-pressed={pressed} disabled={disabled} onClick={onClick} - className={`grid h-11 w-11 place-items-center rounded-lg border border-[var(--color-border)] disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${ + className={`${BUTTON} ${ pressed ? 'bg-[var(--color-ink)] text-white' : 'bg-[var(--color-surface)] text-[var(--color-ink)]' diff --git a/apps/app/src/components/editor/annotations/ViewSwitcher.tsx b/apps/app/src/components/editor/annotations/ViewSwitcher.tsx index 7919932e..55eb15bc 100644 --- a/apps/app/src/components/editor/annotations/ViewSwitcher.tsx +++ b/apps/app/src/components/editor/annotations/ViewSwitcher.tsx @@ -2,6 +2,11 @@ import type { SheetView } from '@faunosteo/core-wasm/types' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' +const CHIP = + 'rounded-full border border-[var(--color-border)] px-3 py-1 text-sm ' + + 'focus-visible:outline-none focus-visible:ring-2 ' + + 'focus-visible:ring-[var(--color-accent)]' + /** One chip per view (board 04): the main view, then each detail view. */ export default function ViewSwitcher({ views, @@ -26,7 +31,7 @@ export default function ViewSwitcher({ type="button" aria-pressed={view.id === current} onClick={() => onSelect(view.id)} - className={`rounded-full border border-[var(--color-border)] px-3 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${ + className={`${CHIP} ${ view.id === current ? 'bg-[var(--color-ink)] text-white' : 'bg-[var(--color-surface)]' diff --git a/apps/app/src/editor/annotations/correction.ts b/apps/app/src/editor/annotations/correction.ts index 252728b8..4169dfe5 100644 --- a/apps/app/src/editor/annotations/correction.ts +++ b/apps/app/src/editor/annotations/correction.ts @@ -18,15 +18,19 @@ export interface Correction { const OUT_OF_FRAME = 'annotation.geometry.out_of_frame' /** - * Candidate C is offered when the core refused a point proposal that was either a - * reduced radius (B) or refused `out_of_frame` (A at a float edge). An A refused - * `too_small` (r0 already capped) offers nothing: the issue is shown instead. + * Candidate C is offered when the core refused the page's own proposal (its radius still + * `proposedRadius`) and that proposal was either a reduced radius (B) or refused + * `out_of_frame` (A at a float edge). A radius the user typed is an explicit value, and + * an A refused `too_small` (r0 already capped) offers nothing: the core's issue is shown. */ export function correctionFor( frame: Frame, attempted: CircleShape, refusedCodes: readonly string[], + proposedRadius: number | undefined, ): Correction | null { + if (proposedRadius === undefined || attempted.r !== proposedRadius) + return null const reduced = attempted.r < defaultRadius(frame) if (!reduced && !refusedCodes.includes(OUT_OF_FRAME)) return null const click = { x: attempted.cx, y: attempted.cy } @@ -47,10 +51,11 @@ export function attemptPoint( frame: Frame, circle: CircleShape, insert: InsertCircle, + proposedRadius: number | undefined, ): PointAttempt { const result = insert(circle) if (result.ok) return { status: 'created', id: result.id } - const correction = correctionFor(frame, circle, result.codes) + const correction = correctionFor(frame, circle, result.codes, proposedRadius) return correction ? { status: 'correction', correction } : { status: 'refused', messages: result.messages } diff --git a/apps/app/src/editor/annotations/creation.ts b/apps/app/src/editor/annotations/creation.ts index 8eeea291..229e2a3b 100644 --- a/apps/app/src/editor/annotations/creation.ts +++ b/apps/app/src/editor/annotations/creation.ts @@ -25,6 +25,23 @@ export interface PendingElement { geometry: EditableGeometry /** Candidate C awaiting the user's confirmation (a point only). */ correction?: Correction | null + /** The radius the page proposed; a radius typed since is the user's own value. */ + proposedRadius?: number +} + +/** The pending element with a geometry the user typed: C and the proposal lapse with it. */ +export function withGeometry( + pending: PendingElement, + geometry: EditableGeometry, +): PendingElement { + const kept = + geometry.type === 'circle' && geometry.r === pending.proposedRadius + return { + ...pending, + geometry, + correction: null, + proposedRadius: kept ? pending.proposedRadius : undefined, + } } /** What the creation panel collects (no default labels: names and laterality are typed). */ @@ -70,7 +87,12 @@ export function directChildren( /** The pending element a keyboard « Ajouter … » button holds at the centre of F. */ export function keyboardPending(kind: NewKind, frame: Frame): PendingElement { if (kind === 'point') { - return { kind, geometry: { type: 'circle', ...centreCircle(frame) } } + const circle = centreCircle(frame) + return { + kind, + geometry: { type: 'circle', ...circle }, + proposedRadius: circle.r, + } } return { kind, geometry: { type: 'polygon', points: centreTriangle(frame) } } } @@ -141,7 +163,12 @@ export function pendingForClick(frame: Frame, click: XY): ClickOutcome { if (proposal.kind === 'outside') return { kind: 'outside' } if (proposal.kind === 'circle') { const geometry = { type: 'circle' as const, ...proposal.circle } - return { kind: 'pending', pending: { kind: 'point', geometry } } + const pending = { + kind: 'point' as const, + geometry, + proposedRadius: proposal.circle.r, + } + return { kind: 'pending', pending } } const at = { x: round2(click.x), y: round2(click.y) } const geometry = { @@ -151,5 +178,9 @@ export function pendingForClick(frame: Frame, click: XY): ClickOutcome { r: defaultRadius(frame), } const correction = { click: at, circle: proposal.circle } - return { kind: 'pending', pending: { kind: 'point', geometry, correction } } + const pending = { kind: 'point' as const, geometry, correction } + return { + kind: 'pending', + pending: { ...pending, proposedRadius: geometry.r }, + } } diff --git a/apps/app/src/editor/annotations/creationAttempt.ts b/apps/app/src/editor/annotations/creationAttempt.ts new file mode 100644 index 00000000..fc40dbb0 --- /dev/null +++ b/apps/app/src/editor/annotations/creationAttempt.ts @@ -0,0 +1,74 @@ +import type { Annotation } from '@faunosteo/core-wasm/types' +import { + insertAnnotation, + type CommitContext, + type CommitResult, +} from './annotationCommit' +import { + attemptPoint, + confirmCorrection, + type Correction, + type PointAttempt, +} from './correction' +import { + annotationOf, + formProblem, + type CreationForm, + type PendingElement, +} from './creation' +import type { Frame } from './frame' +import type { EditableGeometry } from './geometryEdit' + +/** What « Créer » or the confirmation of C works from. */ +export interface CreationInput { + pending: PendingElement + viewId: string + /** F of the current view; null while it is not measured. */ + frame: Frame | null + context: CommitContext +} + +export type Attempt = PointAttempt | { status: 'invalid'; problem: string } + +/** The insert of the pending element under a given geometry, through `accept`. */ +function inserterOf(input: CreationInput, form: CreationForm) { + return (geometry: EditableGeometry): CommitResult => + insertAnnotation( + (id): Annotation => + annotationOf(id, input.viewId, { ...input.pending, geometry }, form), + input.context, + ) +} + +/** « Créer »: a point lets the core's verdict offer C; nothing else is ever invented. */ +export function createAttempt( + input: CreationInput, + form: CreationForm, +): Attempt { + const { pending, frame } = input + const problem = formProblem(pending.kind, form) + if (problem) return { status: 'invalid', problem } + const insert = inserterOf(input, form) + const { geometry } = pending + if (pending.kind === 'point' && geometry.type === 'circle' && frame) { + return attemptPoint( + frame, + geometry, + (c) => insert({ type: 'circle', ...c }), + pending.proposedRadius, + ) + } + const result = insert(geometry) + return result.ok + ? { status: 'created', id: result.id } + : { status: 'refused', messages: result.messages } +} + +export function confirmAttempt( + input: CreationInput, + form: CreationForm, + correction: Correction, +): Attempt { + const insert = inserterOf(input, form) + return confirmCorrection(correction, (c) => insert({ type: 'circle', ...c })) +} diff --git a/apps/app/src/editor/annotations/frame.ts b/apps/app/src/editor/annotations/frame.ts index e46a3dc7..faf48050 100644 --- a/apps/app/src/editor/annotations/frame.ts +++ b/apps/app/src/editor/annotations/frame.ts @@ -58,15 +58,6 @@ export function defaultRadius(frame: Frame): number { return floor2(Math.min(wanted, Math.min(frame.w, frame.h) / 2)) } -/** Where a keyboard-created point sits: the centre of F, which fits by construction. */ -export function centreCircle(frame: Frame): CircleShape { - return { - cx: round2(frame.x + frame.w / 2), - cy: round2(frame.y + frame.h / 2), - r: defaultRadius(frame), - } -} - function distanceToEdge(frame: Frame, at: XY): number { return Math.min( at.x - frame.x, @@ -143,5 +134,16 @@ export function centreTriangle(frame: Frame): [number, number][] { return corners.map(([x, y]) => [round2(x), round2(y)]) } +/** + * Where a keyboard-created point sits: the centre of F with r0. Clamped as candidate C is, + * so it fits even with an origin off the 0.01 grid and r0 = min(w, h) / 2. + */ +export function centreCircle(frame: Frame): CircleShape { + return correctedCircle(frame, { + x: frame.x + frame.w / 2, + y: frame.y + frame.h / 2, + }) +} + export const sameCircle = (a: CircleShape, b: CircleShape): boolean => a.cx === b.cx && a.cy === b.cy && a.r === b.r diff --git a/apps/app/src/editor/annotations/uiState.ts b/apps/app/src/editor/annotations/uiState.ts index 3c59c0da..542fe970 100644 --- a/apps/app/src/editor/annotations/uiState.ts +++ b/apps/app/src/editor/annotations/uiState.ts @@ -69,7 +69,11 @@ export function uiReducer(state: UiState, action: UiAction): UiState { return { ...state, pending: action.pending, - serial: state.serial + 1, + // A second click with the same kind keeps the typed fields (same panel). + serial: + state.pending?.kind === action.pending.kind + ? state.serial + : state.serial + 1, selectedId: null, tracing: null, hint: null, diff --git a/apps/app/src/editor/annotations/useCanvasBuild.ts b/apps/app/src/editor/annotations/useCanvasBuild.ts index bcb75875..22b9d14c 100644 --- a/apps/app/src/editor/annotations/useCanvasBuild.ts +++ b/apps/app/src/editor/annotations/useCanvasBuild.ts @@ -3,52 +3,68 @@ import { buildView } from '@/components/catalogue/CatalogueCanvas' import { coreRuntime } from '@/core/runtime' import { useEditorStore } from '../state/editorStore' -/** The composed root's own attributes, read as text (never `baseVal`). */ +/** The composed root's own attributes, read as text (never `baseVal`), and its view. */ export interface RootAttributes { + /** The view this build was made for: a frame is never paired with another view's. */ + viewId: string viewBox: string | null ratio: string } export type CanvasFailure = 'engine' | 'view' +interface Built { + root: RootAttributes | null + failure: CanvasFailure | null +} + const ANNOTATED = '[data-anno-id]' +function rootOf(viewId: string, svg: Element): RootAttributes { + return { + viewId, + viewBox: svg.getAttribute('viewBox'), + ratio: svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet', + } +} + +/** What the canvas rebuilds on: the handle and its version counter. */ +function useHandle() { + const preview = useEditorStore((s) => s.preview) + const version = useEditorStore((s) => s.handleVersion) + return { preview, version } +} + /** * Builds the core's composed view into `host`, again on every accepted handle change or - * retry (plan « Rendering and canvas »): the edit canvas follows the handle. Reports the - * root's attributes; a failure is the engine notice (retry) or the view notice. + * retry (plan « Rendering and canvas »): the edit canvas follows the handle. Root and + * failure come from the same build; a failure is the engine notice (retry) or the view + * notice. */ export function useCanvasBuild(viewId: string) { - const preview = useEditorStore((s) => s.preview) - const handleVersion = useEditorStore((s) => s.handleVersion) + const handle = useHandle() const host = useRef(null) const [attempt, setAttempt] = useState(0) - const [root, setRoot] = useState(null) - const [failure, setFailure] = useState(null) + const [built, setBuilt] = useState({ root: null, failure: null }) useEffect(() => { const element = host.current - if (!element || !preview) return - const built = buildView(preview, viewId) - element.replaceChildren(...(built.ok ? [built.svg] : [])) - setFailure(built.ok ? null : built.failure) - setRoot( - built.ok - ? { - viewBox: built.svg.getAttribute('viewBox'), - ratio: - built.svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet', - } - : null, + if (!element || !handle.preview) return + const result = buildView(handle.preview, viewId) + element.replaceChildren(...(result.ok ? [result.svg] : [])) + setBuilt( + result.ok + ? { root: rootOf(viewId, result.svg), failure: null } + : { root: null, failure: result.failure }, ) - }, [preview, viewId, handleVersion, attempt]) + }, [handle.preview, viewId, handle.version, attempt]) const retry = useCallback(() => { void coreRuntime() .retry() .finally(() => setAttempt((n) => n + 1)) }, []) - return { host, root, failure, retry, handleVersion } + return { host, ...built, retry } } /** The selected annotation's markers wear `data-state="current"`, restyled in place. */ diff --git a/apps/app/src/editor/annotations/useCanvasGestures.ts b/apps/app/src/editor/annotations/useCanvasGestures.ts new file mode 100644 index 00000000..6964b106 --- /dev/null +++ b/apps/app/src/editor/annotations/useCanvasGestures.ts @@ -0,0 +1,109 @@ +import type { + CSSProperties, + KeyboardEvent, + MouseEvent, + PointerEvent, + RefObject, +} from 'react' +import type { Geometry } from '@faunosteo/core-wasm/types' +import { useFraming } from '@/catalogue/useFraming' +import type { XY } from './frame' +import { clientToDrawing } from './gesture' +import type { ToolId } from './uiState' +import { annotationIdOf } from './useCanvasBuild' +import { useMoveGesture, type MoveTarget } from './useMoveGesture' + +export interface GestureInput { + viewId: string + tool: ToolId + moveTarget: MoveTarget | null + overlay: RefObject + viewport: RefObject + onSelect: (id: string) => void + /** A click with a drawing tool, in drawing units. */ + onPlace: (at: XY) => void + onDrop: (id: string, geometry: Geometry) => void + /** Enter and Escape while the canvas box itself has the focus (a tracing). */ + onTraceKey: (event: KeyboardEvent) => void +} + +type Framing = ReturnType +type Move = ReturnType + +/** Each pointer handler of the framing and of the move gesture, one after the other. */ +function composedPointer(framing: Framing, move: Move) { + const both = + ( + name: + | 'onPointerDown' + | 'onPointerMove' + | 'onPointerUp' + | 'onPointerCancel', + ) => + (event: PointerEvent) => { + framing.handlers[name](event) + move.handlers[name](event) + } + return { + onPointerDown: both('onPointerDown'), + onPointerMove: both('onPointerMove'), + onPointerUp: both('onPointerUp'), + onPointerCancel: both('onPointerCancel'), + onLostPointerCapture: move.handlers.onLostPointerCapture, + } +} + +/** A click selects with the select tool, places with a drawing tool; a drag swallows it. */ +function clickHandler(input: GestureInput, framing: Framing) { + return (event: MouseEvent) => { + if (framing.swallowClick()) return + if (input.tool === 'select') { + const id = annotationIdOf(event.target) + if (id) input.onSelect(id) + return + } + const client = { x: event.clientX, y: event.clientY } + const at = clientToDrawing(input.overlay.current, client) + if (at) input.onPlace(at) + } +} + +/** `touch-action: none` only while a drawing tool, a drag or a zoom is active. */ +function touchStyle( + tool: ToolId, + armed: boolean, + scale: number, +): CSSProperties { + const none = tool !== 'select' || armed || scale !== 1 + return { touchAction: none ? 'none' : 'pan-x pan-y' } +} + +/** + * Everything the canvas box listens to: zoom and pan, the move gesture, the click, and + * the keys. Enter and Escape only count when the box itself is the target, so Enter on + * « Annuler le tracé » (or a list row) is that button's, never a close of the tracing. + */ +export function useCanvasGestures(input: GestureInput) { + const move = useMoveGesture({ + overlay: input.overlay, + target: input.moveTarget, + onDrop: input.onDrop, + }) + const framing = useFraming(input.viewport, input.viewId, { + canPan: (event) => input.tool === 'select' && !move.claims(event), + }) + const onKeyDown = (event: KeyboardEvent) => { + framing.handlers.onKeyDown(event) + if (event.target === event.currentTarget) input.onTraceKey(event) + } + return { + framing, + drag: move.preview, + boxProps: { + ...composedPointer(framing, move), + onKeyDown, + onClick: clickHandler(input, framing), + style: touchStyle(input.tool, move.armed, framing.framing.scale), + }, + } +} diff --git a/apps/app/src/editor/annotations/useMoveGesture.ts b/apps/app/src/editor/annotations/useMoveGesture.ts index 8e84bf8e..a9f6c8f0 100644 --- a/apps/app/src/editor/annotations/useMoveGesture.ts +++ b/apps/app/src/editor/annotations/useMoveGesture.ts @@ -39,13 +39,8 @@ const clientOf = (event: PointerEvent): XY => ({ y: event.clientY, }) -/** - * Drag of the selected circle or polygon as a block (plan « Select »): it starts only - * after 4 CSS px from the press, so a click with jitter never moves it; the overlay - * previews the translated outline; pointer-up commits once, pointer-cancel and lost - * capture drop it with no command; losing the target (read-only mode) drops it too. - */ -export function useMoveGesture({ overlay, target, onDrop }: MoveOptions) { +/** The drag in flight (a ref, read by the handlers) and what the page shows of it. */ +function useDragState(target: MoveTarget | null) { const drag = useRef(null) const [preview, setPreview] = useState(null) const [armed, setArmed] = useState(false) @@ -54,54 +49,80 @@ export function useMoveGesture({ overlay, target, onDrop }: MoveOptions) { setPreview(null) setArmed(false) } + const stopRef = useRef(stop) + stopRef.current = stop + // Losing the target (a switch to read-only, another selection) drops the drag. useEffect(() => { - if (target === null) stop() + if (target === null) stopRef.current() }, [target]) + return { drag, preview, setPreview, armed, setArmed, stop } +} - const translated = (event: PointerEvent): Geometry | null => { - const now = clientToDrawing(overlay.current, clientOf(event)) - const gesture = drag.current - if (!now || !gesture || !target) return null - return translatedGeometry(target.geometry, { - x: now.x - gesture.origin.x, - y: now.y - gesture.origin.y, - }) - } +type DragState = ReturnType + +/** The geometry the pointer's position gives the target, translated as a block. */ +function translatedAt( + overlay: MoveOptions['overlay'], + gesture: Drag | null, + target: MoveTarget | null, + event: PointerEvent, +): Geometry | null { + const now = clientToDrawing(overlay.current, clientOf(event)) + if (!now || !gesture || !target) return null + return translatedGeometry(target.geometry, { + x: now.x - gesture.origin.x, + y: now.y - gesture.origin.y, + }) +} + +function pointerHandlers(options: MoveOptions, state: DragState) { + const { overlay, target, onDrop } = options const claims = (event: PointerEvent): boolean => target !== null && annotationIdOf(event.target) === target.id - const onPointerDown = (event: PointerEvent) => { if (!claims(event) || event.button !== 0) return const origin = clientToDrawing(overlay.current, clientOf(event)) if (!origin) return - drag.current = { start: clientOf(event), origin, started: false } + state.drag.current = { start: clientOf(event), origin, started: false } event.currentTarget.setPointerCapture?.(event.pointerId) - setArmed(true) + state.setArmed(true) } const onPointerMove = (event: PointerEvent) => { - const gesture = drag.current + const gesture = state.drag.current if (!gesture) return if (!gesture.started && !pastDragThreshold(gesture.start, clientOf(event))) return gesture.started = true - setPreview(translated(event)) + state.setPreview(translatedAt(overlay, gesture, target, event)) } const onPointerUp = (event: PointerEvent) => { - const gesture = drag.current - const dropped = gesture?.started ? translated(event) : null - stop() + const gesture = state.drag.current + const dropped = gesture?.started + ? translatedAt(overlay, gesture, target, event) + : null + state.stop() if (dropped && target) onDrop(target.id, dropped) } return { - preview, - armed, claims, handlers: { onPointerDown, onPointerMove, onPointerUp, - onPointerCancel: stop, - onLostPointerCapture: stop, + onPointerCancel: state.stop, + onLostPointerCapture: state.stop, }, } } + +/** + * Drag of the selected circle or polygon as a block (plan « Select »): it starts only + * after 4 CSS px from the press, so a click with jitter never moves it; the overlay + * previews the translated outline; pointer-up commits once, pointer-cancel and lost + * capture drop it with no command; losing the target (read-only mode) drops it too. + */ +export function useMoveGesture(options: MoveOptions) { + const state = useDragState(options.target) + const { claims, handlers } = pointerHandlers(options, state) + return { preview: state.preview, armed: state.armed, claims, handlers } +} diff --git a/apps/app/src/editor/annotations/usePlacement.ts b/apps/app/src/editor/annotations/usePlacement.ts index 7c65d141..ed06ac82 100644 --- a/apps/app/src/editor/annotations/usePlacement.ts +++ b/apps/app/src/editor/annotations/usePlacement.ts @@ -62,24 +62,11 @@ export function closingActions( ] } -/** - * What a click, a key or a drop does with the current tool. Every geometry it proposes is - * arithmetic over F; the core decides at « Créer » or at the commit of an existing one. - */ -export function usePlacement(input: PlacementInput) { - const t = useT() - const { ui, dispatch, frame, doc, context } = input - - const placePoint = (frame: Frame, at: XY) => { - const outcome = pendingForClick(frame, at) - if (outcome.kind === 'pending') { - return dispatch({ type: 'pending_new', pending: outcome.pending }) - } - dispatch({ type: 'hint', hint: t('editor.annotations.outside') }) - } +/** Tracing with the zone and link tools: vertices, closing, Enter and Escape. */ +function tracingActions(input: PlacementInput) { + const { ui, dispatch, frame } = input const closeTracing = () => - closingActions(ui.tracing, doc, context).forEach(dispatch) - + closingActions(ui.tracing, input.doc, input.context).forEach(dispatch) const trace = (tool: Exclude, at: XY) => { if (!frame) return if (ui.tracing && nearFirstVertex(ui.tracing, at, frame)) { @@ -89,21 +76,48 @@ export function usePlacement(input: PlacementInput) { dispatch({ type: 'trace_start', target: TOOL_TARGET[tool] }) dispatch({ type: 'trace_add', point: asPoint(at) }) } - const onPlace = (at: XY) => { - if (ui.tool === 'point' && frame) placePoint(frame, at) - else if (ui.tool === 'zone' || ui.tool === 'link') trace(ui.tool, at) - } - const onDrop = (id: string, geometry: Geometry) => { - const annotation = doc.annotations.find((a) => a.id === id) - if (!annotation) return - const result = updateGeometry(annotation, geometry, context) - const hint = result.ok ? null : result.messages.join(' ') - dispatch({ type: 'hint', hint }) - } - const onKeyDown = (event: KeyboardEvent) => { + const onTraceKey = (event: KeyboardEvent) => { if (!ui.tracing) return if (event.key === 'Enter') closeTracing() if (event.key === 'Escape') dispatch({ type: 'trace_cancel' }) } - return { onPlace, onDrop, onKeyDown, closeTracing } + return { closeTracing, trace, onTraceKey } +} + +/** A drop commits one update; the hint holds the core's words on a refusal. */ +function dropAction(input: PlacementInput) { + return (id: string, geometry: Geometry) => { + const annotation = input.doc.annotations.find((a) => a.id === id) + if (!annotation) return + const result = updateGeometry(annotation, geometry, input.context) + const hint = result.ok ? null : result.messages.join(' ') + input.dispatch({ type: 'hint', hint }) + } +} + +/** + * What a click, a key or a drop does with the current tool. Every geometry it proposes is + * arithmetic over F; the core decides at « Créer » or at the commit of an existing one. + * `onTraceKey` is for the canvas viewport only (a key from a button is the button's). + */ +export function usePlacement(input: PlacementInput) { + const t = useT() + const tracing = tracingActions(input) + const { ui, dispatch, frame } = input + const onPlace = (at: XY) => { + if (ui.tool === 'zone' || ui.tool === 'link') + return tracing.trace(ui.tool, at) + if (ui.tool !== 'point' || !frame) return + const outcome = pendingForClick(frame, at) + if (outcome.kind === 'pending') { + return dispatch({ type: 'pending_new', pending: outcome.pending }) + } + dispatch({ type: 'hint', hint: t('editor.annotations.outside') }) + } + return { + onPlace, + onDrop: dropAction(input), + onTraceKey: tracing.onTraceKey, + closeTracing: tracing.closeTracing, + } } diff --git a/apps/app/src/editor/annotations/useViewModel.ts b/apps/app/src/editor/annotations/useViewModel.ts index 3b9e7a3d..55f336a7 100644 --- a/apps/app/src/editor/annotations/useViewModel.ts +++ b/apps/app/src/editor/annotations/useViewModel.ts @@ -1,4 +1,4 @@ -import { useEffect, useMemo } from 'react' +import { useMemo } from 'react' import type { AnatomicalSheetDocument, Annotation, @@ -32,23 +32,3 @@ export function useViewModel( } }, [doc, state, viewId]) } - -const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]' - -/** Ctrl+Z undoes and Ctrl+Shift+Z redoes, outside text fields (no Ctrl+Y). */ -export function useUndoShortcuts(): void { - useEffect(() => { - const onKey = (event: KeyboardEvent) => { - const target = event.target - if (target instanceof Element && target.closest(TEXT_TARGET)) return - if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z') - return - event.preventDefault() - const store = useEditorStore.getState() - if (event.shiftKey) store.redoStep() - else store.undoStep() - } - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, []) -} diff --git a/apps/app/src/editor/useUndoShortcuts.ts b/apps/app/src/editor/useUndoShortcuts.ts new file mode 100644 index 00000000..7334c508 --- /dev/null +++ b/apps/app/src/editor/useUndoShortcuts.ts @@ -0,0 +1,29 @@ +import { useEffect } from 'react' +import { useEditorStore } from './state/editorStore' + +const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]' +const MODAL_OPEN = 'dialog[open]' + +/** + * Ctrl+Z undoes and Ctrl+Shift+Z redoes, editor-wide (plan « Store and sessions », no + * Ctrl+Y): active only while the draft is writable, ignored in text fields and while a + * modal dialog is open (its own focus and keys come first). + */ +export function useUndoShortcuts(writable: boolean): void { + useEffect(() => { + if (!writable) return + const onKey = (event: KeyboardEvent) => { + const { target } = event + if (target instanceof Element && target.closest(TEXT_TARGET)) return + if (document.querySelector(MODAL_OPEN)) return + if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z') + return + event.preventDefault() + const store = useEditorStore.getState() + if (event.shiftKey) store.redoStep() + else store.undoStep() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [writable]) +} diff --git a/apps/app/tests/unit/editor-annotations-commit.test.ts b/apps/app/tests/unit/editor-annotations-commit.test.ts index 72f83ef2..9de71bc8 100644 --- a/apps/app/tests/unit/editor-annotations-commit.test.ts +++ b/apps/app/tests/unit/editor-annotations-commit.test.ts @@ -277,6 +277,22 @@ describe('a frame change (rule 7)', () => { expect(store.getState().documentText).toBe(before) }) + it('is refused when it makes a point too_small, nothing kept', async () => { + await openWith( + insert(drawnText(), point('anno-a', 2500, 2500, 400)), + '0 0 5000 5000', + ) + const before = store.getState().documentText + const outcome = crop({ min_x: 0, min_y: 0, width: 200000, height: 200000 }) + expect(outcome).toMatchObject({ ok: false, reason: 'refused' }) + if (outcome.ok || outcome.reason !== 'refused') + throw new Error('not refused') + expect(outcome.refusal.issues.map((i) => i.code)).toContain( + 'annotation.geometry.too_small', + ) + expect(store.getState().documentText).toBe(before) + }) + it('is accepted when only an already-invalid point is affected', async () => { await openReady({ text: insert(drawnText(), point('anno-a', 150, 50, 5)) }) expect(crop({ min_x: 0, min_y: 0, width: 80, height: 80 }).ok).toBe(true) diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx index edbf36ad..ba3c7d7b 100644 --- a/apps/app/tests/unit/editor-annotations-tab.test.tsx +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -1,6 +1,7 @@ /** Lot H: the Annotations tab (creation, corrected position, gestures, read-only, repair). */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { + act, cleanup, fireEvent, render, @@ -22,6 +23,7 @@ import { import { USER, VERSION, + commitMove, openReady, resetStore, sb, @@ -693,13 +695,11 @@ describe('polygons and paths', () => { }) const panel = await selectFromList() expect(within(panel).queryByText(/M 20 20/)).toBeNull() - await userEvent - .setup() - .click( - within(panel).getByRole('button', { - name: 'Remplacer par un polygone', - }), - ) + await userEvent.setup().click( + within(panel).getByRole('button', { + name: 'Remplacer par un polygone', + }), + ) const canvas = screen.getByTestId('annotation-canvas') triangle.forEach(([x, y]) => fireEvent.click(canvas, { clientX: x, clientY: y }), @@ -714,25 +714,232 @@ describe('polygons and paths', () => { }) }) -describe('keyboard shortcuts', () => { - it('undoes with Ctrl+Z outside a text field and not inside one', async () => { - await mount() - await selectFromList() - const user = userEvent.setup() - const cx = within( - screen.getByTestId('annotation-properties'), - ).getByLabelText('Centre x') - await user.clear(cx) - await user.type(cx, '60{Enter}') - fireEvent.keyDown(cx, { key: 'z', ctrlKey: true }) - expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) - fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true }) - expect(geometryOf('anno-a')).toMatchObject({ cx: 50 }) - fireEvent.keyDown(document.body, { - key: 'z', - ctrlKey: true, - shiftKey: true, +describe('keys while tracing (H3)', () => { + const clickAt = (x: number, y: number) => + fireEvent.click(screen.getByTestId('annotation-canvas'), { + clientX: x, + clientY: y, }) - expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + + async function traced() { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(), + ) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Zone' })) + triangle.forEach(([x, y]) => clickAt(x, y)) + return user + } + + it('Enter on « Annuler le tracé » cancels the tracing instead of closing it', async () => { + const user = await traced() + screen.getByRole('button', { name: 'Annuler le tracé' }).focus() + await user.keyboard('{Enter}') + expect( + screen.queryByRole('button', { name: 'Annuler le tracé' }), + ).toBeNull() + expect(screen.queryByTestId('annotation-creation')).toBeNull() + }) + + it('Enter on a view chip or a list row never closes the tracing', async () => { + await traced() + const views = screen.getByRole('group', { name: 'Vues' }) + fireEvent.keyDown(within(views).getAllByRole('button')[0], { + key: 'Enter', + }) + expect(screen.queryByTestId('annotation-creation')).toBeNull() + expect( + screen.getByRole('button', { name: 'Annuler le tracé' }), + ).toBeInTheDocument() + }) +}) + +describe('a second click with the point tool (H6)', () => { + it('moves the pending point and keeps what was typed', async () => { + await mount({ text: drawnText() }) + await waitFor(() => + expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(), + ) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Point' })) + fireEvent.click(screen.getByTestId('annotation-canvas'), { + clientX: 50, + clientY: 50, + }) + const panel = await fillCreation(user) + fireEvent.click(screen.getByTestId('annotation-canvas'), { + clientX: 60, + clientY: 40, + }) + await waitFor(() => + expect(within(panel).getByLabelText('Centre x')).toHaveValue('60'), + ) + expect(within(panel).getByLabelText('Nom (FR)')).toHaveValue('Nuque') + expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired') + expect(screen.getByTestId('annotation-creation')).toBe(panel) + }) +}) + +describe('a typed radius (H5)', () => { + it('shows the core issue, not a corrected position', async () => { + const drawing = svgBytes('0 0 5000 5000') + sb.getSheetVersion.mockResolvedValue({ + ...versionAnswer(drawnText(), 3), + drawings: [{ asset_id: ASSET, sha256: drawing.sha256 }], + } as never) + sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes) + store.getState().open(VERSION, USER, { canEdit: true }) + await waitFor(() => expect(store.getState().status).toBe('ready')) + render() + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Ajouter un point' }), + ).toBeEnabled(), + ) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Ajouter un point' })) + const panel = await fillCreation(user) + const r = within(panel).getByLabelText('Rayon') + await user.clear(r) + await user.type(r, '1{Enter}') + await user.click(within(panel).getByRole('button', { name: 'Créer' })) + expect(screen.queryByTestId('correction-notice')).toBeNull() + expect(within(panel).getByRole('alert')).toBeInTheDocument() + expect(annotations()).toHaveLength(0) + }) +}) + +describe('the frame follows the view (H7)', () => { + it('holds the keyboard point at the centre of the view shown, after a switch', async () => { + const withView = insert(drawnText(), { + kind: 'view', + value: { + kind: 'detail', + id: 'view-det', + name: { fr: 'Tête', en: 'Head' }, + svg_asset_id: null, + view_box: { min_x: 10, min_y: 20, width: 40, height: 60 }, + parent_view_id: 'view-main', + }, + }) + await mount({ text: withView }) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Tête' })) + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Ajouter un point' }), + ).toBeEnabled(), + ) + await user.click(screen.getByRole('button', { name: 'Ajouter un point' })) + const panel = await screen.findByTestId('annotation-creation') + expect(within(panel).getByLabelText('Centre x')).toHaveValue('30') + expect(within(panel).getByLabelText('Centre y')).toHaveValue('50') + }) +}) + +describe('refusals through the tab (H8)', () => { + const zoneText = (geometry: object) => + insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) }) + + it('a refused « Remplacer par un polygone » drops the tracing, shows the core message', async () => { + const path = { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' } + await mount({ text: zoneText(path) }) + const panel = await selectFromList() + await userEvent.setup().click( + within(panel).getByRole('button', { + name: 'Remplacer par un polygone', + }), + ) + const canvas = screen.getByTestId('annotation-canvas') + ;[ + [20, 20], + [500, 20], + [50, 80], + ].forEach(([x, y]) => fireEvent.click(canvas, { clientX: x, clientY: y })) + fireEvent.keyDown(canvas, { key: 'Enter' }) + expect(await screen.findByRole('alert')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Annuler le tracé' }), + ).toBeNull() + expect(geometryOf('zone-a')).toEqual(path) + }) + + it('a refused vertex add and a refused remove stay « non appliqué », document unchanged', async () => { + await mount({ + text: zoneText({ type: 'polygon', points: [...triangle, [20, 60]] }), + }) + const panel = await selectFromList() + const user = userEvent.setup() + const before = store.getState().documentText + const x = within(panel).getByLabelText('x du sommet 1') + await user.clear(x) + await user.type(x, '500{Enter}') + await user.click( + within(panel).getByRole('button', { name: 'Ajouter un sommet' }), + ) + expect(store.getState().documentText).toBe(before) + expect(within(panel).getAllByLabelText(/^x du sommet/)).toHaveLength(5) + expect( + within(panel).getByText(/Valeurs non appliquées/), + ).toBeInTheDocument() + await user.click(within(panel).getByRole('button', { name: 'Retirer' })) + expect(store.getState().documentText).toBe(before) + expect( + within(panel).getByText(/Valeurs non appliquées/), + ).toBeInTheDocument() + }) +}) + +describe('the drag and the canvas follow the handle (H8)', () => { + const down = (el: Element, x: number, y: number) => + fireEvent.pointerDown(el, { + clientX: x, + clientY: y, + button: 0, + pointerId: 1, + }) + + it('lostpointercapture drops the drag with no command', async () => { + await mount() + await selectFromList() + const hit = marker('anno-a') + const version = store.getState().handleVersion + down(hit, 50, 50) + fireEvent.pointerMove(hit, { clientX: 70, clientY: 50, pointerId: 1 }) + fireEvent.lostPointerCapture(hit, { pointerId: 1 }) + fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 }) + expect(store.getState().handleVersion).toBe(version) + }) + + it('a switch to read-only mid-drag drops it', async () => { + await openReady({ text: text() }) + const view = render() + await waitFor(() => + expect( + screen.getByTestId('annotation-canvas-drawing').querySelector('svg'), + ).not.toBeNull(), + ) + await selectFromList() + const hit = marker('anno-a') + const version = store.getState().handleVersion + down(hit, 50, 50) + fireEvent.pointerMove(hit, { clientX: 70, clientY: 50, pointerId: 1 }) + view.rerender() + fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 }) + expect(store.getState().handleVersion).toBe(version) + expect(geometryOf('anno-a')).toEqual({ + type: 'circle', + cx: 50, + cy: 50, + r: 5, + }) + }) + + it('rebuilds the drawing when the handle changes under it', async () => { + await mount() + const first = marker('anno-a') + act(() => void commitMove(60)) + await waitFor(() => expect(marker('anno-a')).not.toBe(first)) }) }) diff --git a/apps/app/tests/unit/editor-frame.test.ts b/apps/app/tests/unit/editor-frame.test.ts index 5342f41d..cc2b4913 100644 --- a/apps/app/tests/unit/editor-frame.test.ts +++ b/apps/app/tests/unit/editor-frame.test.ts @@ -147,24 +147,27 @@ describe('correctionFor', () => { it('offers C for a refused B or an A refused out_of_frame, never for A too_small', () => { const reduced = { cx: 13.19, cy: 15, r: 13.19 } expect( - correctionFor(frame, reduced, ['annotation.geometry.too_small']), + correctionFor(frame, reduced, ['annotation.geometry.too_small'], 13.19), ).not.toBeNull() const edge = { cx: 5, cy: 15, r: 13.2 } expect( - correctionFor(frame, edge, ['annotation.geometry.out_of_frame'])?.circle - .cx, + correctionFor(frame, edge, ['annotation.geometry.out_of_frame'], 13.2) + ?.circle.cx, ).toBe(13.2) expect( - correctionFor(frame, { cx: 20, cy: 15, r: 13.2 }, [ - 'annotation.geometry.too_small', - ]), + correctionFor( + frame, + { cx: 20, cy: 15, r: 13.2 }, + ['annotation.geometry.too_small'], + 13.2, + ), ).toBeNull() }) it('offers nothing when C is the circle that was just refused', () => { const circle = { cx: 13.2, cy: 13.2, r: 13.2 } expect( - correctionFor(frame, circle, ['annotation.geometry.out_of_frame']), + correctionFor(frame, circle, ['annotation.geometry.out_of_frame'], 13.2), ).toBeNull() }) }) @@ -211,7 +214,12 @@ describe.each(FRAMES)('a point placed in the frame %s', (viewBox) => { expect(proposal.kind).not.toBe('outside') if (proposal.kind === 'outside') continue const insert = circleInserter(b) - const attempt = attemptPoint(frame, proposal.circle, insert) + const attempt = attemptPoint( + frame, + proposal.circle, + insert, + proposal.circle.r, + ) expect(attempt).toMatchObject({ status: 'created' }) expect(currentErrors(b).size).toBe(0) } @@ -247,7 +255,12 @@ describe('a very elongated frame', () => { const frame = frameOf(b)! const proposal = proposePoint(frame, { x: 500, y: 15 }) if (proposal.kind !== 'circle') throw new Error('proposal') - const attempt = attemptPoint(frame, proposal.circle, circleInserter(b)) + const attempt = attemptPoint( + frame, + proposal.circle, + circleInserter(b), + proposal.circle.r, + ) expect(attempt.status).toBe('refused') expect(b.preview.document).toBe(b.text) }) @@ -267,7 +280,9 @@ describe('a detail crop', () => { const inside = proposePoint(frame, { x: 150, y: 350 }) if (inside.kind !== 'circle') throw new Error('proposal') const insert = circleInserter(b, 'view-det') - expect(attemptPoint(frame, inside.circle, insert)).toMatchObject({ + expect( + attemptPoint(frame, inside.circle, insert, inside.circle.r), + ).toMatchObject({ status: 'created', }) expect(proposePoint(frame, { x: 99, y: 350 })).toEqual({ kind: 'outside' }) @@ -276,3 +291,73 @@ describe('a detail crop', () => { expect(currentErrors(b).size).toBe(0) }) }) + +describe('a radius the user typed (H5)', () => { + const frame = f(0, 0, 40, 30) + + it('is never replaced by a corrected position: the core issue is shown', () => { + const typed = { cx: 20, cy: 15, r: 1 } + const codes = ['annotation.geometry.too_small'] + expect(correctionFor(frame, typed, codes, 13.2)).toBeNull() + expect(correctionFor(frame, typed, codes, undefined)).toBeNull() + }) + + it('on the core: a typed too-small radius creates nothing and keeps the message', () => { + const b = bed('0 0 5000 5000') + const big = frameOf(b)! + const attempt = attemptPoint( + big, + { cx: 2500, cy: 2500, r: 1 }, + circleInserter(b), + defaultRadius(big), + ) + expect(attempt).toMatchObject({ status: 'refused' }) + expect(b.preview.document).toBe(b.text) + }) +}) + +describe('the keyboard point (H4)', () => { + it.each([ + '0.003 0.004 20 20', + '0 0 20 20', + '-50 20 40 30', + '0.003 0.004 1000 30', + ])('fits the frame %s by construction, with no correction', (viewBox) => { + const b = bed(viewBox) + const frame = frameOf(b)! + const circle = centreCircle(frame) + const slack = 1e-9 // float noise of x + w / 2 − r only; the core decides below + expect(circle.cx - circle.r).toBeGreaterThanOrEqual(frame.x - slack) + expect(circle.cy - circle.r).toBeGreaterThanOrEqual(frame.y - slack) + expect(circle.cx + circle.r).toBeLessThanOrEqual(frame.x + frame.w + slack) + expect(circle.cy + circle.r).toBeLessThanOrEqual(frame.y + frame.h + slack) + const attempt = attemptPoint(frame, circle, circleInserter(b), circle.r) + expect(attempt.status).not.toBe('correction') + if (viewBox.endsWith('1000 30')) return + expect(attempt).toMatchObject({ status: 'created' }) + }) +}) + +describe.each(['0 0 1000 30', '0 0 4000 200'])( + 'the elongated frame %s (H8)', + (viewBox) => { + it('gives the core the verdict on every edge and corner click, keeping nothing invalid', () => { + const frame = frameOf(bed(viewBox))! + for (const click of clicksOf(frame)) { + const b = bed(viewBox) + const proposal = proposePoint(frame, click) + if (proposal.kind === 'outside') continue + const attempt = attemptPoint( + frame, + proposal.circle, + circleInserter(b), + proposal.circle.r, + ) + expect(['created', 'refused', 'correction']).toContain(attempt.status) + expect(currentErrors(b).size).toBe(0) + if (attempt.status !== 'created') + expect(b.preview.document).toBe(b.text) + } + }) + }, +) diff --git a/apps/app/tests/unit/editor-undo-shortcuts.test.tsx b/apps/app/tests/unit/editor-undo-shortcuts.test.tsx new file mode 100644 index 00000000..7462a7fd --- /dev/null +++ b/apps/app/tests/unit/editor-undo-shortcuts.test.tsx @@ -0,0 +1,79 @@ +/** Lot H fix H2: Ctrl+Z and Ctrl+Shift+Z are editor-wide, writable only, not in a dialog. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { + baseText, + commitMove, + resetStore, + serverHas, + store, +} 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(() => serverHas(baseText(), 3)) +afterEach(() => { + cleanup() + resetStore() + setWidth(1024) +}) + +const ready = () => + screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) +const cx = () => store.getState().previewState?.document.annotations[0].geometry +const ctrlZ = (target: Element, shift = false) => + fireEvent.keyDown(target, { key: 'z', ctrlKey: true, shiftKey: shift }) + +describe('editor-wide undo', () => { + it('undoes and redoes from another tab', async () => { + mountDraft() + await ready() + act(() => void commitMove(40)) + await userEvent.setup().click(screen.getByRole('tab', { name: 'Général' })) + ctrlZ(document.body) + expect(cx()).toMatchObject({ cx: 50 }) + ctrlZ(document.body, true) + expect(cx()).toMatchObject({ cx: 40 }) + }) + + it('does nothing in a text field', async () => { + mountDraft() + await ready() + act(() => void commitMove(40)) + await userEvent.setup().click(screen.getByRole('tab', { name: 'Général' })) + ctrlZ(document.querySelector('input') as Element) + expect(cx()).toMatchObject({ cx: 40 }) + }) + + it('does nothing while a modal dialog is open', async () => { + mountDraft() + await ready() + act(() => void commitMove(40)) + const dialog = document.createElement('dialog') + dialog.setAttribute('open', '') + document.body.append(dialog) + ctrlZ(document.body) + expect(cx()).toMatchObject({ cx: 40 }) + dialog.remove() + }) + + it('is off in a read-only mode', async () => { + mountDraft({ width: 800 }) + await ready() + store.getState().setCanEdit(true) + act(() => void commitMove(40)) + store.getState().setCanEdit(false) + ctrlZ(document.body) + expect(cx()).toMatchObject({ cx: 40 }) + }) +})