Files
faunosteo/apps/app/tests/unit/editor-references-view.test.tsx
T
bchanot 8db6f4287f feat(editor): contextual citations panel of a finding (board 25)
The panel opens only from a finding's « {n} références » trigger: 34 rem
at most, never wider than the room, a scrim, slide in 180 ms and out
140 ms (motion/react; none under reduced motion, callbacks still fire).
It lists the finding's references as tiles with « Modifier », « Retirer
de ce constat » (one « Défaire » restores it and the review status) and
« Aller à »; dangling ids read « Référence introuvable »; zero left
reads « Ce constat ne cite plus aucune référence. ». « Tout afficher
dans l'onglet Références » resets search and sort, keeps open tiles and
edits. Every close (✕, Escape outside fields, scrim, tab, « Aller à »,
« Tout afficher », element gone) records one pending move applied
after the exit, page inert until then; focus back to the trigger, else
the active tab button. A refused draft cancels a user close; a forced
close drops it and announces « Saisie non appliquée : {field} ». Places
keeps a permanent dvh min-height; the panel fits the visible viewport
at every scroll position, document size unchanged.

Gates: typecheck, lint, test:run (app 1488), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (admin and editor-equine excluded):
117 passed / 107 skipped / 0 failed, rerun after the fix rounds: 118
passed / 108 skipped / 0 failed; layout spec 13 passed after round 2;
full-row guard: no pre-existing row changed in any table. Known limit:
landscape 667 x 375 at scroll 0 leaves ~13 px of panel (the trigger is
below the fold there).

## R-24 (removed or rewritten assertions)

| file | old | new |
|---|---|---|
| editor-references-panel.test.tsx (whole file) | R2.1 interim-panel tests, synchronous closes | rewritten: 39 tests (opening, motion, close matrix in both modes, exit, Retirer, P22'', library + history) |
| same, opening | heading `Références` focused right after the click | heading `Références citées` focused after the enter (`waitFor`), `aria-expanded` only after click |
| same | chip `references-filter-chip` « Citées par « Node A » (2) » | REMOVED (REVUE: path line + count line « 2 références citées par ce constat ») |
| same | `listitem` cards « Citée 2 fois » | tiles (`ul > li`) with the same counts, in the finding's order |
| same | field id `#panel-reference-0-ref-a-citation` present at once | tile opened + « Modifier » first (tiles since R2.2) |
| same | « Tout afficher (3) », sync | « Tout afficher dans l'onglet Références », after exit, heading focus asserted |
| same | Escape / ✕ / scrim / tab / vanish: sync null panel | all `await closed()` + `document.activeElement` checks, `describe.each` normal / reduced motion |
| same | « makes the tab panels inert while open, header usable » | split: inert page + inert panel until the exit ends then lifted; « Défaire / Refaire usable »; the `Enregistrer` enabled check dropped (covered by the focus-moved-off test) |
| same | Ctrl+Z test on an always-open field | open tile + Modifier first |
| same | read-only: no Supprimer, no textbox | open tile: no Modifier, no Retirer, no textbox |
| same | P6 under « Plus »: sync | in the close matrix, awaited |
| editor-escape.test.tsx (2 tests) | `expect(citations()).toBeNull()` right after Escape | `await waitFor(...)`; trigger `aria-expanded` false after exit |
| editor-keep-alive.test.tsx | « Escape in a citations panel field commits the text before the panel closes » | REPLACED by « Escape in a field of a panel tile neither closes nor commits » (A5, P27) |
| same | scrim click closes the panel after committing, sync, id on a closed tile | tile opened in edit first, close awaited, commit asserted before the exit |
| editor-focus-request.test.tsx | `ReferenceLibrary` with `resetSignal`; `ownedBy(ref,'citations')` undefined | `ReferencesTab` (+ `reloadSheet`); the `'citations'` assertion removed with the type |
| editor-references-tab / -view.test.tsx | `ReferenceLibrary`, `resetSignal` | `ReferencesTab`, `libraryReset` (+ `reloadSheet`) |
| e2e support `openCitations` | waited for the panel visible | also waits for the heading focus (slide over) |

