Files
faunosteo/apps/app/tests/unit/editor-findings.test.tsx
T
bchanot 4499bc740c feat(editor): fifth tab « Références », citations panel from a finding
The reference library moves into a fifth editor tab (Général,
Annotations, Constats, Références, Vérification; under « Plus » below
640 px with Général and Constats). The header « Références » button is
removed. The side panel becomes the citations list of one finding,
opened only from a finding's trigger (owner GO 2026-11-12: never from a
family; the family keeps its inline list with « Retirer »). Selecting a
tab closes it; every close records one pending move applied after the
panel is gone, focus back to the trigger else the active tab button.
Vérification's reference issues land on the tab. e2e seed gains a
reference cited by « Constat A ».

Gates: typecheck, lint, test:run (app 1396), build, e2e:ui 251 passed;
e2e:shell 15 specs on db:sandbox (editor-equine never listed): 107
passed / 95 skipped / 2 failed (test remap dropped its edit), fixed and
rerun: editor-shell.spec 11 passed; full-row data guard: no
pre-existing row changed in any table. editor-equine.spec.ts helper
calls updated, not run.

## R-24 table (removed or rewritten assertions; old = fc3fec7 line, new = current file)

Unit tests:

| file:old line | old | new |
|---|---|---|
| editor-verification.test.tsx:87-96 | `navigate` called with target AND `expect.any(HTMLElement)` | called with the target only (opener dropped) |
| editor-verification.test.tsx:238-241 | `references[0]` path -> `{place:'references', citedBy:null}` | `{place:'tab', tab:'references', section:null}` |
| editor-verification.test.tsx:262-264 | `placeKey(references[9])` = `editor.place.references` | `editor.tab.references` |
| editor-navigation.test.ts:63 | targetOfKey reference -> `{place:'references', key, citedBy:null}` | `{place:'tab', tab:'references', section:null, key}` |
| editor-navigation.test.ts:80 | `referencesMounted` false at start | `citationsOf` null and `libraryReset` 0 |
| editor-navigation.test.ts:95-110 | go_to a reference opens the panel over the place | go_to a reference shows the Références tab with its focus request |
| editor-navigation.test.ts:112-122 | go_to a tab closes the panel (`references` object) | same, via `citationsOf` null |
| editor-navigation.test.ts:124-136 | select_tab keeps the panel | select_tab CLOSES the panel (P21), keeps section, no request |
| editor-navigation.test.ts:138-146 | `clear_cited_by` drops the filter | removed (action gone); replaced by `open_citations` refuses family/zone/view, `show_all_references` (closes, tab, reset bump), plain go_to leaves reset alone |
| editor-navigation.test.ts:160-175 | open/close references keep tab and section | open/close citations, same assertions on `citationsOf` |
| editor-mode.test.ts:100-109 | tabsFor four tabs, small more = general, findings | five tabs, small more = general, findings, references |
| editor-route.test.tsx:46,50 | TABS four, title « four tabs » | five |
| editor-route.test.tsx:139-146 | 640-1023 px four tabs | five tabs, tablist has `flex-wrap` |
| editor-route.test.tsx:149-161 | « Plus » lists Général, Constats | lists Général, Constats, Références |
| editor-route.test.tsx:168-190 | header button opens panel, ✕ returns focus to button | no header button, panel not mounted at start (full panel flow moved to editor-references-panel.test.tsx) |
| editor-route.test.tsx:192-206 | Escape closes, panel content kept for next opening | removed: the panel is no longer kept mounted (design choice 3); Escape/close covered in editor-references-panel + editor-escape |
| editor-route.test.tsx:208-218 | read-only: panel lists references, no edit control | read-only: the Références tab lists them, no textbox, no add button; plus new: tab keeps mounted when left |
| editor-tabs-lists.test.tsx:47,75,114,130 | render `ReferencesPanel` | render `ReferencesTab` |
| editor-tabs-lists.test.tsx:77 | selector `#reference-ref-a-url` | `#tab-reference-ref-a-url` |
| editor-tabs-lists.test.tsx:131-135 | read-only buttons = only « Fermer les références » | no button at all |
| editor-focus-request.test.tsx:166-171,200-202,346 | `ReferencesPanel` with `panel` props and focus | `ReferenceLibrary` with focus (same assertions) |
| editor-focus-request.test.tsx:226 | `ownedBy(ref,'citations')` is the request | `ownedBy(ref,'references')` is the request, `'citations'` undefined |
| editor-focus-request.test.tsx (Probe) | none | new: Vérification « Aller à » reference -> tab + focused row; reference path naming no element -> tab heading |
| editor-keep-alive.test.tsx:71,178-190 | add form survives closing/reopening the panel | survives leaving/returning to the Références tab (`#tab-reference-new-citation`) |
| editor-keep-alive.test.tsx:300-326 | « Aller à » without focus move commits Références text | a tab click without focus move commits it (one undo entry): « Aller à » is not reachable from the Références tab in R2.1 |
| editor-keep-alive.test.tsx:333-347 | Escape in panel reference field commits, panel hides | same, panel opened from a finding node, field `#panel-reference-ref-1-citation` |
| editor-keep-alive.test.tsx:350-363 | header toggle (no focus move) closes after committing | scrim click (no focus move) closes after committing |
| editor-keep-alive.test.tsx:425 | `referencesButton` click in the all-places sweep | `Références` added to the tab loop |
| editor-escape.test.tsx:218-227 | header button toggle, Escape on body closes panel, annotation selection kept | trigger-opened panel (A5), Escape closes it, `aria-expanded` back to false, selection kept after returning to Annotations |
| editor-escape.test.tsx:255-266 | Escape from tab row closes panel | same from the Constats tab button |
| editor-no-loss.test.tsx:146-153 | reference creation form, in the panel | in the Références tab, id `tab-reference-new-citation` |
| editor-no-loss.test.tsx:285-291 | focused header button survives crossing | focused tab button (Constats) survives crossing: no header button left |
| editor-no-loss.test.tsx:293-307 | references search in panel keeps focus/text | same in the Références tab body |
| editor-no-loss.test.tsx:390-400 | `everyPlace` ends by opening the panel | visits Références in the tab loop, no panel open |
| editor-no-loss-decisions.test.tsx:248-259 | open references panel holds the decision back | REMOVED: the panel exists only over Constats, decisions live in Annotations (hidden then); « a widening on another tab opens nothing » (same file) covers the withholding |
| editor-route-recovery.test.tsx:93-97 | recovery offer: header button opens panel, `aria-labelledby` | tab Références shows `editor-tab-references` labelled by `editor-references-title` |
| editor-references-panel.test.tsx (all) | header-button-driven panel tests incl. search, order, add, « Aller à » | split: panel tests (finding path only) stay in this file; library tests moved to new editor-references-tab.test.tsx (search matching, ↑/↓ only without search, counts, Ctrl+Z, read-only, « Aller à », add clears search, refused add keeps it); new: reset signal, ids unique with both mounted (P14), P6 fallback under « Plus » |

