Files
faunosteo/apps/app/tests/unit/editor-creation-dialog.test.tsx
T
bchanot 837ec9f436 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.
2026-11-18 00:06:16 +01:00

539 lines
21 KiB
TypeScript

/** U2 Task 7: creation on the drawing, then the creation dialog (A2, A4, A5, A7, A12, A15). */
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 HistoryButtons from '@/components/editor/HistoryButtons'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
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'
import { openReady, pressAt, resetStore, store } from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
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(),
}
/** Screen = drawing: the overlay's inverse CTM is the identity in the page under test. */
function stubCtm(): void {
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 }),
})
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
stubCtm()
})
afterEach(() => {
cleanup()
resetStore()
})
/** A second category, coloured, so the ghost's colour can follow the form (A4). */
function twoCategories(): string {
return insert(insert(drawnText(), point('anno-a', 20, 20, 5)), {
kind: 'category',
value: { id: 'cat-b', name: { fr: 'Os', en: 'Bone' }, color: '#aa3366' },
} as never)
}
/** The tab with the header's history controls, as the workspace shows them. */
function Page({ readOnly = false }: { readOnly?: boolean }) {
useUndoShortcuts(true)
return (
<>
<HistoryButtons />
<LayeredTab {...props} readOnly={readOnly} />
</>
)
}
let view: ReturnType<typeof render>
async function mount(text = twoCategories()) {
await openReady({ text })
view = render(<Page />)
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
)
return userEvent.setup()
}
const canvas = () => screen.getByTestId('annotation-canvas')
const withDetail = () =>
insert(twoCategories(), {
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)
const ghost = () => screen.getByTestId('overlay-ghost')
const creation = () => useAnnotationWork.getState().creation
const annotations = () => store.getState().previewState!.document.annotations
const dialog = (name = 'Nouveau point') => screen.findByRole('dialog', { name })
async function placePoint(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(canvas(), 50, 50)
return dialog()
}
describe('the creation dialog asks before leaving, always (A12)', () => {
it('✕ with nothing typed asks; « Continuer » keeps the shape', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.click(within(shown).getByRole('button', { name: 'Fermer' }))
const ask = within(shown).getByRole('group', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(screen.getByRole('dialog', { name: 'Nouveau point' })).toBe(shown)
expect(creation()).not.toBeNull()
expect(ghost()).toBeInTheDocument()
})
it('Échap with nothing typed asks inside the dialog, never the workspace question', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.keyboard('{Escape}')
expect(
within(shown).getByRole('group', { name: 'Abandonner la création ?' }),
).toBeInTheDocument()
expect(screen.getAllByRole('dialog')).toHaveLength(1)
})
it('« Abandonner » asks, then clears the creation; the focus goes to the tool', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.click(within(shown).getByRole('button', { name: 'Abandonner' }))
expect(creation()).not.toBeNull()
const ask = within(shown).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(screen.queryByTestId('overlay-ghost')).toBeNull()
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toHaveFocus(),
)
expect(annotations()).toHaveLength(1)
})
it('a keyboard creation abandoned gives the focus back to its « Ajouter … » button', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
const shown = await dialog('Nouvelle zone')
await user.click(within(shown).getByRole('button', { name: 'Abandonner' }))
await user.click(
within(
within(shown).getByRole('group', { name: 'Abandonner la création ?' }),
).getByRole('button', { name: 'Abandonner' }),
)
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter une zone' }),
).toHaveFocus(),
)
})
})
describe('placing and the form (A4, A5)', () => {
it('the category prefilled, the laterality without default; a category recolours the ghost', async () => {
const user = await mount()
const shown = await placePoint(user)
expect(within(shown).getByLabelText('Catégorie')).toHaveValue('cat-a')
expect(within(shown).getByLabelText('Latéralité')).toHaveValue('')
expect(within(shown).queryByLabelText('Couleur')).toBeNull()
expect(ghost()).toHaveAttribute('data-colour', 'var(--color-accent)')
await user.selectOptions(within(shown).getByLabelText('Catégorie'), 'cat-b')
expect(ghost()).toHaveAttribute('data-colour', '#aa3366')
})
it('the point tool previews the next point under a mouse, never under a finger', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Point' }))
const at = { clientX: 40, clientY: 30 }
fireEvent.pointerMove(canvas(), { ...at, pointerType: 'touch' })
expect(screen.queryByTestId('overlay-point-preview')).toBeNull()
fireEvent.pointerMove(canvas(), { ...at, pointerType: 'mouse' })
const preview = screen.getByTestId('overlay-point-preview')
// A5: the view's most used size (the only point has r = 5).
expect(preview.querySelector('circle')).toHaveAttribute('r', '5')
expect(preview.querySelector('circle')).toHaveAttribute('cx', '40')
fireEvent.pointerLeave(canvas())
expect(screen.queryByTestId('overlay-point-preview')).toBeNull()
})
it('a link shows « Vue ouverte »', async () => {
const text = insert(twoCategories(), {
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)
const user = await mount(text)
await user.click(screen.getByRole('button', { name: 'Ajouter un accès' }))
const shown = await dialog('Nouvel accès')
expect(within(shown).getByLabelText('Vue ouverte')).toBeInTheDocument()
expect(
within(shown).getByText('Accès tracé, 3 sommets'),
).toBeInTheDocument()
})
})
describe('« Reprendre le tracé » and « Revenir aux propriétés » (board 04 C)', () => {
it('keeps the vertices and the form; a new vertex, then the dialog again', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Zone' }))
;[
[20, 20],
[80, 20],
[50, 80],
].forEach(([x, y]) => pressAt(canvas(), x, y))
await user.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
let shown = await dialog('Nouvelle zone')
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Tibia')
await user.click(
within(shown).getByRole('button', { name: 'Reprendre le tracé' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
const strip = screen.getByTestId('edit-strip')
expect(strip).toHaveTextContent('Tracé repris, saisie gardée')
expect(
within(strip).getByRole('button', { name: 'Retirer le dernier sommet' }),
).toBeEnabled()
pressAt(canvas(), 30, 60)
await user.click(
within(strip).getByRole('button', { name: 'Revenir aux propriétés' }),
)
shown = await dialog('Nouvelle zone')
expect(within(shown).getByLabelText('Nom (FR)')).toHaveValue('Tibia')
expect(
within(shown).getByText('Zone tracée, 4 sommets'),
).toBeInTheDocument()
})
})
describe('« Créer » (A7, board 32)', () => {
it('one insert, one undo; « Sélectionner », the new zone selected, its row focused', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Zone' }))
;[
[20, 20],
[80, 20],
[50, 80],
].forEach(([x, y]) => pressAt(canvas(), x, y))
fireEvent.keyDown(canvas(), { key: 'Enter' })
const shown = await dialog('Nouvelle zone')
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Tibia')
await user.type(within(shown).getByLabelText('Nom (EN)'), 'Tibia')
await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left')
const before = store.getState().undo.length
await user.click(within(shown).getByRole('button', { name: 'Créer' }))
expect(store.getState().undo).toHaveLength(before + 1)
const created = annotations().find((a) => a.kind === 'zone')!
expect(created).toMatchObject({ name: { fr: 'Tibia', en: 'Tibia' } })
expect(screen.getByTestId('gesture-line')).toHaveTextContent('Zone créée')
expect(
screen.getByRole('button', { name: 'Sélectionner et déplacer' }),
).toHaveAttribute('aria-pressed', 'true')
await waitFor(() =>
expect(document.activeElement).toHaveAttribute(
'data-focus-key',
JSON.stringify({ kind: 'annotation', id: created.id }),
),
)
})
})
describe('during a creation (A12, R-13)', () => {
it('the other markers are dimmed; undo is inactive; « Défaire » leaves the line', async () => {
const user = await mount()
// A kept gesture first, so the line under the drawing offers « Défaire ».
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(canvas(), 50, 50)
const shown = await dialog()
await user.type(within(shown).getByLabelText('Nom (FR)'), 'A')
await user.type(within(shown).getByLabelText('Nom (EN)'), 'B')
await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left')
await user.click(within(shown).getByRole('button', { name: 'Créer' }))
const line = screen.getByTestId('gesture-line')
expect(within(line).getByRole('button', { name: /Défaire/ })).toBeTruthy()
expect(canvas()).not.toHaveAttribute('data-creating')
// A tracing: no dialog, the page itself is live.
await user.click(screen.getByRole('button', { name: 'Zone' }))
pressAt(canvas(), 20, 80)
expect(canvas()).toHaveAttribute('data-creating')
expect(within(line).queryByRole('button', { name: /Défaire/ })).toBeNull()
const undo = screen.getByRole('button', { name: /Défaire la dernière/ })
expect(undo).toHaveAttribute('aria-disabled', 'true')
const depth = store.getState().undo.length
await user.click(undo)
fireEvent.keyDown(window, { key: 'z', ctrlKey: true })
expect(store.getState().undo).toHaveLength(depth)
expect(creation()).not.toBeNull()
})
it('Escape while the point is replaced asks « Abandonner la création ? »', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.click(
within(shown).getByRole('button', { name: 'Replacer le point' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
act(() => canvas().focus())
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).toBeInTheDocument()
})
})
describe('the question never outlives its creation', () => {
it('Escape, then « Replacer le point »: no question left over the page', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.keyboard('{Escape}')
expect(useAnnotationWork.getState().question?.work).toBe('creation')
await user.click(
within(shown).getByRole('button', { name: 'Replacer le point' }),
)
expect(useAnnotationWork.getState().question).toBeNull()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})
it('Escape, then « Utiliser cette position » (C26): created, nothing asked', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(canvas(), 0, 0)
const shown = await dialog()
await user.type(within(shown).getByLabelText('Nom (FR)'), 'A')
await user.type(within(shown).getByLabelText('Nom (EN)'), 'B')
await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left')
await user.click(within(shown).getByRole('button', { name: 'Créer' }))
const notice = await screen.findByTestId('correction-notice')
await user.keyboard('{Escape}')
await user.click(
within(notice).getByRole('button', { name: 'Utiliser cette position' }),
)
expect(creation()).toBeNull()
expect(useAnnotationWork.getState().question).toBeNull()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})
})
describe('the guard sites of the drawing during a tracing (R-12)', () => {
async function tracing() {
const user = await mount(withDetail())
await user.click(screen.getByRole('button', { name: 'Zone' }))
pressAt(canvas(), 20, 20)
return user
}
const answer = async (
user: ReturnType<typeof userEvent.setup>,
name: 'Continuer' | 'Abandonner',
) =>
user.click(
within(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).getByRole('button', { name }),
)
it('a view chip asks; « Continuer » keeps the tracing, « Abandonner » shows the view', async () => {
const user = await tracing()
const chip = screen.getByRole('button', { name: 'Tête' })
await user.click(chip)
await answer(user, 'Continuer')
expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
await user.click(chip)
await answer(user, 'Abandonner')
expect(creation()).toBeNull()
expect(chip).toHaveAttribute('aria-pressed', 'true')
})
it('a tool asks the same way', async () => {
const user = await tracing()
await user.click(screen.getByRole('button', { name: 'Point' }))
await answer(user, 'Continuer')
expect(screen.getByRole('button', { name: 'Zone' })).toHaveAttribute(
'aria-pressed',
'true',
)
await user.click(screen.getByRole('button', { name: 'Point' }))
await answer(user, 'Abandonner')
expect(screen.getByRole('button', { name: 'Point' })).toHaveAttribute(
'aria-pressed',
'true',
)
})
})
describe('the mode flip (R-14, Review Focus 3)', () => {
it('read-only by a mode change, then back: the dialog, its form and the ghost stay', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Gardé')
view.rerender(<Page readOnly />)
const kept = screen.getByRole('dialog', { name: 'Nouveau point' })
expect(within(kept).getByLabelText('Nom (FR)')).toHaveValue('Gardé')
expect(within(kept).getByRole('button', { name: 'Créer' })).toBeDisabled()
expect(
within(kept).getByRole('button', { name: 'Replacer le point' }),
).toBeDisabled()
expect(screen.getByTestId('overlay-ghost')).toBeInTheDocument()
view.rerender(<Page />)
const back = screen.getByRole('dialog', { name: 'Nouveau point' })
expect(within(back).getByLabelText('Nom (FR)')).toHaveValue('Gardé')
expect(within(back).getByRole('button', { name: 'Créer' })).toBeEnabled()
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)
})
})