fix(editor): slider while replacing, announced drop, review minors

Task 7 fix round 1 (review task-7-review.md).
- Important 1: « Taille » shows beside « Revenir aux propriétés » while
  a point is replaced (still hidden under the modal dialog); it feeds
  the hover preview and the re-placed point (R-10).
- Important 2: a creation whose view leaves the document is dropped
  and said, « Création abandonnée : la fiche a changé. » (dropped:
  'creation', read by useDroppedNotice).
- Minor 3: DrawingGuardDialog leaves a creation question to the
  creation dialog only while that dialog is really on screen
  (creationShown, set by the dialog).
- Minor 7: the dialog's long className strings split into constants.
- Minor 8: dead TOOL_OF removed; trace_start is a redraw's only.

Tests added (no assertion removed): slider while replacing (unit,
RED then GREEN; e2e under expectNoShift at three widths, last strip
command inside the strip); view removed during a creation (RED then
GREEN); question shown by the workspace when the dialog is not on
screen (RED then GREEN); « Abandonner » while read-only; R-13 with a
restored copy during a started move; leaving the route resets the
work (fails with the session reset removed). The unit Back test's
comment is corrected: it does pin the modal branch.
This commit is contained in:
bchanot committed 2026-11-18 00:06:16 +01:00
1 parent fe333c2bbd
commit 837ec9f436
14 files changed
+315 -29

No files matched your search

