Files
faunosteo/apps/app/tests/unit/editor-history-buttons.test.tsx
T
bchanot 0467885527 fix(editor): final review fixes (touch undo guard, focus, save line)
Important 1: a touch press fires pointer leave between up and click; only a
mouse leave (or a pointer cancel) forgets the refused field, so Annuler no
longer undoes an unrelated change. Important 2: the LAN spec reads the
revision before the attach, through shownRevision, which throws instead of NaN
(spec stays not run). Minor 1: refocusIfHidden refocuses a still shown element
the commit blurred (references search on a 1 024 px crossing). Minor 2:
discardChanges keeps lastSave (reload path still drops it). Minor 3: the
overview filter term lives in UiState / the read-only twin, not the card.
Minor 4: categories section drops its inner h3 and the unused
editor.general.categories keys. AC8: badge test.

Assertions rewritten or added (R-24):
- editor-tabs-general « Général no longer holds the categories editor »:
  queryByText of the deleted heading (now vacuous) -> queryByLabelText of the
  category name fields.
- editor-focus-request « Annotations: selects the annotation »: findAllByText
  /anno-b|Sélection/ -> the properties panel holds Centre x = 20 (anno-b) and
  owns the focused heading.
- editor-shell-layout panel walk: added after.at(-1) === 'side'.
- editor-recovery title « Annuler les modifications » -> « Abandonner ».
- new: touch/cancel/mouse press, references search crossing, discard keeps
  lastSave, filter kept, one categories heading, badge 1/2/0, shownRevision.
2026-11-09 12:19:32 +01:00

531 lines
18 KiB
TypeScript