e2e (updated only, not run):

| file:old line | old | new |
|---|---|---|
| editor-shell.spec.ts:95-108 | panel keeps form text, no id repeats | Références tab keeps form text (`#tab-reference-new-citation`), ids unique with the panel open |
| editor-shell.spec.ts:121-142 | open panel leaves header and tab row clickable (incl. header Références button, add form) | `openCitations`; header button target and form steps dropped |
| editor-shell-journeys.spec.ts:113-123 | four tabs, `old` list includes « Références » | five tabs, « Références » removed from the old-layout list |
| editor-shell-journeys.spec.ts:246-249 | Aller à reference -> panel visible, close | `place('references')` visible, tab Références selected, row focus key, no close |
| editor-shell-layout.spec.ts:84-103 | overflow on four tabs + panel over drawing | five tabs + `openCitations`/`closeCitations` |
| editor-shell-layout.spec.ts:54-63 | local `goToTab` | removed, uses `openTab` |
| editor-shell-layout.spec.ts:140-158 | canvas width without/with panel over the drawing | E1: width measured before open and after a P21 switch to Annotations, asserted equal |
| editor-shell-layout.spec.ts:161-189 | axe on four tabs + open panel | five tabs + citations panel |
| editor-shell-layout.spec.ts:~255-310 | keyboard order began with `header` (the Références button) | `header` dropped from both orders (no focusable header control while the draft is clean); panel test selects Annotations before walking to `side` |
| editor-access.spec.ts:150-152,191-194,219-220 | axe/overflow with the panel at 320/375/768/800, 1024, read-only | same checks through `openCitations` (`showDrawing` calls dropped) |
| editor-shell-crossing.spec.ts:194-206 | references form with panel open, tab `annotations` | in the tab, focus expected on `editor-tab-references` |
| editor-shell-crossing.spec.ts:264-282 | panel open + add-form text across crossing | citations panel over a crossing, no typed-text step |
| editor-shell-crossing.spec.ts:~385-410 | decision withheld while panel open, Reprendre | REMOVED (state unreachable, see unit row) |
| editor-deselect.spec.ts:226-229 | Escape closes header-opened panel, selection kept | opened via Constats, Escape, back to Annotations, selection kept |
| editor-structures.spec.ts:80-122 | two references added, counts 2/1 | shape now holds `ref-a`: counts 3/2, `nth(1)` after move, saved list `['Référence A','Seconde référence']`, no panel |
| editor-equine.spec.ts:304-305,404-405 | openReferences/closeReferences | `openTab(page, dict, 'references')`: mis à jour, non exécuté, non vérifié |

Fix round 1: 1. e2e/shell/editor-shell.spec.ts « the open citations panel leaves the header and the tab row clickable »: before `openCitations`, the test now opens the Références tab and adds a reference through the library form (`#tab-reference-new-type` book, `#tab-reference-new-citation` « Smith 1999 », « Ajouter la référence »), so the draft is dirty and Save is enabled. All original assertion
2026-11-12 20:29:27 +01:00

