feat(editor): drawing guard before navigations drop a started move (R-12)

The move mode lives in the work store with its document stamp. guardDrawing
ends an unstarted mode at once and asks « Abandonner le déplacement ? »
(DrawingGuardDialog, at workspace level) once work is started, before a
tab, a section, « Aller à », Back and a history jump out of the editor;
the leave guard and sign-out count started work. An undo from the header,
Ctrl+Z or the message only cancels a pending mode or preview (R-13), and a
document change drops a stale mode, keeping a started one to be said.
ConfirmDialog takes an optional body. Strings for Task 4 added.
This commit is contained in:
bchanot committed 2026-11-17 18:26:49 +01:00
1 parent 8cd1bda6c2
commit 2882821661
18 files changed
+465 -37

No files matched your search

@@ -25,6 +25,7 @@ import {
} from '@/editor/mode'
import { releaseEditFocus } from '@/editor/focusRequest'
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
import { guardWork, useAnnotationWork } from '@/editor/annotations/workStore'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { useTabTier } from '@/editor/useViewport'
import { useAuthStore } from '@/state/authStore'
@@ -90,7 +91,8 @@ function DraftEditor({
useLayoutEffect(() => {
if (readOnly) releaseEditFocus()
}, [readOnly])
useLeaveGuard(useEditorStore(leaveGuardArmed))
const drawingWork = useAnnotationWork((work) => guardWork(work) !== null)
useLeaveGuard(useEditorStore(leaveGuardArmed) || drawingWork)
useUndoShortcuts(!readOnly)
if (status === 'failed' && failure !== null) {
@@ -4,7 +4,8 @@ import Dialog from '@/components/ui/Dialog'
export interface ConfirmDialogProps {
open: boolean
title: string
body: string
/** Absent: the title is the whole question. */
body?: string
confirmLabel: string
cancelLabel: string
onConfirm: () => void
@@ -29,7 +30,7 @@ export default function ConfirmDialog({
onClose={onCancel}
title={title}
description={
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
body && <p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
}
size="sm"
>
@@ -26,6 +26,7 @@ import {
import type { TabTier } from '@/editor/useViewport'
import { useT } from '@/i18n/useT'
import { useAuthStore } from '@/state/authStore'
import DrawingGuardDialog from './annotations/DrawingGuardDialog'
import ConflictDialog from './ConflictDialog'
import CopyIssueNotice from './CopyIssueNotice'
import DraftHeader from './DraftHeader'
@@ -240,6 +241,7 @@ function Workspace(props: Props & Who) {
{nav.live}
</p>
<ConflictDialog />
<DrawingGuardDialog />
</div>
</EditingState>
)
@@ -7,6 +7,7 @@ import {
import { useEditorReadOnly } from '@/editor/editingContext'
import { commitFocusedField } from '@/editor/focusRequest'
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
import { cancelPending } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from './EditorGlyph'
@@ -73,6 +74,8 @@ function usePress(
return
}
const store = useEditorStore.getState()
// R-13: a pending preview or mode is only cancelled; the next undo undoes.
if (!readOnly && direction === 'undo' && cancelPending()) return
const can = direction === 'undo' ? canUndo(store) : canRedo(store)
if (readOnly || !can) return
if (direction === 'undo') store.undoStep()
@@ -0,0 +1,28 @@
import { useRef } from 'react'
import { answerDrawing } from '@/editor/annotations/drawingGuard'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import ConfirmDialog from '../ConfirmDialog'
/**
* The drawing guard's question (R-12), mounted with the workspace so it shows whatever
* tab is in view: « Continuer » keeps the work, « Abandonner » drops it and makes the move
* that was held.
*/
export default function DrawingGuardDialog() {
const t = useT()
const question = useAnnotationWork((s) => s.question)
// The title stays while the dialog closes.
const title = useRef('')
if (question) title.current = t(`editor.annotations.guard.${question.work}`)
return (
<ConfirmDialog
open={question !== null}
title={title.current}
confirmLabel={t('editor.annotations.guard.discard')}
cancelLabel={t('editor.annotations.guard.continue')}
onConfirm={() => answerDrawing(true)}
onCancel={() => answerDrawing(false)}
/>
)
}
@@ -2,15 +2,17 @@ import type { ReactNode } from 'react'
import { useEditorReadOnly } from '@/editor/editingContext'
import type { GestureMessages } from '@/editor/annotations/useGestureMessage'
import { canUndo, useEditorStore } from '@/editor/state/editorStore'
import { cancelPending } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
const PILL =
'inline-flex h-9 max-w-full items-center gap-2 rounded-md px-3 text-sm'
/** The header's undo (T15): the same store step, under the same conditions. */
/** The header's undo (T15): the same store step, under the same conditions (R-13 first). */
function undoLast(readOnly: boolean): void {
const store = useEditorStore.getState()
if (!readOnly && canUndo(store)) store.undoStep()
if (readOnly || cancelPending()) return
if (canUndo(store)) store.undoStep()
}
/**
@@ -5,6 +5,7 @@ import Icon from '@/components/ui/Icon'
import SignOutLossDialog from './SignOutLossDialog'
import { hasUserCopies, removeUserCopies } from '@/editor/state/recovery'
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
import { guardWork, useAnnotationWork } from '@/editor/annotations/workStore'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
@@ -17,7 +18,10 @@ export default function SignOutButton({
const navigate = useNavigate()
const signOut = useAuthStore((s) => s.signOut)
const userId = useAuthStore((s) => s.user?.id)
const unsavedWork = useEditorStore(leaveGuardArmed)
const sheetWork = useEditorStore(leaveGuardArmed)
// A started move on the drawing is unsaved work too (R-12).
const drawingWork = useAnnotationWork((work) => guardWork(work) !== null)
const unsavedWork = sheetWork || drawingWork
const [busy, setBusy] = useState(false)
const [confirming, setConfirming] = useState(false)
@@ -0,0 +1,27 @@
import { endMode, guardWork, useAnnotationWork } from './workStore'
/**
* The drawing guard (R-12), asked by every navigation that would drop the drawing's work:
* a tab, a section, « Aller à », a view chip, a tool, Back, leaving the editor. Nothing
* started: an unstarted mode ends at once and the caller goes on (true). Work started:
* the question is shown (`DrawingGuardDialog`) and `proceed` waits for « Abandonner »
* (false).
*/
export function guardDrawing(proceed: () => void): boolean {
const work = guardWork(useAnnotationWork.getState())
if (work === null) {
endMode()
return true
}
useAnnotationWork.setState({ question: { work, proceed } })
return false
}
/** « Continuer » keeps the work as it is; « Abandonner » drops it and makes the move. */
export function answerDrawing(discard: boolean): void {
const { question } = useAnnotationWork.getState()
useAnnotationWork.setState({ question: null })
if (!discard || !question) return
endMode()
question.proceed()
}
+69 -8
View File
@@ -22,44 +22,105 @@ export interface Creation {
/** The dialog is shown; false while the shape is replaced or the trace resumed. */
dialog: boolean
}
/** A move mode or a redraw; `started` once the position differs or a vertex is placed (R-12). */
/**
* A move mode or a redraw, stamped with the document text it started on; `started` once
* the position differs or a vertex is placed (R-12).
*/
export interface ModeWork {
kind: 'move' | 'redraw'
annotationId: string
started: boolean
base: string
}
export type GuardWork = 'creation' | 'move' | 'redraw' | null
/** A navigation held by the drawing guard (R-12): what it asks about, and the move itself. */
export interface DrawingQuestion {
work: Exclude<GuardWork, null>
proceed: () => void
}
interface Work {
creation: Creation | null
mode: ModeWork | null
preview: Preview | null
chosen: Chosen | null
/** A started mode a document change dropped (R-13): the tab says so, then clears it. */
dropped: ModeWork['kind'] | null
question: DrawingQuestion | null
}
const NO_WORK: Work = {
creation: null,
mode: null,
preview: null,
chosen: null,
dropped: null,
question: null,
}
export const useAnnotationWork = create<Work>(() => NO_WORK)
export type GuardWork = 'creation' | 'move' | 'redraw' | null
/** R-12: what a navigation must ask about; an unstarted mode asks nothing and simply ends. */
export function guardWork(work: Work): GuardWork {
if (work.creation !== null) return 'creation'
return work.mode?.started ? work.mode.kind : null
}
/** The end of a mode without a question (unstarted, or « Abandonner » answered). */
/** The end of a mode without a question (unstarted, « Annuler », or « Abandonner »). */
export function endMode(): void {
useAnnotationWork.setState({ mode: null, preview: null })
}
/** R-13: drop what was computed on another document text; the caller passes the current text. */
/** « Déplacer … »: the mode on `annotationId`, nothing moved yet. */
export function startMove(annotationId: string, base: string): void {
useAnnotationWork.setState({
mode: { kind: 'move', annotationId, started: false, base },
preview: null,
chosen: null,
})
}
const sameGeometry = (a: Geometry, b: Geometry) =>
JSON.stringify(a) === JSON.stringify(b)
/** The move mode's target at `geometry`; started while it differs from `stored`. */
export function setModePreview(geometry: Geometry, stored: Geometry): void {
const { mode } = useAnnotationWork.getState()
if (mode?.kind !== 'move') return
const started = !sameGeometry(geometry, stored)
const { annotationId, base } = mode
useAnnotationWork.setState({
mode: { ...mode, started },
preview: { annotationId, geometry, base, source: 'move' },
})
}
/**
* R-13: an undo while a mode, a slider or a keyboard series is pending only cancels it.
* Answers whether there was something to cancel.
*/
export function cancelPending(): boolean {
const { mode, preview } = useAnnotationWork.getState()
if (mode === null && preview === null) return false
endMode()
return true
}
const fresh = <T extends { base: string }>(item: T | null, text: string) =>
item && item.base !== text ? null : item
/**
* R-13: drop what was computed on another document text; the caller passes the current
* text. A started mode dropped this way is kept in `dropped`, to be said.
*/
export function dropStale(text: string): void {
useAnnotationWork.setState((work) => ({
preview: work.preview && work.preview.base !== text ? null : work.preview,
chosen: work.chosen && work.chosen.base !== text ? null : work.chosen,
}))
useAnnotationWork.setState((work) => {
const mode = fresh(work.mode, text)
const lost = work.mode !== null && mode === null && work.mode.started
return {
mode,
preview: mode === null && work.mode ? null : fresh(work.preview, text),
chosen: fresh(work.chosen, text),
dropped: lost ? work.mode!.kind : work.dropped,
}
})
}
/** Another sheet opened, or the editor closed: nothing of the previous one survives. */
@@ -9,6 +9,7 @@ import {
cancelLanding,
landAfterModalsClosed,
} from '@/components/ui/afterModalsClosed'
import { guardDrawing } from '../annotations/drawingGuard'
import { focusActiveTab } from '../focusRequest'
import { LAYERS_TOP_DOWN } from '../leftDraft'
import { citationsOfView, sameView, type EditorView } from '../navigation'
@@ -239,18 +240,22 @@ function leavingLayers(from: EditorView, to: EditorView): LayerName[] {
* layer is open (its place-scoped state is not in the history, every layer is asked), or
* a dirty layer would be removed. Only the layers the POP removes are asked, top down, and
* the first to refuse stops the walk: a lower dirty layer's question is never left pending.
* Then the drawing guard (R-12): started work asks and the view stays (`drawing`); as
* after a layer's question, « Abandonner » drops the work and the user goes Back again.
*/
function refusal(
ctx: PopContext,
entry: HistoryEntry | null,
): LayerName | 'modal' | null {
): LayerName | 'modal' | 'drawing' | null {
const { nav, view } = ctx
if (document.querySelector('dialog[open]:not([data-layer])')) {
nav.guards.askAll(false)
return 'modal'
}
const leaving = leavingLayers(view, entry?.view ?? ctx.defaultView)
return leaving.find((layer) => !nav.guards.ask(layer, false).allowed) ?? null
const layer = leaving.find((l) => !nav.guards.ask(l, false).allowed)
if (layer) return layer
return guardDrawing(() => undefined) ? null : 'drawing'
}
/** `view` without the dialogs over `layer`: the clean layers above the one that asks. */
@@ -293,7 +298,8 @@ function refusePop(ctx: PopContext, landed: HistoryEntry | null): boolean {
if (!refused) return false
const { book, writer, view } = ctx
if (landed) adopt(book, landed)
const kept = refused === 'modal' ? view : upTo(view, refused)
const kept =
refused === 'modal' || refused === 'drawing' ? view : upTo(view, refused)
if (!sameView(kept, view)) ctx.nav.restoreView(kept)
writer.push(kept)
return true
+17 -5
View File
@@ -1,5 +1,7 @@
import { useCallback, useEffect, useRef } from 'react'
import { useLocation } from 'react-router-dom'
import { guardDrawing } from '../annotations/drawingGuard'
import { guardWork, useAnnotationWork } from '../annotations/workStore'
import { topDirtyLayer } from '../leftDraft'
import { citationsOfView } from '../navigation'
import {
@@ -74,6 +76,12 @@ function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
finished.catch(failed)
}
/** The drawing's started work asks too (R-12) before the jump goes; an unstarted mode ends. */
function jumpAfterDrawing(jump: Jump, keep: () => void): void {
const go = () => jumpTo(jump, keep)
if (guardDrawing(go)) go()
}
/**
* `layer` asks « Abandonner les modifications ? » and holds the jump, once the layers over
* it are closed (they are clean: it is the top dirty one). Its « Abandonner » closes it,
@@ -88,7 +96,7 @@ function askLeave(jump: Jump, layer: LayerName): void {
layer,
go: (exit: LayerExit) => {
const next = topDirtyLayer(guards, layer)
if (!next) return jumpTo(jump, exit.keep)
if (!next) return jumpAfterDrawing(jump, exit.keep)
// One commit closes both: the history writes one replace, never a Back racing it.
exit.close()
askLeave(jump, next)
@@ -97,17 +105,21 @@ function askLeave(jump: Jump, layer: LayerName): void {
}
/**
* A jump out of the editor while a dialog holds changes is cancelled when the browser
* lets the page cancel it; the dirty dialogs ask, top down, before it goes.
* A jump out of the editor while a dialog holds changes, or the drawing started work, is
* cancelled when the browser lets the page cancel it; the dirty dialogs ask, top down,
* then the drawing, before it goes.
*/
function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
if (!leavesEditor(event, w.path)) return
const { key } = event.destination
if (w.passing.current === key || !event.cancelable) return
const layer = topDirtyLayer(w.guards)
if (!layer) return
const drawing = guardWork(useAnnotationWork.getState()) !== null
if (!layer && !drawing) return
event.preventDefault()
askLeave({ api, key, watch: w }, layer)
const jump = { api, key, watch: w }
if (layer) askLeave(jump, layer)
else jumpAfterDrawing(jump, () => undefined)
}
type LeaveNav = Pick<
+31 -13
View File
@@ -15,6 +15,7 @@ import {
landAfterModalsClosed,
} from '@/components/ui/afterModalsClosed'
import { useT } from '@/i18n/useT'
import { guardDrawing } from './annotations/drawingGuard'
import {
commitFocusedField,
placeOf,
@@ -319,10 +320,14 @@ function useSectionMoves(go: Go, openers: Openers) {
const t = useT()
const openSection = useCallback(
(section: AnnotationSection, opener?: Opener) => {
openers.section.current = opener ?? null
const place = t(`editor.place.${section}`)
const text = `${t('editor.tab.annotations')} · ${place}`
go({ type: 'open_section', section }, 'section', text)
const open = () => {
openers.section.current = opener ?? null
const place = t(`editor.place.${section}`)
const text = `${t('editor.tab.annotations')} · ${place}`
go({ type: 'open_section', section }, 'section', text)
}
// The drawing is left: its work asks first (R-12).
if (guardDrawing(open)) open()
},
[go, openers, t],
)
@@ -458,16 +463,22 @@ function useLeavingMoves(go: Go, askLeaving: () => boolean) {
const moveText = useMoveText()
const navigate = useCallback(
(target: EditorTarget) => {
if (!askLeaving()) return
go({ type: 'go_to', target }, 'go_to', moveText(target))
const move = () => {
if (!askLeaving()) return
go({ type: 'go_to', target }, 'go_to', moveText(target))
}
if (guardDrawing(move)) move()
},
[go, askLeaving, moveText],
)
const showAllReferences = useCallback(
(filter: ElementKey) => {
if (!askLeaving()) return
const text = t('editor.tab.references')
go({ type: 'show_all_references', filter }, 'show_all', text)
const move = () => {
if (!askLeaving()) return
const text = t('editor.tab.references')
go({ type: 'show_all_references', filter }, 'show_all', text)
}
if (guardDrawing(move)) move()
},
[go, askLeaving, t],
)
@@ -550,16 +561,23 @@ function useReceipts(dispatch: Dispatch<NavigationAction>) {
return { outcomes, consumed }
}
/** A tab choice: the typed text is committed, the history asked for a push or a replace. */
/**
* A tab choice: the typed text is committed, the history asked for a push or a replace.
* Started drawing work asks first (R-12): false while the question is open.
*/
function useTabSelect(
dispatch: Dispatch<NavigationAction>,
mark: (replace?: boolean) => void,
) {
return useCallback(
(tab: EditorTabId, options?: SelectOptions): boolean => {
commitFocusedField()
mark(options?.replace)
dispatch({ type: 'select_tab', tab })
const select = () => {
commitFocusedField()
mark(options?.replace)
dispatch({ type: 'select_tab', tab })
}
if (!guardDrawing(select)) return false
select()
return true
},
[dispatch, mark],
+3 -1
View File
@@ -1,4 +1,5 @@
import { useEffect } from 'react'
import { cancelPending } from './annotations/workStore'
import { useEditorStore } from './state/editorStore'
const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]'
@@ -21,7 +22,8 @@ export function useUndoShortcuts(writable: boolean): void {
event.preventDefault()
const store = useEditorStore.getState()
if (event.shiftKey) store.redoStep()
else store.undoStep()
// R-13: a pending preview or mode is only cancelled; the next undo undoes.
else if (!cancelPending()) store.undoStep()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
+19
View File
@@ -1661,6 +1661,25 @@ export const en: Dict = {
'editor.annotations.message.moved.zone': 'Zone moved',
'editor.annotations.message.moved.detail_trigger': 'Access moved',
'editor.annotations.message.move_refused': 'Move refused: {text}',
'editor.annotations.message.resized': 'Size changed',
'editor.annotations.message.size_refused': 'Size refused: {text}',
'editor.annotations.size': 'Size',
'editor.annotations.move.point': 'Move point',
'editor.annotations.move.hint': 'Drag anywhere, or use the arrows',
'editor.annotations.move.left': 'Move left',
'editor.annotations.move.up': 'Move up',
'editor.annotations.move.down': 'Move down',
'editor.annotations.move.right': 'Move right',
'editor.annotations.move.confirm': 'Confirm position',
'editor.annotations.move.cancel': 'Cancel',
'editor.annotations.handle.point': 'Point {name}',
'editor.annotations.guard.move': 'Discard the move?',
'editor.annotations.guard.redraw': 'Discard the new tracing?',
'editor.annotations.guard.creation': 'Discard the creation?',
'editor.annotations.guard.continue': 'Continue',
'editor.annotations.guard.discard': 'Discard',
'editor.annotations.dropped.move': 'Move discarded: the sheet changed.',
'editor.annotations.dropped.redraw': 'New tracing discarded: the sheet changed.',
'editor.annotations.replace_polygon': 'Replace with a polygon',
'editor.annotations.no_geometry': 'This annotation has no geometry: trace a polygon to give it one.',
'editor.annotations.path': 'This annotation is a free path: its data cannot be edited here.',
+19
View File
@@ -1691,6 +1691,25 @@ export const fr: Dict = {
'editor.annotations.message.moved.zone': 'Zone déplacée',
'editor.annotations.message.moved.detail_trigger': 'Accès déplacé',
'editor.annotations.message.move_refused': 'Déplacement refusé : {text}',
'editor.annotations.message.resized': 'Taille modifiée',
'editor.annotations.message.size_refused': 'Taille refusée : {text}',
'editor.annotations.size': 'Taille',
'editor.annotations.move.point': 'Déplacer le point',
'editor.annotations.move.hint': "Glissez n'importe où, ou utilisez les flèches",
'editor.annotations.move.left': 'Déplacer vers la gauche',
'editor.annotations.move.up': 'Déplacer vers le haut',
'editor.annotations.move.down': 'Déplacer vers le bas',
'editor.annotations.move.right': 'Déplacer vers la droite',
'editor.annotations.move.confirm': 'Valider la position',
'editor.annotations.move.cancel': 'Annuler',
'editor.annotations.handle.point': 'Point {name}',
'editor.annotations.guard.move': 'Abandonner le déplacement ?',
'editor.annotations.guard.redraw': 'Abandonner le nouveau tracé ?',
'editor.annotations.guard.creation': 'Abandonner la création ?',
'editor.annotations.guard.continue': 'Continuer',
'editor.annotations.guard.discard': 'Abandonner',
'editor.annotations.dropped.move': 'Déplacement abandonné : la fiche a changé.',
'editor.annotations.dropped.redraw': 'Nouveau tracé abandonné : la fiche a changé.',
'editor.annotations.replace_polygon': 'Remplacer par un polygone',
'editor.annotations.no_geometry': "Cette annotation n'a pas de géométrie : tracez un polygone pour lui en donner une.",
'editor.annotations.path': 'Cette annotation est un tracé libre (path) : ses données ne se modifient pas ici.',
@@ -1,8 +1,14 @@
/** U2 Task 2: the annotation work store and its stale stamp (R-13). */
import { afterEach, describe, expect, it } from 'vitest'
import { vi } from 'vitest'
import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import {
cancelPending,
dropStale,
guardWork,
resetWork,
setModePreview,
startMove,
useAnnotationWork,
type Preview,
} from '@/editor/annotations/workStore'
@@ -44,9 +50,89 @@ describe('dropStale (R-13)', () => {
it('a new session (another sheet, the editor closed) resets the work', () => {
useAnnotationWork.setState({
mode: { kind: 'move', annotationId: 'a', started: true },
mode: { kind: 'move', annotationId: 'a', started: true, base: 'one' },
})
useEditorStore.setState({ session: useEditorStore.getState().session + 1 })
expect(useAnnotationWork.getState().mode).toBeNull()
})
})
const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 }
const MOVED = { type: 'circle' as const, cx: 5, cy: 2, r: 3 }
describe('the move mode in the work store (R-12, R-13)', () => {
it('is started once its preview differs from the stored shape', () => {
startMove('a', 'one')
expect(guardWork(useAnnotationWork.getState())).toBeNull()
setModePreview(STORED, STORED)
expect(useAnnotationWork.getState().mode?.started).toBe(false)
setModePreview(MOVED, STORED)
const work = useAnnotationWork.getState()
expect(work.mode?.started).toBe(true)
expect(work.preview).toMatchObject({ source: 'move', base: 'one' })
expect(guardWork(work)).toBe('move')
})
it('an undo only cancels what is pending (cancelPending)', () => {
expect(cancelPending()).toBe(false)
startMove('a', 'one')
setModePreview(MOVED, STORED)
expect(cancelPending()).toBe(true)
expect(useAnnotationWork.getState()).toMatchObject({
mode: null,
preview: null,
})
useAnnotationWork.setState({
preview: { ...preview('one'), source: 'keys' },
})
expect(cancelPending()).toBe(true)
expect(useAnnotationWork.getState().preview).toBeNull()
})
it('a document change drops the mode; a started one is kept to be said', () => {
startMove('a', 'one')
dropStale('two')
expect(useAnnotationWork.getState()).toMatchObject({
mode: null,
dropped: null,
})
startMove('a', 'two')
setModePreview(MOVED, STORED)
dropStale('two')
expect(useAnnotationWork.getState().mode).not.toBeNull()
dropStale('three')
expect(useAnnotationWork.getState()).toMatchObject({
mode: null,
preview: null,
dropped: 'move',
})
})
})
describe('the drawing guard (R-12)', () => {
it('an unstarted mode ends at once and the move goes on', () => {
startMove('a', 'one')
const proceed = vi.fn()
expect(guardDrawing(proceed)).toBe(true)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(useAnnotationWork.getState().question).toBeNull()
expect(proceed).not.toHaveBeenCalled()
})
it('a started mode asks; « Continuer » keeps it, « Abandonner » drops it and moves', () => {
startMove('a', 'one')
setModePreview(MOVED, STORED)
const proceed = vi.fn()
expect(guardDrawing(proceed)).toBe(false)
expect(useAnnotationWork.getState().question?.work).toBe('move')
answerDrawing(false)
const kept = useAnnotationWork.getState()
expect(kept.question).toBeNull()
expect(kept.preview?.geometry).toEqual(MOVED)
expect(proceed).not.toHaveBeenCalled()
guardDrawing(proceed)
answerDrawing(true)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(proceed).toHaveBeenCalledTimes(1)
})
})
@@ -8,6 +8,7 @@ import {
renderHook,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ElementKey } from '@faunosteo/core-wasm/types'
@@ -26,6 +27,13 @@ import useEditorHistory from '@/editor/history/useEditorHistory'
import { defaultView, targetOfKey } from '@/editor/navigation'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import { useLocaleStore } from '@/state/localeStore'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import {
resetWork,
setModePreview,
startMove,
useAnnotationWork,
} from '@/editor/annotations/workStore'
afterEach(cleanup)
@@ -66,6 +74,7 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) {
<button onClick={() => nav.announce('one')}>say one</button>
<button onClick={() => nav.announce('two')}>say two</button>
<p data-testid="live">{nav.live}</p>
<DrawingGuardDialog />
</>
)
}
@@ -372,3 +381,81 @@ describe('final review: queued landings (M-6)', () => {
expect(focused).not.toContain(references)
})
})
describe('the drawing guard (R-12): a move mode and the navigations', () => {
const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 }
afterEach(resetWork)
const tabShown = () => screen.getByRole('tab', { selected: true })
const started = () => {
startMove('a', 'doc')
setModePreview({ ...STORED, cx: 9 }, STORED)
}
it('with no step taken, a tab ends the mode at once, without a question', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount()
startMove('a', 'doc')
await user.click(screen.getByRole('tab', { name: 'Constats' }))
expect(tabShown()).toHaveTextContent('Constats')
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('dialog')).toBeNull()
})
it('after one step a tab asks; « Continuer » keeps the mode and its position', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount()
started()
await user.click(screen.getByRole('tab', { name: 'Constats' }))
const dialog = screen.getByRole('dialog', {
name: 'Abandonner le déplacement ?',
})
expect(tabShown()).toHaveTextContent('Général')
await user.click(within(dialog).getByRole('button', { name: 'Continuer' }))
expect(tabShown()).toHaveTextContent('Général')
expect(useAnnotationWork.getState().preview?.geometry).toMatchObject({
cx: 9,
})
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('button', { name: 'Abandonner' }))
expect(tabShown()).toHaveTextContent('Constats')
expect(useAnnotationWork.getState().mode).toBeNull()
})
it('« Aller à » asks the same way', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount()
started()
await user.click(screen.getByRole('button', { name: 'go to' }))
expect(
screen.getByRole('dialog', { name: 'Abandonner le déplacement ?' }),
).toBeInTheDocument()
expect(tabShown()).toHaveTextContent('Général')
})
it('a Back asks and keeps the view; an unstarted mode lets it go and ends', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount()
await user.click(screen.getByRole('tab', { name: 'Constats' }))
started()
act(() => navigate(-1))
expect(tabShown()).toHaveTextContent('Constats')
expect(
screen.getByRole('dialog', { name: 'Abandonner le déplacement ?' }),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Abandonner' }))
expect(useAnnotationWork.getState().mode).toBeNull()
// As after a layer's question, the Back is not replayed: the user goes Back again.
expect(tabShown()).toHaveTextContent('Constats')
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
startMove('a', 'doc')
act(() => navigate(-1))
expect(tabShown()).toHaveTextContent('Général')
expect(useAnnotationWork.getState().mode).toBeNull()
})
})
@@ -10,6 +10,11 @@ import {
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import {
setModePreview,
startMove,
useAnnotationWork,
} from '@/editor/annotations/workStore'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -83,3 +88,47 @@ describe('editor-wide undo', () => {
expect(store.getState().unsaved).toBe(true)
})
})
describe('undo with something pending (R-13)', () => {
it('Ctrl+Z only cancels a move mode; the next one undoes', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
const stored = store.getState().previewState!.document.annotations[0]
act(() => {
startMove(stored.id, store.getState().documentText)
setModePreview(
{ type: 'circle', cx: 90, cy: 50, r: 10 },
stored.geometry!,
)
})
ctrlZ(document.body)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(cx()).toMatchObject({ cx: 40 })
ctrlZ(document.body)
expect(cx()).toMatchObject({ cx: 50 })
})
it('the header « Défaire » only cancels a pending size preview', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
const stored = store.getState().previewState!.document.annotations[0]
act(() =>
useAnnotationWork.setState({
preview: {
annotationId: stored.id,
geometry: { type: 'circle', cx: 40, cy: 50, r: 20 },
base: store.getState().documentText,
source: 'size',
},
}),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: /Défaire/ }))
expect(useAnnotationWork.getState().preview).toBeNull()
expect(cx()).toMatchObject({ cx: 40 })
await user.click(screen.getByRole('button', { name: /Défaire/ }))
expect(cx()).toMatchObject({ cx: 50 })
})
})