Files
faunosteo/apps/app/tests/unit/editor-findings.test.tsx
T
bchanot 18085cecf8 feat(editor): finding dialog and citations side sheet in the history
Constats opens each element in one modal dialog (view, edit with a
local draft, creation) driven by the editor view layer of the browser
history. The citations panel becomes a modal side sheet stacked over
it; its geometry, exit machinery and page inertness are removed.
Back and Forward restore the layers, a dirty form asks first.
2026-11-13 18:51:35 +01:00

844 lines
30 KiB
TypeScript

/** Lot I: the Constats tree. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
FindingNode,
} from '@faunosteo/core-wasm/types'
import FindingCreateForm from '@/components/editor/findings/FindingCreateForm'
import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree'
import {
citationsOfView,
initialNavigation,
navigationReducer,
} from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
serverHas,
resetStore,
store,
} from '../helpers/editorHarness'
import { findingDialog, inFindingDialog } from '../helpers/findingDialog'
import FindingsHost from '../helpers/findingsHost'
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(),
}))
type User = ReturnType<typeof userEvent.setup>
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const name = (n: string) => ({ fr: n, en: n })
const node = (id: string): FindingNode => ({
id,
name: name(id),
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'to_confirm',
children: [],
})
/** zone-a > fcat-a > node-a > node-b, and zone-b alone. */
function treeText(): string {
let text = insert(baseText(), {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
text = insert(text, {
kind: 'zone',
value: { id: 'zone-b', name: name('Zone B'), 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: [],
},
},
})
const under = (id: string, path: string[]) =>
edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path },
element: { kind: 'finding_node', value: node(id) },
})
text = under('node-a', ['fcat-a'])
return under('node-b', ['fcat-a', 'node-a'])
}
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
const items = () => screen.getAllByRole('treeitem')
const labels = () => items().map((i) => i.textContent ?? '')
/** The X of the finding dialog: it closes and the row it opened from holds the focus. */
async function closeDialog(user: User) {
const dialog = findingDialog()!
await user.click(within(dialog).getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(findingDialog()).toBeNull())
}
/** Selects a row by activating it (its dialog opens) and closes the dialog again. */
async function pick(user: User, row: HTMLElement) {
await user.click(row)
await waitFor(() => expect(findingDialog()).not.toBeNull())
await closeDialog(user)
}
/** The deletion dialog stacked over the finding dialog: the last dialog of the page. */
async function deleteDialog() {
await waitFor(() =>
expect(document.querySelectorAll('dialog[open]')).toHaveLength(2),
)
return within(document.querySelectorAll('dialog[open]')[1] as HTMLElement)
}
/** The dialog's one « Enregistrer »: names, descriptions and the vet flag in one save. */
async function startEdit(user: User) {
await user.click(inFindingDialog().getByRole('button', { name: 'Modifier' }))
}
describe('findings tree model', () => {
it('flattens in order and hides collapsed branches', async () => {
await openReady({ text: treeText() })
const all = buildItems(doc())
expect(all.map((i) => i.level)).toEqual([1, 2, 3, 4, 1])
const shown = visibleItems(all, new Set(['["zone-a"]']))
expect(shown.map((i) => i.kind)).toEqual(['zone', 'category', 'zone'])
})
it('loads a stored draft whose nodes omit defaulted fields, filled and clean', async () => {
const stored = JSON.parse(baseText()) as Record<string, unknown>
const bare = {
id: 'n1',
name: name('N1'),
children: [{ id: 'n2', name: name('N2') }],
}
stored.finding_zones = [
{
id: 'z',
name: name('Z'),
categories: [
{ id: 'c', kind: 'dysfunction', name: name('C'), children: [bare] },
],
},
]
await openReady({ text: JSON.stringify(stored) })
const n2 = doc().finding_zones[0].categories[0].children[0].children[0]
expect(n2).toMatchObject({
reference_ids: [],
children: [],
review_status: 'inherited',
})
render(<FindingsHost />)
expect(screen.getAllByRole('treeitem').length).toBeGreaterThan(0)
})
it('a reload that brings bare nodes keeps the filled text, not dirty', async () => {
await openReady()
const stored = JSON.parse(baseText()) as Record<string, unknown>
stored.finding_zones = [
{
id: 'z',
name: name('Z'),
categories: [
{
id: 'c',
kind: 'dysfunction',
name: name('C'),
children: [{ id: 'n1', name: name('N1') }],
},
],
},
]
serverHas(JSON.stringify(stored), 7)
expect(
await store.getState().reloadServerDraft({ confirmed: true }),
).toEqual({
ok: true,
})
const state = store.getState()
expect(state.unsaved).toBe(false)
expect(state.savedText).toBe(state.documentText)
expect(state.savedRevision).toBe(7)
expect(doc().finding_zones[0].categories[0].children[0]).toMatchObject({
reference_ids: [],
children: [],
review_status: 'inherited',
})
})
it('maps the WAI-ARIA keys', async () => {
await openReady({ text: treeText() })
const all = buildItems(doc())
const open = new Set(all.map((i) => i.id))
const [zone, category] = all
expect(keyMove(all, zone, open, 'ArrowDown')).toEqual({
select: category.id,
})
expect(keyMove(all, category, open, 'ArrowLeft')).toEqual({
collapse: category.id,
})
expect(keyMove(all, all[4], open, 'ArrowRight')).toBeNull()
expect(keyMove(all, all[4], open, 'End')).toEqual({ select: all[4].id })
expect(keyMove(all, zone, new Set(), 'ArrowRight')).toEqual({
expand: zone.id,
})
})
})
describe('Constats tab', () => {
it('renders a tree with levels, and zones carry no badge', async () => {
await openReady({ text: treeText() })
render(<FindingsHost />)
expect(screen.getByRole('tree')).toBeInTheDocument()
const [zoneA] = items()
expect(zoneA).toHaveAttribute('aria-level', '1')
expect(zoneA).toHaveAttribute('aria-expanded', 'true')
expect(within(zoneA).queryByText('À confirmer')).toBeNull()
expect(items()).toHaveLength(3)
expect(within(items()[1]).getByText('À confirmer')).toBeInTheDocument()
})
it('moves with the arrows, opens and closes branches', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
items()[0].focus()
await user.keyboard('{ArrowDown}')
expect(items()[1]).toHaveFocus()
expect(items()[1]).toHaveAttribute('aria-selected', 'true')
await user.keyboard('{ArrowRight}')
expect(items()).toHaveLength(4)
await user.keyboard('{ArrowRight}')
expect(items()[2]).toHaveFocus()
await user.keyboard('{ArrowLeft}')
expect(items()[1]).toHaveFocus()
await user.keyboard('{ArrowLeft}')
expect(items()).toHaveLength(3)
await user.keyboard('{ArrowLeft}')
expect(items()[0]).toHaveFocus()
})
it('creates a zone only with both names', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Tête',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(screen.getByRole('alert')).toHaveTextContent('Renseignez le nom')
expect(doc().finding_zones).toHaveLength(2)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'Head',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(doc().finding_zones).toHaveLength(3)
expect(doc().finding_zones[2].id).toMatch(/^zone-[a-z2-7]{10}$/)
// the creation turns into the view of the new element, in the same dialog
expect(inFindingDialog().getByText('Zone de constats')).toBeInTheDocument()
expect(document.querySelector('#finding-name-fr')).toHaveTextContent('Tête')
expect(document.querySelector('#finding-new-name-fr')).toBeNull()
})
it('creates a category with a kind and a node under the selection', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await pick(user, items()[0])
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Nouv',
)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'New',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(screen.getByRole('alert')).toBeInTheDocument()
await user.selectOptions(screen.getByLabelText('Zone'), 'zone-a')
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(screen.getByRole('alert')).toBeInTheDocument()
await user.selectOptions(
screen.getByLabelText('Type de catégorie'),
'anamnesis',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
const categories = doc().finding_zones[0].categories
expect(categories).toHaveLength(2)
expect(categories[1]).toMatchObject({
kind: 'anamnesis',
review_status: 'to_confirm',
})
// the new category is selected behind its dialog: close it, add a node under it
await closeDialog(user)
await user.click(screen.getByRole('button', { name: 'Ajouter un constat' }))
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Fr',
)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'En',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(doc().finding_zones[0].categories[1].children).toHaveLength(1)
})
async function fillCategory(user: ReturnType<typeof userEvent.setup>) {
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Nouv',
)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'New',
)
await user.selectOptions(
screen.getByLabelText('Type de catégorie'),
'anamnesis',
)
}
it('lands in the zone chosen in the form, not the zone of the selected node (C46)', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
items()[0].focus()
await user.keyboard('{ArrowDown}{ArrowRight}{ArrowRight}')
expect(items()[2]).toHaveAttribute('aria-selected', 'true')
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
expect(screen.getByLabelText('Zone')).toHaveValue('')
await user.selectOptions(screen.getByLabelText('Zone'), 'zone-b')
expect(
screen.getByText('Nouvelle catégorie dans la zone « Zone B »'),
).toBeInTheDocument()
await fillCategory(user)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(doc().finding_zones[1].categories).toHaveLength(1)
expect(doc().finding_zones[1].categories[0].kind).toBe('anamnesis')
expect(doc().finding_zones[0].categories.map((c) => c.id)).toEqual([
'fcat-a',
])
})
it('appends the category after the existing ones of the chosen zone', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
await user.selectOptions(screen.getByLabelText('Zone'), 'zone-a')
await fillCategory(user)
await user.click(screen.getByRole('button', { name: 'Créer' }))
const ids = doc().finding_zones[0].categories.map((c) => c.id)
expect(ids).toEqual(['fcat-a', expect.any(String)])
})
it('is enabled with nothing selected and preselects nothing among several zones', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
const add = screen.getByRole('button', { name: 'Ajouter une catégorie' })
expect(add).toBeEnabled()
await pick(user, items()[2])
await user.click(add)
expect(screen.getByLabelText('Zone')).toHaveValue('')
})
it('preselects the zone when exactly one exists', async () => {
const text = edit(baseText(), {
op: 'insert',
element: {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
expect(screen.getByLabelText('Zone')).toHaveValue('zone-a')
expect(
screen.getByText('Nouvelle catégorie dans la zone « Zone A »'),
).toBeInTheDocument()
})
it('is disabled with its hint while no zone exists', async () => {
await openReady()
render(<FindingsHost />)
expect(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
).toBeDisabled()
expect(
screen.getByText("Créez d'abord une zone pour ajouter une catégorie."),
).toBeInTheDocument()
})
it('disables « Ajouter un constat » on a zone and at depth 8', async () => {
let text = treeText()
let path = ['fcat-a', 'node-a', 'node-b']
for (let i = 0; i < 5; i++) {
const id = `deep-${i}`
text = edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path },
element: { kind: 'finding_node', value: node(id) },
})
path = [...path, id]
}
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
const add = screen.getByRole('button', { name: 'Ajouter un constat' })
await pick(user, items()[0])
expect(add).toBeDisabled()
await pick(user, items()[1])
for (let i = 0; i < 30; i++) {
if (document.activeElement?.getAttribute('aria-level') === '8') break
await user.keyboard('{ArrowRight}')
}
expect(add).toBeEnabled()
await user.keyboard('{ArrowRight}{ArrowRight}')
expect(document.activeElement).toHaveAttribute('aria-level', '9')
expect(add).toBeDisabled()
})
it('marks reviewed and resets to confirm from the dialog, at once', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
await user.click(
inFindingDialog().getByRole('button', { name: 'Marquer comme relu' }),
)
expect(doc().finding_zones[0].categories[0].review_status).toBe('reviewed')
expect(within(items()[1]).getByText('Relu')).toBeInTheDocument()
await user.click(
inFindingDialog().getByRole('button', { name: 'Remettre à confirmer' }),
)
expect(doc().finding_zones[0].categories[0].review_status).toBe(
'to_confirm',
)
})
it('renames in the edit form: nothing is written before « Enregistrer », one update after', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
await startEdit(user)
const fr = inFindingDialog().getByLabelText('Nom (FR)')
await user.clear(fr)
await user.type(fr, 'Renommée')
await user.tab()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
const before = store.getState().undo.length
await user.click(
inFindingDialog().getByRole('button', { name: 'Enregistrer' }),
)
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Renommée')
expect(store.getState().undo.length).toBe(before + 1)
expect(inFindingDialog().getByRole('status')).toHaveTextContent(
'Modifications enregistrées',
)
expect(document.querySelector('#finding-name-fr')).toHaveTextContent(
'Renommée',
)
})
it('marks a node with set_status and a zone with mark_reviewed', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[0])
expect(
screen.queryByRole('button', { name: 'Remettre à confirmer' }),
).toBeNull()
await user.click(screen.getByRole('button', { name: 'Marquer comme relu' }))
const cat = doc().finding_zones[0].categories[0]
expect(cat.review_status).toBe('reviewed')
expect(cat.children[0].children[0].review_status).toBe('reviewed')
await closeDialog(user)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
await user.click(
screen.getByRole('button', { name: 'Remettre à confirmer' }),
)
expect(doc().finding_zones[0].categories[0].children[0].review_status).toBe(
'to_confirm',
)
})
it('reorders siblings with the arrows', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
expect(screen.getByRole('button', { name: 'Monter' })).toBeDisabled()
await closeDialog(user)
await user.click(items()[0])
await user.click(screen.getByRole('button', { name: 'Descendre' }))
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-b', 'zone-a'])
expect(labels()[0]).toContain('Zone B')
})
it('deletes with the descendants listed, then removes them', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
await user.click(
inFindingDialog().getByRole('button', { name: 'Supprimer' }),
)
const dialog = await deleteDialog()
expect(dialog.getByText(/aussi supprimés/)).toBeInTheDocument()
expect(dialog.getAllByRole('listitem')).toHaveLength(2)
await user.click(dialog.getByRole('button', { name: 'Supprimer' }))
expect(doc().finding_zones[0].categories).toEqual([])
// the deletion closes both dialogs: the finding layer is replaced, no Back step
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
expect(screen.queryByText('Cat A')).toBeNull()
})
it('lists the annotations that still use a zone and offers no deletion', async () => {
let text = treeText()
const anno = JSON.parse(text).annotations[0]
text = edit(text, {
op: 'update',
key: { kind: 'annotation', id: 'anno-a' },
element: {
kind: 'annotation',
value: { ...anno, finding_zone_id: 'zone-a' },
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[0])
await user.click(
inFindingDialog().getByRole('button', { name: 'Supprimer' }),
)
const dialog = await deleteDialog()
expect(dialog.getByText(/ne peut pas être supprimé/)).toBeInTheDocument()
expect(dialog.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(doc().finding_zones).toHaveLength(2)
})
it('is plain text and keyboard-navigable when read-only', async () => {
await openReady({ text: treeText() })
render(<FindingsHost readOnly />)
expect(
screen.queryByRole('button', { name: 'Ajouter une zone' }),
).toBeNull()
expect(screen.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(items()).toHaveLength(3)
const user = userEvent.setup()
await user.click(items()[1])
expect(screen.queryByRole('textbox')).toBeNull()
expect(
inFindingDialog().queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(document.querySelector('#finding-name-fr')).toHaveTextContent(
'Cat A',
)
})
it('edits descriptions (blank side omitted) and the vet flag in one save, cites at once', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
const node = () => doc().finding_zones[0].categories[0].children[0]
const save = () =>
user.click(inFindingDialog().getByRole('button', { name: 'Enregistrer' }))
await startEdit(user)
const fr = inFindingDialog().getByLabelText('Description (FR)')
await user.type(fr, 'Texte')
await user.click(
inFindingDialog().getByLabelText('Renvoi vers un vétérinaire'),
)
expect(node().description).toEqual({})
const before = store.getState().undo.length
await save()
expect(node().description).toEqual({ fr: 'Texte' })
expect(node().requires_vet_referral).toBe(true)
expect(store.getState().undo.length).toBe(before + 1)
await startEdit(user)
await user.clear(inFindingDialog().getByLabelText('Description (FR)'))
await save()
expect(node().description).toEqual({})
// « Citer une référence » is no part of the form: it acts at once, in view mode
await user.selectOptions(
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(node().reference_ids).toEqual(['ref-a'])
// a finding node lists its citations in the sheet, not inline
expect(
inFindingDialog().queryByRole('button', { name: /Retirer Alpha/ }),
).toBeNull()
expect(
inFindingDialog().getByRole('button', { name: '1 référence' }),
).toBeInTheDocument()
})
it('a family keeps its inline list of citations with « Retirer »', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
const family = () => doc().finding_zones[0].categories[0]
await user.selectOptions(
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(family().reference_ids).toEqual(['ref-a'])
await user.click(
inFindingDialog().getByRole('button', { name: /Retirer Alpha/ }),
)
expect(family().reference_ids).toEqual([])
expect(
inFindingDialog().getByText('Aucune référence citée.'),
).toBeInTheDocument()
})
it('the trigger shows exactly for the keys open_citations accepts', async () => {
let text = insert(treeText(), {
kind: 'reference',
value: { id: 'ref-a', type: 'book', citation: 'A', url: null, doi: null },
})
for (const item of buildItems(JSON.parse(text))) {
if (item.element.kind === 'zone') continue
text = edit(text, {
op: 'update',
key: item.key,
element: {
...item.element,
value: { ...item.element.value, reference_ids: ['ref-a'] },
} as never,
})
}
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}{ArrowRight}')
const all = buildItems(doc())
expect(items()).toHaveLength(all.length)
const truth: [string, boolean][] = []
for (const [index, item] of all.entries()) {
await user.click(items()[index])
await waitFor(() => expect(findingDialog()).not.toBeNull())
const shown = inFindingDialog().queryByRole('button', {
name: /^1 référence$/,
})
const start = initialNavigation('findings')
const accepted =
citationsOfView(
navigationReducer(start, {
type: 'open_citations',
citedBy: item.key,
}),
) !== null
expect(shown !== null, item.id).toBe(accepted)
truth.push([item.kind, shown !== null])
await closeDialog(user)
}
expect(truth).toEqual([
['zone', false],
['category', false],
['node', true],
['node', true],
['zone', false],
])
expect(all.some((item) => item.kind === 'category')).toBe(true)
expect(all.filter((item) => item.kind === 'node')).toHaveLength(2)
})
it('the trigger reads « expanded » while the sheet of its finding is open', async () => {
let text = insert(treeText(), {
kind: 'reference',
value: { id: 'ref-a', type: 'book', citation: 'A', url: null, doi: null },
})
const nodes = buildItems(JSON.parse(text)).filter((i) => i.kind === 'node')
for (const item of nodes) {
text = edit(text, {
op: 'update',
key: item.key,
element: {
...item.element,
value: { ...item.element.value, reference_ids: ['ref-a'] },
} as never,
})
}
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
const trigger = () =>
inFindingDialog().getByRole('button', { name: /^1 référence$/ })
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
expect(trigger()).toHaveAttribute('aria-controls', 'editor-citations-panel')
await user.click(trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
await user.click(
screen.getByRole('button', { name: 'Fermer les références' }),
)
await waitFor(() =>
expect(trigger()).toHaveAttribute('aria-expanded', 'false'),
)
})
it('a category has no vet flag; read-only hides the editing actions', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
const { rerender } = render(<FindingsHost />)
await user.click(items()[1])
await startEdit(user)
expect(screen.queryByLabelText('Renvoi vers un vétérinaire')).toBeNull()
expect(screen.getByLabelText('Description (FR)')).toBeInTheDocument()
rerender(<FindingsHost readOnly />)
expect(screen.queryByLabelText('Citer une référence')).toBeNull()
// the open form is kept, its fields read-only, « Enregistrer » disabled
expect(screen.getByLabelText('Nom (FR)')).toHaveAttribute('readonly')
expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
})
it('collapsing an ancestor of the selection selects the ancestor', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowRight}')
expect(items()[2]).toHaveAttribute('aria-selected', 'true')
await user.click(items()[0].querySelector('span') as HTMLElement)
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()).toHaveLength(2)
})
it('after a delete the previous sibling, else the parent, is selected and focused', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
const remove = async (row: HTMLElement) => {
await user.click(row)
await user.click(
inFindingDialog().getByRole('button', { name: 'Supprimer' }),
)
const dialog = await deleteDialog()
await user.click(dialog.getByRole('button', { name: 'Supprimer' }))
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
}
await remove(items()[2])
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-a'])
await waitFor(() => expect(items()[0]).toHaveFocus())
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
await remove(items()[1])
await waitFor(() => expect(items()[0]).toHaveFocus())
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
})
})
describe('the category form zone line (N1 review, C46)', () => {
it('names the chosen zone once it is chosen, nothing before the choice', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(
<FindingCreateForm
pending={{ kind: 'category', parent: null }}
readOnly={false}
guards={{
register: vi.fn(),
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
}}
onCreated={vi.fn()}
onClose={vi.fn()}
/>,
)
const line = () => document.querySelector('p.font-medium')?.textContent
expect(line()).toBeUndefined()
await user.selectOptions(screen.getByLabelText('Zone'), 'zone-a')
expect(line()).toBe('Nouvelle catégorie dans la zone « Zone A »')
})
})