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

1035 lines
37 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 { ElementKey } from '@faunosteo/core-wasm/types'
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 { 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('« Modifier » puts the focus on the first control of the draft', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await user.click(inDialog().getByRole('button', { name: 'Modifier' }))
const active = document.activeElement
expect(active).not.toBe(document.body)
expect(active?.closest('form[data-draft-form]')).not.toBeNull()
})
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 save = (user: User) =>
user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
const panelOpen = () => screen.queryByTestId('editor-citations-panel')
const nodeKey: ElementKey = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
}
/** Node A cites `ids` from now on: a change made outside the finding's edit form. */
function citeElsewhere(ids: string[]) {
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: ids } },
})
})
}
describe('the finding dialog holds no citation control (Rev 5, owner item 1)', () => {
it('the view shows « Références citées » and « X références » only', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
expect(inDialog().getByText('Références citées')).toBeVisible()
expect(inDialog().queryByText('Alpha')).toBeNull()
expect(
inDialog().queryByLabelText('Citer une référence existante'),
).toBeNull()
expect(inDialog().queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(
inDialog().getByRole('button', { name: '1 référence' }),
).toBeVisible()
})
it('a family view lists nothing inline; its « X références » opens the dialog', 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().queryByText('Alpha')).toBeNull()
await user.click(inDialog().getByRole('button', { name: '1 référence' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
expect(within(panelOpen()!).getByText('Alpha')).toBeVisible()
})
it('a zone has no « Références citées »', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Zone A/)
expect(inDialog().queryByText('Références citées')).toBeNull()
})
it('the edit form shows the header and the button only, at zero too', async () => {
const user = await mount(1280, citingText([]))
await openFinding(user, /Node A/)
await modify(user)
expect(inDialog().getByText('Références citées')).toBeVisible()
expect(
inDialog().getByRole('button', { name: '0 référence' }),
).toBeVisible()
expect(
inDialog().queryByLabelText('Citer une référence existante'),
).toBeNull()
expect(inDialog().queryByRole('button', { name: /^Retirer/ })).toBeNull()
})
it('a save keeps a citations change made elsewhere while the form was open', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await user.clear(nameField())
await user.type(nameField(), 'Renommé')
citeElsewhere(['ref-a', 'ref-b'])
const before = entries()
await save(user)
const node = doc().finding_zones[0].categories[0].children[0]
expect(node.name.fr).toBe('Renommé')
expect(nodeIds()).toEqual(['ref-a', 'ref-b'])
expect(entries()).toBe(before + 1)
})
})
describe('the references dialog over a dirty edit form', () => {
const question = 'Abandonner les modifications ?'
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 its name changed, its references dialog open over the form. */
async function dialogOverDirtyForm() {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' x')
await user.click(inDialog().getByRole('button', { name: '1 référence' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
await waitFor(() =>
expect(written()?.view.finding).toMatchObject({ citations: true }),
)
return user
}
const draftKept = () => expect(nameField()).toHaveValue('Node A x')
it('a Back closes the clean references dialog and asks nothing', async () => {
await dialogOverDirtyForm()
await back()
await waitFor(() => expect(panelOpen()).toBeNull())
expect(screen.queryByText(question)).toBeNull()
expect(written()?.view.finding).toMatchObject({ citations: false })
draftKept()
})
it('a jump of two entries inside the editor closes the dialog, then the form asks', async () => {
await dialogOverDirtyForm()
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('a jump out of the editor closes the dialog, then the form asks in view', async () => {
await dialogOverDirtyForm()
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()
})
it('« Tout afficher » refused by the form: the dialog closes first, the question in view', async () => {
const user = await dialogOverDirtyForm()
await user.click(
within(panelOpen()!).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
await waitFor(() => expect(panelOpen()).toBeNull())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(document.activeElement).toBe(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
),
)
expect(written()?.view.tab).toBe('findings')
expect(written()?.view.finding).toMatchObject({ citations: false })
draftKept()
})
it('« Aller à » refused by the form: the dialog closes first, the question in view', async () => {
const user = await dialogOverDirtyForm()
const sheet = within(panelOpen()!)
await user.click(sheet.getByRole('button', { name: /^Alpha/ }))
await user.click(sheet.getAllByRole('button', { name: /^Aller à / })[0])
await waitFor(() => expect(panelOpen()).toBeNull())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(document.activeElement).toBe(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
),
)
draftKept()
})
})