Files
faunosteo/apps/app/tests/unit/editor-reference-dialog.test.tsx
T
bchanot 6bf9290da7 fix(editor): final review round, history, dialogs, Plus and limits
I1 scroll restored at once on a Back into layers; I2 Aller a opens the target dialog in one push; M1-M9, criteria 8 and 17 (left-draft notice), entry caps, no exhaustive-deps disables, locals within 5.
2026-11-13 23:42:32 +01:00

562 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** R2F-5 and R2F-6: the reference dialog, the reading tiles, the finding filter, their history. */
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 type { Location, NavigateFunction } from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import { findingDialog, 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(),
}))
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]
const back = () => act(async () => navigate(-1))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string, url = '') =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: url || null, doi: null },
}) as const
/** Three references; Node A (under Cat A) cites ref-a and ref-b. */
function sheetText(): string {
let text = baseText()
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
text = insert(text, ref('ref-b', 'Denoix', 'https://exemple.org/p'))
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: {},
requires_vet_referral: false,
reference_ids: ['ref-a', 'ref-b'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280): Promise<User> {
serverHas(sheetText(), 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: 'Références' }))
await waitFor(() => expect(written()?.view.tab).toBe('references'))
return user
}
const doc = () => JSON.parse(store.getState().documentText)
const entries = () => store.getState().undo.length
const dialogs = () => document.querySelectorAll('dialog[open]')
const refDialog = () =>
[...dialogs()].find((d) => d.querySelector('[data-draft-form]')) as
| HTMLElement
| undefined
const inRef = () => within(refDialog()!)
const closed = () => waitFor(() => expect(refDialog()).toBeUndefined())
const tab = () => screen.getByRole('tabpanel', { name: 'Références' })
const header = (citation: string) =>
within(tab()).getByRole('button', { name: new RegExp(`^${citation}`) })
const modify = async (user: User, citation: string) => {
if (header(citation).getAttribute('aria-expanded') === 'false') {
await user.click(header(citation))
}
const tile = header(citation).closest('li')!
await user.click(within(tile).getByRole('button', { name: 'Modifier' }))
await waitFor(() => expect(refDialog()).toBeDefined())
}
const field = (label: string) => inRef().getByLabelText(label)
const save = (user: User) =>
user.click(
inRef().getByRole('button', {
name: /^(Enregistrer|Ajouter la référence)$/,
}),
)
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
describe('the dialog', () => {
it('opens from « Modifier » with the first control focused, one entry on top', async () => {
const user = await mount()
const first = written()!.id
await modify(user, 'Barone')
expect(
inRef().getByRole('heading', { name: 'Modifier la référence' }),
).toBeVisible()
expect(refDialog()!.contains(document.activeElement)).toBe(true)
expect(field('Citation')).toHaveValue('Barone, Ostéologie')
await waitFor(() => expect(written()?.id).not.toBe(first))
expect(written()?.view.reference).toEqual({ edit: 'ref-a' })
expect(written()?.below?.reference).toBeNull()
})
it('a pristine « Enregistrer » closes with no command; a changed one is one entry', async () => {
const user = await mount()
await modify(user, 'Barone')
const before = entries()
await save(user)
await closed()
expect(entries()).toBe(before)
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1000/x')
await user.clear(field('Citation'))
await user.type(field('Citation'), 'Neuf')
await user.type(field('Adresse web (URL)'), 'https://a.org/')
await save(user)
await closed()
expect(entries()).toBe(before + 1)
expect(doc().references[0]).toMatchObject({
citation: 'Neuf',
doi: '10.1000/x',
url: 'https://a.org/',
})
act(() => void store.getState().undoStep())
expect(doc().references[0]).toMatchObject({
citation: 'Barone, Ostéologie',
doi: null,
url: null,
})
})
it('a double click on « Enregistrer » writes once and pops at most one entry', async () => {
const user = await mount()
const mounted = written()!.id
await modify(user, 'Barone')
await user.clear(field('Citation'))
await user.type(field('Citation'), 'Neuf')
const button = inRef().getByRole('button', { name: 'Enregistrer' })
fireEvent.click(button)
fireEvent.click(button)
await closed()
expect(entries()).toBe(1)
await waitFor(() => expect(written()?.id).toBe(mounted))
})
it('a blank citation and a non-http address are refused on their field', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.clear(field('Citation'))
await save(user)
expect(field('Citation')).toHaveFocus()
expect(field('Citation')).toHaveAccessibleDescription(
'Ce champ est obligatoire.',
)
await user.type(field('Citation'), 'Barone')
await user.type(field('Adresse web (URL)'), 'exemple.org')
await save(user)
expect(field('Adresse web (URL)')).toHaveFocus()
expect(field('Adresse web (URL)')).toHaveAccessibleDescription(
/http:\/\/ ou https:\/\//,
)
expect(entries()).toBe(0)
expect(refDialog()).toBeDefined()
})
it('« Annuler » with changes asks, « Abandonner » writes nothing', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
await user.click(inRef().getByRole('button', { name: 'Annuler' }))
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible()
expect(
inRef().getByRole('button', { name: 'Continuer la saisie' }),
).toHaveFocus()
await user.click(
inRef().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(field('DOI')).toHaveValue('10.1/x')
await user.click(inRef().getByRole('button', { name: 'Annuler' }))
await user.click(inRef().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(entries()).toBe(0)
})
it('a real dialog.close() on a dirty dialog keeps it, with its confirmation', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
act(() => (refDialog() as HTMLDialogElement).close())
await waitFor(() =>
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible(),
)
expect(refDialog()!.hasAttribute('open')).toBe(true)
expect(field('DOI')).toHaveValue('10.1/x')
})
it('Escape asks once when dirty; a held Escape (repeat) is ignored', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
fireEvent.keyDown(field('DOI'), { key: 'Escape', repeat: true })
expect(inRef().queryByText('Abandonner les modifications ?')).toBeNull()
fireEvent.keyDown(field('DOI'), { key: 'Escape' })
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible()
})
it('Défaire is unreachable under the dialog and a mode flip leaves the draft untouched', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(field('DOI')).toHaveValue('10.1/x')
const same = field('DOI')
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(field('DOI')).toBe(same)
expect(same).toHaveAttribute('readonly')
expect(inRef().getByText(/Élargissez la fenêtre/)).toBeVisible()
expect(inRef().getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
expect(entries()).toBe(0)
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(same).not.toHaveAttribute('readonly')
expect(same).toHaveValue('10.1/x')
})
it('a reference that vanishes closes its dialog by replace and says so', async () => {
const user = await mount()
await modify(user, 'Code rural')
const open = written()!
act(() => {
store
.getState()
.commit({ op: 'remove', key: { kind: 'reference', id: 'ref-c' } })
})
await closed()
await waitFor(() =>
expect(live()).toHaveTextContent("Cette référence n'existe plus"),
)
expect(written()?.id).toBe(open.id)
expect(written()?.view.reference).toBeNull()
})
})
describe('creation', () => {
const add = () =>
screen.getByRole('button', { name: 'Ajouter une référence' })
it('needs a type and a citation, creates in one command, leaves the list and says so', async () => {
const user = await mount()
await user.click(add())
await waitFor(() => expect(refDialog()).toBeDefined())
expect(written()?.view.reference).toEqual({ create: true })
await save(user)
expect(field('Type')).toHaveFocus()
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
await save(user)
await closed()
expect(entries()).toBe(1)
expect(doc().references).toHaveLength(4)
// Appended after the three, the sheet order untouched: nothing moved.
expect(within(tab()).getAllByRole('listitem')).toHaveLength(4)
expect(
within(tab()).getByText('Référence ajoutée : Nouvelle source'),
).toBeVisible()
await waitFor(() =>
expect(live()).toHaveTextContent('Référence ajoutée : Nouvelle source'),
)
expect(add()).toHaveFocus()
})
it('« Afficher » shows the new tile open and focuses it', async () => {
const user = await mount()
await user.click(add())
await waitFor(() => expect(refDialog()).toBeDefined())
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
await save(user)
await closed()
await user.click(within(tab()).getByRole('button', { name: 'Afficher' }))
expect(within(tab()).queryByText(/Référence ajoutée/)).toBeNull()
await waitFor(() =>
expect(header('Nouvelle source')).toHaveAttribute(
'aria-expanded',
'true',
),
)
await waitFor(() => expect(header('Nouvelle source')).toHaveFocus())
})
it('the entry becomes the reference’s own: Back, then Forward, reopens an edit, never a creation', async () => {
const user = await mount()
const first = written()!.id
await user.click(add())
await waitFor(() =>
expect(written()?.view.reference).toEqual({ create: true }),
)
const entry = written()!.id
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
await save(user)
await closed()
await waitFor(() => expect(written()?.id).toBe(first))
await act(async () => navigate(1))
await waitFor(() => expect(written()?.id).toBe(entry))
const created = doc().references[3].id
expect(written()?.view.reference).toEqual({ edit: created })
})
it('a dirty creation asks before it closes and writes nothing', async () => {
const user = await mount()
await user.click(add())
await waitFor(() => expect(refDialog()).toBeDefined())
await user.type(field('Citation'), 'x')
await user.keyboard('{Escape}')
await user.click(inRef().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(entries()).toBe(0)
await waitFor(() => expect(add()).toHaveFocus())
})
})
describe('history', () => {
it('Back closes the dialog and the opener holds the focus; Forward reopens it', async () => {
const user = await mount()
await modify(user, 'Barone')
const opener = within(header('Barone').closest('li')!).getByRole('button', {
name: 'Modifier',
})
await back()
await closed()
await waitFor(() => expect(opener).toHaveFocus())
await act(async () => navigate(1))
await waitFor(() => expect(refDialog()).toBeDefined())
expect(field('Citation')).toHaveValue('Barone, Ostéologie')
})
it('a dirty dialog keeps its draft when Back asks, then Abandonner pops once', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
await back()
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible()
fireEvent.click(
inRef().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(field('DOI')).toHaveValue('10.1/x')
fireEvent.click(inRef().getByRole('button', { name: 'Annuler' }))
await user.click(inRef().getByRole('button', { name: 'Abandonner' }))
await closed()
await waitFor(() => expect(written()?.view.reference).toBeNull())
expect(entries()).toBe(0)
}, 20_000)
it('a reload keeps the tab but never reopens the form', async () => {
const user = await mount()
await modify(user, 'Barone')
const entry = written()!
cleanup()
serverHas(sheetText(), 3)
mountDraft({
probe,
entries: [{ pathname: location.pathname, state: { [ENTRY_KEY]: entry } }],
})
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await waitFor(() => expect(written()?.view.reference).toBeNull())
expect(written()?.view.tab).toBe('references')
expect(refDialog()).toBeUndefined()
})
})
describe('the finding filter', () => {
const chip = () => screen.getByTestId('editor-references-filter')
/** Node A's dialog, its sheet, then « Tout afficher »: the tab filtered by Node A. */
async function filtered(user: User) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(screen.getByRole('button', { name: '2 références' }))
await user.click(
await screen.findByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
await waitFor(() => expect(written()?.view.tab).toBe('references'))
}
it('« Tout afficher » lists the finding’s references, counts within the filter, no reorder', async () => {
const user = await mount()
await filtered(user)
expect(written()?.view.referenceFilter).toMatchObject({ kind: 'finding' })
expect(chip()).toHaveTextContent('Références du constat : Node A')
expect(within(tab()).getAllByRole('listitem')).toHaveLength(2)
expect(within(tab()).getByText('2 références')).toBeVisible()
await user.click(header('Barone'))
expect(
within(tab()).queryByRole('button', { name: 'Descendre' }),
).toBeNull()
await user.type(
within(tab()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'Code',
)
expect(within(tab()).getByText('0 référence sur 2')).toBeVisible()
expect(screen.getByTestId('editor-references-no-result')).toBeVisible()
})
it('the × removes the filter by replace; the search text is never in the entry', async () => {
const user = await mount()
await filtered(user)
const id = written()!.id
await user.type(
within(tab()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'Code',
)
await user.click(
within(chip()).getByRole('button', {
name: 'Retirer le filtre du constat Node A',
}),
)
await waitFor(() => expect(written()?.view.referenceFilter).toBeNull())
expect(written()?.id).toBe(id)
expect(JSON.stringify(location.state)).not.toContain('Code')
expect(within(tab()).getAllByRole('listitem').length).toBeGreaterThan(0)
})
it('« Revenir au constat » pops to the finding with its sheet open when the entry below shows it', async () => {
const user = await mount()
await filtered(user)
await user.click(screen.getByRole('button', { name: 'Revenir au constat' }))
await waitFor(() => expect(dialogs()).toHaveLength(2))
expect(written()?.view.finding).toMatchObject({ citations: true })
expect(written()?.view.referenceFilter).toBeNull()
})
it('a finding that vanishes clears the filter and says so', async () => {
const user = await mount()
await filtered(user)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await waitFor(() => expect(written()?.view.referenceFilter).toBeNull())
expect(screen.queryByTestId('editor-references-filter')).toBeNull()
await waitFor(() =>
expect(live()).toHaveTextContent(
"Le constat n'existe plus : le filtre est retiré",
),
)
})
it('the finding dialog and the sheet come back by Back, the filtered tab by Forward', async () => {
const user = await mount()
await filtered(user)
await back()
await waitFor(() => expect(dialogs()).toHaveLength(2))
expect(findingDialog()).not.toBeNull()
await act(async () => navigate(1))
await waitFor(() => expect(dialogs()).toHaveLength(0))
expect(chip()).toBeVisible()
})
})
describe('final review: the creation dialog fades out as a creation (M-9)', () => {
it('never shows the edit title while it closes', async () => {
const user = await mount()
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
await waitFor(() => expect(refDialog()).toBeDefined())
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
const titles = new Set<string>()
const seen = new MutationObserver(() => {
document
.querySelectorAll('dialog h2')
.forEach((h) => titles.add(h.textContent ?? ''))
})
seen.observe(document.body, {
subtree: true,
childList: true,
characterData: true,
})
await save(user)
await closed()
seen.disconnect()
expect(titles).not.toContain('Modifier la référence')
})
})