Files
faunosteo/apps/app/tests/unit/editor-history-buttons.test.tsx
T
bchanot 99b669bf8f feat(editor): header history, save line and Abandonner les modifications
Header Annuler/Retablir on every tab (aria-disabled, commit on pointerdown,
refused blur commit skips the undo). Save line: unsaved count selector
(savedDistance), saveLineState forms, server save time via readSaveTime
(lastSave in the store, never the browser clock). Discard relabelled and
names the stored copy. Tool column pair removed, glyphs in EditorGlyph.

Rewritten or removed assertions (R-24):
- editor-route.test: Revision 3 / unsaved text / Annuler les modifications
  -> save-line testid, Abandonner label, copy sentence in the dialog
- editor-route-conflict, editor-route-recovery: Revision n and copy_cap/
  copy_quota text queries -> save-line testid
- editor-no-loss: discard button label
- editor-annotations-tab: tool column undo/redo test -> no pair left
  (behaviour moved to editor-history-buttons.test)
- e2e journey/annotations/recovery/structures/support saveDraft/lan:
  undo/redo and revision/unsaved text -> historyButton, saveLine helpers;
  structures toHaveCount(0) on old text -> exact Revision n line
- editor-shell clickability: header Annuler/Retablir added
2026-11-08 17:55:49 +01:00

390 lines
13 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,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
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('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 })
})
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('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()
})
})