Files
faunosteo/apps/app/tests/unit/editor-finding-dialog.test.tsx
T

1183 lines
43 KiB
TypeScript

/** R2F-3: the finding dialog (view, edit, creation), its history entries and its guards. */
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 {
forgetSessionTag,
resolveSessionTag,
} from '@/editor/history/sessionTag'
import { useCitationDraft } from '@/editor/findings/citationDraft'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import { defaultView } from '@/editor/navigation'
import {
baseText,
resetStore,
serverHas,
SHEET,
store,
USER,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import {
findingDialog,
inFindingDialog,
openFinding,
treeRow,
} 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))
/** The session tag of USER in this tab: entries and flags carry it (criterion 22). */
let TAG: string
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
TAG = resolveSessionTag(USER)
})
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const path = `/app/admin/sheets/${SHEET}/draft`
const name = (n: string) => ({ fr: n, en: n })
/** Zone A > Cat A > Node A (cites nothing). */
function sheetText(): string {
let text = insert(baseText(), {
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: [],
review_status: 'to_confirm',
children: [],
},
},
})
}
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 entries = () => store.getState().undo.length
const inDialog = () => inFindingDialog()
const modify = (user: User) =>
user.click(inDialog().getByRole('button', { name: 'Modifier' }))
const nameField = () => inDialog().getByLabelText('Nom (FR)')
const closed = () => waitFor(() => expect(findingDialog()).toBeNull())
describe('opening', () => {
it('a click, Enter and Space each select the row and open its dialog; the tree stays', async () => {
const user = await mount()
const before = screen.getAllByRole('treeitem').length
await openFinding(user, /Cat A/)
expect(treeRow(/Cat A/)).toHaveAttribute('aria-selected', 'true')
expect(inDialog().getByRole('heading', { name: 'Cat A' })).toBeVisible()
await user.click(inDialog().getByRole('button', { name: 'Fermer' }))
await closed()
treeRow(/Cat A/).focus()
await user.keyboard('{Enter}')
await waitFor(() => expect(findingDialog()).not.toBeNull())
await user.keyboard('{Escape}')
await closed()
await user.keyboard(' ')
await waitFor(() => expect(findingDialog()).not.toBeNull())
expect(screen.getAllByRole('treeitem')).toHaveLength(before)
})
it('writes one entry on open; Back closes it and the row holds the focus', async () => {
const user = await mount()
const first = written()!.id
await openFinding(user, /Cat A/)
await waitFor(() => expect(written()?.id).not.toBe(first))
expect(written()?.view.finding).toMatchObject({ citations: false })
expect(written()?.below?.finding).toBeNull()
await back()
await closed()
await waitFor(() => expect(document.activeElement).toBe(treeRow(/Cat A/)))
expect(written()?.id).toBe(first)
})
it('the close button asks nothing of a pristine view and pops its entry', async () => {
const user = await mount()
const first = written()!.id
await openFinding(user, /Cat A/)
await waitFor(() => expect(written()?.id).not.toBe(first))
await user.click(inDialog().getByRole('button', { name: 'Fermer' }))
await closed()
await waitFor(() => expect(written()?.id).toBe(first))
expect(document.activeElement).toBe(treeRow(/Cat A/))
})
})
/** Deletes the open dialog's element through its confirmation. */
async function deleteOpen(user: User) {
await user.click(inDialog().getByRole('button', { name: 'Supprimer' }))
const confirm = await screen.findAllByRole('button', { name: 'Supprimer' })
await user.click(confirm[confirm.length - 1])
await closed()
}
describe('deleting (owner item 3)', () => {
it('closes the dialog by popping its entry: the first Back moves', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await deleteOpen(user)
expect(written()?.view.finding).toBeNull()
expect(written()?.view.tab).toBe('findings')
await back()
await waitFor(() => expect(written()?.view.tab).not.toBe('findings'))
})
it('one « Défaire » restores the row, selected, shown and focused', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await deleteOpen(user)
expect(screen.queryByRole('treeitem', { name: /Node A/ })).toBeNull()
await user.click(screen.getByRole('button', { name: /^Défaire/ }))
const row = await screen.findByRole('treeitem', { name: /Node A/ })
expect(row).toHaveAttribute('aria-selected', 'true')
await waitFor(() => expect(row).toHaveFocus())
})
it('a later step that brings no finding back refocuses nothing', async () => {
const user = await mount()
const zone = { kind: 'zone', id: 'zone-a' }
const element = {
kind: 'zone',
value: {
id: 'zone-a',
name: name('Zone B'),
categories: doc().finding_zones[0].categories,
},
}
act(() => {
store.getState().commit({ op: 'update', key: zone, element } as never)
})
await openFinding(user, /Node A/)
await deleteOpen(user)
const undo = () =>
user.click(screen.getByRole('button', { name: /^Défaire/ }))
await undo()
const row = await screen.findByRole('treeitem', { name: /Node A/ })
await waitFor(() => expect(row).toHaveFocus())
expect(store.getState().revealed).toBeNull()
act(() => row.blur())
await undo()
await screen.findByRole('treeitem', { name: /Zone A/ })
expect(store.getState().revealed).toBeNull()
expect(row).not.toHaveFocus()
})
it('« Refaire » of a creation shows its row the same way', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await deleteOpen(user)
await user.click(screen.getByRole('button', { name: /^Défaire/ }))
await user.click(screen.getByRole('button', { name: /^Refaire/ }))
await waitFor(() =>
expect(screen.queryByRole('treeitem', { name: /Node A/ })).toBeNull(),
)
await user.click(screen.getByRole('button', { name: /^Défaire/ }))
const row = await screen.findByRole('treeitem', { name: /Node A/ })
await waitFor(() => expect(row).toHaveFocus())
})
})
describe('edit mode', () => {
it('a pristine « Enregistrer » is no command and no entry; a changed one is one', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
const before = entries()
await modify(user)
await user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
expect(entries()).toBe(before)
expect(inDialog().getByRole('button', { name: 'Modifier' })).toHaveFocus()
await modify(user)
await user.clear(nameField())
await user.type(nameField(), 'Renommée')
await user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
expect(entries()).toBe(before + 1)
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Renommée')
expect(inDialog().getByRole('status')).toHaveTextContent(
'Modifications enregistrées',
)
})
it('a blank name is refused on its field, nothing is written', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
const before = entries()
await user.clear(nameField())
await user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
expect(entries()).toBe(before)
expect(nameField()).toHaveFocus()
expect(nameField()).toHaveAccessibleDescription('Ce champ est obligatoire.')
})
it('« Annuler » with changes asks first; « Abandonner » commits nothing', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
const before = entries()
await user.type(nameField(), ' bis')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
expect(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
).toHaveFocus()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(nameField()).toHaveValue('Cat A bis')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(entries()).toBe(before)
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
expect(inDialog().getByRole('button', { name: 'Modifier' })).toBeVisible()
})
it('a dirty close request (Escape, ✕, a native cancel) asks and keeps the dialog', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
await user.type(nameField(), ' bis')
await user.keyboard('{Escape}')
expect(findingDialog()).not.toBeNull()
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
await user.click(inDialog().getByRole('button', { name: 'Fermer' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
fireEvent(findingDialog()!, new Event('cancel', { cancelable: true }))
expect(findingDialog()).not.toBeNull()
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
})
it('a Back with changes asks, keeps the page and the draft, then Abandonner pops once', async () => {
const user = await mount()
const first = written()!.id
await openFinding(user, /Cat A/)
await waitFor(() => expect(written()?.id).not.toBe(first))
await modify(user)
await user.type(nameField(), ' bis')
await back()
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
expect(findingDialog()).not.toBeNull()
fireEvent.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(nameField()).toHaveValue('Cat A bis')
fireEvent(findingDialog()!, new Event('cancel', { cancelable: true }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await closed()
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(entries()).toBe(0)
// The refused Back pushes the view again from an effect: the test router's low-priority
// transition lands up to 5 s later (a test-DOM artifact, a browser applies it at once).
}, 20_000)
})
describe('creation', () => {
it('is a layer of its own, replaced by the element after « Créer » (no extra entry)', async () => {
const user = await mount()
const first = written()!.id
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await waitFor(() => expect(written()?.id).not.toBe(first))
const creation = written()!.id
expect(written()?.view.finding).toEqual({
create: { kind: 'zone', parent: null },
})
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
await user.type(document.getElementById('finding-new-name-en')!, 'Head')
await user.click(
within(findingDialog()!).getByRole('button', { name: 'Créer' }),
)
await waitFor(() => expect(written()?.view.finding).toHaveProperty('key'))
expect(written()?.id).toBe(creation)
expect(doc().finding_zones).toHaveLength(2)
await back()
await closed()
expect(written()?.id).toBe(first)
})
it('a dirty creation asks before it closes and writes nothing', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
await user.keyboard('{Escape}')
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(doc().finding_zones).toHaveLength(1)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Ajouter une zone' }),
),
)
})
})
describe('read-only flip and the gone rule', () => {
it('1280 to 900 to 1280 keeps the draft and the focus, « Enregistrer » off meanwhile', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
await user.type(nameField(), ' bis')
const field = nameField()
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(nameField()).toBe(field)
expect(field).toHaveAttribute('readonly')
expect(field).toHaveFocus()
expect(inDialog().getByText(/Élargissez la fenêtre/)).toBeVisible()
expect(
inDialog().getByRole('button', { name: 'Enregistrer' }),
).toBeDisabled()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(field).not.toHaveAttribute('readonly')
expect(field).toHaveValue('Cat A bis')
expect(field).toHaveFocus()
})
it('a flip to read-only while « Modifier » holds the focus keeps it in the dialog (the tab row is inert)', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
const button = inDialog().getByRole('button', { name: 'Modifier' })
button.focus()
expect(button).toHaveFocus()
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
// The edit-only actions left the page: the focus moved to the dialog's first control.
expect(button.isConnected).toBe(false)
expect(findingDialog()!.contains(document.activeElement)).toBe(true)
})
it('a forced close of a dirty form says the dropped draft once, with the gone text', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await closed()
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
await waitFor(() =>
expect(live().textContent).toBe(
"Saisie abandonnée. Ce constat n'existe plus",
),
)
})
it('an element that vanishes closes its dialog by replace and says so', async () => {
const user = await mount()
await openFinding(user, /Node A/)
const open = written()!
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await closed()
await waitFor(() =>
expect(
document.querySelector('p.sr-only[aria-live="polite"]'),
).toHaveTextContent("Ce constat n'existe plus"),
)
expect(written()?.id).toBe(open.id)
expect(written()?.view.finding).toBeNull()
})
it('a reading dialog restored for a key the sheet lacks is dropped, with its announcement', async () => {
serverHas(sheetText(), 3)
const gone = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'gone'],
}
const view = {
...defaultView('findings'),
finding: { key: gone, citations: false },
}
const state = {
[ENTRY_KEY]: {
id: 'old',
view,
below: null,
sheetId: SHEET,
tag: TAG,
},
}
mountDraft({ probe, entries: [{ pathname: path, state }] })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(findingDialog()).toBeNull()
expect(written()?.id).toBe('old')
await waitFor(() =>
expect(
document.querySelector('p.sr-only[aria-live="polite"]'),
).toHaveTextContent("Ce constat n'existe plus"),
)
})
it('a creation form in the entry is never restored by a reload', async () => {
serverHas(sheetText(), 3)
const view = {
...defaultView('findings'),
finding: { create: { kind: 'zone', parent: null } },
}
const state = {
[ENTRY_KEY]: {
id: 'old',
view,
below: null,
sheetId: SHEET,
tag: TAG,
},
}
mountDraft({ probe, entries: [{ pathname: path, state }] })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(findingDialog()).toBeNull()
})
})
const liveText = () =>
document.querySelector('p.sr-only[aria-live="polite"]')!.textContent
describe('final review: a creation whose parent vanishes (M-1)', () => {
it('says the dropped names with the gone text, never silently', async () => {
const user = await mount()
act(() => treeRow(/Cat A/).focus())
await user.keyboard('{ArrowUp}{ArrowDown}')
await user.click(screen.getByRole('button', { name: 'Ajouter un constat' }))
await waitFor(() => expect(findingDialog()).not.toBeNull())
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
})
})
await closed()
await waitFor(() =>
expect(liveText()).toBe("Saisie abandonnée. Ce constat n'existe plus"),
)
})
})
describe('final review: the zone of a new category is part of the draft (criterion 8)', () => {
it('a zone changed alone asks before « Annuler » closes', async () => {
serverHas(
insert(sheetText(), {
kind: 'zone',
value: { id: 'zone-b', name: name('Zone B'), categories: [] },
}),
3,
)
const user = userEvent.setup()
mountDraft({ width: 1280, probe })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
await waitFor(() => expect(findingDialog()).not.toBeNull())
await user.selectOptions(inDialog().getByLabelText('Zone'), 'zone-b')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
act(() => inDialog().getByLabelText('Zone').focus())
await user.keyboard('{Escape}')
expect(findingDialog()).not.toBeNull()
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
})
})
describe('final review: leaving the editor with a dirty dialog (criterion 17)', () => {
const flagKey = () => `faunosteo:editor:left-draft:${SHEET}:${TAG}`
const notice =
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur"
it('leaves one flag without the text, then a notice once on the next mount', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
cleanup()
const flag = sessionStorage.getItem(flagKey())
expect(flag).not.toBeNull()
expect(flag).not.toContain('bis')
expect(JSON.parse(flag!)).toEqual({
kind: 'finding',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'fnode-a'] },
})
await mount()
expect(screen.getByText(notice)).toBeVisible()
expect(sessionStorage.getItem(flagKey())).toBeNull()
cleanup()
await mount()
expect(screen.queryByText(notice)).toBeNull()
})
it('a sign-out with a dirty dialog is said once to the same account, never to another', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
act(() => {
forgetSessionTag()
useAuthStore.setState({ user: null })
})
await waitFor(() => expect(findingDialog()).toBeNull())
const values = Object.keys(sessionStorage).map((k) => k + sessionStorage[k])
expect(values.join()).not.toContain('bis')
expect(values.join()).not.toContain(USER)
cleanup()
serverHas(sheetText(), 3)
mountDraft({ width: 1280, probe, user: 'user-2' })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
expect(screen.queryByText(notice)).toBeNull()
cleanup()
await mount()
expect(screen.getByText(notice)).toBeVisible()
cleanup()
await mount()
expect(screen.queryByText(notice)).toBeNull()
})
it('a clean dialog leaves no flag', async () => {
const user = await mount()
await openFinding(user, /Node A/)
cleanup()
expect(sessionStorage.getItem(flagKey())).toBeNull()
})
})
/** The Navigation API as the 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 jump of several entries out of the editor (criterion 23)', () => {
const flagKey = () => `faunosteo:editor:left-draft:${SHEET}:${TAG}`
const notice =
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur"
let api: NavigationStub
beforeEach(() => {
api = new NavigationStub()
Object.defineProperty(window, 'navigation', {
value: api,
configurable: true,
})
})
afterEach(() => {
Reflect.deleteProperty(window, 'navigation')
})
/** A history jump to `pathname`, as Chromium dispatches it before it commits. */
function traverse(
pathname: string,
key: string,
cancelable = true,
sameDocument = true,
) {
const url = new URL(pathname, window.location.origin).href
const event = Object.assign(new Event('navigate', { cancelable }), {
navigationType: 'traverse',
destination: { url, key, sameDocument },
})
act(() => {
api.dispatchEvent(event)
})
return event
}
async function dirtyDialog() {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
return user
}
it('is cancelled and asks first; « Continuer la saisie » keeps the draft', async () => {
const user = await dirtyDialog()
const jump = traverse('/app/admin/sheets', 'list')
expect(jump.defaultPrevented).toBe(true)
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(nameField()).toHaveValue('Node A bis')
expect(api.traverseTo).not.toHaveBeenCalled()
expect(sessionStorage.getItem(flagKey())).toBeNull()
})
it('« Abandonner » goes to the destination, with no notice afterwards', async () => {
const user = await dirtyDialog()
traverse('/app/admin/sheets', 'list')
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).toHaveBeenCalledWith('list')
expect(traverse('/app/admin/sheets', 'list').defaultPrevented).toBe(false)
cleanup()
expect(sessionStorage.getItem(flagKey())).toBeNull()
await mount()
expect(screen.queryByText(notice)).toBeNull()
})
it('« Abandonner » after « Continuer la saisie » closes the dialog only', async () => {
const user = await dirtyDialog()
traverse('/app/admin/sheets', 'list')
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).not.toHaveBeenCalled()
expect(findingDialog()).not.toBeNull()
})
it('a jump that cannot be cancelled keeps the notice after the fact', async () => {
await dirtyDialog()
expect(traverse('/app/admin/sheets', 'list', false).defaultPrevented).toBe(
false,
)
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull()
cleanup()
expect(sessionStorage.getItem(flagKey())).not.toBeNull()
})
it('a failed jump closes the question and keeps the draft', async () => {
const user = await dirtyDialog()
api.traverseTo.mockImplementation(() => ({
committed: Promise.reject(new Error('gone')),
finished: Promise.reject(new Error('gone')),
}))
traverse('/app/admin/sheets', 'list')
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await waitFor(() =>
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull(),
)
expect(nameField()).toHaveValue('Node A bis')
cleanup()
expect(sessionStorage.getItem(flagKey())).not.toBeNull()
})
it('a jump to another sheet is a leave; another document is not cancelled', async () => {
await dirtyDialog()
const other = '/app/admin/sheets/other-sheet/draft'
expect(traverse('/app/admin', 'admin', true, false).defaultPrevented).toBe(
false,
)
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull()
expect(traverse(other, 'other').defaultPrevented).toBe(true)
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
})
it('a traversal inside the editor, or a clean dialog, is left alone', async () => {
const user = await mount()
await openFinding(user, /Node A/)
expect(traverse('/app/admin/sheets', 'list').defaultPrevented).toBe(false)
await modify(user)
await user.type(nameField(), ' bis')
expect(traverse(path, 'inside').defaultPrevented).toBe(false)
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull()
})
})
describe('final review: the category creation title', () => {
it('reads « Nouvelle catégorie », never a raw key', async () => {
const user = await mount()
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
await waitFor(() => expect(findingDialog()).not.toBeNull())
const title = within(findingDialog()!).getByRole('heading', { level: 2 })
expect(title).toHaveTextContent(/^Nouvelle catégorie$/)
expect(title.textContent).not.toContain('editor.')
})
})
const reference = (id: string, citation: string) => ({
kind: 'reference' as const,
value: { id, type: 'book' as const, citation, url: null, doi: null },
})
/** Node A cites Alpha; Beta is cited by nobody. */
function citingText(ids = ['ref-a']): string {
let text = insert(sheetText(), reference('ref-a', 'Alpha'))
text = insert(text, reference('ref-b', 'Beta'))
const key = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
} as const
const node = JSON.parse(text).finding_zones[0].categories[0].children[0]
const element = {
kind: 'finding_node',
value: { ...node, reference_ids: ids },
}
return edit(text, { op: 'update', key, element } as never)
}
const nodeIds = () =>
doc().finding_zones[0].categories[0].children[0].reference_ids
const cite = (user: User, label: string) =>
user.selectOptions(inDialog().getByLabelText('Citer une référence'), label)
const save = (user: User) =>
user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
const panelOpen = () => screen.queryByTestId('editor-citations-panel')
describe('citing references lives in the edit form (owner item 1)', () => {
it('the view has no cite control and no remove; the trigger opens the sheet', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
expect(inDialog().queryByLabelText('Citer une référence')).toBeNull()
expect(inDialog().queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(
inDialog().getByRole('button', { name: '1 référence' }),
).toBeVisible()
})
it('a family view lists its citations read-only', async () => {
let text = insert(sheetText(), reference('ref-a', 'Alpha'))
const key = { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] }
const cat = JSON.parse(text).finding_zones[0].categories[0]
const element = {
kind: 'finding_category',
value: { ...cat, reference_ids: ['ref-a'] },
}
text = edit(text, { op: 'update', key, element } as never)
const user = await mount(1280, text)
await openFinding(user, /Cat A/)
expect(inDialog().getByText('Alpha')).toBeVisible()
expect(inDialog().queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(inDialog().queryByLabelText('Citer une référence')).toBeNull()
})
it('the form stages a cite and a remove, written only by « Enregistrer »', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
const before = entries()
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: 'Retirer Alpha' }))
expect(nodeIds()).toEqual(['ref-a'])
expect(entries()).toBe(before)
expect(
inDialog().getByRole('button', { name: '1 référence' }),
).toBeVisible()
await save(user)
expect(nodeIds()).toEqual(['ref-b'])
expect(entries()).toBe(before + 1)
})
it('one undo restores the names and the citations together', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await user.clear(nameField())
await user.type(nameField(), 'Renommé')
await cite(user, 'Beta')
await save(user)
expect(doc().finding_zones[0].categories[0].children[0].name.fr).toBe(
'Renommé',
)
expect(nodeIds()).toEqual(['ref-a', 'ref-b'])
act(() => void store.getState().undoStep())
expect(doc().finding_zones[0].categories[0].children[0].name.fr).toBe(
'Node A',
)
expect(nodeIds()).toEqual(['ref-a'])
})
it('a cite then its remove is pristine: « Enregistrer » writes nothing', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
const before = entries()
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: 'Retirer Beta' }))
await save(user)
expect(entries()).toBe(before)
})
it('« Annuler » with only a citation change asks, « Abandonner » writes nothing', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
const before = entries()
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(entries()).toBe(before)
expect(nodeIds()).toEqual(['ref-a'])
})
it('the sheet opened from the form lists the draft and cannot remove', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: '2 références' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
const sheet = within(panelOpen()!)
expect(sheet.getByText(/2 références citées/)).toBeVisible()
expect(sheet.queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(nodeIds()).toEqual(['ref-a'])
})
it('the published draft returns to null on « Abandonner » and on save', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await cite(user, 'Beta')
expect(useCitationDraft.getState().draft?.ids).toEqual(['ref-a', 'ref-b'])
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(useCitationDraft.getState().draft).toBeNull()
await modify(user)
await cite(user, 'Beta')
await save(user)
expect(useCitationDraft.getState().draft).toBeNull()
})
it('a Retirer-only change counts and lists the draft, the document stays', async () => {
const user = await mount(1280, citingText(['ref-a', 'ref-b']))
await openFinding(user, /Node A/)
await modify(user)
await user.click(inDialog().getByRole('button', { name: 'Retirer Alpha' }))
await user.click(inDialog().getByRole('button', { name: '1 référence' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
const sheet = within(panelOpen()!)
expect(sheet.getByText(/1 référence citée/)).toBeVisible()
expect(sheet.getByText(/Beta/)).toBeVisible()
expect(sheet.queryByText(/Alpha/)).toBeNull()
expect(nodeIds()).toEqual(['ref-a', 'ref-b'])
})
it('a read-only flip keeps a citation-only draft, never dropped silently', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await cite(user, 'Beta')
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(findingDialog()).not.toBeNull()
expect(
inDialog().getByRole('button', { name: '2 références' }),
).toBeVisible()
expect(inDialog().queryByLabelText('Citer une référence')).toBeNull()
expect(
inDialog().getByRole('button', { name: 'Enregistrer' }),
).toBeDisabled()
expect(nodeIds()).toEqual(['ref-a'])
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(
inDialog().getByRole('button', { name: '2 références' }),
).toBeVisible()
})
})
describe('the citations sheet over a dirty edit form (final review rev 4, item 1)', () => {
const question = 'Abandonner les modifications ?'
const dialogs = () => [...document.querySelectorAll('dialog[open]')]
const refForm = () =>
dialogs().find((d) => d.querySelector('#reference-form-citation')) as
| HTMLElement
| undefined
let api: NavigationStub
beforeEach(() => {
api = new NavigationStub()
Object.defineProperty(window, 'navigation', {
value: api,
configurable: true,
})
})
afterEach(() => {
Reflect.deleteProperty(window, 'navigation')
})
/** Node A in edit with Beta cited in the draft, its sheet open over the form. */
async function sheetOverDirtyForm() {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: '2 références' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
await waitFor(() =>
expect(written()?.view.finding).toMatchObject({ citations: true }),
)
return user
}
const draftKept = () =>
expect(
inDialog().getByRole('button', { name: '2 références' }),
).toBeVisible()
it('a Back closes the clean sheet and asks nothing', async () => {
await sheetOverDirtyForm()
await back()
await waitFor(() => expect(panelOpen()).toBeNull())
expect(screen.queryByText(question)).toBeNull()
expect(written()?.view.finding).toMatchObject({ citations: false })
draftKept()
})
it('a Back from a clean reference dialog over the sheet closes it only', async () => {
const user = await sheetOverDirtyForm()
const sheet = within(panelOpen()!)
const head = sheet.getByRole('button', { name: /^Alpha/ })
if (head.getAttribute('aria-expanded') === 'false') await user.click(head)
const tile = within(head.closest('li')!)
await user.click(tile.getByRole('button', { name: 'Modifier' }))
await waitFor(() => expect(refForm()).toBeDefined())
await back()
await waitFor(() => expect(refForm()).toBeUndefined())
expect(panelOpen()).not.toBeNull()
expect(screen.queryByText(question)).toBeNull()
})
it('a jump of two entries inside the editor closes the sheet, then the form asks', async () => {
await sheetOverDirtyForm()
await act(async () => navigate(-2))
await waitFor(() => expect(panelOpen()).toBeNull())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(findingDialog()!.contains(document.activeElement)).toBe(true),
)
expect(written()?.view.finding).toMatchObject({ citations: false })
draftKept()
})
it('after the cascade keeps the form, one Back reopens the sheet (docs, limit 5)', async () => {
const user = await sheetOverDirtyForm()
const sheet = within(panelOpen()!)
const head = sheet.getByRole('button', { name: /^Alpha/ })
if (head.getAttribute('aria-expanded') === 'false') await user.click(head)
const tile = within(head.closest('li')!)
await user.click(tile.getByRole('button', { name: 'Modifier' }))
await waitFor(() => expect(refForm()).toBeDefined())
await user.type(within(refForm()!).getByLabelText('Citation'), ' x')
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)
})
await user.click(
within(refForm()!).getByRole('button', { name: 'Abandonner' }),
)
await waitFor(() => expect(panelOpen()).toBeNull())
// The reference dialog plays its exit, then leaves: only the finding dialog stays.
await waitFor(() => expect(dialogs()).toHaveLength(1))
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
await back()
await waitFor(() => expect(panelOpen()).not.toBeNull())
expect(screen.queryByText(question)).toBeNull()
expect(api.traverseTo).not.toHaveBeenCalled()
draftKept()
})
/** The reference Alpha's edit dialog opened from the sheet; `dirty` types in it. */
async function referenceOverSheet(user: User, dirty: boolean) {
const sheet = within(panelOpen()!)
const head = sheet.getByRole('button', { name: /^Alpha/ })
if (head.getAttribute('aria-expanded') === 'false') await user.click(head)
const tile = within(head.closest('li')!)
await user.click(tile.getByRole('button', { name: 'Modifier' }))
await waitFor(() => expect(refForm()).toBeDefined())
if (dirty)
await user.type(within(refForm()!).getByLabelText('Citation'), ' x')
}
it('a jump of three entries asks the dirty reference only, nothing stays pending under it', async () => {
const user = await sheetOverDirtyForm()
await referenceOverSheet(user, true)
await act(async () => navigate(-3))
await waitFor(() => expect(screen.queryAllByText(question)).toHaveLength(1))
expect(refForm()!.contains(screen.getByText(question))).toBe(true)
await user.click(
within(refForm()!).getByRole('button', { name: 'Abandonner' }),
)
await waitFor(() => expect(refForm()).toBeUndefined())
// The refused jump is dropped: the sheet stays, and no question comes up unasked.
expect(panelOpen()).not.toBeNull()
expect(screen.queryByText(question)).toBeNull()
draftKept()
})
it('a clean reference over the sheet over a dirty form: a Back asks the form in view', async () => {
const user = await sheetOverDirtyForm()
await referenceOverSheet(user, false)
await act(async () => navigate(-3))
await waitFor(() => expect(panelOpen()).toBeNull())
await waitFor(() => expect(refForm()).toBeUndefined())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(findingDialog()!.contains(document.activeElement)).toBe(true),
)
draftKept()
})
it('a clean reference over the sheet over a dirty form: a leave out asks the form in view', async () => {
const user = await sheetOverDirtyForm()
await referenceOverSheet(user, false)
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)
})
expect(event.defaultPrevented).toBe(true)
await waitFor(() => expect(panelOpen()).toBeNull())
await waitFor(() => expect(refForm()).toBeUndefined())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(findingDialog()!.contains(document.activeElement)).toBe(true),
)
draftKept()
})
it('a jump out of the editor closes the sheet, then the form asks in view', async () => {
await sheetOverDirtyForm()
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)
})
expect(event.defaultPrevented).toBe(true)
await waitFor(() => expect(panelOpen()).toBeNull())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(findingDialog()!.contains(document.activeElement)).toBe(true),
)
draftKept()
})
})