New unit coverage: editor-citations-exit.test.tsx (hook, fake timers), editor-findings (aria-expanded per finding),
`useDecisionsOpen` gate, panel file (Retirer + status + one undo, P20 chain, zero state, dangling id, P4 reset, P6 after undo,
P22'' four paths, reduced motion, inert/exit, second close, tab replace, focus-moved-off).

## i18n (FR / EN)

Added: `editor.references.panel_title` Références citées / Cited references; `panel_count_one|other` « {count} référence citée par
ce constat » / « {count} références citées par ce constat » and « {count} reference cited by this finding » / « … references … »;
`panel_show_all` Tout afficher dans l'onglet Références / Show all in the References tab; `panel_empty` Ce constat ne cite plus
aucune référence. / This finding no longer cites any reference.; `remove_citation` Retirer de ce constat / Remove from this finding;
`this_finding` ce constat / this finding; `missing` Référence introuvable / Reference not found; `draft_dropped`
Saisie non appliquée : {field} / Entry not applied: {field}.
Changed: none. Removed: `editor.references.cited_by` (« Citées par « {name} » ({count}) » / « Cited by « {name} » ({count}) »),
`editor.references.show_all` (« Tout afficher ({count}) » / « Show all ({count}) »). R10 grep over src, tests and e2e including
editor-equine: no reader left. `editor-equine` has no panel reference: « updated, not run » (nothing to update). The three
provisional FR labels are exactly as listed in the brief; `…` = the refused field's label.
2026-11-12 22:27:32 +01:00

495 lines
17 KiB
TypeScript