@@ -469,6 +469,46 @@ test.describe('editor annotations (A3)', () => {
await button(page, 'editor.annotations.back_to_properties').click()
await expect(creationDialog(page, 'zone')).toBeVisible()
})
// The zone abandoned (asked inside its dialog), then a point placed and replaced:
// « Taille » shows beside « Revenir aux propriétés » (board 02), nothing moves.
await creationDialog(page, 'zone')
.getByRole('button', {
name: dict['editor.annotations.creation.discard'],
})
.click()
await creationDialog(page, 'zone')
.getByRole('group', {
name: dict['editor.annotations.guard.creation'],
})
.getByRole('button', {
name: dict['editor.annotations.guard.discard'],
})
.click()
await expect(creationDialog(page, 'zone')).toHaveCount(0)
await tool(page, 'point').click()
await clickDrawing(page, 300, 500)
await expect(creationDialog(page, 'point')).toBeVisible()
await expect(strip.getByTestId('size-slider')).toHaveCount(0)
await expectNoShift(page, async () => {
await creationDialog(page, 'point')
.getByRole('button', {
name: dict['editor.annotations.creation.replace'],
})
.click()
await expect(creationDialog(page, 'point')).toHaveCount(0)
await expect(strip.getByTestId('size-slider')).toBeVisible()
})
const edge = (await strip.boundingBox())!
const end = (await strip
.getByRole('button', {
name: dict['editor.annotations.creation.discard'],
})
.boundingBox())!
expect(end.x + end.width).toBeLessThanOrEqual(edge.x + edge.width)
await expectNoShift(page, async () => {
await clickDrawing(page, 320, 520)
await expect(creationDialog(page, 'point')).toBeVisible()
})
})
}
@@ -1,4 +1,4 @@
import { useRef, useState, type RefObject } from 'react'
import { useEffect, useRef, useState, type RefObject } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
@@ -87,6 +87,17 @@ function useCreate(work: Creation, created: { current: boolean }) {
/** « Point placé · Replacer le point », « Zone tracée, 5 sommets · Reprendre le tracé ». */
const GLYPH = { point: 'point', zone: 'zone', detail_trigger: 'link' } as const
/** The dialog's first line (board 02, 04): the shape, then « Replacer » or « Reprendre ». */
const LINE =
'flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg ' +
'bg-[var(--color-surface-strong)] px-3 py-2 text-sm outline-none'
/** Its link-styled button: the strong accent passes axe's contrast on that background. */
const LINK =
'min-h-11 font-medium text-[var(--color-accent-strong)] underline underline-offset-2 ' +
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ' +
'disabled:cursor-not-allowed disabled:opacity-40 xl:min-h-0'
/** « Point placé », « Zone tracée, 5 sommets », « Accès tracé, 3 sommets ». */
function useShapeText(pending: Creation['pending']): string {
const t = useT()
@@ -104,18 +115,14 @@ function ShapeLine({ work, readOnly }: { work: Creation; readOnly: boolean }) {
const text = useShapeText(work.pending)
const point = work.pending.kind === 'point'
return (
<div
data-creation-focus=""
tabIndex={-1}
className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg bg-[var(--color-surface-strong)] px-3 py-2 text-sm outline-none"
>
<div data-creation-focus="" tabIndex={-1} className={LINE}>
<EditorGlyph name={GLYPH[work.pending.kind]} size={16} />
<span>{text}</span>
<button
type="button"
disabled={readOnly}
onClick={point ? replacePoint : resumeTrace}
className="min-h-11 font-medium text-[var(--color-accent-strong)] underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] disabled:cursor-not-allowed disabled:opacity-40 xl:min-h-0"
className={LINK}
>
{t(`editor.annotations.creation.${point ? 'replace' : 'resume'}`)}
</button>
@@ -244,6 +251,14 @@ function useCreationReturn(work: Creation | null) {
return { created, returnFocus }
}
/** Tells the workspace's guard dialog whether this dialog is on screen (it asks inside). */
function useShownFlag(open: boolean) {
useEffect(() => {
useAnnotationWork.setState({ creationShown: open })
return () => useAnnotationWork.setState({ creationShown: false })
}, [open])
}
/**
* « Nouveau point », « Nouvelle zone », « Nouvel accès » (board 02, 04): a modal without a
* history layer over the right column, mounted outside the edit-only body so a read-only
@@ -255,9 +270,11 @@ export default function CreationDialog(props: CreationDialogProps) {
const visible = usePlaceVisible()
const work = useAnnotationWork((s) => s.creation)
const back = useCreationReturn(work)
const open = visible && work !== null && work.dialog
useShownFlag(open)
return (
<Dialog
open={visible && work !== null && work.dialog}
open={open}
anchor={props.anchor}
veilCloses={false}
title={work ? t(`editor.annotations.new.${work.pending.kind}`) : ''}
@@ -13,7 +13,7 @@ export default function DrawingGuardDialog() {
const t = useT()
// Over a shown creation dialog the question is that dialog's own (R-12, board 31 D).
const question = useAnnotationWork((s) =>
s.question?.work === 'creation' && s.creation?.dialog ? null : s.question,
s.question?.work === 'creation' && s.creationShown ? null : s.question,
)
// The title stays while the dialog closes.
const title = useRef('')
@@ -140,7 +140,24 @@ function SceneCommands({
)
// The dialog shown: its own actions; hidden after it was shown: board 04 C.
if (creation?.dialog) return null
if (creation?.resumed) return <CreationCommands creation={creation} />
if (creation?.resumed) {
// A point being replaced: its size is still chosen here (board 02, R-10).
const replacing = creation.closed && frame
return (
<>
{replacing && (
<ToolSize
doc={doc}
viewId={viewId}
frame={frame}
size={ui.size}
dispatch={dispatch}
/>
)}
<CreationCommands creation={creation} />
</>
)
}
if (tracing) {
// « Annuler le tracé » is an explicit cancel: it acts at once (board 04 A).
const redraw = tracing.target === 'replace'
@@ -139,6 +139,15 @@ export function dropCreation(): void {
useAnnotationWork.setState({ creation: null, question: lapsed() })
}
/** A document change removed the creation's view (R-13): dropped, and said by the tab. */
export function dropCreationGone(): void {
useAnnotationWork.setState({
creation: null,
question: lapsed(),
dropped: 'creation',
})
}
/** « Créer » succeeded: the creation ends, the drawing selects `id` (A7). */
export function finishCreation(id: string, kind: NewKind): void {
useAnnotationWork.setState({
+5 -10
View File
@@ -32,7 +32,8 @@ export type UiAction =
| { type: 'view'; viewId: string }
| { type: 'tool'; tool: ToolId }
| { type: 'select'; id: string | null }
| { type: 'trace_start'; target: Tracing['target']; annotationId?: string }
/** A redraw's tracing (a new shape's is the creation's, U2 Task 7). */
| { type: 'trace_start'; target: 'replace'; annotationId: string }
| { type: 'trace_add'; point: Point }
| { type: 'trace_pop' }
| { type: 'trace_cancel' }
@@ -51,13 +52,6 @@ export const initialUi: UiState = {
size: null,
}
const TOOL_OF: Record<Tracing['target'], ToolId> = {
point: 'point',
zone: 'zone',
detail_trigger: 'link',
replace: 'zone',
}
/** A redraw lends the zone tool to its tracing: whatever ends it gives the select tool back. */
const toolAfterTracing = (state: UiState): ToolId =>
state.tracing?.target === 'replace' ? 'select' : state.tool
@@ -89,11 +83,12 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
case 'trace_start':
return {
...state,
tool: TOOL_OF[action.target],
// A redraw lends the zone tool to its tracing.
tool: 'zone',
hint: null,
tracing: {
target: action.target,
annotationId: action.annotationId ?? null,
annotationId: action.annotationId,
points: [],
refused: false,
},
@@ -2,7 +2,7 @@ import { useEffect, useRef, type Dispatch } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
import type { NewKind } from './creation'
import { dropCreation } from './creationWork'
import { dropCreationGone } from './creationWork'
import { focusRowOrDrawing } from './deselect'
import type { ToolId, UiAction, UiState } from './uiState'
import type { GestureMessages } from './useGestureMessage'
@@ -26,7 +26,7 @@ export interface CreationFollow {
/**
* The drawing kept in step with the creation: nothing selected once its shape is placed, its tool
* on while the dialog is hidden (« Replacer le point » places with the point tool, a
* resumed tracing traces), and dropped when its view no longer exists.
* resumed tracing traces), and dropped, said, when its view no longer exists (R-13).
*/
function useDrawingFollows({ doc, ui, dispatch, creation }: CreationFollow) {
const wanted =
@@ -43,7 +43,7 @@ function useDrawingFollows({ doc, ui, dispatch, creation }: CreationFollow) {
if (selected) dispatch({ type: 'select', id: null })
}, [selected, dispatch])
useEffect(() => {
if (gone) dropCreation()
if (gone) dropCreationGone()
}, [gone])
}
+11 -2
View File
@@ -59,16 +59,25 @@ export interface DrawingQuestion {
}
interface Work {
creation: Creation | null
/**
* The creation dialog is really on screen (its place shown): only then does it ask the
* creation's question in its own footer instead of the workspace's dialog.
*/
creationShown: boolean
created: Created | 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
/**
* Work a document change dropped (R-13): a started mode, or a creation whose view left the
* document. The tab says so, then clears it.
*/
dropped: ModeWork['kind'] | 'creation' | null
question: DrawingQuestion | null
}
const NO_WORK: Work = {
creation: null,
creationShown: false,
created: null,
mode: null,
preview: null,
+2
View File
@@ -1883,6 +1883,8 @@ export const en: Dict = {
'editor.annotations.dropped.move': 'Move discarded: the sheet changed.',
'editor.annotations.dropped.redraw':
'New tracing discarded: the sheet changed.',
'editor.annotations.dropped.creation':
'Creation 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.',
+2
View File
@@ -1953,6 +1953,8 @@ export const fr: Dict = {
'Déplacement abandonné : la fiche a changé.',
'editor.annotations.dropped.redraw':
'Nouveau tracé abandonné : la fiche a changé.',
'editor.annotations.dropped.creation':
'Création abandonnée : 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.",
@@ -12,7 +12,11 @@ import {
import userEvent from '@testing-library/user-event'
import HistoryButtons from '@/components/editor/HistoryButtons'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import { emptyForm } from '@/editor/annotations/creation'
import { placePending } from '@/editor/annotations/creationWork'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { LayeredTab } from '../helpers/annotationLayer'
@@ -426,3 +430,109 @@ describe('the mode flip (R-14, Review Focus 3)', () => {
expect(annotations()).toHaveLength(1)
})
})
describe('fix round 1: the size while a point is replaced (board 02, R-10)', () => {
const sized = () =>
[
point('a', 20, 20, 7),
point('b', 40, 40, 7),
point('c', 60, 60, 9),
].reduce((text, p) => insert(text, p), drawnText())
const slider = () =>
within(screen.getByTestId('size-slider')).getByRole('slider')
it('hidden under the dialog, shown beside « Revenir aux propriétés »; it sizes the re-placed point', async () => {
const user = await mount(sized())
const shown = await placePoint(user)
const strip = screen.getByTestId('edit-strip')
// The modal makes the strip inert: no slider while the dialog shows.
expect(within(strip).queryByTestId('size-slider')).toBeNull()
await user.click(
within(shown).getByRole('button', { name: 'Replacer le point' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(
within(strip).getByRole('button', { name: 'Revenir aux propriétés' }),
).toBeInTheDocument()
expect(slider()).toHaveValue('7')
fireEvent.change(slider(), { target: { value: '9' } })
fireEvent.pointerMove(canvas(), {
clientX: 30,
clientY: 70,
pointerType: 'mouse',
})
expect(
screen.getByTestId('overlay-point-preview').querySelector('circle'),
).toHaveAttribute('r', '9')
pressAt(canvas(), 30, 70)
await dialog()
expect(ghost().querySelector('circle')).toHaveAttribute('r', '9')
})
})
describe('fix round 1: a creation whose view leaves the document (no silent loss)', () => {
it('a document change removes the view: the creation goes and the line says so', async () => {
const user = await mount(withDetail())
await user.click(screen.getByRole('button', { name: 'Tête' }))
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter une zone' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
const shown = await dialog('Nouvelle zone')
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Perdue')
act(
() =>
void store
.getState()
.commit({ op: 'remove', key: { kind: 'view', id: 'view-det' } }),
)
await waitFor(() => expect(creation()).toBeNull())
expect(
await screen.findByText('Création abandonnée : la fiche a changé.'),
).toBeInTheDocument()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})
})
describe('fix round 1: the question is never hidden behind a dialog not shown', () => {
afterEach(() => act(() => resetWork()))
it('a creation whose dialog is not on screen (its place hidden): the workspace asks', () => {
render(<DrawingGuardDialog />)
act(() =>
placePending(
{
viewId: 'view-main',
frame: null,
origin: 'tool',
form: emptyForm(JSON.parse(drawnText())),
},
{ kind: 'point', geometry: { type: 'circle', cx: 5, cy: 5, r: 2 } },
),
)
act(() => void guardDrawing(() => undefined))
expect(
screen.getByRole('dialog', { name: 'Abandonner la création ?' }),
).toBeInTheDocument()
})
})
describe('fix round 1: « Abandonner » while read-only (R-14)', () => {
it('asks, then drops the creation', async () => {
const user = await mount()
await placePoint(user)
view.rerender(<Page readOnly />)
const kept = screen.getByRole('dialog', { name: 'Nouveau point' })
await user.click(within(kept).getByRole('button', { name: 'Abandonner' }))
expect(creation()).not.toBeNull()
const ask = within(kept).getByRole('group', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Abandonner' }))
expect(creation()).toBeNull()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(annotations()).toHaveLength(1)
})
})
@@ -628,9 +628,8 @@ describe('the drawing guard at every site: creation, move, redraw', () => {
/**
* U2 Task 7: the creation dialog is a modal without a history layer. A Back while it is
* open is refused, and its « Abandonner la création ? » shows inside it. (Under happy-dom
* the refusal is reached through the drawing guard; the browser's modal branch is proved
* by the e2e in editor-annotations.spec.ts.)
* open is refused as a modal (the real `dialog[open]` of happy-dom), and its « Abandonner la
* création ? » shows inside it: without the modal branch's guard call this test fails.
*/
describe('a Back on the creation dialog', () => {
afterEach(() => act(() => resetWork()))
@@ -18,6 +18,8 @@ import { FocusConsumedContext } from '@/editor/focusRequest'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { emptyForm } from '@/editor/annotations/creation'
import { traceVertex } from '@/editor/annotations/creationWork'
import { cleanSvg } from '@/editor/core/cleaning'
import {
ASSET,
@@ -575,3 +577,40 @@ describe('a tab while a creation or a tracing is in progress', () => {
expect(within(back).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
})
})
/**
* Fix round 1 (review ⚠️): a shell link with nothing at stake is not intercepted, so the
* route's own cleanup must end the drawing's work. The route closes the store session on
* unmount (`AdminSheetDraftRoute`), and a session change resets the work store.
*/
describe('leaving the editor route resets the drawing work', () => {
// A mode on no selection is ended by the body itself (`useModeFollowsSelection`), so the
// work held here is a creation; the reset is the same `resetWork` for a mode.
it('a creation is gone once the route unmounts, its question too', async () => {
serverHas(baseText(), 3)
const view = mountDraft()
await ready()
const base = store.getState().documentText
const viewId = JSON.parse(base).views[0].id as string
act(() => {
traceVertex(
{
viewId,
frame: null,
origin: 'tool',
form: emptyForm({ categories: [] } as never),
},
'zone',
[1, 1],
)
})
expect(useAnnotationWork.getState().creation).not.toBeNull()
view.unmount()
expect(useAnnotationWork.getState()).toMatchObject({
mode: null,
preview: null,
creation: null,
question: null,
})
})
})
@@ -397,6 +397,53 @@ describe('the move mode (A11, R-12, R-13)', () => {
})
})
describe('fix round 1: a recovery during a started move (R-13)', () => {
const two = () => withPoints(point('a', 50, 50, 5), point('b', 20, 20, 5))
it('a restored copy replaces the document: the mode is dropped and said', async () => {
await mount(two())
await select()
await userEvent.setup().click(moveButton())
fireEvent.click(arrow('la droite'))
expect(useAnnotationWork.getState().mode?.started).toBe(true)
const { savedRevision, drawings } = store.getState()
const copy = {
v: 1 as const,
user_id: USER,
version_id: VERSION,
sheet_id: 'sheet-1',
sheet_name: 'Fiche',
revision: savedRevision,
written_at: '2026-11-03T10:00:00Z',
document: JSON.parse(
withPoints(point('a', 30, 30, 5), point('b', 20, 20, 5)),
),
drawings: drawings.map((d) => ({
asset_id: d.asset_id,
sha256: d.sha256,
})),
}
act(() =>
store.setState({
recovery: 'pending',
offer: {
revision: savedRevision,
writtenAt: copy.written_at,
sheetName: 'Fiche',
serverRevision: savedRevision,
copy,
},
}),
)
await act(async () => {
expect(await store.getState().restoreCopy()).toEqual({ ok: true })
})
expect(useAnnotationWork.getState().mode).toBeNull()
expect(
await screen.findByText('Déplacement abandonné : la fiche a changé.'),
).toBeInTheDocument()
})
})
describe('the point handle (R-9, R-11)', () => {
it('is a focusable button outside any aria-hidden subtree, named « Point {nom} »', async () => {
await mount(withPoints(point('a', 50, 50, 5)))