663 lines
24 KiB
TypeScript

/** Lot I: the Constats tree. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, 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 FindingsTab from '@/components/editor/tabs/FindingsTab'
import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree'
import { 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'
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(),
}))
const props = { readOnly: false, navigate: vi.fn(), reloadSheet: vi.fn() }
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 ?? '')
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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
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}$/)
expect(
screen.getByLabelText('Nom (FR)', { selector: '#finding-name-fr' }),
).toHaveValue('Tête')
})
it('creates a category with a kind and a node under the selection', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(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',
})
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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
const add = screen.getByRole('button', { name: 'Ajouter une catégorie' })
expect(add).toBeEnabled()
await user.click(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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
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(<FindingsTab {...props} />)
const add = screen.getByRole('button', { name: 'Ajouter un constat' })
await user.click(items()[0])
expect(add).toBeDisabled()
await user.click(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('renames, marks reviewed and resets to confirm', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
await user.click(screen.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(
screen.getByRole('button', { name: 'Remettre à confirmer' }),
)
expect(doc().finding_zones[0].categories[0].review_status).toBe(
'to_confirm',
)
const fr = screen.getByLabelText('Nom (FR)', {
selector: '#finding-name-fr',
})
await user.clear(fr)
await user.type(fr, 'Renommée')
await user.tab()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('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(<FindingsTab {...props} />)
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 user.click(items()[1])
await user.keyboard('{ArrowRight}{ArrowDown}')
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(<FindingsTab {...props} />)
await user.click(items()[1])
expect(screen.getByRole('button', { name: 'Monter' })).toBeDisabled()
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(<FindingsTab {...props} />)
await user.click(items()[1])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/aussi supprimés/)).toBeInTheDocument()
expect(within(dialog).getAllByRole('listitem')).toHaveLength(2)
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
expect(doc().finding_zones[0].categories).toEqual([])
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(<FindingsTab {...props} />)
await user.click(items()[0])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(
within(dialog).getByText(/ne peut pas être supprimé/),
).toBeInTheDocument()
expect(
within(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(<FindingsTab {...props} 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(document.querySelector('#finding-name-fr')).toHaveTextContent(
'Cat A',
)
})
it('edits descriptions (blank side omitted), the vet flag and the cited references', 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(<FindingsTab {...props} />)
await user.click(items()[1])
await user.keyboard('{ArrowRight}{ArrowDown}')
const node = () => doc().finding_zones[0].categories[0].children[0]
const fr = screen.getByLabelText('Description (FR)')
await user.type(fr, 'Texte')
await user.tab()
expect(node().description).toEqual({ fr: 'Texte' })
await user.clear(fr)
await user.tab()
expect(node().description).toEqual({})
await user.click(screen.getByLabelText('Renvoi vers un vétérinaire'))
expect(node().requires_vet_referral).toBe(true)
await user.selectOptions(
screen.getByLabelText('Citer une référence'),
'ref-a',
)
expect(node().reference_ids).toEqual(['ref-a'])
await user.click(screen.getByRole('button', { name: /Retirer Alpha/ }))
expect(node().reference_ids).toEqual([])
})
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()
const openCitations = vi.fn()
render(<FindingsTab {...props} openCitations={openCitations} />)
await user.click(items()[1])
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])
const shown = screen.queryByRole('button', { name: /^1 référence$/ })
const start = initialNavigation('findings')
const accepted =
navigationReducer(start, { type: 'open_citations', citedBy: item.key })
.citationsOf !== null
expect(shown !== null, item.id).toBe(accepted)
truth.push([item.kind, shown !== null])
}
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('a category has no vet flag; read-only hides the editing actions', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
const { rerender } = render(<FindingsTab {...props} />)
await user.click(items()[1])
expect(screen.queryByLabelText('Renvoi vers un vétérinaire')).toBeNull()
rerender(<FindingsTab {...props} readOnly />)
expect(screen.queryByLabelText('Citer une référence')).toBeNull()
expect(screen.queryByRole('textbox')).toBeNull()
})
it('collapsing an ancestor of the selection selects the ancestor', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
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(<FindingsTab {...props} />)
await user.click(items()[2])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-a'])
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()[0]).toHaveFocus()
await user.click(items()[1])
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[0])
const second = (await screen.findAllByRole('dialog')).at(-1) as HTMLElement
await user.click(within(second).getByRole('button', { name: 'Supprimer' }))
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()[0]).toHaveFocus()
})
})
describe('the category form title (N1 review, C46)', () => {
it('names the chosen zone, and falls back to an existing label before the choice', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(
<FindingCreateForm
pending={{ kind: 'category', parent: null }}
onCreated={vi.fn()}
onCancel={vi.fn()}
/>,
)
const title = () => document.querySelector('p.font-medium')?.textContent
expect(title()).toBe('Ajouter une catégorie')
await user.selectOptions(screen.getByLabelText('Zone'), 'zone-a')
expect(title()).toBe('Nouvelle catégorie dans la zone « Zone A »')
})
})