/** R2.3: search, sort, count, no-result notice, A1, the add flow, the pin and the reset. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
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(),
}))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string, type: ReferenceType) =>
({
kind: 'reference',
value: { id, type, citation, url: null, doi: null },
}) as const
/** Stored order r1..r5; counts r2: 2, r1: 1, r5: 1, r3: 0, r4: 0. */
function sortText(): string {
let text = baseText()
text = insert(text, ref('r1', 'Zèbre 10', 'web'))
text = insert(text, ref('r2', 'zebre 9', 'journal'))
text = insert(text, ref('r3', 'Étude', 'book'))
text = insert(text, ref('r4', 'etude', 'book'))
text = insert(text, ref('r5', 'Alpha', 'legal'))
text = insert(text, {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
text = edit(text, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: name('Cat A'),
description: {},
reference_ids: ['r1', 'r2', 'r5'],
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: ['r2'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
const doc = () => JSON.parse(store.getState().documentText)
const lib = (readOnly = false, extra = {}) => (
<ReferencesTab
readOnly={readOnly}
navigate={vi.fn()}
reloadSheet={vi.fn()}
{...extra}
/>
)
async function mount(readOnly = false) {
await openReady({ text: sortText() })
const user = userEvent.setup()
const view = render(lib(readOnly))
return { user, view }
}
const search = () =>
screen.getByRole('searchbox', { name: 'Rechercher une référence' })
const sortBox = () => screen.getByLabelText('Trier par')
/** The ids shown, in display order (header ids `tab-reference-<position>-<id>-header`). */
const order = () =>
[...document.querySelectorAll('button[id$="-header"]')].map((button) =>
button.id.replace(/^tab-reference-\d+-(.*)-header$/, '$1'),
)
const header = (id: string) =>
document.querySelector<HTMLElement>(`button[id$="-${id}-header"]`)!
const snapshot = () => ({
text: store.getState().documentText,
history: store.getState().undo.length,
unsaved: store.getState().unsaved,
})
describe('the four sorts', () => {
it('reorder the tiles for display, each stable on ties', async () => {
const { user } = await mount()
expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5'])
await user.selectOptions(sortBox(), 'citation')
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
await user.selectOptions(sortBox(), 'count')
expect(order()).toEqual(['r2', 'r1', 'r5', 'r3', 'r4'])
await user.selectOptions(sortBox(), 'type')
expect(order()).toEqual(['r3', 'r4', 'r2', 'r5', 'r1'])
await user.selectOptions(sortBox(), 'sheet')
expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5'])
})
it('offers the four labelled options', async () => {
await mount()
const labels = within(sortBox())
.getAllByRole('option')
.map((option) => option.textContent)
expect(labels).toEqual([
'Ordre de la fiche',
'Citation (A → Z)',
'Nombre de citations',
'Type',
])
})
it('keep the document, its stored order and the history untouched (BDR-114)', async () => {
const { user } = await mount()
const before = snapshot()
for (const sort of ['citation', 'count', 'type', 'sheet']) {
await user.selectOptions(sortBox(), sort)
}
await user.type(search(), 'zebre')
await user.selectOptions(sortBox(), 'citation')
await user.clear(search())
await user.type(search(), 'zzz')
await user.click(
screen.getAllByRole('button', { name: 'Effacer la recherche' })[0],
)
expect(snapshot()).toEqual(before)
expect(doc().references.map((r: { id: string }) => r.id)).toEqual([
'r1',
'r2',
'r3',
'r4',
'r5',
])
})
})
describe('the count line', () => {
it('says « {n} références », then « {n} références sur {total} »', async () => {
const { user } = await mount()
expect(screen.getByText('5 références')).toBeInTheDocument()
await user.type(search(), 'zebre')
expect(screen.getByText('2 références sur 5')).toBeInTheDocument()
await user.clear(search())
await user.type(search(), 'alpha')
expect(screen.getByText('1 référence sur 5')).toBeInTheDocument()
await user.clear(search())
await user.type(search(), 'zzz')
expect(screen.getByText('0 référence sur 5')).toBeInTheDocument()
})
})
describe('the count with a pinned tile', () => {
it('counts the matches only, the pinned tile stays shown', async () => {
const { user } = await mount()
await startEdit(user, 'r1')
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
expect(screen.getByText('1 référence sur 5')).toBeInTheDocument()
})
})
describe('clearing the search', () => {
it('the button appears with a query, empties it and refocuses the field', async () => {
const { user } = await mount()
expect(
screen.queryByRole('button', { name: 'Effacer la recherche' }),
).toBeNull()
await user.type(search(), 'etude')
expect(order()).toEqual(['r3', 'r4'])
await user.click(
screen.getByRole('button', { name: 'Effacer la recherche' }),
)
expect(search()).toHaveValue('')
expect(document.activeElement).toBe(search())
expect(order()).toHaveLength(5)
})
it('Escape empties a non-empty search and stops there (P12)', async () => {
const { user } = await mount()
const bubbled = vi.fn()
document.body.addEventListener('keydown', bubbled)
await user.type(search(), 'etude')
await user.keyboard('{Escape}')
expect(search()).toHaveValue('')
expect(bubbled.mock.calls.at(-1)?.[0].defaultPrevented).toBe(true)
bubbled.mockClear()
await user.keyboard('{Escape}')
expect(bubbled).toHaveBeenCalledTimes(1)
expect(bubbled.mock.calls[0][0].defaultPrevented).toBe(false)
document.body.removeEventListener('keydown', bubbled)
})
})
describe('no result (board 24 B)', () => {
it('shows the notice with its own clear button, and no reorder hint', async () => {
const { user } = await mount()
await user.type(search(), 'radiographie')
expect(order()).toEqual([])
const notice = screen.getByRole('status', {
name: '',
})
expect(notice).toHaveTextContent(
"Aucune référence ne contient « radiographie ». La recherche porte sur la citation, le DOI et l'URL.",
)
expect(screen.queryByText(/Pour réorganiser/)).toBeNull()
await user.click(
within(notice).getByRole('button', { name: 'Effacer la recherche' }),
)
expect(search()).toHaveValue('')
expect(document.activeElement).toBe(search())
expect(order()).toHaveLength(5)
})
})
describe('the move buttons (A1)', () => {
const movers = () => screen.queryAllByRole('button', { name: 'Descendre' })
const hint = () => screen.queryByText(/Pour réorganiser, affichez/)
const openAll = async (user: User) => {
for (const button of document.querySelectorAll<HTMLElement>(
'button[id$="-header"]',
)) {
await user.click(button)
}
}
it('exist only in sheet order without a search', async () => {
const { user } = await mount()
await openAll(user)
expect(movers()).toHaveLength(5)
expect(hint()).toBeNull()
await user.selectOptions(sortBox(), 'citation')
expect(movers()).toHaveLength(0)
expect(hint()).not.toBeNull()
await user.selectOptions(sortBox(), 'sheet')
expect(movers()).toHaveLength(5)
await user.type(search(), 'e')
expect(movers()).toHaveLength(0)
expect(hint()).not.toBeNull()
await user.selectOptions(sortBox(), 'type')
expect(movers()).toHaveLength(0)
await user.clear(search())
expect(movers()).toHaveLength(0)
expect(hint()).not.toBeNull()
})
it('are absent in read-only, and so is the hint', async () => {
const { user } = await mount(true)
await openAll(user)
await user.selectOptions(sortBox(), 'count')
expect(movers()).toHaveLength(0)
expect(hint()).toBeNull()
expect(
screen.queryByRole('button', { name: 'Ajouter une référence' }),
).toBeNull()
})
})
/** Opens the tile of `id` and enters edit. */
async function startEdit(user: User, id: string) {
await user.click(header(id))
const item = header(id).closest('li')!
await user.click(within(item).getByRole('button', { name: 'Modifier' }))
return item
}
describe('the tile in edit is pinned (P23)', () => {
it('keeps its index when the sort changes', async () => {
const { user } = await mount()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r1')
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
await user.selectOptions(sortBox(), 'count')
expect(order()).toEqual(['r2', 'r5', 'r3', 'r4', 'r1'])
await user.selectOptions(sortBox(), 'sheet')
expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5'])
})
it('starts in sheet order and holds its place under a later sort', async () => {
const { user } = await mount()
await startEdit(user, 'r3')
await user.selectOptions(sortBox(), 'citation')
expect(order()).toEqual(['r5', 'r4', 'r3', 'r2', 'r1'])
})
it('stays shown under a search that does not match it, until it leaves edit', async () => {
const { user } = await mount()
const item = await startEdit(user, 'r1')
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
expect(within(item).getByLabelText('Citation')).toBeInTheDocument()
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
expect(order()).toEqual(['r5'])
})
it('is suspended in read-only: the tile renders its read view', async () => {
const { user, view } = await mount()
await startEdit(user, 'r1')
await user.selectOptions(sortBox(), 'citation')
view.rerender(lib(true))
expect(screen.queryByLabelText('Citation')).toBeNull()
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
})
})
describe('adding (P24)', () => {
const add = () =>
screen.getByRole('button', { name: 'Ajouter une référence' })
const draftCitation = () =>
document.querySelector<HTMLElement>('#tab-reference-new-citation')
it('resets search and sort, appends a draft tile in edit, citation focused', async () => {
const { user } = await mount()
await user.selectOptions(sortBox(), 'count')
await user.type(search(), 'e')
await user.click(add())
expect(search()).toHaveValue('')
expect(sortBox()).toHaveValue('sheet')
expect(order()).toHaveLength(5)
expect(document.activeElement).toBe(draftCitation())
expect(screen.getByLabelText('Type')).toHaveValue('')
expect(
within(screen.getByLabelText('Type')).getByText('Choisir…'),
).toBeInTheDocument()
expect(
screen.getByText('Type et citation obligatoires.'),
).toBeInTheDocument()
expect(snapshot().history).toBe(0)
})
it('creates the reference in one modification; the tile stays open, out of edit, focused', async () => {
const { user } = await mount()
await user.click(add())
await user.selectOptions(screen.getByLabelText('Type'), 'book')
await user.type(draftCitation()!, 'Nouvelle source')
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
expect(store.getState().undo.length).toBe(1)
expect(doc().references).toHaveLength(6)
const id = doc().references[5].id
expect(order()).toHaveLength(6)
expect(header(id)).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(header(id))
expect(draftCitation()).toBeNull()
expect(
within(header(id).closest('li')!).getByRole('button', {
name: 'Modifier',
}),
).toBeInTheDocument()
})
it('a second click on the button takes the focus back to the citation', async () => {
const { user } = await mount()
await user.click(add())
await user.click(search())
await user.click(add())
expect(document.activeElement).toBe(draftCitation())
expect(
document.querySelectorAll('#tab-reference-new-citation'),
).toHaveLength(1)
})
it('leaves the tile in edit first: a refused field cancels the add (P22)', async () => {
const { user } = await mount()
const item = await startEdit(user, 'r1')
const url = within(item).getByLabelText('Adresse web (URL)')
await user.type(url, 'exemple.org')
await user.click(add())
expect(draftCitation()).toBeNull()
expect(document.activeElement).toBe(url)
await user.clear(url)
await user.click(add())
expect(draftCitation()).not.toBeNull()
expect(within(item).queryByLabelText('Citation')).toBeNull()
})
it('keeps the draft hidden in read-only and resumes it when editable again', async () => {
const { user, view } = await mount()
await user.click(add())
await user.type(draftCitation()!, 'En cours')
view.rerender(lib(true))
expect(draftCitation()).not.toBeVisible()
view.rerender(lib(false))
expect(draftCitation()).toBeVisible()
expect(draftCitation()).toHaveValue('En cours')
})
})
describe('the reset path (« Tout afficher »)', () => {
it('empties the search and the sort, keeping open tiles and the tile in edit', async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
const view = render(lib(false, { libraryReset: 0 }))
await user.click(header('r2'))
const item = await startEdit(user, 'r1')
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'e')
view.rerender(lib(false, { libraryReset: 1 }))
expect(search()).toHaveValue('')
expect(sortBox()).toHaveValue('sheet')
expect(order()).toHaveLength(5)
expect(header('r2')).toHaveAttribute('aria-expanded', 'true')
expect(within(item).getByLabelText('Citation')).toBeInTheDocument()
})
})
describe('« Aller à » a reference hidden by the search (P3, P8)', () => {
const request = (id: string, serial: number) => ({
target: targetOfKey({ kind: 'reference', id }),
serial,
})
it('clears the search only, opens the tile, focuses its button, keeps other tiles open', async () => {
const { user, view } = await mount()
await user.click(header('r2'))
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'alpha')
await act(async () =>
view.rerender(lib(false, { focus: request('r3', 1) })),
)
expect(search()).toHaveValue('')
expect(sortBox()).toHaveValue('citation')
expect(header('r3')).toHaveAttribute('aria-expanded', 'true')
expect(header('r2')).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(header('r3'))
})
it('keeps a search that does not hide it', async () => {
const { user, view } = await mount()
await user.type(search(), 'etude')
await act(async () =>
view.rerender(lib(false, { focus: request('r4', 1) })),
)
expect(search()).toHaveValue('etude')
expect(document.activeElement).toBe(header('r4'))
expect(header('r4')).toHaveAttribute('aria-expanded', 'true')
})
})
describe('state of a reference that left the document (P23-prime)', () => {
it('is dropped: undoing the removal brings the tile back closed and out of edit', async () => {
const { user } = await mount()
await startEdit(user, 'r4')
act(() => {
store
.getState()
.commit({ op: 'remove', key: { kind: 'reference', id: 'r4' } })
})
expect(order()).toEqual(['r1', 'r2', 'r3', 'r5'])
act(() => {
store.getState().undoStep()
})
expect(order()).toContain('r4')
expect(header('r4')).toHaveAttribute('aria-expanded', 'false')
expect(
within(header('r4').closest('li')!).queryByLabelText('Citation'),
).toBeNull()
})
})