feat(editor): frame work item with its guard, Escape and history hold

This commit is contained in:
bchanot committed 2026-11-23 13:28:42 +01:00
1 parent 8d690edae7
commit 5736fe148d
15 files changed
+367 -9

No files matched your search

@@ -44,13 +44,16 @@ function asField(element: Element | EventTarget | null): HTMLElement | null {
}
/**
* A12: both are inactive during a creation (R-13); I-1: redo also while work it would drop
* A12: both are inactive during a creation or an open frame (R-13); I-1: redo also while work it would drop
* is pending (a started mode, a keyboard series, a slider change).
*/
const inactive = (
direction: Direction,
work: ReturnType<typeof useAnnotationWork.getState>,
) => work.creation !== null || (direction === 'redo' && holdsRedo(work))
) =>
work.creation !== null ||
work.frame !== null ||
(direction === 'redo' && holdsRedo(work))
const steppableNow = (direction: Direction) => {
const store = useEditorStore.getState()
@@ -67,6 +70,7 @@ function holdOf(
steppable: boolean,
): HistoryHold | null {
if (!steppable || !inactive(direction, work)) return null
if (work.frame !== null) return 'frame'
if (work.creation === null) return 'pending'
return direction === 'undo' ? 'creation' : 'creation_redo'
}
@@ -1,9 +1,21 @@
import { useRef } from 'react'
import { answerDrawing } from '@/editor/annotations/drawingGuard'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import {
useAnnotationWork,
type FrameWork,
type GuardWork,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import ConfirmDialog from '../ConfirmDialog'
const guardKey = (
work: GuardWork,
purpose: FrameWork['purpose'] | undefined,
) =>
work === 'frame'
? `editor.annotations.guard.frame_${purpose ?? 'create'}`
: `editor.annotations.guard.${work}`
/**
* 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
@@ -17,7 +29,8 @@ export default function DrawingGuardDialog() {
)
// The title stays while the dialog closes.
const title = useRef('')
if (question) title.current = t(`editor.annotations.guard.${question.work}`)
const purpose = useAnnotationWork((s) => s.frame?.purpose)
if (question) title.current = t(guardKey(question.work, purpose))
return (
<ConfirmDialog
open={question !== null}
@@ -10,6 +10,7 @@ import {
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { askCreation } from './creationAsk'
import { askFrame } from './frameWork'
import { commitFocusedSeries } from './drawingGuard'
import { escapeAction, type EscapeAction } from './escape'
import { endMode, useAnnotationWork } from './workStore'
@@ -110,6 +111,7 @@ function escapeOf(id: string | null, creating: boolean): EscapeAction {
return escapeAction({
previewPending: work.preview !== null && work.preview.source !== 'move',
creating,
framing: work.frame !== null,
inMode: work.mode !== null,
chosenVertex: work.chosen?.annotationId === id ? work.chosen.vertex : null,
selectedId: id,
@@ -124,6 +126,7 @@ function runEscape(action: EscapeAction, deselect: () => boolean): boolean {
else if (action === 'deselect') return deselect()
// The dialog hidden (a tracing, a point being replaced): « Abandonner la création ? ».
else if (action === 'ask_creation') askCreation()
else if (action === 'ask_frame') askFrame()
return action !== null
}
@@ -67,7 +67,7 @@ export function guardDrawing(proceed: () => void): boolean {
/**
* « Continuer » keeps the work as it is; « Abandonner » drops the work the question
* named (the mode, or the whole creation) and makes the move.
* named (the mode, the whole creation, or the frame) and makes the move.
*/
export function answerDrawing(discard: boolean): void {
const { question } = useAnnotationWork.getState()
@@ -78,6 +78,8 @@ export function answerDrawing(discard: boolean): void {
creation: null,
chosen: choiceAfterCreation(work.chosen),
}))
else if (question.work === 'frame')
useAnnotationWork.setState({ frame: null })
else endMode()
question.proceed()
}
@@ -2,6 +2,8 @@ export interface EscapeInput {
/** A keyboard series or a slider not yet committed (outside a move mode). */
previewPending: boolean
creating: boolean
/** A detail view's frame is open. */
framing: boolean
/** A redraw or a move mode. */
inMode: boolean
chosenVertex: number | null
@@ -11,6 +13,7 @@ export interface EscapeInput {
export type EscapeAction =
| 'drop_preview'
| 'ask_creation'
| 'ask_frame'
| 'drop_mode'
| 'unchoose'
| 'deselect'
@@ -23,6 +26,7 @@ export type EscapeAction =
export function escapeAction(s: EscapeInput): EscapeAction {
if (s.previewPending) return 'drop_preview'
if (s.creating) return 'ask_creation'
if (s.framing) return 'ask_frame'
if (s.inMode) return 'drop_mode'
if (s.chosenVertex !== null) return 'unchoose'
return s.selectedId !== null ? 'deselect' : null
@@ -0,0 +1,89 @@
import { useEditorStore } from '../state/editorStore'
import type { Frame } from './frame'
import { guardDrawing } from './drawingGuard'
import { useAnnotationWork, type FrameWork } from './workStore'
/** Where a frame work begins: the view it crops, the view that draws it, and its box. */
export interface FrameStart {
purpose: FrameWork['purpose']
viewId: string
drawnOn: string
/** create: null (nothing drawn yet); recrop: the view's current crop. */
box: Frame | null
returnTo: string
}
const frame = () => useAnnotationWork.getState().frame
/**
* The frame's own question (« Abandonner la création ? » or « … le recadrage ? ») lapses
* once the frame ends: it would otherwise reappear over the page with nothing to ask.
*/
const lapsed = () => {
const { question } = useAnnotationWork.getState()
return question?.work === 'frame' ? null : question
}
function patch(change: Partial<FrameWork>): void {
const current = frame()
if (current) useAnnotationWork.setState({ frame: { ...current, ...change } })
}
/**
* A frame work begins on the current document text. A creation or a mode already open
* keeps the drawing: it answers false and nothing changes.
*/
export function startFrame(start: FrameStart): boolean {
const { creation, mode } = useAnnotationWork.getState()
if (creation !== null || mode !== null) return false
useAnnotationWork.setState({
frame: {
...start,
startBox: start.box,
keepRatio: false,
moveAccess: false,
moving: false,
dialog: false,
started: false,
base: useEditorStore.getState().documentText,
},
})
return true
}
/** The box as it is now; the work is started (R-12). */
export function setFrameBox(box: Frame): void {
patch({ box, started: true })
}
export function setKeepRatio(on: boolean): void {
patch({ keepRatio: on })
}
export function setMoveAccess(on: boolean): void {
patch({ moveAccess: on })
}
export function setFrameMoving(on: boolean): void {
patch({ moving: on })
}
/** The view dialog opens over the frame. */
export function openViewDialog(): void {
patch({ dialog: true })
}
/** « Revenir au cadre »: the view dialog hides, the frame is as it was. */
export function backToFrame(): void {
patch({ dialog: false })
}
/** « Abandonner », or a guard's « Abandonner »: nothing of the frame is left. */
export function dropFrame(): void {
useAnnotationWork.setState({ frame: null, question: lapsed() })
}
/** Escape over a frame: the guard asks (once started); « Abandonner » drops it. */
export function askFrame(): void {
guardDrawing(() => {})
}
+35 -2
View File
@@ -57,12 +57,34 @@ export interface ModeWork {
/** The chosen vertex a move mode moves alone (« Déplacer le sommet »); null: the shape. */
vertex: number | null
}
/**
* A detail view's crop being drawn (`create`, on the parent view) or adjusted (`recrop`),
* stamped with the document text it started on; `started` once a box is set (R-12).
*/
export interface FrameWork {
purpose: 'create' | 'recrop'
/** create: the parent view; recrop: the view recropped. */
viewId: string
/** The view whose drawing shows the frame. */
drawnOn: string
box: Frame | null
/** The box the work began with (null on create): a recrop is changed once it differs. */
startBox: Frame | null
keepRatio: boolean
moveAccess: boolean
moving: boolean
dialog: boolean
started: boolean
base: string
/** The view shown before the work began. */
returnTo: string
}
/** The chosen vertex once the creation ends: a choice on its shape ends with it. */
export function choiceAfterCreation(chosen: Chosen | null): Chosen | null {
return chosen?.annotationId === PENDING_ID ? null : chosen
}
export type GuardWork = 'creation' | 'move' | 'redraw' | null
export type GuardWork = 'creation' | 'frame' | '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>
@@ -77,6 +99,7 @@ interface Work {
creationShown: boolean
created: Created | null
mode: ModeWork | null
frame: FrameWork | null
preview: Preview | null
chosen: Chosen | null
/**
@@ -93,6 +116,7 @@ const NO_WORK: Work = {
creationShown: false,
created: null,
mode: null,
frame: null,
preview: null,
chosen: null,
dropped: null,
@@ -103,11 +127,19 @@ const NO_WORK: Work = {
export const useAnnotationWork = create<Work>(() => NO_WORK)
/** Why « Défaire » or « Refaire » is held (point 6): a creation, or pending work. */
export type HistoryHold = 'creation' | 'creation_redo' | 'pending'
export type HistoryHold = 'creation' | 'creation_redo' | 'frame' | 'pending'
const sameBox = (a: Frame | null, b: Frame | null) =>
JSON.stringify(a) === JSON.stringify(b)
/** A frame asks only once a box is drawn (create) or differs from its start (recrop). */
const frameChanged = (frame: FrameWork | null) =>
frame !== null && frame.started && !sameBox(frame.box, frame.startBox)
/** 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'
if (frameChanged(work.frame)) return 'frame'
return work.mode?.started ? work.mode.kind : null
}
/** The end of a mode without a question (unstarted, « Annuler », or « Abandonner »). */
@@ -196,6 +228,7 @@ export function dropStale(text: string): void {
const lost = work.mode !== null && mode === null && work.mode.started
return {
mode,
frame: fresh(work.frame, text),
preview: mode === null && work.mode ? null : fresh(work.preview, text),
chosen: fresh(work.chosen, text),
dropped: lost ? work.mode!.kind : work.dropped,
+4 -1
View File
@@ -22,7 +22,10 @@ export function useUndoShortcuts(writable: boolean): void {
if (isTextField(event.target)) return
if (document.querySelector(MODAL_OPEN)) return
// A12: undo is inactive during a creation, its dialog shown or not (R-13).
if (useAnnotationWork.getState().creation) return
const work = useAnnotationWork.getState()
if (work.creation) return
// An open frame holds both directions until it is finished or abandoned.
if (work.frame) return
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z')
return
event.preventDefault()
+3
View File
@@ -1421,6 +1421,7 @@ export const en: Dict = {
'Redo is paused during a creation: discard it to redo.',
'editor.history.hold_pending':
'Redo is paused during the change in progress: cancel it with Undo to redo.',
'editor.history.hold_frame': 'Finish or abandon the frame in progress.',
'editor.draft.status.saving': 'Saving…',
'editor.draft.status.copy_quota':
'Temporary local copy impossible (tab full): not saved on the server',
@@ -1903,6 +1904,8 @@ export const en: Dict = {
'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.frame_create': 'Abandon the creation?',
'editor.annotations.guard.frame_recrop': 'Abandon the recrop?',
'editor.annotations.guard.continue': 'Continue',
'editor.annotations.guard.discard': 'Discard',
'editor.annotations.dropped.move': 'Move discarded: the sheet changed.',
+3
View File
@@ -1478,6 +1478,7 @@ export const fr: Dict = {
'Refaire est suspendu pendant une création : abandonnez-la pour pouvoir refaire.',
'editor.history.hold_pending':
'Refaire est suspendu pendant la modification en cours : annulez-la avec Défaire pour pouvoir refaire.',
'editor.history.hold_frame': 'Terminez ou abandonnez le cadre en cours.',
'editor.draft.status.saving': 'Enregistrement…',
'editor.draft.status.copy_quota':
'Copie locale temporaire impossible (onglet plein) : non enregistré sur le serveur',
@@ -1973,6 +1974,8 @@ export const fr: Dict = {
'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.frame_create': 'Abandonner la création ?',
'editor.annotations.guard.frame_recrop': 'Abandonner le recadrage ?',
'editor.annotations.guard.continue': 'Continuer',
'editor.annotations.guard.discard': 'Abandonner',
'editor.annotations.dropped.move':
@@ -89,6 +89,7 @@ describe('escapeAction (board 32 rows 3 to 6)', () => {
const none: EscapeInput = {
previewPending: false,
creating: false,
framing: false,
inMode: false,
chosenVertex: null,
selectedId: null,
@@ -106,6 +107,13 @@ describe('escapeAction (board 32 rows 3 to 6)', () => {
expect(escapeAction({ ...none, selectedId: 'a' })).toBe('deselect')
expect(escapeAction(none)).toBeNull()
})
it('asks about a frame at the rank of a creation', () => {
const framing = { ...none, framing: true, inMode: true, selectedId: 'a' }
expect(escapeAction(framing)).toBe('ask_frame')
expect(escapeAction({ ...framing, previewPending: true })).toBe(
'drop_preview',
)
})
})
describe('moveStep (R-11)', () => {
@@ -2,6 +2,14 @@
import { afterEach, describe, expect, it } from 'vitest'
import { vi } from 'vitest'
import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import {
backToFrame,
dropFrame,
openViewDialog,
setFrameBox,
startFrame,
type FrameStart,
} from '@/editor/annotations/frameWork'
import {
cancelPending,
dropStale,
@@ -12,6 +20,8 @@ import {
useAnnotationWork,
type Preview,
} from '@/editor/annotations/workStore'
import { emptyForm } from '@/editor/annotations/creation'
import { traceVertex } from '@/editor/annotations/creationWork'
import { useEditorStore } from '@/editor/state/editorStore'
const preview = (base: string): Preview => ({
@@ -142,3 +152,113 @@ describe('the drawing guard (R-12)', () => {
expect(proceed).toHaveBeenCalledTimes(1)
})
})
describe('the frame work item', () => {
const BOX = { x: 1, y: 2, w: 30, h: 40 }
const start = (change: Partial<FrameStart> = {}): FrameStart => ({
purpose: 'create',
viewId: 'v',
drawnOn: 'v',
box: null,
returnTo: 'v',
...change,
})
const frame = () => useAnnotationWork.getState().frame
it('starts with the document text as its base, nothing drawn yet', () => {
useEditorStore.setState({ documentText: 'one' })
expect(startFrame(start())).toBe(true)
expect(frame()).toMatchObject({
purpose: 'create',
box: null,
started: false,
base: 'one',
dialog: false,
moving: false,
})
})
it('refuses while a creation or a mode is open, the store unchanged', () => {
startMove('a', 'one')
const before = useAnnotationWork.getState()
expect(startFrame(start())).toBe(false)
expect(useAnnotationWork.getState()).toBe(before)
resetWork()
traceVertex(
{
viewId: 'v',
frame: null,
origin: 'tool',
form: emptyForm({ categories: [] } as never),
},
'zone',
[1, 1],
)
const created = useAnnotationWork.getState()
expect(startFrame(start())).toBe(false)
expect(useAnnotationWork.getState()).toBe(created)
expect(frame()).toBeNull()
})
it('setFrameBox marks the work started', () => {
startFrame(start())
setFrameBox(BOX)
expect(frame()).toMatchObject({ box: BOX, started: true })
})
it('opens the view dialog and goes back to the frame', () => {
startFrame(start())
openViewDialog()
expect(frame()?.dialog).toBe(true)
backToFrame()
expect(frame()?.dialog).toBe(false)
})
it('dropStale drops a frame whose base differs, keeps one that matches', () => {
useEditorStore.setState({ documentText: 'one' })
startFrame(start())
dropStale('one')
expect(frame()).not.toBeNull()
dropStale('two')
expect(frame()).toBeNull()
})
it('resetWork drops it, dropFrame ends it and its question', () => {
startFrame(start())
setFrameBox(BOX)
guardDrawing(vi.fn())
expect(useAnnotationWork.getState().question?.work).toBe('frame')
dropFrame()
expect(frame()).toBeNull()
expect(useAnnotationWork.getState().question).toBeNull()
startFrame(start())
resetWork()
expect(frame()).toBeNull()
})
it('guards a create only once a box is drawn', () => {
startFrame(start())
expect(guardWork(useAnnotationWork.getState())).toBeNull()
setFrameBox(BOX)
expect(guardWork(useAnnotationWork.getState())).toBe('frame')
})
it('guards a recrop only once the box differs from the one it started with', () => {
startFrame(start({ purpose: 'recrop', box: BOX }))
expect(guardWork(useAnnotationWork.getState())).toBeNull()
setFrameBox({ ...BOX })
expect(guardWork(useAnnotationWork.getState())).toBeNull()
setFrameBox({ ...BOX, w: 31 })
expect(guardWork(useAnnotationWork.getState())).toBe('frame')
})
it('« Abandonner » of the guard drops the frame and makes the move', () => {
startFrame(start())
setFrameBox(BOX)
const proceed = vi.fn()
expect(guardDrawing(proceed)).toBe(false)
answerDrawing(true)
expect(frame()).toBeNull()
expect(proceed).toHaveBeenCalled()
})
})
@@ -12,6 +12,10 @@ import {
import userEvent from '@testing-library/user-event'
import type { Annotation } from '@faunosteo/core-wasm/types'
import ModalDialog from '@/components/ui/ModalDialog'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { setFrameBox, startFrame } from '@/editor/annotations/frameWork'
import { resetWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, edit, insert, point } from '../helpers/editorFixtures'
import { pressAt, resetStore, serverHas, store } from '../helpers/editorHarness'
@@ -388,3 +392,27 @@ describe('Escape and the other layers', () => {
expect(hidden).toHaveLength(1)
})
})
describe('the frame guard dialog titles', () => {
const frame = (purpose: 'create' | 'recrop') => {
startFrame({
purpose,
viewId: 'v',
drawnOn: 'v',
box: purpose === 'recrop' ? { x: 0, y: 0, w: 5, h: 5 } : null,
returnTo: 'v',
})
setFrameBox({ x: 1, y: 1, w: 9, h: 9 })
guardDrawing(() => {})
}
afterEach(() => act(() => resetWork()))
it.each([
['create', 'Abandonner la création ?'],
['recrop', 'Abandonner le recadrage ?'],
] as const)('asks « %s » with its own title', async (purpose, title) => {
render(<DrawingGuardDialog />)
act(() => frame(purpose))
expect(await screen.findByRole('dialog', { name: title })).toBeVisible()
})
})
@@ -16,6 +16,7 @@ import { fr } from '@/i18n/fr'
import { useLocaleStore } from '@/state/localeStore'
import { emptyForm } from '@/editor/annotations/creation'
import { traceVertex } from '@/editor/annotations/creationWork'
import { setFrameBox, startFrame } from '@/editor/annotations/frameWork'
import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore'
import {
baseText,
@@ -652,6 +653,29 @@ describe('why a button is held (point 6)', () => {
expect(bubble()).toHaveTextContent(CREATION)
})
it('an open frame holds both buttons with the frame reason', async () => {
const user = await openAnnotations()
stacks()
act(() => {
startFrame({
purpose: 'create',
viewId: 'v',
drawnOn: 'v',
box: null,
returnTo: 'v',
})
})
const FRAME = 'Terminez ou abandonnez le cadre en cours.'
expect(reason(undoButton())).toBe(FRAME)
expect(reason(redoButton())).toBe(FRAME)
expect(disabled(undoButton())).toBe(true)
expect(disabled(redoButton())).toBe(true)
act(() => setFrameBox({ x: 1, y: 1, w: 5, h: 5 }))
await user.click(undoButton())
expect(bubble()).toHaveTextContent(FRAME)
expect(store.getState().undo).toHaveLength(1)
})
it('pending work holds redo only, with its own reason', async () => {
const user = await openAnnotations()
stacks()
@@ -10,7 +10,8 @@ import {
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { startFrame } from '@/editor/annotations/frameWork'
import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -47,6 +48,26 @@ describe('editor-wide undo', () => {
expect(cx()).toMatchObject({ cx: 40 })
})
it('does nothing while a frame is open', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
act(() => {
startFrame({
purpose: 'create',
viewId: 'v',
drawnOn: 'v',
box: null,
returnTo: 'v',
})
})
ctrlZ(document.body)
expect(cx()).toMatchObject({ cx: 40 })
ctrlZ(document.body, true)
expect(cx()).toMatchObject({ cx: 40 })
act(() => resetWork())
})
it('does nothing in a text field', async () => {
mountDraft()
await ready()