feat(app): sheet draft editor route, modes, recovery offer and conflict dialog

This commit is contained in:
bchanot committed 2026-11-04 12:35:33 +01:00
1 parent b14509f221
commit 6aba9711f0
44 files changed
+3143 -13

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
import { render } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import {
SheetFailure,
type OwnCatalogGrant,
type PlatformRole,
type SheetFailureKind,
} from '@faunosteo/supabase'
import AdminSheetDraftRoute from '@/app/routes/app/admin/AdminSheetDraftRoute'
import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useLocaleStore } from '@/state/localeStore'
import { SHEET, USER, VERSION, sb } from './editorHarness'
/** The route harness: the calling file declares the same module mocks as the store harness. */
export const grant = (kind: OwnCatalogGrant['kind']): OwnCatalogGrant => ({
kind,
expires_at: null,
revoked_at: null,
})
export function adminAnswer(patch: Record<string, unknown> = {}) {
return {
sheet_id: SHEET,
species_id: 'equine',
slug: 'cheval',
status: 'active',
archived_at: null,
created_at: '2026-11-01T10:00:00Z',
updated_at: '2026-11-01T10:00:00Z',
name: {
fr: 'Cheval, squelette et rachis',
en: 'Horse, skeleton and spine',
},
historical: false,
working_copy: true,
working_copy_active: null,
working_copy_source: null,
latest_version: {
version_id: VERSION,
version_number: 4,
status: 'draft',
revision: 3,
},
current_version: null,
draft_version: { version_id: VERSION, version_number: 4, revision: 3 },
draft_last_save: null,
version_statuses: ['draft'],
open_rounds: 0,
latest_round: null,
versions: [],
rounds: [],
...patch,
}
}
export function round(status: string, patch: Record<string, unknown> = {}) {
return {
review_id: 'r-1',
version_id: VERSION,
version_number: 4,
round: 1,
revision: 3,
status,
submitted_by: null,
submitted_at: null,
verified_at: null,
failure_outcome: null,
failure_code: null,
decided_by: null,
decided_at: null,
withdrawn_at: null,
...patch,
}
}
export function setWidth(width: number): void {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: width,
})
}
export interface MountOptions {
grants?: OwnCatalogGrant[]
roles?: PlatformRole[]
grantsStatus?: 'loading' | 'ready' | 'failed'
width?: number
answer?: Record<string, unknown>
/** The admin read is refused with this closed kind. */
adminFailure?: SheetFailureKind
}
/** Mounts the draft route as an editor with the admin role, at a wide screen, by default. */
export function mountDraft(options: MountOptions = {}) {
setWidth(options.width ?? 1280)
useLocaleStore.setState({ locale: 'fr' })
useLeaveGuardStore.setState({ armed: false })
useAuthStore.setState({
user: { id: USER } as never,
catalogGrants: options.grants ?? [grant('sheet_editor')],
catalogGrantsStatus: options.grantsStatus ?? 'ready',
roles: options.roles ?? ['admin'],
})
if (options.adminFailure) {
sb.getOfficialSheetAdmin.mockRejectedValue(
new SheetFailure(options.adminFailure),
)
} else {
sb.getOfficialSheetAdmin.mockResolvedValue(
(options.answer ?? adminAnswer()) as never,
)
}
return render(
<MemoryRouter initialEntries={[`/app/admin/sheets/${SHEET}/draft`]}>
<Routes>
<Route
path="/app/admin/sheets/:sheetId/draft"
element={<AdminSheetDraftRoute />}
/>
<Route
path="/app/admin/sheets/:sheetId"
element={<p>overview page</p>}
/>
</Routes>
</MemoryRouter>,
)
}
+122
View File
@@ -0,0 +1,122 @@
/** Lot E: the shared field components: commit once per change, text when read-only. */
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
const OPTIONS = [
{ value: 'a', label: 'Alpha' },
{ value: 'b', label: 'Beta' },
]
describe('TextField', () => {
it('commits on blur with a changed value, never per keystroke', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
render(<TextField id="f" label="Nom" value="Cheval" onCommit={onCommit} />)
await user.type(screen.getByLabelText('Nom'), 's')
expect(onCommit).not.toHaveBeenCalled()
await user.tab()
expect(onCommit).toHaveBeenCalledOnce()
expect(onCommit).toHaveBeenCalledWith('Chevals')
})
it('Enter commits a single line; an unchanged value commits nothing', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
render(<TextField id="f" label="Nom" value="Cheval" onCommit={onCommit} />)
const input = screen.getByLabelText('Nom')
await user.click(input)
await user.keyboard('{Enter}')
await user.tab()
expect(onCommit).not.toHaveBeenCalled()
await user.type(input, 'x{Enter}')
expect(onCommit).toHaveBeenCalledWith('Chevalx')
})
it('a value still pending when the field unmounts is committed', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
const view = render(
<TextField id="f" label="Nom" value="Cheval" onCommit={onCommit} />,
)
await user.type(screen.getByLabelText('Nom'), 'z')
view.unmount()
expect(onCommit).toHaveBeenCalledWith('Chevalz')
})
it('a new committed value replaces what was typed; the refusal shows next to the control', () => {
const view = render(
<TextField
id="f"
label="Nom"
value="a"
onCommit={vi.fn()}
error="Refusé"
/>,
)
expect(screen.getByRole('alert')).toHaveTextContent('Refusé')
expect(screen.getByLabelText('Nom')).toHaveAttribute('aria-invalid', 'true')
view.rerender(<TextField id="f" label="Nom" value="b" onCommit={vi.fn()} />)
expect(screen.getByLabelText('Nom')).toHaveValue('b')
})
it('read-only: the value as text, no control; empty reads as a dash', () => {
const view = render(
<TextField
id="f"
label="Nom"
value="Cheval"
onCommit={vi.fn()}
readOnly
/>,
)
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.getByText('Cheval')).toBeInTheDocument()
view.rerender(
<TextField id="f" label="Nom" value="" onCommit={vi.fn()} readOnly />,
)
expect(screen.getByText('—')).toBeInTheDocument()
})
})
describe('SelectField and ActionButton', () => {
it('a choice commits at once; read-only shows the option label', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
const view = render(
<SelectField
id="s"
label="Type"
value="a"
options={OPTIONS}
onCommit={onCommit}
/>,
)
await user.selectOptions(screen.getByLabelText('Type'), 'b')
expect(onCommit).toHaveBeenCalledWith('b')
view.rerender(
<SelectField
id="s"
label="Type"
value="b"
options={OPTIONS}
onCommit={onCommit}
readOnly
/>,
)
expect(screen.queryByRole('combobox')).toBeNull()
expect(screen.getByText('Beta')).toBeInTheDocument()
})
it('the action is absent while read-only', () => {
const view = render(<ActionButton readOnly={false}>Supprimer</ActionButton>)
expect(
screen.getByRole('button', { name: 'Supprimer' }),
).toBeInTheDocument()
view.rerender(<ActionButton readOnly>Supprimer</ActionButton>)
expect(screen.queryByRole('button')).toBeNull()
})
})
+117
View File
@@ -0,0 +1,117 @@
/** Lot E: the display rules of the draft's mode (the server decides every write). */
import { describe, expect, it } from 'vitest'
import {
draftEditable,
editorMode,
freezingRound,
hasEditRight,
modeAfterSave,
storeCanEdit,
} from '@/editor/mode'
import { tabsFor } from '@/editor/tabs'
const sheet = (patch: Record<string, unknown> = {}) =>
({
status: 'active',
historical: false,
draft_version: { version_id: 'v1', version_number: 1, revision: 1 },
rounds: [],
...patch,
}) as never
const round = (status: string, version_id = 'v1') =>
({ version_id, status }) as never
describe('editorMode', () => {
const base = { hasRight: true, sheet: sheet(), wide: true }
it('edit, narrow and the reasons that read only, strongest first', () => {
expect(editorMode(base)).toBe('edit')
expect(editorMode({ ...base, wide: false })).toBe('narrow')
expect(editorMode({ ...base, hasRight: false, wide: false })).toBe('rights')
expect(
editorMode({
...base,
sheet: sheet({ status: 'archived' }),
wide: false,
}),
).toBe('inactive')
expect(editorMode({ ...base, sheet: sheet({ historical: true }) })).toBe(
'historical',
)
expect(
editorMode({ ...base, sheet: sheet({ rounds: [round('open')] }) }),
).toBe('frozen')
})
it('only verifying, open and approved rounds of the edited draft freeze it', () => {
for (const status of ['verifying', 'open', 'approved']) {
expect(freezingRound(sheet({ rounds: [round(status)] }))).not.toBeNull()
}
for (const status of [
'changes_requested',
'withdrawn',
'verification_failed',
]) {
expect(freezingRound(sheet({ rounds: [round(status)] }))).toBeNull()
}
expect(
freezingRound(sheet({ rounds: [round('open', 'other')] })),
).toBeNull()
})
it('the right needs the capability and the admin or owner role', () => {
expect(hasEditRight(true, ['admin'])).toBe(true)
expect(hasEditRight(true, ['owner'])).toBe(true)
expect(hasEditRight(true, ['support'])).toBe(false)
expect(hasEditRight(false, ['admin'])).toBe(false)
})
it('the overview offers « Ouvrir » only when the draft can be edited', () => {
expect(draftEditable(true, sheet())).toBe(true)
expect(draftEditable(true, sheet({ rounds: [round('verifying')] }))).toBe(
false,
)
expect(draftEditable(false, sheet())).toBe(false)
})
it('the store may use a recovery copy where the account could save', () => {
expect(['edit', 'narrow'].every((m) => storeCanEdit(m as never))).toBe(true)
expect(
['rights', 'frozen', 'historical', 'inactive'].some((m) =>
storeCanEdit(m as never),
),
).toBe(false)
})
})
describe('modeAfterSave', () => {
it('a refused save names the state the page missed', () => {
expect(modeAfterSave('edit', 'draft.frozen')).toBe('frozen')
expect(modeAfterSave('edit', 'sheet.inactive')).toBe('inactive')
expect(modeAfterSave('edit', 'rights.mfa')).toBe('rights')
expect(modeAfterSave('edit', 'network')).toBe('edit')
expect(modeAfterSave('edit', null)).toBe('edit')
expect(modeAfterSave('narrow', 'draft.frozen')).toBe('narrow')
})
})
describe('tabsFor', () => {
it('the static lists of board 05', () => {
expect(tabsFor('wide').more).toEqual([])
expect(tabsFor('medium').shown).toEqual([
'general',
'annotations',
'findings',
'verification',
])
expect(tabsFor('small').shown).toEqual(['annotations', 'verification'])
expect(tabsFor('small').more).toEqual([
'general',
'views',
'findings',
'references',
'vertebrae',
])
})
})
@@ -0,0 +1,207 @@
/** Lot E: the conflict dialog, known and unknown variants, and its two confirmations. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SheetFailure } from '@faunosteo/supabase'
import {
USER,
VERSION,
baseText,
commitMove,
resetStore,
sb,
serverHas,
store,
} from '../helpers/editorHarness'
import { adminAnswer, mountDraft, 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 ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const conflict = () => new SheetFailure('draft_conflict')
function serverDraft(revision: number, lastSaveBy: string | null) {
const save =
lastSaveBy === null
? null
: {
revision,
saved_at: '2026-11-04T13:32:00Z',
saved_by: {
user_id: lastSaveBy,
display_name: lastSaveBy === USER ? 'Moi' : 'Autre Praticien',
},
}
return adminAnswer({
draft_version: { version_id: VERSION, version_number: 4, revision },
draft_last_save: save,
})
}
/** What the conflict read answers: a draft, or a failure (built when the read runs). */
type Read = ReturnType<typeof serverDraft> | (() => Promise<never>)
async function startConflict(next: Read) {
const user = userEvent.setup()
sb.saveSheetDraft.mockRejectedValueOnce(conflict())
mountDraft()
await ready()
act(() => void commitMove(40))
if (typeof next === 'function')
sb.getOfficialSheetAdmin.mockImplementationOnce(next as never)
else sb.getOfficialSheetAdmin.mockResolvedValueOnce(next as never)
await user.click(await screen.findByRole('button', { name: 'Enregistrer' }))
return { user, dialog: within(await screen.findByRole('dialog')) }
}
describe('known revision', () => {
it('names N, the author and the Paris time; keep asks first, then saves against N', async () => {
const { user, dialog } = await startConflict(serverDraft(5, 'other-user'))
expect(
await dialog.findByText(
'par Autre Praticien, le 4 novembre 2026 à 14:32',
),
).toBeInTheDocument()
expect(screen.getByRole('dialog')).toHaveAccessibleName(
'Une autre session a enregistré la révision 5',
)
expect(dialog.queryByRole('button', { name: 'Réessayer' })).toBeNull()
sb.saveSheetDraft.mockResolvedValueOnce({ revision: 6 } as never)
await user.click(dialog.getByRole('button', { name: 'Garder ma version' }))
expect(
dialog.getByText(
'Remplacer la révision 5 (Autre Praticien, 4 novembre 2026 à 14:32) par votre version ?',
),
).toBeInTheDocument()
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
await user.click(dialog.getByRole('button', { name: 'Garder ma version' }))
await waitFor(() => expect(sb.saveSheetDraft).toHaveBeenCalledTimes(2))
expect(sb.saveSheetDraft).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ expected_revision: 5 }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(await screen.findByText('Révision 6')).toBeInTheDocument()
})
it('saved by the caller: the neutral own-account wording', async () => {
const { dialog } = await startConflict(serverDraft(5, USER))
expect(
await dialog.findByText(
'depuis une autre session de votre compte, le 4 novembre 2026 à 14:32',
),
).toBeInTheDocument()
expect(dialog.queryByText(/Moi/)).toBeNull()
})
it('no matching last save: N alone, never an invented author', async () => {
const { user, dialog } = await startConflict(serverDraft(5, null))
expect(
await screen.findByRole('dialog', {
name: 'Une autre session a enregistré la révision 5',
}),
).toBeInTheDocument()
expect(dialog.queryByText(/par |depuis/)).toBeNull()
await user.click(dialog.getByRole('button', { name: 'Garder ma version' }))
expect(
dialog.getByText('Remplacer la révision 5 par votre version ?'),
).toBeInTheDocument()
})
it('reload asks first, then reloads the server draft and clears the dialog', async () => {
const { user, dialog } = await startConflict(serverDraft(5, 'other-user'))
await dialog.findByText(/Autre Praticien/)
serverHas(baseText(), 5)
await user.click(dialog.getByRole('button', { name: 'Recharger' }))
expect(
dialog.getByText(
'Abandonner vos modifications et recharger la révision 5 ?',
),
).toBeInTheDocument()
await user.click(dialog.getByRole('button', { name: 'Recharger' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(store.getState()).toMatchObject({ unsaved: false, savedRevision: 5 })
expect(await screen.findByText('Révision 5')).toBeInTheDocument()
})
it('Annuler leaves everything as it was', async () => {
const { user, dialog } = await startConflict(serverDraft(5, 'other-user'))
await dialog.findByText(/Autre Praticien/)
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(store.getState().unsaved).toBe(true)
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
})
})
describe('unknown revision (failed read)', () => {
const failed = () => Promise.reject(new SheetFailure('unavailable')) // a Read: built when called
it('no number, no author; keep disabled with its hint; reload and retry offered', async () => {
const { user, dialog } = await startConflict(failed)
expect(
await screen.findByRole('dialog', {
name: 'Une autre session a enregistré une version plus récente de ce brouillon.',
}),
).toBeInTheDocument()
expect(dialog.queryByText(/révision \d/)).toBeNull()
const keep = dialog.getByRole('button', { name: 'Garder ma version' })
expect(keep).toBeDisabled()
expect(keep).toHaveAccessibleDescription(
'Révision du serveur inconnue : rechargez ou réessayez.',
)
expect(dialog.getByRole('button', { name: 'Recharger' })).toBeEnabled()
// « Réessayer » repeats the read and reaches the known variant
sb.getOfficialSheetAdmin.mockResolvedValueOnce(
serverDraft(7, 'other-user') as never,
)
await user.click(dialog.getByRole('button', { name: 'Réessayer' }))
expect(
await screen.findByRole('dialog', {
name: 'Une autre session a enregistré la révision 7',
}),
).toBeInTheDocument()
})
it('reload names the server version without a number', async () => {
const { user, dialog } = await startConflict(failed)
await user.click(await dialog.findByRole('button', { name: 'Recharger' }))
expect(
dialog.getByText(
'Abandonner vos modifications et recharger la version du serveur ?',
),
).toBeInTheDocument()
})
})
describe('after the dialog is dismissed', () => {
it('the header keeps a notice that a newer version exists', async () => {
const { user, dialog } = await startConflict(() =>
Promise.reject(new SheetFailure('unavailable')),
)
await dialog.findByRole('button', { name: 'Garder ma version' })
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(
screen.getByText(
'Une autre session a enregistré une version plus récente de ce brouillon.',
),
).toBeInTheDocument()
})
})
@@ -0,0 +1,286 @@
/** Lot E: the blocking recovery offer, the unreadable copy, the cap and quota notice. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { fr } from '@/i18n/fr'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import {
SHEET,
USER,
VERSION,
baseText,
commitMove,
copyKeyOf,
resetStore,
sb,
serverHas,
storedCopy,
store,
} from '../helpers/editorHarness'
import { grant, mountDraft, 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 ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
function movedText(x: number): string {
return JSON.stringify(
JSON.parse(baseText(), (key, value) => (key === 'cx' ? x : value)),
)
}
function seed(
version: string,
revision: number,
text = movedText(10),
over = {},
) {
sessionStorage.setItem(
copyKeyOf(version, USER),
JSON.stringify({
v: 1,
user_id: USER,
version_id: version,
sheet_id: version === VERSION ? SHEET : `sheet-${version}`,
sheet_name: 'Autre fiche',
revision,
written_at: '2026-11-03T10:00:00Z',
document: JSON.parse(text),
drawings: [],
...over,
}),
)
}
describe('the blocking offer', () => {
it('names the copy and its answers; consultation works, editing is refused', async () => {
const user = userEvent.setup()
seed(VERSION, 3)
mountDraft()
await ready()
expect(
screen.getByText(
/Une copie locale temporaire de ce brouillon existe dans cet onglet \(révision 3, \d\d:\d\d\)/,
),
).toBeInTheDocument()
expect(
screen.getByText(/Choisissez avant de modifier le brouillon\./),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Restaurer la copie' }),
).toBeEnabled()
expect(
screen.getByRole('button', { name: 'Ignorer la copie' }),
).toBeEnabled()
expect(useLeaveGuardStore.getState().armed).toBe(true)
// consultation: tabs still switch
await user.click(screen.getByRole('tab', { name: 'Références' }))
expect(screen.getByTestId('editor-tab-references')).toHaveAttribute(
'aria-label',
'Références',
)
// editing: refused by the store, no save offered
expect(commitMove(40)).toMatchObject({
ok: false,
kind: 'recovery.pending',
})
expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull()
})
it('an older base adds the server revision to the notice', async () => {
seed(VERSION, 2)
mountDraft()
await ready()
expect(
screen.getByText(
/Elle est basée sur la révision 2 ; le serveur est à la révision 3\./,
),
).toBeInTheDocument()
})
it('restore applies the copy as unsaved work and lifts the block', async () => {
const user = userEvent.setup()
seed(VERSION, 3)
mountDraft()
await ready()
await user.click(screen.getByRole('button', { name: 'Restaurer la copie' }))
expect(
await screen.findByText('Révision 3 · modifications non enregistrées'),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Restaurer la copie' }),
).toBeNull()
expect(store.getState()).toMatchObject({ recovery: 'none', unsaved: true })
})
it('ignore asks first and keeps the copy until confirmed', async () => {
const user = userEvent.setup()
seed(VERSION, 3)
mountDraft()
await ready()
await user.click(screen.getByRole('button', { name: 'Ignorer la copie' }))
const dialog = within(await screen.findByRole('dialog'))
expect(
dialog.getByText(
/Abandonner la copie locale non enregistrée \(révision 3, \d\d:\d\d\) \? Elle sera supprimée de cet onglet\./,
),
).toBeInTheDocument()
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull()
await user.click(screen.getByRole('button', { name: 'Ignorer la copie' }))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Abandonner la copie',
}),
)
await waitFor(() => expect(sessionStorage.getItem(copyKeyOf())).toBeNull())
expect(
screen.queryByRole('button', { name: 'Ignorer la copie' }),
).toBeNull()
expect(useLeaveGuardStore.getState().armed).toBe(false)
expect(store.getState().recovery).toBe('none')
})
it('an unreadable copy: the loss named, « Ignorer » only, kept until ignored', async () => {
const user = userEvent.setup()
sessionStorage.setItem(copyKeyOf(), 'not json{')
mountDraft()
await ready()
expect(
screen.getByText(fr['editor.draft.recovery.unreadable']),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Restaurer la copie' }),
).toBeNull()
expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' })
expect(sessionStorage.getItem(copyKeyOf())).toBe('not json{')
await user.click(screen.getByRole('button', { name: 'Ignorer la copie' }))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Abandonner la copie',
}),
)
await waitFor(() => expect(sessionStorage.getItem(copyKeyOf())).toBeNull())
})
it('a copy the core refuses is kept: its kind shown, restore disabled', async () => {
const broken = JSON.parse(baseText())
broken.views = 'broken'
seed(VERSION, 3, JSON.stringify(broken))
const user = userEvent.setup()
mountDraft()
await ready()
await user.click(screen.getByRole('button', { name: 'Restaurer la copie' }))
expect(
await screen.findByText(
/La copie locale ne passe pas le contrôle du document : .+\. Elle est conservée\./,
),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Restaurer la copie' }),
).toBeDisabled()
expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull()
})
it('narrow screen: the offer shows; a mode that cannot save names the copy and leaves it', async () => {
seed(VERSION, 3)
mountDraft({ width: 800 })
await ready()
expect(
screen.getByRole('button', { name: 'Restaurer la copie' }),
).toBeInTheDocument()
cleanup()
resetStore()
serverHas(baseText(), 3)
seed(VERSION, 3)
const raw = sessionStorage.getItem(copyKeyOf())
mountDraft({ grants: [grant('sheet_reviewer')] })
await ready()
expect(
screen.queryByRole('button', { name: 'Restaurer la copie' }),
).toBeNull()
expect(
screen.getByText(fr['editor.draft.mode.unusable_copy']),
).toBeInTheDocument()
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
})
})
describe('cap and quota', () => {
it('cap: the header says so, the other copies are listed with their sheet link; abandon retries the write', async () => {
const user = userEvent.setup()
seed('ver-2', 5)
seed('ver-3', 6)
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText(fr['editor.draft.status.copy_cap']),
).toBeInTheDocument()
expect(storedCopy()).toBeNull()
const items = screen.getAllByRole('listitem')
expect(items).toHaveLength(2)
expect(
within(items[0]).getByText(/Autre fiche · révision 5 · \d\d:\d\d/),
).toBeInTheDocument()
expect(
within(items[0]).getByRole('link', { name: 'Ouvrir ce brouillon' }),
).toHaveAttribute('href', '/app/admin/sheets/sheet-ver-2/draft')
await user.click(
within(items[0]).getByRole('button', { name: 'Abandonner cette copie' }),
)
const dialog = within(await screen.findByRole('dialog'))
expect(dialog.getByText(/révision 5/)).toBeInTheDocument()
await user.click(
dialog.getByRole('button', { name: 'Abandonner la copie' }),
)
await waitFor(() => expect(storedCopy()).not.toBeNull())
expect(sessionStorage.getItem(copyKeyOf('ver-2'))).toBeNull()
expect(sessionStorage.getItem(copyKeyOf('ver-3'))).not.toBeNull()
expect(screen.queryByText(fr['editor.draft.status.copy_cap'])).toBeNull()
})
it('quota: the full-storage status and notice, the other copies untouched', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText('Copie locale impossible (stockage plein)'),
).toBeInTheDocument()
expect(
screen.getByText(fr['editor.draft.copy_issue.quota']),
).toBeInTheDocument()
expect(store.getState().copyWritten).toBe(false)
})
})
describe('the save stays disabled while the offer is pending', () => {
it('no save call is made', async () => {
seed(VERSION, 3)
mountDraft()
await ready()
await store.getState().save()
expect(sb.saveSheetDraft).not.toHaveBeenCalled()
})
})
+394
View File
@@ -0,0 +1,394 @@
/** Lot E: the draft route, header, tabs, modes and permission states, leave guard. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { fr } from '@/i18n/fr'
import {
VERSION,
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 ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const TABS = [
'Général',
'Vues et illustrations',
'Annotations',
'Constats',
'Références',
'Vertèbres',
'Vérification',
]
describe('edit mode', () => {
it('header, badges, the seven tabs, nothing read-only', async () => {
mountDraft()
await ready()
expect(screen.getByText('Brouillon')).toBeInTheDocument()
expect(screen.getByText('Copie de travail')).toBeInTheDocument()
expect(screen.getByRole('status', { name: '' })).toBeDefined()
expect(screen.getByText('Révision 3')).toBeInTheDocument()
const tabs = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(tabs.map((tab) => tab.textContent)).toEqual(TABS)
expect(screen.getByRole('tab', { name: 'Annotations' })).toHaveAttribute(
'aria-selected',
'true',
)
expect(screen.queryByText('Lecture seule')).toBeNull()
expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
expect(store.getState()).toMatchObject({
canEdit: true,
versionId: VERSION,
})
})
it('opens the draft read for this version only and closes the session on leaving', async () => {
const view = mountDraft()
await ready()
expect(sb.getSheetVersion).toHaveBeenCalledWith(expect.anything(), VERSION)
view.unmount()
expect(store.getState().status).toBe('idle')
})
it('a commit shows the unsaved line; Enregistrer saves against the loaded revision', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText('Révision 3 · modifications non enregistrées'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(await screen.findByText('Révision 4')).toBeInTheDocument()
expect(sb.saveSheetDraft).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ version_id: VERSION, expected_revision: 3 }),
)
expect(storedCopy()).toBeNull()
})
it('« Annuler les modifications » asks first, then reloads the server draft', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(
await screen.findByRole('button', { name: 'Annuler les modifications' }),
)
const dialog = within(await screen.findByRole('dialog'))
expect(dialog.getByText(fr['editor.draft.discard_ask'])).toBeInTheDocument()
await user.click(
dialog.getByRole('button', { name: 'Abandonner les modifications' }),
)
await waitFor(() => expect(store.getState().unsaved).toBe(false))
expect(await screen.findByText('Révision 3')).toBeInTheDocument()
})
})
describe('tabs', () => {
it('arrow keys move between the shown tabs, only the active body is mounted', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
expect(screen.getByTestId('editor-tab-annotations')).toBeInTheDocument()
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
await user.keyboard('{ArrowRight}')
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
expect(screen.getByTestId('editor-tab-findings')).toBeInTheDocument()
expect(screen.queryByTestId('editor-tab-annotations')).toBeNull()
expect(screen.getByRole('tabpanel')).toHaveAccessibleName('Constats')
})
it('640 to 1 023 px: four tabs and « Plus »; the others sit under the disclosure', async () => {
const user = userEvent.setup()
mountDraft({ width: 800 })
await ready()
const shown = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(shown.map((tab) => tab.textContent)).toEqual([
'Général',
'Annotations',
'Constats',
'Vérification',
])
const more = screen.getByRole('button', { name: 'Plus' })
expect(more).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByRole('button', { name: 'Références' })).toBeNull()
await user.click(more)
expect(more).toHaveAttribute('aria-expanded', 'true')
await user.click(screen.getByRole('button', { name: 'Références' }))
expect(screen.getByTestId('editor-tab-references')).toBeInTheDocument()
expect(more).toHaveAttribute('aria-expanded', 'false')
})
it('below 640 px: two tabs and « Plus » listing the five others', async () => {
const user = userEvent.setup()
mountDraft({ width: 375 })
await ready()
const shown = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(shown.map((tab) => tab.textContent)).toEqual([
'Annotations',
'Vérification',
])
await user.click(screen.getByRole('button', { name: 'Plus' }))
const rest = within(screen.getByRole('list')).getAllByRole('button')
expect(rest.map((b) => b.textContent)).toEqual([
'Général',
'Vues et illustrations',
'Constats',
'Références',
'Vertèbres',
])
})
})
describe('read-only modes', () => {
it('narrow: the L15 notice alone, the lock badge, no save, tabs readable, copy offered', async () => {
mountDraft({ width: 800 })
await ready()
expect(
screen.getByText(
"L'édition nécessite une largeur d'écran d'au moins 1 024 px.",
),
).toBeInTheDocument()
expect(screen.getByText('Lecture seule')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Enregistrer' })).toBeNull()
expect(screen.queryByText(/Ici, consultation seule/)).toBeNull()
})
it('a width switch keeps the unsaved work and the leave guard', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
act(() => {
setWidth(800)
window.dispatchEvent(new Event('resize'))
})
expect(await screen.findByText('Lecture seule')).toBeInTheDocument()
expect(store.getState().unsaved).toBe(true)
expect(useLeaveGuardStore.getState().armed).toBe(true)
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(
await screen.findByRole('button', { name: 'Enregistrer' }),
).toBeEnabled()
expect(store.getState().unsaved).toBe(true)
})
it('rights: a reviewer without the editor capability reads the draft', async () => {
mountDraft({ grants: [grant('sheet_reviewer')] })
await ready()
expect(screen.getByText(fr['editor.draft.mode.rights'])).toBeInTheDocument()
expect(screen.getByText('Lecture seule')).toBeInTheDocument()
expect(store.getState().canEdit).toBe(false)
})
it('rights: the editor capability without the admin or owner role is read-only', async () => {
mountDraft({ roles: [] })
await ready()
expect(screen.getByText(fr['editor.draft.mode.rights'])).toBeInTheDocument()
})
it('frozen: the round, its label and the link to the overview', async () => {
mountDraft({ answer: adminAnswer({ rounds: [round('verifying')] }) })
await ready()
expect(
screen.getByText('Revue n° 1 · vérification en cours'),
).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Voir la fiche' })).toHaveAttribute(
'href',
expect.stringMatching(/\/app\/admin\/sheets\/[^/]+$/),
)
})
it('frozen by an open round: the round status label', async () => {
mountDraft({
answer: adminAnswer({ rounds: [round('open', { round: 2 })] }),
})
await ready()
expect(screen.getByText('Revue n° 2 · À relire')).toBeInTheDocument()
})
it('a round that no longer freezes (changes requested) leaves the draft editable', async () => {
mountDraft({
answer: adminAnswer({ rounds: [round('changes_requested')] }),
})
await ready()
expect(screen.queryByText('Lecture seule')).toBeNull()
})
it('historical and inactive sheets', async () => {
mountDraft({ answer: adminAnswer({ historical: true }) })
await ready()
expect(
screen.getByText(fr['editor.draft.mode.historical']),
).toBeInTheDocument()
cleanup()
resetStore()
serverHas(baseText(), 3)
mountDraft({ answer: adminAnswer({ status: 'archived' }) })
await ready()
expect(
screen.getByText(fr['editor.draft.mode.inactive']),
).toBeInTheDocument()
})
})
describe('permission states', () => {
it('own grants loading: waits, reads nothing of the draft', async () => {
mountDraft({ grantsStatus: 'loading' })
expect(screen.getByText(fr['shell.loading_session'])).toHaveAttribute(
'role',
'status',
)
await act(async () => {})
expect(sb.getSheetVersion).not.toHaveBeenCalled()
})
it('a rights refusal of the admin read: « Accès non autorisé »', async () => {
mountDraft({ adminFailure: 'rights.capability' })
expect(
await screen.findByRole('heading', { name: fr['access_denied.title'] }),
).toBeInTheDocument()
})
it('own grants unreadable: the unavailable notice with its retry', async () => {
const reloadAccess = vi.fn(async () =>
useAuthStore.setState({ catalogGrantsStatus: 'ready' }),
)
mountDraft({ grantsStatus: 'failed' })
act(() => useAuthStore.setState({ reloadAccess }))
await act(async () => {})
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Réessayer' }))
expect(reloadAccess).toHaveBeenCalled()
await ready()
})
it('an unknown sheet: the not found page', async () => {
mountDraft({ adminFailure: 'not_found' })
expect(
await screen.findByRole('heading', {
name: fr['admin.overview.not_found_title'],
}),
).toBeInTheDocument()
})
it('no draft: a notice and the link to the overview', async () => {
mountDraft({ answer: adminAnswer({ draft_version: null }) })
expect(await screen.findByText(fr['editor.draft.none'])).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'Voir la fiche' }),
).toBeInTheDocument()
expect(sb.getSheetVersion).not.toHaveBeenCalled()
})
})
describe('leave guard', () => {
it('armed from the store flag while unsaved, disarmed once saved', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
expect(useLeaveGuardStore.getState().armed).toBe(false)
act(() => void commitMove(40))
await waitFor(() => expect(useLeaveGuardStore.getState().armed).toBe(true))
const event = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(event)
expect(event.defaultPrevented).toBe(true)
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() => expect(useLeaveGuardStore.getState().armed).toBe(false))
const after = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(after)
expect(after.defaultPrevented).toBe(false)
})
it('leaving the page disarms it', async () => {
const view = mountDraft()
await ready()
act(() => void commitMove(40))
await waitFor(() => expect(useLeaveGuardStore.getState().armed).toBe(true))
view.unmount()
expect(useLeaveGuardStore.getState().armed).toBe(false)
})
})
describe('permission lost during the session', () => {
async function refusedSave(
kind: ConstructorParameters<typeof SheetFailure>[0],
) {
const user = userEvent.setup()
sb.saveSheetDraft.mockRejectedValue(new SheetFailure(kind))
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(await screen.findByRole('button', { name: 'Enregistrer' }))
}
it('draft.frozen: the message promises a copy only because it was written; read-only follows', async () => {
await refusedSave('draft.frozen')
expect(
await screen.findByText(/Une revue est en cours sur ce brouillon/),
).toHaveTextContent('Une copie locale temporaire existe dans cet onglet.')
expect(screen.getByText('Lecture seule')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Enregistrer' })).toBeNull()
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
})
it('session lost with a failed copy write: the changes cannot be kept', async () => {
const user = userEvent.setup()
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('session_expired'))
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText('Copie locale impossible (stockage plein)'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
const notice = await screen.findByText(/Votre session a expiré/)
expect(notice).toHaveTextContent(fr['editor.draft.copy_not_kept'])
expect(notice).not.toHaveTextContent(fr['editor.draft.copy_kept'])
})
})
+23 -2
View File
@@ -159,6 +159,7 @@ function mount(
<Route path="sheets" element={<AdminSheetsRoute />} />
<Route path="sheets/new" element={<AdminSheetCreateRoute />} />
<Route path="sheets/:sheetId" element={<AdminSheetRoute />} />
<Route path="sheets/:sheetId/draft" element={<p>draft page</p>} />
<Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} />
</Route>
@@ -782,7 +783,7 @@ describe('Sheet creation (A1)', () => {
await waitFor(() =>
expect(screen.getByTestId('where')).toHaveTextContent(
`/app/admin/sheets/${NEW_ID}`,
`/app/admin/sheets/${NEW_ID}/draft`,
),
)
const [args] = rpcArgs('create_official_sheet')
@@ -916,6 +917,26 @@ describe('Sheet overview (H3)', () => {
).toBeNull()
})
it('links to the draft: « Ouvrir » for an editor with the admin role, « Consulter » otherwise', async () => {
fake.rpcResults.get_official_sheet_admin = { data: overview() }
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')], ['admin'])
const open = await screen.findByRole('link', { name: 'Ouvrir le brouillon' })
expect(open).toHaveAttribute('href', `/app/admin/sheets/${SHEET}/draft`)
cleanup()
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_reviewer')])
const view = await screen.findByRole('link', { name: 'Consulter le brouillon' })
expect(view).toHaveAttribute('href', `/app/admin/sheets/${SHEET}/draft`)
})
it('links nothing without a draft', async () => {
fake.rpcResults.get_official_sheet_admin = {
data: overview({ draft_version: null }),
}
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')], ['admin'])
await screen.findByRole('heading', { level: 1 })
expect(screen.queryByRole('link', { name: /brouillon/ })).toBeNull()
})
it('historical sheet: the working copy action disabled while a copy is active', async () => {
fake.rpcResults.get_official_sheet_admin = {
data: {
@@ -965,7 +986,7 @@ describe('Sheet overview (H3)', () => {
await user.click(dialog.getByRole('button', { name: 'Créer la copie' }))
await waitFor(() =>
expect(screen.getByTestId('where')).toHaveTextContent(
`/app/admin/sheets/${NEW_ID}`,
`/app/admin/sheets/${NEW_ID}/draft`,
),
)
expect(rpcArgs('create_sheet_working_copy')).toEqual([
@@ -41,6 +41,8 @@ function mount(path = '/app') {
<Route path="/app" element={<AppLayout />}>
<Route index element={<p>dashboard page</p>} />
<Route path="account" element={<p>account page</p>} />
<Route path="admin/sheets/:sheetId/draft" element={<p>draft page</p>} />
<Route path="admin/sheets/:sheetId" element={<p>overview page</p>} />
</Route>
</Routes>
</MemoryRouter>,
@@ -58,6 +60,18 @@ describe('AppLayout', () => {
expect(screen.getByText('dashboard page')).toBeInTheDocument()
})
it('gives the draft editor the whole width, every other page the 4xl column', () => {
const column = (path: string) => {
const view = mount(path)
const wrapper = screen.getByText(/page$/).parentElement
view.unmount()
return wrapper
}
expect(column('/app/admin/sheets/s-1/draft')).not.toHaveClass('max-w-4xl')
expect(column('/app/admin/sheets/s-1')).toHaveClass('max-w-4xl')
expect(column('/app')).toHaveClass('max-w-4xl')
})
it('links the top-bar avatar and name to the account page', async () => {
const user = userEvent.setup()
mount()