Files
faunosteo/apps/app/tests/unit/editor-citations-edit.test.tsx
T

1091 lines
40 KiB
TypeScript

/** Rev 5 Task 12: the references dialog's edit mode (draft, save, guards, stacked dialogs). */
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 type { Location, NavigateFunction } from 'react-router-dom'
import CitationsEditForm from '@/components/editor/references/CitationsEditForm'
import { flushAfterModals } from '@/components/ui/afterModalsClosed'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import {
forgetSessionTag,
resolveSessionTag,
} from '@/editor/history/sessionTag'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
serverHas,
SHEET,
store,
USER,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import {
findingDialog,
inFindingDialog,
openFinding,
} from '../helpers/findingDialog'
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(),
}))
/** Ids handed out before the real generator: a clash at the save (Rev 6). */
const minted = vi.hoisted((): string[] => [])
vi.mock('@/editor/ids', async (orig) => {
const real = await orig<typeof import('@/editor/ids')>()
return {
...real,
newElementId: (prefix: Parameters<typeof real.newElementId>[0]) =>
minted.shift() ?? real.newElementId(prefix),
}
})
let navigate: NavigateFunction
let location: Location
const probe = (n: NavigateFunction, l: Location) => {
navigate = n
location = l
}
const written = () =>
(location.state as Record<string, HistoryEntry> | null)?.[ENTRY_KEY]
let TAG: string
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
TAG = resolveSessionTag(USER)
})
afterEach(() => {
minted.length = 0
cleanup()
resetStore()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string) =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: null, doi: null },
}) as const
/** Barone (ref-a), Denoix (ref-b), Code rural (ref-c); Node A cites `ids`. */
function sheetText(ids = ['ref-a', 'ref-c']): string {
let text = baseText()
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
text = insert(text, ref('ref-b', 'Denoix'))
text = insert(text, ref('ref-c', 'Code rural'))
text = insert(text, {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
text = edit(text, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: name('Cat A'),
description: {},
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
return edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
element: {
kind: 'finding_node',
value: {
id: 'fnode-a',
name: name('Node A'),
description: {},
reference_ids: ids,
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
}
const nodeKey = {
kind: 'finding' as const,
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
}
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280, text = sheetText()): Promise<User> {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft({ width, probe })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
return user
}
const doc = () => JSON.parse(store.getState().documentText)
const nodeA = () =>
doc().finding_zones[0].categories[0].children[0] as {
name: { fr: string }
reference_ids: string[]
}
const library = () =>
(doc().references as { id: string; citation: string }[]).map(
(r) => r.citation,
)
const undos = () => store.getState().undo.length
const back = (steps = 1) => act(async () => navigate(-steps))
const question = 'Abandonner les modifications ?'
const openDialogs = () => [
...document.querySelectorAll<HTMLElement>('dialog[open][data-layer]'),
]
const citations = () =>
openDialogs().find((d) => d.querySelector('[data-place="citations"]'))
const inCitations = () => within(citations()!)
const referenceDialog = () =>
openDialogs().find((d) => d.querySelector('#reference-form-citation'))
const inReference = () => within(referenceDialog()!)
const button = (label: string | RegExp) =>
inCitations().getByRole('button', { name: label })
const rows = () =>
[...citations()!.querySelectorAll('[data-citation-row]')].map((row) =>
row.getAttribute('data-citation-row'),
)
/** Node A's dialog, then its references dialog. */
async function openCitations(user: User, trigger = '2 références') {
await openFinding(user, /Node A/)
await user.click(inFindingDialog().getByRole('button', { name: trigger }))
await waitFor(() => expect(citations()).toBeDefined())
}
/** The references dialog of Node A, in its edit mode. */
async function editCitations(user: User, trigger?: string) {
await openCitations(user, trigger)
await user.click(button('Modifier'))
await waitFor(() =>
expect(
inCitations().getByRole('heading', {
name: 'Modifier les références du constat',
}),
).toBeVisible(),
)
}
const removeRow = (user: User, citation: RegExp) =>
user.click(
inCitations().getByRole('button', {
name: new RegExp(`^Retirer ${citation.source}`),
}),
)
const select = () =>
inCitations().getByLabelText('Citer une référence existante')
/** Rev 6: a choice in the select, then « Citer ». */
async function cite(user: User, id: string) {
await user.selectOptions(select(), id)
await user.click(button('Citer'))
}
/** The reference dialog over the edit mode: type and citation, then « Ajouter la référence ». */
async function createPending(user: User, citation: string) {
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), citation)
await user.click(
inReference().getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
}
const pendingRow = () =>
[...citations()!.querySelectorAll<HTMLElement>('[data-citation-row]')][2]
const status = () =>
citations()!.querySelector('[data-place="citations"] > [role="status"]')!
.textContent
const live = () =>
document.querySelector('p.sr-only[aria-live="polite"]')!.textContent ?? ''
describe('the « Modifier » of the references dialog', () => {
it('edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => {
const user = await mount()
await openCitations(user)
const before = written()!.id
await user.click(button('Modifier'))
expect(written()!.id).toBe(before)
expect(rows()).toEqual(['ref-a', 'ref-c'])
expect(
inCitations().queryByRole('button', { name: /Tout afficher/ }),
).toBeNull()
expect(inCitations().queryByRole('button', { name: 'Aller à' })).toBeNull()
})
it('puts the focus on the first control of the draft', async () => {
const user = await mount()
await editCitations(user)
const active = document.activeElement
expect(active).not.toBe(document.body)
expect(active?.closest('form[data-draft-form]')).not.toBeNull()
})
it('is not offered read only (below 1 024 px)', async () => {
const user = await mount(900)
await openCitations(user)
expect(inCitations().queryByRole('button', { name: 'Modifier' })).toBeNull()
})
})
describe('the draft', () => {
it('stages a removal and a citation, writes nothing until « Enregistrer »', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await cite(user, 'ref-b')
expect(rows()).toEqual(['ref-c', 'ref-b'])
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(undos()).toBe(0)
})
it('one save is one update, one undo; back to the view mode, focus on « Modifier »', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await cite(user, 'ref-b')
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b'])
expect(undos()).toBe(1)
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(
inCitations().getByText('Modifications enregistrées'),
).toBeInTheDocument()
act(() => {
store.getState().undoStep()
})
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
it('a pristine save writes nothing', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Enregistrer'))
expect(undos()).toBe(0)
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(inCitations().queryByText('Modifications enregistrées')).toBeNull()
})
it('the draft list is named; an empty draft shows no list', async () => {
const user = await mount(1280, sheetText([]))
await editCitations(user, '0 référence')
expect(inCitations().queryByRole('list')).toBeNull()
expect(inCitations().getByText('Aucune référence citée.')).toBeVisible()
await cite(user, 'ref-b')
expect(
inCitations().getByRole('list', { name: 'Références citées' }),
).toBeVisible()
})
it('a dangling id is named and removable', async () => {
const user = await mount(1280, sheetText(['ref-a', 'ref-x']))
await editCitations(user)
expect(inCitations().getByText(/^Référence introuvable/)).toBeVisible()
await removeRow(user, /ref-x/)
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-a'])
})
it('a save applies the draft to the current list (changes made elsewhere stay)', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
const node = doc().finding_zones[0].categories[0].children[0]
store.getState().commit({
op: 'update',
key: nodeKey,
element: {
kind: 'finding_node',
value: { ...node, reference_ids: ['ref-a', 'ref-c', 'ref-b'] },
},
})
})
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b'])
})
})
describe('« Citer » (Rev 6)', () => {
const citeButton = () => button('Citer')
const pendingLine =
'Référence choisie mais pas encore citée : choisissez « Citer » ou revenez au choix vide.'
it('a choice or an arrow key leaves the draft clean: ✕ closes without a question', async () => {
const user = await mount()
await editCitations(user)
expect(citeButton()).toBeDisabled()
await user.selectOptions(select(), 'ref-b')
// happy-dom moves nothing on a key: this covers the change event only. The real
// ArrowDown is proven in Chromium (e2e/shell/editor-citations.spec.ts, keyboard test).
fireEvent.keyDown(select(), { key: 'ArrowDown' })
fireEvent.change(select(), { target: { value: 'ref-b' } })
expect(rows()).toEqual(['ref-a', 'ref-c'])
expect(citeButton()).toBeEnabled()
await user.click(button('Fermer'))
await waitFor(() => expect(citations()).toBeUndefined())
expect(undos()).toBe(0)
})
it('« Citer » cites once, resets and focuses the select, stays in edit mode', async () => {
const user = await mount()
await editCitations(user)
await user.selectOptions(select(), 'ref-b')
expect(citeButton()).toHaveAttribute('type', 'button')
await user.click(citeButton())
expect(rows()).toEqual(['ref-a', 'ref-c', 'ref-b'])
expect(select()).toHaveValue('')
expect(select()).toHaveFocus()
expect(citeButton()).toBeDisabled()
await user.click(citeButton())
expect(rows()).toEqual(['ref-a', 'ref-c', 'ref-b'])
expect(
inCitations().getByRole('heading', {
name: 'Modifier les références du constat',
}),
).toBeVisible()
expect(undos()).toBe(0)
})
it('a choice no longer offered goes back to the placeholder', async () => {
const user = await mount()
await editCitations(user)
await user.selectOptions(select(), 'ref-b')
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'reference', id: 'ref-b' },
})
})
await waitFor(() => expect(select()).toHaveValue(''))
expect(citeButton()).toBeDisabled()
})
it('a vanished choice stays reset when its reference comes back by an undo', async () => {
const user = await mount()
await editCitations(user)
await user.selectOptions(select(), 'ref-b')
await user.click(button('Enregistrer'))
expect(inCitations().getByRole('alert')).toBeInTheDocument()
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'reference', id: 'ref-b' },
})
})
await waitFor(() => expect(select()).toHaveValue(''))
act(() => {
store.getState().undoStep()
})
await waitFor(() =>
expect(
inCitations().getByRole('option', { name: 'Denoix' }),
).toBeInTheDocument(),
)
expect(select()).toHaveValue('')
expect(citeButton()).toBeDisabled()
expect(inCitations().queryByRole('alert')).toBeNull()
})
it('« Enregistrer » with a choice not cited refuses: the line, focus on « Citer »', async () => {
const user = await mount()
await editCitations(user)
await user.selectOptions(select(), 'ref-b')
await user.click(button('Enregistrer'))
expect(undos()).toBe(0)
expect(inCitations().getByRole('alert')).toHaveTextContent(pendingLine)
expect(citeButton()).toHaveFocus()
expect(
inCitations().getByRole('heading', {
name: 'Modifier les références du constat',
}),
).toBeVisible()
await user.selectOptions(select(), '')
expect(inCitations().queryByText(pendingLine)).toBeNull()
await user.click(button('Enregistrer'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(undos()).toBe(0)
})
it('read only: no select and no « Citer »', async () => {
const user = await mount()
await editCitations(user)
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(inCitations().queryByRole('button', { name: 'Citer' })).toBeNull()
expect(
inCitations().queryByLabelText('Citer une référence existante'),
).toBeNull()
})
})
describe('leaving the edit mode with changes', () => {
it('an explicit « Abandonner » after ✕ closes the dialog without a word', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await user.click(button('Fermer'))
await user.click(button('Abandonner'))
await waitFor(() => expect(citations()).toBeUndefined())
await user.click(inFindingDialog().getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(findingDialog()).toBeNull())
await act(async () => undefined)
expect(live()).not.toContain('Saisie abandonnée')
})
it('a system close of the draft (the finding vanished) says it was dropped', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
store.getState().commit({ op: 'remove', key: nodeKey })
})
await waitFor(() => expect(citations()).toBeUndefined())
await waitFor(() => expect(live()).toContain('Saisie abandonnée'))
})
it('« Annuler » asks; « Abandonner » goes back to the view, nothing written', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await user.click(button('Annuler'))
expect(inCitations().getByText(question)).toBeVisible()
await user.click(button('Abandonner'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(citations()).toBeDefined()
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
it('« Annuler » without changes goes back at once', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Annuler'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
})
it('Escape and ✕ ask; the dialog stays', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await user.click(button('Fermer'))
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
await user.click(button('Continuer la saisie'))
act(() => button('Annuler').focus())
await user.keyboard('{Escape}')
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
})
it('a Back that closes only the references dialog asks; the draft stays', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await back()
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
expect(rows()).toEqual(['ref-c'])
expect(written()!.view.finding).toMatchObject({ citations: true })
})
it('a flip to read only keeps the draft, every control off, only « Abandonner »', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(rows()).toEqual(['ref-c'])
expect(inCitations().getByText(/Élargissez la fenêtre/)).toBeVisible()
expect(button('Enregistrer')).toBeDisabled()
expect(button(/^Retirer/)).toBeDisabled()
expect(button(/^Modifier la référence/)).toBeDisabled()
expect(button('Nouvelle référence')).toBeDisabled()
expect(
inCitations().queryByLabelText('Citer une référence existante'),
).toBeNull()
expect(inCitations().queryByRole('button', { name: 'Annuler' })).toBeNull()
await user.click(button('Abandonner'))
await waitFor(() =>
expect(
inCitations().getByRole('heading', { name: 'Références du constat' }),
).toBeVisible(),
)
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
})
describe('the reference dialog over the edit mode', () => {
it('« Modifier la référence » stacks it; closed, the draft and the focus are back', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Code rural/)
const opener = button(/^Modifier la référence Barone/)
await user.click(opener)
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(openDialogs()).toHaveLength(3)
expect(
inReference().getByRole('heading', { name: 'Modifier la référence' }),
).toBeVisible()
await user.click(inReference().getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(referenceDialog()).toBeUndefined())
await waitFor(() => expect(opener).toHaveFocus())
expect(rows()).toEqual(['ref-a'])
})
it('« Nouvelle référence » cites it in the draft only; the library is unchanged', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
await createPending(user, 'Neuf')
expect(library()).not.toContain('Neuf')
expect(rows()).toHaveLength(3)
expect(rows().slice(0, 2)).toEqual(['ref-a', 'ref-c'])
const row = pendingRow()
expect(within(row).getByText('Neuf')).toBeVisible()
expect(within(row).getByText('Nouvelle')).toBeVisible()
await waitFor(() =>
expect(status()).toBe(
'Nouvelle référence citée dans le brouillon : Neuf. ' +
'Elle sera enregistrée avec les citations.',
),
)
expect(live()).not.toContain('sera enregistrée')
expect(undos()).toBe(0)
})
it('« Enregistrer » writes the reference and the citations as ONE undo step', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
await user.click(button('Enregistrer'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
const id = doc().references.find(
(r: { citation: string }) => r.citation === 'Neuf',
).id
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', id])
expect(undos()).toBe(1)
act(() => {
store.getState().undoStep()
})
expect(library()).not.toContain('Neuf')
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
act(() => {
store.getState().redoStep()
})
expect(library()).toContain('Neuf')
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', id])
})
it('created, then the draft abandoned: library unchanged, nothing said', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
await user.click(button('Annuler'))
await user.click(button('Abandonner'))
expect(library()).not.toContain('Neuf')
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(undos()).toBe(0)
await user.click(button('Fermer'))
await waitFor(() => expect(citations()).toBeUndefined())
await user.click(inFindingDialog().getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(findingDialog()).toBeNull())
await act(async () => undefined)
expect(live()).not.toContain('sera enregistrée')
})
it('a pending reference is modified, prefilled; nothing is written', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
const pendingId = rows()[2]
await user.click(button(/^Modifier la référence Neuf/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(
inReference().getByRole('heading', { name: 'Nouvelle référence' }),
).toBeVisible()
const citation = inReference().getByLabelText('Citation')
expect(citation).toHaveValue('Neuf')
await user.type(citation, ' 2')
await user.click(inReference().getByRole('button', { name: 'Valider' }))
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(rows()).toEqual(['ref-a', 'ref-c', pendingId])
expect(within(pendingRow()).getByText('Neuf 2')).toBeVisible()
await waitFor(() =>
expect(status()).toBe('Nouvelle référence modifiée : Neuf 2'),
)
expect(library()).not.toContain('Neuf 2')
await user.click(button('Enregistrer'))
expect(library().filter((c) => c.startsWith('Neuf'))).toEqual(['Neuf 2'])
expect(undos()).toBe(1)
})
it('« Retirer » drops a pending reference entirely and says so in the dialog', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
await removeRow(user, /Neuf/)
expect(rows()).toEqual(['ref-a', 'ref-c'])
expect(status()).toBe('Nouvelle référence retirée : Neuf')
await user.click(button('Annuler'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(library()).not.toContain('Neuf')
expect(undos()).toBe(0)
})
it('a double submit of the creation makes one pending row', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
const form = referenceDialog()!.querySelector('form')!
act(() => {
fireEvent.submit(form)
fireEvent.submit(form)
})
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(rows()).toHaveLength(3)
})
it('the creation is dry-run: a refusal shows in its form, nothing cited', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
minted.push('ref-a')
await user.click(
inReference().getByRole('button', { name: 'Ajouter la référence' }),
)
expect(inReference().getByRole('alert')).toBeVisible()
expect(referenceDialog()).toBeDefined()
expect(rows()).toEqual(['ref-a', 'ref-c'])
expect(undos()).toBe(0)
})
it('a clashing id at the save is minted again once', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
minted.push('ref-a')
await user.click(button('Enregistrer'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
const added = doc().references.find(
(r: { citation: string }) => r.citation === 'Neuf',
)
expect(added.id).not.toBe('ref-a')
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', added.id])
expect(undos()).toBe(1)
})
it('a save refused twice keeps the draft and names the pending reference', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
minted.push('ref-a', 'ref-c')
await user.click(button('Enregistrer'))
const alert = inCitations().getByRole('alert')
expect(alert).toHaveTextContent(/Neuf/)
expect(rows()).toHaveLength(3)
expect(library()).not.toContain('Neuf')
expect(undos()).toBe(0)
})
it('a refused save names several pending references as a list of the locale', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
await user.click(button('Nouvelle référence'))
await createPending(user, 'Vieux')
minted.push('ref-a', 'ref-c', 'ref-a', 'ref-c')
await user.click(button('Enregistrer'))
const alert = inCitations().getByRole('alert')
expect(alert).toHaveTextContent('Neuf et Vieux')
expect(alert).not.toHaveTextContent(';')
})
it('the creation notice is set once the reference dialog is gone, never under it', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
const seen: string[] = []
const observer = new MutationObserver(() => {
if (referenceDialog()) seen.push(status() ?? '')
})
observer.observe(document.body, {
subtree: true,
childList: true,
characterData: true,
})
await user.click(
inReference().getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
await waitFor(() => expect(status()).toContain('Neuf'))
observer.disconnect()
expect(seen.filter((text) => text !== '')).toEqual([])
})
it('a notice still waiting when the edit mode ends is dropped, not shown later', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
// The focus never comes back into the dialog: the notice keeps waiting.
const focus = vi
.spyOn(HTMLElement.prototype, 'focus')
.mockImplementation(() => undefined)
await user.click(
inReference().getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(status()).toBe('')
fireEvent.click(button('Enregistrer'))
await waitFor(() => expect(button('Modifier')).toBeVisible())
focus.mockRestore()
fireEvent.click(button('Modifier'))
await waitFor(() =>
expect(
document.activeElement?.closest('form[data-draft-form]'),
).not.toBeNull(),
)
expect(status()).not.toContain('Nouvelle référence')
})
it('the draft notice goes with the next draft action: cite, remove, new', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'Neuf')
await waitFor(() => expect(status()).toContain('Neuf'))
await cite(user, 'ref-b')
expect(status()).toBe('')
await user.click(button('Nouvelle référence'))
await createPending(user, 'Vieux')
await waitFor(() => expect(status()).toContain('Vieux'))
await removeRow(user, /Code rural/)
expect(status()).toBe('')
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(status()).toBe('')
})
it('a citation holding « $& » reaches every notice as typed', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await createPending(user, 'A$&B')
await waitFor(() => expect(status()).toContain('A$&B'))
expect(status()).not.toContain('{citation}')
minted.push('ref-a', 'ref-c')
await user.click(button('Enregistrer'))
expect(inCitations().getByRole('alert')).toHaveTextContent('A$&B')
expect(inCitations().getByRole('alert')).not.toHaveTextContent('{citation}')
await removeRow(user, /A\$&B/)
expect(status()).toContain('A$&B')
expect(status()).not.toContain('{citation}')
})
})
describe('a save of the edit form when its element is unreadable', () => {
it('is a refusal on the save line: the draft stays, nothing written', async () => {
await openReady({ text: sheetText() })
const pending = {
id: 'ref-p',
type: 'book',
citation: 'Neuf',
doi: null,
url: null,
} as const
const start = vi.fn(
(_opener: unknown, cite?: (value: typeof pending) => void) =>
cite?.(pending),
)
const guards = {
register: vi.fn(),
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
holdLeave: vi.fn(),
takeLeave: () => null,
}
const onDone = vi.fn()
const user = userEvent.setup()
render(
<CitationsEditForm
citedBy={{ ...nodeKey, path: ['fcat-a', 'fnode-gone'] }}
readOnly={false}
guards={guards}
references={{ open: vi.fn(), start }}
onDone={onDone}
onNotice={vi.fn()}
onDiscardClose={vi.fn()}
/>,
)
await user.click(screen.getByRole('button', { name: 'Nouvelle référence' }))
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
const alert = screen.getByRole('alert')
expect(alert).toHaveTextContent("Ce constat n'existe plus")
expect(alert).toHaveTextContent(
'Nouvelle référence non enregistrée, toujours dans le brouillon : Neuf',
)
expect(onDone).not.toHaveBeenCalled()
expect(screen.getByText('Neuf')).toBeVisible()
expect(undos()).toBe(0)
})
})
describe('a finding draft and a references draft on the same element', () => {
it('are both saved; neither overwrites the other', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: 'Modifier' }),
)
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() => expect(citations()).toBeDefined())
await user.click(button('Modifier'))
await removeRow(user, /Barone/)
await user.click(button('Enregistrer'))
await user.click(button('Fermer'))
await waitFor(() => expect(citations()).toBeUndefined())
await user.click(
inFindingDialog().getByRole('button', { name: 'Enregistrer' }),
)
expect(nodeA().name.fr).toBe('Node A bis')
expect(nodeA().reference_ids).toEqual(['ref-c'])
expect(undos()).toBe(2)
})
})
describe('leaving the editor with a citations draft', () => {
it('a sign-out leaves the account flag of the citations layer', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
forgetSessionTag()
useAuthStore.setState({ user: null })
})
await waitFor(() => expect(citations()).toBeUndefined())
const flags = Object.keys(sessionStorage)
.filter((k) => k.startsWith('faunosteo:editor:left-draft-account:'))
.map((k) => JSON.parse(sessionStorage.getItem(k)!))
expect(flags).toHaveLength(1)
expect(flags[0]).toMatchObject({ kind: 'citations', key: nodeKey })
expect(JSON.stringify(flags)).not.toContain('Barone')
})
it('a plain leave flags the citations layer', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
cleanup()
const flag = sessionStorage.getItem(
`faunosteo:editor:left-draft:${SHEET}:${TAG}`,
)
expect(JSON.parse(flag!)).toEqual({ kind: 'citations', key: nodeKey })
})
})
/** The Navigation API as the leave guard reads it: `navigate` events and `traverseTo`. */
class NavigationStub extends EventTarget {
traverseTo = vi.fn((key: string) => {
void key
return { committed: Promise.resolve(), finished: Promise.resolve() }
})
}
describe('a reference over the references dialog of a dirty finding (criterion 23)', () => {
let api: NavigationStub
beforeEach(() => {
api = new NavigationStub()
Object.defineProperty(window, 'navigation', {
value: api,
configurable: true,
})
})
afterEach(() => {
Reflect.deleteProperty(window, 'navigation')
})
function jump() {
const url = new URL('/app/admin/sheets', window.location.origin).href
const event = Object.assign(new Event('navigate', { cancelable: true }), {
navigationType: 'traverse',
destination: { url, key: 'list', sameDocument: true },
})
act(() => {
api.dispatchEvent(event)
})
return event
}
/** Node A in edit with a typed name, its references in edit, Barone in edit, typed. */
async function stacked(user: User) {
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: 'Modifier' }),
)
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() => expect(citations()).toBeDefined())
await user.click(button('Modifier'))
await user.click(button(/^Modifier la référence Barone/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.type(inReference().getByLabelText('Citation'), ' x')
}
it('the finding asks next, references dialog closed, focused; then the jump goes', async () => {
const user = await mount()
await stacked(user)
expect(jump().defaultPrevented).toBe(true)
expect(inReference().getByText(question)).toBeVisible()
await user.click(inReference().getByRole('button', { name: 'Abandonner' }))
await waitFor(() => expect(referenceDialog()).toBeUndefined())
await waitFor(() => expect(citations()).toBeUndefined())
const finding = within(findingDialog()!)
expect(finding.getByText(question)).toBeVisible()
const keep = finding.getByRole('button', { name: 'Continuer la saisie' })
await waitFor(() => expect(keep).toHaveFocus())
expect(api.traverseTo).not.toHaveBeenCalled()
await user.click(finding.getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).toHaveBeenCalledWith('list')
})
it('the cascade after the user answered « Abandonner » says nothing', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: 'Modifier' }),
)
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() => expect(citations()).toBeDefined())
await user.click(button('Modifier'))
await removeRow(user, /Barone/)
expect(jump().defaultPrevented).toBe(true)
await user.click(button('Abandonner'))
await waitFor(() => expect(citations()).toBeUndefined())
const finding = within(findingDialog()!)
await user.click(finding.getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).toHaveBeenCalledWith('list')
// The jump is a stub: the page stays. Its dialogs go, so what waited is said.
await act(async () => {
document.querySelectorAll('dialog[open]').forEach((d) => d.remove())
flushAfterModals()
})
expect(live()).not.toContain('Saisie abandonnée')
})
it('« Continuer la saisie » there keeps the finding draft and drops the jump', async () => {
const user = await mount()
await stacked(user)
jump()
await user.click(inReference().getByRole('button', { name: 'Abandonner' }))
await waitFor(() => expect(citations()).toBeUndefined())
const finding = within(findingDialog()!)
await user.click(
finding.getByRole('button', { name: 'Continuer la saisie' }),
)
expect(finding.getByLabelText('Nom (FR)')).toHaveValue('Node A bis')
expect(api.traverseTo).not.toHaveBeenCalled()
})
it('a citations draft under a clean reference dialog asks once it is closed', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Code rural/)
await user.click(button(/^Modifier la référence Barone/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(jump().defaultPrevented).toBe(true)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(inCitations().getByText(question)).toBeVisible()
const keep = inCitations().getByRole('button', {
name: 'Continuer la saisie',
})
await waitFor(() => expect(keep).toHaveFocus())
await user.click(button('Abandonner'))
expect(api.traverseTo).toHaveBeenCalledWith('list')
})
})
describe('a Back over a citations draft under a clean reference dialog', () => {
it('the reference dialog closes, the draft asks, the view is pushed again', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Code rural/)
await user.click(button(/^Modifier la référence Barone/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await back(2)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
expect(rows()).toEqual(['ref-a'])
expect(written()!.view).toMatchObject({
reference: null,
finding: { citations: true },
})
})
})