diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index 636cd5d3..fcad2e92 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -1,5 +1,4 @@ import { useEffect, useReducer, useState, type Dispatch } from 'react' -import { flushSync } from 'react-dom' import type { AnatomicalSheetDocument, Annotation, @@ -18,10 +17,8 @@ import { } from '@/editor/annotations/workStore' import { parseFrame, type Frame } from '@/editor/annotations/frame' import { newPointSize } from '@/editor/annotations/pointSize' -import { - focusPressedIfLost, - guardDrawing, -} from '@/editor/annotations/drawingGuard' +import { guardDrawing } from '@/editor/annotations/drawingGuard' +import { guardedPress } from '@/editor/annotations/guardedPress' import { usePointEdit } from '@/editor/annotations/usePointEdit' import { useZoneEdit, type ZoneTarget } from '@/editor/annotations/useZoneEdit' import { useRedrawFollowsTracing } from '@/editor/annotations/redraw' @@ -286,17 +283,6 @@ const guarded = (action: () => void) => () => { if (guardDrawing(action)) action() } -/** - * A tool, a view chip or an overview row, guarded as above. Pressed with the focus still on - * a handle (Safari focuses no clicked button), the change unmounts that handle: the focus - * then lands on the pressed control, where the keyboard's press leaves it, never on `body` (rev 4 M-4). - */ -function guardedPress(button: HTMLElement, action: () => void) { - if (!guardDrawing(action)) return - flushSync(action) - focusPressedIfLost(button) -} - function CanvasColumn({ scene, work, @@ -307,6 +293,7 @@ function CanvasColumn({ onDeselect: () => void }) { const { doc, dispatch, model } = scene + const framing = useAnnotationWork((s) => s.frame !== null) const noCategory = ordinaryCategories(doc.categories).length === 0 return (
@@ -321,7 +308,7 @@ function CanvasColumn({ v.id === scene.viewId) - const blocked = !model.measured + // A frame being drawn or adjusted keeps the drawing: no creation tool starts over it. + const framing = useAnnotationWork((s) => s.frame !== null) + const blocked = !model.measured || framing const noCategory = ordinaryCategories(doc.categories).length === 0 if (!view) return null return ( @@ -456,7 +445,7 @@ function CanvasStage({ onFutileDrag={() => hintTwoFingers(work.message, work.context.t)} onTraceKey={work.placement.onTraceKey} onFrameCentred={() => - work.message.show(work.context.t('editor.annotations.frame.centred'), { + work.message.show(work.context.t('editor.annotations.frame.placed'), { undo: false, tone: 'info', }) diff --git a/apps/app/src/components/editor/annotations/FrameCommands.tsx b/apps/app/src/components/editor/annotations/FrameCommands.tsx new file mode 100644 index 00000000..9af62eca --- /dev/null +++ b/apps/app/src/components/editor/annotations/FrameCommands.tsx @@ -0,0 +1,206 @@ +import { useRef, type ReactNode } from 'react' +import Button from '@/components/ui/Button' +import type { Frame, XY } from '@/editor/annotations/frame' +import { moveStep } from '@/editor/annotations/frame' +import { moveBox, ratioLabel } from '@/editor/annotations/frameBox' +import { + askFrame, + openViewDialog, + redrawFrame, + setFrameBox, + setFrameMoving, + setKeepRatio, + setMoveAccess, +} from '@/editor/annotations/frameWork' +import type { Direction } from '@/editor/annotations/usePointEdit' +import type { FrameWork } from '@/editor/annotations/workStore' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' +import MoveModeBar from './MoveModeBar' + +const COMMAND = 'min-h-11 xl:min-h-9' + +const DELTA: Record = { + left: { x: -1, y: 0 }, + up: { x: 0, y: -1 }, + down: { x: 0, y: 1 }, + right: { x: 1, y: 0 }, +} + +function Check({ + checked, + label, + onChange, +}: { + checked: boolean + label: string + onChange: (on: boolean) => void +}): ReactNode { + return ( + + ) +} + +/** The box's ratio, « Format 4:3 »: it follows the box. */ +function FormatChip({ box }: { box: Frame }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const ratio = ratioLabel(box.w, box.h, locale) + return ( + + {t('editor.annotations.frame.format').replace('{ratio}', () => ratio)} + + ) +} + +function Abandon() { + const t = useT() + return ( + + ) +} + +/** « Déplacer »: the arrows move the box by one step (A11, WCAG 2.5.7), never out of F. */ +function FrameMoveBar({ box, bounds }: { box: Frame; bounds: Frame | null }) { + const before = useRef(box) + const step = (direction: Direction) => { + if (!bounds) return + const size = moveStep(bounds, false) + const { x, y } = DELTA[direction] + setFrameBox(moveBox(box, { x: x * size, y: y * size }, bounds)) + } + return ( + setFrameMoving(false)} + onCancel={() => { + setFrameBox(before.current) + setFrameMoving(false) + }} + /> + ) +} + +export interface FrameCommandsProps { + frame: FrameWork + /** The parent drawing's frame: the box never leaves it; null while unmeasured. */ + bounds: Frame | null + /** Task 11 wires « Appliquer » of a recrop. */ + onApply?: () => void +} + +/** A new frame's adjusting: « Déplacer », « Retracer », « Abandonner », « Valider le cadre ». */ +function CreateCommands() { + const t = useT() + return ( + <> + + + + + + ) +} + +/** A recrop: « Déplacer l'accès avec le cadre », « Abandonner », « Appliquer ». */ +function RecropCommands({ + frame, + onApply, +}: { + frame: FrameWork + onApply?: () => void +}) { + const t = useT() + return ( + <> + + + + + ) +} + +/** + * The strip's commands while a frame is open (boards 03, 18, 19). Drawing: « Abandonner ». + * Adjusting: the format and the proportions, then the purpose's own. Moving: the move bar + * in the same box (the commands key is the phase's, A14). + */ +export default function FrameCommands({ + frame, + bounds, + onApply, +}: FrameCommandsProps) { + const t = useT() + const { box } = frame + if (box === null) return + if (frame.moving) return + return ( +
+ + + {frame.purpose === 'create' ? ( + + ) : ( + + )} +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/FrameHandles.tsx b/apps/app/src/components/editor/annotations/FrameHandles.tsx index 8c999314..ab93cd55 100644 --- a/apps/app/src/components/editor/annotations/FrameHandles.tsx +++ b/apps/app/src/components/editor/annotations/FrameHandles.tsx @@ -9,7 +9,7 @@ import { type FrameHandle, type FramePart, } from '@/editor/annotations/frameBox' -import { setFrameBox } from '@/editor/annotations/frameWork' +import { confirmFrameByKey, setFrameBox } from '@/editor/annotations/frameWork' import type { HandleSizes } from '@/editor/annotations/handleSize' import { useAnnotationWork } from '@/editor/annotations/workStore' import { useT } from '@/i18n/useT' @@ -71,9 +71,17 @@ function steppedBox(props: FrameHandlesProps, part: FramePart, delta: XY) { }) } -/** Arrows step by `moveStep` (ten with Shift); Escape reaches the document's listener. */ +/** + * Arrows step by `moveStep` (ten with Shift); Enter confirms a new frame; Escape reaches the + * document's listener. + */ function keyOf(props: FrameHandlesProps, part: FramePart) { return (event: KeyboardEvent) => { + if (event.key === 'Enter') { + event.preventDefault() + confirmFrameByKey() + return + } const arrow = ARROWS[event.key] if (!arrow) return event.preventDefault() @@ -101,7 +109,7 @@ function Handle({ s.frame) useModeFocusReturn(useFocusMode(mode !== null, scene.tracing)) const chosenVertex = useChosenVertex(selected?.id) const lead = mode @@ -52,7 +61,12 @@ export default function SceneStrip({ icon: 'move' as const, } : stripLeadOf( - { tool: ui.tool, tracing: scene.tracing, creation: scene.creation }, + { + tool: ui.tool, + tracing: scene.tracing, + creation: scene.creation, + frame, + }, selected, doc, { t, locale, chosenVertex }, @@ -62,6 +76,7 @@ export default function SceneStrip({ mode !== null, work.target, chosenVertex, + frame, ) return ( + startFrame({ + purpose: 'create', + viewId, + drawnOn: viewId, + box: null, + returnTo: viewId, + }), + ) + const surface = keyboard ? canvasSurface() : null + if (!surface || useAnnotationWork.getState().frame === null) return + if (!placeAtCentre(surface)) return + work.message.show(work.context.t('editor.annotations.frame.placed'), { + undo: false, + tone: 'info', + }) +} + /** * A tracing's commands; a selection's own, then « Propriétés » and « Désélectionner »; * or the Point tool's size (A5). @@ -151,6 +204,8 @@ function SceneCommands({ const { byButton } = useDeselect(selected?.id ?? null, () => dispatch({ type: 'select', id: null }), ) + const framing = useAnnotationWork((s) => s.frame) + if (framing) return // The dialog shown: its own actions; hidden after it was shown: board 04 C. if (creation?.dialog) return null if (creation?.resumed) { @@ -199,6 +254,13 @@ function SceneCommands({ ) } + if (ui.tool === 'select' && !creation) { + return ( + newView(scene, work, button, keyboard)} + /> + ) + } if (ui.tool !== 'point' || creation || !frame) return null return ( void + onParent?: (button: HTMLElement) => void + onRecrop?: (button: HTMLElement) => void +} + +/** + * The strip's commands when nothing is selected and nothing is in progress (board 01): the + * view's own commands. A command whose handler is absent is not rendered, so each task + * that wires one leaves a working strip. + */ +export default function ViewCommands({ + onNew, + onParent, + onRecrop, +}: ViewCommandsProps) { + const t = useT() + return ( +
+ {onParent && ( + + )} + {onRecrop && ( + + )} + +
+ ) +} diff --git a/apps/app/src/editor/annotations/frameDraw.ts b/apps/app/src/editor/annotations/frameDraw.ts index a4830df3..218241c2 100644 --- a/apps/app/src/editor/annotations/frameDraw.ts +++ b/apps/app/src/editor/annotations/frameDraw.ts @@ -63,3 +63,19 @@ export function placeAtCentre(surface: FrameSurface): boolean { setFrameBox(defaultBox(at, visible, AREA_RATIO, bounds)) return true } + +/** + * The drawing's two elements, read from the page for a command outside the canvas (the + * strip's keyboard press); null while no drawing is shown. + */ +export function canvasSurface(): FrameSurface | null { + const column = document.querySelector('[data-drawing-column]') + const viewport = column?.querySelector( + '[data-testid="annotation-canvas"]', + ) + const overlay = column?.querySelector( + '[data-testid="annotation-overlay"]', + ) + if (!viewport || !overlay) return null + return { viewport: { current: viewport }, overlay: { current: overlay } } +} diff --git a/apps/app/src/editor/annotations/frameWork.ts b/apps/app/src/editor/annotations/frameWork.ts index 0923f1c8..598423fd 100644 --- a/apps/app/src/editor/annotations/frameWork.ts +++ b/apps/app/src/editor/annotations/frameWork.ts @@ -56,6 +56,11 @@ export function setFrameBox(box: Frame): void { patch({ box, started: true }) } +/** « Retracer »: the box is dropped, the frame is drawn again from nothing. */ +export function redrawFrame(): void { + patch({ box: null, started: false, moving: false }) +} + export function setKeepRatio(on: boolean): void { patch({ keepRatio: on }) } @@ -87,3 +92,8 @@ export function dropFrame(): void { export function askFrame(): void { guardDrawing(() => {}) } + +/** Enter on a frame handle or the body: confirms a new frame; a recrop waits for « Appliquer ». */ +export function confirmFrameByKey(): void { + if (frame()?.purpose === 'create') openViewDialog() +} diff --git a/apps/app/src/editor/annotations/guardedPress.ts b/apps/app/src/editor/annotations/guardedPress.ts new file mode 100644 index 00000000..fe33dbd3 --- /dev/null +++ b/apps/app/src/editor/annotations/guardedPress.ts @@ -0,0 +1,13 @@ +import { flushSync } from 'react-dom' +import { focusPressedIfLost, guardDrawing } from './drawingGuard' + +/** + * A tool, a view chip or an overview row, guarded like every move that drops the drawing's work (R-12, `guardDrawing`). Pressed with the focus still on + * a handle (Safari focuses no clicked button), the change unmounts that handle: the focus + * then lands on the pressed control, where the keyboard's press leaves it, never on `body` (rev 4 M-4). + */ +export function guardedPress(button: HTMLElement, action: () => void) { + if (!guardDrawing(action)) return + flushSync(action) + focusPressedIfLost(button) +} diff --git a/apps/app/src/editor/annotations/stripLead.ts b/apps/app/src/editor/annotations/stripLead.ts index ef799a92..86909c19 100644 --- a/apps/app/src/editor/annotations/stripLead.ts +++ b/apps/app/src/editor/annotations/stripLead.ts @@ -11,7 +11,7 @@ import { pluralKey } from '../plural' import type { PendingElement } from './creation' import { HANDLE_CAP } from './polygonEdit' import type { ToolId, Tracing } from './uiState' -import type { Creation } from './workStore' +import type { Creation, FrameWork } from './workStore' /** The strip's left part: what is selected or in progress, then its type and detail. */ export interface StripLead { @@ -183,15 +183,46 @@ export interface LeadState { tool: ToolId tracing: Tracing | null creation?: Creation | null + /** An open frame work: it leads before anything else. */ + frame?: FrameWork | null } -/** What the strip leads with: a creation, then a tracing, then the selection, then the tool. */ +/** + * An open frame: « Nouvelle vue de détail » with the drawing or adjusting hint, or, on a + * recrop, « Recadrer · {nom} » with the count of annotations that go back to « à confirmer ». + */ +function frameLead( + frame: FrameWork, + doc: AnatomicalSheetDocument, + ctx: LeadContext, +): StripLead { + if (frame.purpose === 'create') { + const hint = frame.box === null ? 'draw_hint' : 'adjust_hint' + return { + title: ctx.t('editor.annotations.view.new'), + detail: ctx.t(`editor.annotations.frame.${hint}`), + icon: 'fit', + } + } + const view = doc.views.find((v) => v.id === frame.viewId) + const count = doc.annotations.filter((a) => a.view_id === frame.viewId).length + return { + title: ctx + .t('editor.annotations.frame.recrop_title') + .replace('{name}', () => view?.name[ctx.locale] ?? ''), + detail: counted(ctx, 'editor.annotations.frame.recrop_warning', count), + icon: 'fit', + } +} + +/** What the strip leads with: a frame, a creation, a tracing, the selection, then the tool. */ export function stripLeadOf( ui: LeadState, selected: Annotation | undefined, doc: AnatomicalSheetDocument, ctx: LeadContext, ): StripLead { + if (ui.frame) return frameLead(ui.frame, doc, ctx) const creation = ui.creation ? creationLead(ui.creation, ctx) : null if (creation) return creation if (ui.tracing) { diff --git a/apps/app/src/editor/annotations/workStore.ts b/apps/app/src/editor/annotations/workStore.ts index 7c19ba78..3ae52acd 100644 --- a/apps/app/src/editor/annotations/workStore.ts +++ b/apps/app/src/editor/annotations/workStore.ts @@ -155,6 +155,8 @@ export function startMove( base: string, vertex: number | null = null, ): void { + // An open frame keeps the drawing: nothing else starts over it. + if (useAnnotationWork.getState().frame !== null) return useAnnotationWork.setState({ mode: { kind: 'move', annotationId, started: false, base, vertex }, preview: null, @@ -163,6 +165,7 @@ export function startMove( /** « Redessiner »: the redraw of `annotationId`, no vertex placed yet (R-12). */ export function startRedraw(annotationId: string, base: string): void { + if (useAnnotationWork.getState().frame !== null) return useAnnotationWork.setState({ mode: { kind: 'redraw', annotationId, started: false, base, vertex: null }, preview: null, diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index db396838..573512ef 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1906,16 +1906,36 @@ export const en: Dict = { 'editor.annotations.guard.creation': 'Discard the creation?', 'editor.annotations.guard.frame_create': 'Abandon the creation?', 'editor.annotations.guard.frame_recrop': 'Abandon the recrop?', - 'editor.annotations.frame.body': 'Frame', - 'editor.annotations.frame.handle.nw': 'Top left corner', - 'editor.annotations.frame.handle.n': 'Top side', - 'editor.annotations.frame.handle.ne': 'Top right corner', - 'editor.annotations.frame.handle.e': 'Right side', - 'editor.annotations.frame.handle.se': 'Bottom right corner', - 'editor.annotations.frame.handle.s': 'Bottom side', - 'editor.annotations.frame.handle.sw': 'Bottom left corner', - 'editor.annotations.frame.handle.w': 'Left side', - 'editor.annotations.frame.centred': 'Frame placed at the centre.', + 'editor.annotations.frame.part.body': 'Frame', + 'editor.annotations.frame.part.nw': 'Top-left corner', + 'editor.annotations.frame.part.n': 'Top side', + 'editor.annotations.frame.part.ne': 'Top-right corner', + 'editor.annotations.frame.part.e': 'Right side', + 'editor.annotations.frame.part.se': 'Bottom-right corner', + 'editor.annotations.frame.part.s': 'Bottom side', + 'editor.annotations.frame.part.sw': 'Bottom-left corner', + 'editor.annotations.frame.part.w': 'Left side', + 'editor.annotations.frame.placed': 'Frame placed at the centre.', + 'editor.annotations.view.new': 'New detail view', + 'editor.annotations.view.parent': 'Parent view', + 'editor.annotations.view.recrop': 'Recrop the view', + 'editor.annotations.frame.draw_hint': + 'Drag on the drawing to draw the frame, or click to place a default frame.', + 'editor.annotations.frame.adjust_hint': + 'Drag a corner or a side to adjust, the inside to move.', + 'editor.annotations.frame.format': 'Ratio {ratio}', + 'editor.annotations.frame.keep_ratio': 'Keep the proportions', + 'editor.annotations.frame.move': 'Move', + 'editor.annotations.frame.redraw': 'Draw again', + 'editor.annotations.frame.abandon': 'Abandon', + 'editor.annotations.frame.validate': 'Confirm the frame', + 'editor.annotations.frame.apply': 'Apply', + 'editor.annotations.frame.recrop_title': 'Recrop · {name}', + 'editor.annotations.frame.recrop_warning_one': + 'The annotation of this view will go back to “to confirm”.', + 'editor.annotations.frame.recrop_warning_other': + 'The {count} annotations of this view will go back to “to confirm”.', + 'editor.annotations.frame.move_access': 'Move the access with the frame', 'editor.annotations.guard.continue': 'Continue', 'editor.annotations.guard.discard': 'Discard', 'editor.annotations.dropped.move': 'Move discarded: the sheet changed.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 2eebc00c..a847c247 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1976,16 +1976,36 @@ export const fr: Dict = { 'editor.annotations.guard.creation': 'Abandonner la création ?', 'editor.annotations.guard.frame_create': 'Abandonner la création ?', 'editor.annotations.guard.frame_recrop': 'Abandonner le recadrage ?', - 'editor.annotations.frame.body': 'Cadre', - 'editor.annotations.frame.handle.nw': 'Coin haut gauche', - 'editor.annotations.frame.handle.n': 'Côté haut', - 'editor.annotations.frame.handle.ne': 'Coin haut droit', - 'editor.annotations.frame.handle.e': 'Côté droit', - 'editor.annotations.frame.handle.se': 'Coin bas droit', - 'editor.annotations.frame.handle.s': 'Côté bas', - 'editor.annotations.frame.handle.sw': 'Coin bas gauche', - 'editor.annotations.frame.handle.w': 'Côté gauche', - 'editor.annotations.frame.centred': 'Cadre posé au centre.', + 'editor.annotations.frame.part.body': 'Cadre', + 'editor.annotations.frame.part.nw': 'Coin haut gauche', + 'editor.annotations.frame.part.n': 'Côté haut', + 'editor.annotations.frame.part.ne': 'Coin haut droit', + 'editor.annotations.frame.part.e': 'Côté droit', + 'editor.annotations.frame.part.se': 'Coin bas droit', + 'editor.annotations.frame.part.s': 'Côté bas', + 'editor.annotations.frame.part.sw': 'Coin bas gauche', + 'editor.annotations.frame.part.w': 'Côté gauche', + 'editor.annotations.frame.placed': 'Cadre posé au centre.', + 'editor.annotations.view.new': 'Nouvelle vue de détail', + 'editor.annotations.view.parent': 'Vue parente', + 'editor.annotations.view.recrop': 'Recadrer la vue', + 'editor.annotations.frame.draw_hint': + 'Glissez sur le dessin pour tracer le cadre, ou cliquez pour poser un cadre par défaut.', + 'editor.annotations.frame.adjust_hint': + "Glissez un coin ou un côté pour ajuster, l'intérieur pour déplacer.", + 'editor.annotations.frame.format': 'Format {ratio}', + 'editor.annotations.frame.keep_ratio': 'Garder les proportions', + 'editor.annotations.frame.move': 'Déplacer', + 'editor.annotations.frame.redraw': 'Retracer', + 'editor.annotations.frame.abandon': 'Abandonner', + 'editor.annotations.frame.validate': 'Valider le cadre', + 'editor.annotations.frame.apply': 'Appliquer', + 'editor.annotations.frame.recrop_title': 'Recadrer · {name}', + 'editor.annotations.frame.recrop_warning_one': + "L'annotation de cette vue repassera « à confirmer ».", + 'editor.annotations.frame.recrop_warning_other': + 'Les {count} annotations de cette vue repasseront « à confirmer ».', + 'editor.annotations.frame.move_access': "Déplacer l'accès avec le cadre", 'editor.annotations.guard.continue': 'Continuer', 'editor.annotations.guard.discard': 'Abandonner', 'editor.annotations.dropped.move': diff --git a/apps/app/tests/unit/editor-view-commands.test.tsx b/apps/app/tests/unit/editor-view-commands.test.tsx new file mode 100644 index 00000000..911e19b2 --- /dev/null +++ b/apps/app/tests/unit/editor-view-commands.test.tsx @@ -0,0 +1,426 @@ +/** U2 Task 9: the strip's view commands and the frame commands (draw, adjust, recrop). */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { Frame } from '@/editor/annotations/frame' +import { + openViewDialog, + setFrameBox, + startFrame, +} from '@/editor/annotations/frameWork' +import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore' +import { useLocaleStore } from '@/state/localeStore' +import { LayeredTab } from '../helpers/annotationLayer' +import { + ASSET, + drawnText, + edit, + emptyText, + insert, + point, +} from '../helpers/editorFixtures' +import { openReady, resetStore } from '../helpers/editorHarness' + +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(), +})) + +const props = { + readOnly: false, + navigate: vi.fn(), + reloadSheet: vi.fn(), + section: 'drawing' as const, + visited: ['drawing'] as const, + onOpenSection: vi.fn(), + onBack: vi.fn(), +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } + Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', { + configurable: true, + value: () => ({ ...identity, inverse: () => identity }), + }) +}) +afterEach(() => { + cleanup() + act(() => resetWork()) + resetStore() +}) + +const withDetail = (text: string) => + insert(text, { + 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: 10, width: 80, height: 80 }, + parent_view_id: 'view-main', + }, + } as never) + +/** + * A drawn main view with no ordinary category: the state of a sheet whose only category is + * the internal `cat-access` (the core refuses a direct insert of that reserved one). + */ +function noOrdinaryCategoryText(): string { + const text = emptyText() + const main = JSON.parse(text).views.find( + (v: { id: string }) => v.id === 'view-main', + ) + return edit(text, { + op: 'update', + key: { kind: 'view', id: 'view-main' }, + element: { kind: 'view', value: { ...main, svg_asset_id: ASSET } }, + }) +} + +async function mount(text = drawnText()) { + await openReady({ text }) + render() + await waitFor(() => + expect( + document.querySelector('[data-testid$="canvas-drawing"] svg'), + ).not.toBeNull(), + ) + return userEvent.setup() +} + +const strip = () => screen.getByTestId('edit-strip') +const inStrip = (name: string) => + within(strip()).queryByRole('button', { name }) +const boxNow = () => useAnnotationWork.getState().frame!.box +const frameNow = () => useAnnotationWork.getState().frame! + +function open(box: Frame | null, purpose: 'create' | 'recrop' = 'create') { + act(() => { + startFrame({ + purpose, + viewId: purpose === 'create' ? 'view-main' : 'view-det', + drawnOn: 'view-main', + box: purpose === 'recrop' ? box : null, + returnTo: 'view-main', + }) + if (box && purpose === 'create') setFrameBox(box) + }) +} + +const BOX: Frame = { x: 10, y: 10, w: 80, h: 60 } + +describe('the idle commands', () => { + it('the main view offers « Nouvelle vue de détail » only', async () => { + await mount() + expect(inStrip('Nouvelle vue de détail')).not.toBeNull() + expect(inStrip('Vue parente')).toBeNull() + expect(inStrip('Recadrer la vue')).toBeNull() + }) + + it('a detail view offers it too, the other two wait for their tasks', async () => { + const user = await mount(withDetail(drawnText())) + await user.click(screen.getByRole('button', { name: 'Tête' })) + expect(inStrip('Nouvelle vue de détail')).not.toBeNull() + }) + + it('stays available on a sheet whose only category is the access one', async () => { + await mount(noOrdinaryCategoryText()) + expect(inStrip('Nouvelle vue de détail')).toBeEnabled() + }) + + it('opens the frame work on the current view, nothing drawn yet', async () => { + const user = await mount() + await user.click(inStrip('Nouvelle vue de détail')!) + expect(frameNow()).toMatchObject({ + purpose: 'create', + viewId: 'view-main', + drawnOn: 'view-main', + box: null, + returnTo: 'view-main', + }) + expect(within(strip()).getByTestId('edit-strip-title')).toHaveTextContent( + 'Nouvelle vue de détail', + ) + expect(within(strip()).getByTestId('edit-strip-detail')).toHaveTextContent( + 'Glissez sur le dessin pour tracer le cadre, ou cliquez pour poser un cadre par défaut.', + ) + expect(inStrip('Abandonner')).not.toBeNull() + expect(inStrip('Nouvelle vue de détail')).toBeNull() + }) + + it('the keyboard press also places the default frame at the centre', async () => { + await mount() + const button = inStrip('Nouvelle vue de détail')! + fireEvent.click(button, { detail: 0 }) + expect(boxNow()).not.toBeNull() + expect(await screen.findByText('Cadre posé au centre.')).toBeVisible() + }) +}) + +describe('the commands follow the phase', () => { + it('the commands box is remounted between drawing and adjusting', async () => { + await mount() + open(null) + const drawing = inStrip('Abandonner') + act(() => setFrameBox(BOX)) + expect(inStrip('Abandonner')).not.toBe(drawing) + expect(inStrip('Valider le cadre')).not.toBeNull() + }) + + it('adjusting shows the format, the proportions, then the commands', async () => { + await mount() + open(BOX) + expect(within(strip()).getByText('Format 4:3')).toBeVisible() + expect( + within(strip()).getByRole('checkbox', { name: 'Garder les proportions' }), + ).not.toBeChecked() + for (const name of ['Déplacer', 'Retracer', 'Abandonner']) { + expect(inStrip(name)).not.toBeNull() + } + expect(within(strip()).getByTestId('edit-strip-detail')).toHaveTextContent( + "Glissez un coin ou un côté pour ajuster, l'intérieur pour déplacer.", + ) + }) + + it('the format chip follows the box', async () => { + await mount() + open(BOX) + act(() => setFrameBox({ x: 10, y: 10, w: 40, h: 40 })) + expect(within(strip()).getByText('Format 1:1')).toBeVisible() + }) + + it('« Retracer » clears the box and goes back to drawing', async () => { + const user = await mount() + open(BOX) + await user.click(inStrip('Retracer')!) + expect(boxNow()).toBeNull() + expect(inStrip('Valider le cadre')).toBeNull() + expect(within(strip()).getByTestId('edit-strip-detail')).toHaveTextContent( + 'Glissez sur le dessin', + ) + }) + + it('« Valider le cadre » opens the view dialog', async () => { + const user = await mount() + open(BOX) + await user.click(inStrip('Valider le cadre')!) + expect(frameNow().dialog).toBe(true) + }) + + it('« Abandonner » asks once the frame is started', async () => { + const user = await mount() + open(BOX) + await user.click(inStrip('Abandonner')!) + expect( + await screen.findByRole('dialog', { name: 'Abandonner la création ?' }), + ).toBeVisible() + }) + + it('« Abandonner » on an unstarted frame ends it at once', async () => { + const user = await mount() + open(null) + await user.click(inStrip('Abandonner')!) + expect(useAnnotationWork.getState().frame).toBeNull() + }) +}) + +describe('keeping the proportions', () => { + const side = () => screen.getByRole('button', { name: 'Côté droit' }) + + it('the checkbox keeps the ratio while a handle moves by key', async () => { + const user = await mount() + open(BOX) + await user.click( + within(strip()).getByRole('checkbox', { name: 'Garder les proportions' }), + ) + expect(frameNow().keepRatio).toBe(true) + fireEvent.keyDown(side(), { key: 'ArrowRight', shiftKey: true }) + const box = boxNow()! + expect(box.w / box.h).toBeCloseTo(80 / 60) + expect(box.h).toBeGreaterThan(60) + }) + + it('without it a side handle changes one dimension only', async () => { + await mount() + open(BOX) + fireEvent.keyDown(side(), { key: 'ArrowRight', shiftKey: true }) + expect(boxNow()!.h).toBe(60) + }) +}) + +describe('Enter on a frame handle or the body', () => { + it('confirms the frame in the create purpose', async () => { + await mount() + open(BOX) + fireEvent.keyDown(screen.getByRole('button', { name: 'Côté droit' }), { + key: 'Enter', + }) + expect(frameNow().dialog).toBe(true) + }) + + it('does the same on the body', async () => { + await mount() + open(BOX) + fireEvent.keyDown(screen.getByRole('button', { name: 'Cadre' }), { + key: 'Enter', + }) + expect(frameNow().dialog).toBe(true) + }) + + it('does nothing yet in the recrop purpose', async () => { + await mount(withDetail(drawnText())) + open(BOX, 'recrop') + fireEvent.keyDown(screen.getByRole('button', { name: 'Cadre' }), { + key: 'Enter', + }) + expect(frameNow().dialog).toBe(false) + }) +}) + +describe('« Déplacer »', () => { + it('moves the box by the arrows, « Valider la position » leaves', async () => { + const user = await mount() + open(BOX) + await user.click(inStrip('Déplacer')!) + expect(frameNow().moving).toBe(true) + expect(screen.getByTestId('move-mode-bar')).toBeVisible() + await user.click( + screen.getByRole('button', { name: 'Déplacer vers la droite' }), + ) + expect(boxNow()!.x).toBeGreaterThan(10) + expect(boxNow()!.y).toBe(10) + await user.click( + screen.getByRole('button', { name: 'Valider la position' }), + ) + expect(frameNow().moving).toBe(false) + expect(boxNow()!.x).toBeGreaterThan(10) + expect(screen.queryByTestId('move-mode-bar')).toBeNull() + }) + + it('« Annuler » puts the box back', async () => { + const user = await mount() + open(BOX) + await user.click(inStrip('Déplacer')!) + await user.click( + screen.getByRole('button', { name: 'Déplacer vers le bas' }), + ) + await user.click(screen.getByRole('button', { name: 'Annuler' })) + expect(boxNow()).toEqual(BOX) + expect(frameNow().moving).toBe(false) + }) +}) + +describe('the recrop phase', () => { + async function recrop(annotations: number) { + let text = withDetail(drawnText()) + for (let i = 0; i < annotations; i++) { + text = insert(text, point(`p${i}`, 20 + i, 20, 2, 'view-det') as never) + } + await mount(text) + open(BOX, 'recrop') + } + + it('names the view and the count of annotations to confirm (plural)', async () => { + await recrop(2) + expect(within(strip()).getByTestId('edit-strip-title')).toHaveTextContent( + 'Recadrer · Tête', + ) + expect(within(strip()).getByTestId('edit-strip-detail')).toHaveTextContent( + 'Les 2 annotations de cette vue repasseront « à confirmer ».', + ) + }) + + it('uses the singular for one annotation', async () => { + await recrop(1) + expect(within(strip()).getByTestId('edit-strip-detail')).toHaveTextContent( + "L'annotation de cette vue repassera « à confirmer ».", + ) + }) + + it('shows the recrop commands and « Appliquer » as the primary', async () => { + await recrop(1) + expect(within(strip()).getByText('Format 4:3')).toBeVisible() + expect( + within(strip()).getByRole('checkbox', { + name: "Déplacer l'accès avec le cadre", + }), + ).not.toBeChecked() + expect(inStrip('Appliquer')).not.toBeNull() + expect(inStrip('Abandonner')).not.toBeNull() + expect(inStrip('Valider le cadre')).toBeNull() + }) + + it('the access checkbox is the frame work flag', async () => { + const user = await mount(withDetail(drawnText())) + open(BOX, 'recrop') + await user.click( + within(strip()).getByRole('checkbox', { + name: "Déplacer l'accès avec le cadre", + }), + ) + expect(frameNow().moveAccess).toBe(true) + }) +}) + +describe('no other creation while a frame is open', () => { + it('the add and tool buttons are disabled', async () => { + await mount() + open(null) + for (const name of [ + 'Ajouter un point', + 'Ajouter une zone', + 'Ajouter un accès', + 'Point', + 'Zone', + ]) { + expect(screen.getByRole('button', { name })).toBeDisabled() + } + }) + + it('a pointer press on an add button arms nothing', async () => { + const user = await mount() + open(null) + await user.click(screen.getByRole('button', { name: 'Ajouter un point' })) + expect(screen.getByRole('button', { name: 'Point' })).toHaveAttribute( + 'aria-pressed', + 'false', + ) + expect(useAnnotationWork.getState().frame).not.toBeNull() + }) + + it('a started creation or move cannot begin over a frame', async () => { + await mount() + open(BOX) + const { startMove, startRedraw } = + await import('@/editor/annotations/workStore') + act(() => { + startMove('x', 'base') + startRedraw('x', 'base') + }) + expect(useAnnotationWork.getState().mode).toBeNull() + }) +}) + +describe('the view dialog flag', () => { + it('openViewDialog marks the work', async () => { + await mount() + open(BOX) + act(() => openViewDialog()) + expect(frameNow().dialog).toBe(true) + }) +})