/** Lot E: the header « Annuler » / « Rétablir », the save line's announcements, discard. */
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 DeleteDialog from '@/components/editor/DeleteDialog'
import { fr } from '@/i18n/fr'
import {
baseText,
commitMove,
resetStore,
sb,
serverHas,
storedCopy,
store,
} from '../helpers/editorHarness'
import {
adminAnswer,
grant,
mountDraft,
round,
setWidth,
} from '../helpers/editorRoute'
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(),
}))
beforeEach(() => serverHas(baseText(), 3))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const UNDO = 'Annuler la dernière modification'
const REDO = 'Rétablir la dernière modification annulée'
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const undoButton = () => screen.getByRole('button', { name: UNDO })
const redoButton = () => screen.getByRole('button', { name: REDO })
const disabled = (button: HTMLElement) =>
button.getAttribute('aria-disabled') === 'true'
const geometry = () =>
store.getState().previewState?.document.annotations[0].geometry
const nameFr = () =>
store.getState().previewState?.document.annotations[0].name?.fr
async function selectAnnotation(user: ReturnType<typeof userEvent.setup>) {
const list = await screen.findByRole('list', {
name: 'Annotations de la vue',
})
await user.click(within(list).getAllByRole('button')[0])
const panel = await screen.findByTestId('annotation-properties')
return within(panel).getByLabelText('Nom (FR)') as HTMLInputElement
}
describe('the buttons', () => {
it('have the T15 names, titles, shortcuts and a visible label', async () => {
mountDraft()
await ready()
const row = within(screen.getByTestId('history-buttons'))
expect(undoButton()).toHaveAttribute('title', UNDO)
expect(redoButton()).toHaveAttribute('title', REDO)
expect(undoButton()).toHaveAttribute('aria-keyshortcuts', 'Control+Z')
expect(redoButton()).toHaveAttribute('aria-keyshortcuts', 'Control+Shift+Z')
expect(row.getAllByRole('button').map((b) => b.textContent)).toEqual([
'Annuler',
'Rétablir',
])
expect(undoButton()).not.toHaveAttribute('disabled')
})
it('are enabled exactly when the store can step, and step', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
expect([disabled(undoButton()), disabled(redoButton())]).toEqual([
true,
true,
])
act(() => void commitMove(40))
expect([disabled(undoButton()), disabled(redoButton())]).toEqual([
false,
true,
])
await user.click(undoButton())
expect(geometry()).toMatchObject({ cx: 50 })
expect([disabled(undoButton()), disabled(redoButton())]).toEqual([
true,
false,
])
await user.click(redoButton())
expect(geometry()).toMatchObject({ cx: 40 })
})
it('stay focused when the last undo empties the stack', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(undoButton())
expect(disabled(undoButton())).toBe(true)
expect(undoButton()).toHaveFocus()
})
it('are disabled in every mode that cannot edit', async () => {
const modes: Array<[string, Parameters<typeof mountDraft>[0]]> = [
['narrow', { width: 800 }],
['rights', { grants: [grant('sheet_reviewer')], roles: [] }],
['frozen', { answer: adminAnswer({ rounds: [round('open')] }) }],
['historical', { answer: adminAnswer({ historical: true }) }],
['inactive', { answer: adminAnswer({ status: 'archived' }) }],
]
for (const [, options] of modes) {
serverHas(baseText(), 3)
const view = mountDraft(options)
await ready()
store.setState({ undo: [{ text: baseText(), bytes: 1 }] })
expect(disabled(undoButton())).toBe(true)
await userEvent.setup().click(undoButton())
expect(store.getState().undo).toHaveLength(1)
view.unmount()
cleanup()
resetStore()
}
})
it('are disabled while a recovery decision is pending', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
act(() => store.setState({ recovery: 'pending' }))
expect(disabled(undoButton())).toBe(true)
})
it('stay enabled while saving, in step with Ctrl+Z', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockReturnValue(new Promise(() => undefined) as never)
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() => expect(store.getState().saving).toBe(true))
expect(disabled(undoButton())).toBe(false)
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(geometry()).toMatchObject({ cx: 50 })
expect(store.getState().redo).toHaveLength(1)
await user.click(redoButton())
expect(geometry()).toMatchObject({ cx: 40 })
})
it('undo from Général and from Constats reverts a canvas change', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(screen.getByRole('tab', { name: 'Général' }))
await user.click(undoButton())
expect(geometry()).toMatchObject({ cx: 50 })
await user.click(redoButton())
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(undoButton())
expect(geometry()).toMatchObject({ cx: 50 })
})
it('undo from Annotations reverts a Général change', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
const original = store.getState().previewState?.document.name?.fr
await user.click(screen.getByRole('tab', { name: 'Général' }))
const place = document.querySelector(
'[data-place="general"]',
) as HTMLElement
const field = within(place).getByLabelText('Nom (FR)')
await user.clear(field)
await user.type(field, 'Renommée')
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(store.getState().previewState?.document.name?.fr).toBe('Renommée')
await user.click(undoButton())
expect(store.getState().previewState?.document.name?.fr).toBe(original)
})
it('leave no undo or redo pair in the tool column', async () => {
mountDraft()
await ready()
const tools = screen.getByRole('toolbar', {
name: fr['editor.annotations.tools'],
})
expect(
within(tools).queryByRole('button', { name: /Annuler|Rétablir/ }),
).toBeNull()
})
})
describe('typed text and the press', () => {
it('undo reverts exactly the typed text, with and without earlier history', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
const field = await selectAnnotation(user)
const original = nameFr()
await user.clear(field)
await user.type(field, 'Nouveau')
await user.pointer({ keys: '[MouseLeft]', target: undoButton() })
expect(nameFr()).toBe(original)
expect(store.getState().redo).toHaveLength(1)
act(() => void commitMove(40))
await user.clear(field)
await user.type(field, 'Encore')
await user.pointer({ keys: '[MouseLeft]', target: undoButton() })
expect(nameFr()).toBe(original)
expect(geometry()).toMatchObject({ cx: 40 })
})
it('the pointer press blurs the focused field', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
const field = await selectAnnotation(user)
await user.clear(field)
await user.type(field, 'Saisie')
fireEvent.pointerDown(undoButton())
expect(field).not.toHaveFocus()
expect(nameFr()).toBe('Saisie')
})
it('a refused blur commit skips the undo and returns focus to the field', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const field = await selectAnnotation(user)
await user.clear(field)
await user.pointer({ keys: '[MouseLeft]', target: undoButton() })
expect(field).toHaveAttribute('aria-invalid', 'true')
expect(field).toHaveFocus()
expect(geometry()).toMatchObject({ cx: 40 })
})
async function refusedField() {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const field = await selectAnnotation(user)
await user.clear(field)
return field
}
/** A press as a touch sends it: down, up, the leave it fires, then the click. */
function touchPress() {
const init = { pointerType: 'touch' }
fireEvent.pointerDown(undoButton(), init)
fireEvent.pointerUp(undoButton(), init)
fireEvent.pointerLeave(undoButton(), init)
fireEvent.click(undoButton())
}
it('a touch press keeps the refused field across pointer leave and click', async () => {
const field = await refusedField()
touchPress()
expect(field).toHaveAttribute('aria-invalid', 'true')
expect(field).toHaveFocus()
expect(geometry()).toMatchObject({ cx: 40 })
expect(store.getState().undo).toHaveLength(1)
})
it('a touch press cancelled by the browser forgets the field', async () => {
const field = await refusedField()
fireEvent.pointerDown(undoButton(), { pointerType: 'touch' })
fireEvent.pointerCancel(undoButton(), { pointerType: 'touch' })
fireEvent.click(undoButton())
expect(field).not.toHaveFocus()
expect(geometry()).toMatchObject({ cx: 50 })
})
it('a mouse leaving the button forgets the field', async () => {
const field = await refusedField()
fireEvent.pointerDown(undoButton(), { pointerType: 'mouse' })
fireEvent.pointerLeave(undoButton(), { pointerType: 'mouse' })
fireEvent.click(undoButton())
expect(field).not.toHaveFocus()
expect(geometry()).toMatchObject({ cx: 50 })
})
it('a keyboard activation after a refused blur commit skips the undo too', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const field = await selectAnnotation(user)
await user.clear(field)
field.blur()
act(() => undoButton().focus())
fireEvent.focus(undoButton(), { relatedTarget: field })
await user.keyboard('{Enter}')
expect(field).toHaveAttribute('aria-invalid', 'true')
expect(field).toHaveFocus()
expect(geometry()).toMatchObject({ cx: 40 })
expect(store.getState().undo).toHaveLength(1)
})
it('a field left through « Rétablir » to « Annuler » still skips the undo', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const field = await selectAnnotation(user)
await user.clear(field)
field.blur()
const redo = screen.getByRole('button', {
name: 'Rétablir la dernière modification annulée',
})
act(() => redo.focus())
fireEvent.focus(redo, { relatedTarget: field })
act(() => undoButton().focus())
fireEvent.focus(undoButton(), { relatedTarget: redo })
await user.keyboard('{Enter}')
expect(field).toHaveFocus()
expect(store.getState().undo).toHaveLength(1)
})
it('Ctrl+Z is ignored while a DeleteDialog is open', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
render(
<DeleteDialog
target={{ key: { kind: 'annotation', id: 'anno-a' }, label: 'N' }}
onClose={vi.fn()}
/>,
)
await screen.findByRole('dialog')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(geometry()).toMatchObject({ cx: 40 })
})
it('Ctrl+Z inside a field leaves the store untouched', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
const before = store.getState().documentText
fireEvent.keyDown(document.querySelector('input') as Element, {
key: 'z',
ctrlKey: true,
})
expect(store.getState().documentText).toBe(before)
})
})
describe('the save status', () => {
it('announces state transitions, never each count', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
const status = screen.getByTestId('save-status')
expect(status).toHaveTextContent(/^$/)
act(() => void commitMove(40))
expect(status).toHaveTextContent(/^Modifications non enregistrées$/)
act(() => void commitMove(41))
expect(status).toHaveTextContent(/^Modifications non enregistrées$/)
expect(screen.getByTestId('save-line')).toHaveTextContent(
/^2 modifications non enregistrées$/,
)
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() =>
expect(status).toHaveTextContent(/^Enregistré · révision 4$/),
)
})
it('shows the server time once read, « Enregistré · révision n » otherwise', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
act(() => void commitMove(40))
sb.getOfficialSheetAdmin.mockResolvedValue(
adminAnswer({
draft_version: { version_id: 'ver-1', version_number: 4, revision: 4 },
draft_last_save: {
revision: 4,
saved_at: '2026-11-04T13:32:00Z',
saved_by: null,
},
}) as never,
)
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() =>
expect(screen.getByTestId('save-line')).toHaveTextContent(
/^Enregistré à 14:32 · révision 4$/,
),
)
})
it('shows « Enregistré · révision n » when the read fails, editor still mounted', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
act(() => void commitMove(40))
sb.getOfficialSheetAdmin.mockRejectedValue(new Error('offline'))
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() =>
expect(screen.getByTestId('save-line')).toHaveTextContent(
/^Enregistré · révision 4$/,
),
)
expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument()
})
it('shows no saved line while the save is in flight', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockReturnValue(new Promise(() => undefined) as never)
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(screen.getByTestId('save-line')).toHaveTextContent(
/^Enregistrement…$/,
)
})
it('reserves its widest form so the row does not move', async () => {
mountDraft()
await ready()
const sizers = screen
.getByTestId('save-line')
.parentElement!.querySelectorAll('[aria-hidden]')
expect([...sizers].map((el) => el.textContent)).toEqual([
'Enregistré à 00:00 · révision 999',
'999 modifications non enregistrées',
])
})
})
describe('« Abandonner les modifications »', () => {
const open = async (user: ReturnType<typeof userEvent.setup>) => {
await user.click(
screen.getByRole('button', { name: 'Abandonner les modifications' }),
)
return within(await screen.findByRole('dialog'))
}
it('names the stored copy, and keeps changes and copy on cancel', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const dialog = await open(user)
expect(
dialog.getByText(new RegExp(fr['editor.draft.discard_copy'])),
).toBeInTheDocument()
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
expect(store.getState().unsaved).toBe(true)
expect(storedCopy()).not.toBeNull()
})
it('names a copy left by an earlier write after a quota refusal', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
expect(storedCopy()).not.toBeNull()
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => void commitMove(41))
await waitFor(() => expect(store.getState().copyIssue).toBe('quota'))
const dialog = await open(user)
expect(
dialog.getByText(new RegExp(fr['editor.draft.discard_copy'])),
).toBeInTheDocument()
})
it('keeps the session\'s save in the save line, and the save line says it', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
sb.getOfficialSheetAdmin.mockRejectedValue(new Error('offline'))
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
const line = screen.getByTestId('save-line')
await waitFor(() =>
expect(line).toHaveTextContent(/^Enregistré · révision 4$/),
)
act(() => void commitMove(41))
expect(line).toHaveTextContent(/^1 modification non enregistrée$/)
const dialog = await open(user)
await user.click(
dialog.getByRole('button', { name: fr['editor.draft.discard_confirm'] }),
)
expect(store.getState().unsaved).toBe(false)
expect(geometry()).toMatchObject({ cx: 40 })
expect(line).toHaveTextContent(/^Enregistré · révision 4$/)
})
it('does not mention a copy when none is stored', async () => {
const user = userEvent.setup()
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
mountDraft()
await ready()
act(() => void commitMove(40))
const dialog = await open(user)
expect(dialog.getByText(fr['editor.draft.discard_ask'])).toBeInTheDocument()
expect(
dialog.queryByText(new RegExp(fr['editor.draft.discard_copy'])),
).toBeNull()
})
})