Files
faunosteo/apps/app/tests/unit/editor-references-panel.test.tsx
T
bchanot c21995b3fb feat(editor): collapsible reference tiles in the Références tab
Board 23 / 24 / 27 tiles: closed (citation on two lines, type, « Citée
{n} fois » / « Non citée »), open (Type, DOI, URL as safe links, the
citers with « famille » badge and « Aller à »), edit (« Terminer » with a
leave guard re-committing every changed field; a refusal keeps edit
and focuses the field). A cited reference shows the deletion hint, an
uncited one keeps « Supprimer ». Read-only keeps DOI, URL, « Aller à ».
« Terminer » keeps focus in the field on press, so a refusal message
can no longer move the button under the pointer.

Gates: typecheck, lint, test:run (app 1419), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (editor-equine never listed): 111
passed / 99 skipped / 3 failed in the new editor-references.spec (two
test bugs, one app bug), fixed and rerun: 5 passed / 4 skipped; full-row
guard: no pre-existing row changed in any table.

## R-24 (removed or rewritten assertions)
| file | old | new |
|---|---|---|
| editor-citations.test.ts | `citationCounts` counts 2/1/0, memoised, empty | `citersOf`: ordered citers (Cat, Node), family flag, trail from zone, key, memoised, empty |
| editor-references-tab.test.tsx | cards say « citée N fois » (ref-a 1, ref-c 0) | « Citée 2 fois » (fixture gains a node citing ref-a), « Citée 1 fois », « Non citée » |
| same | ids `#tab-reference-ref-a-citation` exist when closed | header id `#tab-reference-0-ref-a-header`; field ids only inside an open edit tile |
| same | ↑/↓ on every card | in open tiles only, absent under a search |
| same | Ctrl+Z on an always-visible field | open tile, Modifier, then same assertion on `#tab-reference-0-ref-a-citation` |
| same | « Aller à » focuses the card (`listitem` count 3, focus key) | tile opened (aria-expanded true), header focused, 3 tiles |
| same | add: `getByText('Nouvelle source')` | tile header named « Nouvelle source » |
| same | read-only: no Supprimer / add | same after opening every tile |
| editor-tabs-lists.test.tsx | edit on blur and arrows on always-open cards | open tile, Modifier, blur applies, Terminer, Monter on opened tile |
| same | cited reference deletion refused in a dialog listing citers | REMOVED: no Supprimer on a cited tile (hint asserted, citer listed); uncited delete kept. The dialog's blocked path stays covered by `DeleteDialog`'s own tests |
| same | read-only: no button at all | read-only: facts shown, no Modifier / Supprimer / Citation textbox (header buttons exist now) |
| editor-keep-alive.test.tsx:~330 | tab-click commit of `#tab-reference-ref-1-citation` | opens tile + Modifier first, id `#tab-reference-0-ref-1-citation` |
| editor-keep-alive.test.tsx:~350,367 | `#panel-reference-ref-1-citation` | `#panel-reference-0-ref-1-citation` |
| editor-references-panel.test.tsx | « citée 2 fois / 1 fois » | « Citée 2 fois / 1 fois » |
| same | `#panel-reference-ref-a-citation`; no `#tab-reference-ref-a-citation` | `#panel-reference-0-ref-a-citation`; no `[id^="tab-reference-"]` while the tab tiles are closed |
| same | ids unique, tab and panel field ids present | tab tile opened in edit first; `tab-reference-0-ref-a-citation` and `panel-reference-0-ref-a-citation` unique |
| e2e editor-structures.spec.ts:~88-110 | citation inputs count 3/1/2, « citée 0 fois » x2, « citée 1 fois », move via row buttons | tile headers count, « Non citée » x2, « Citée 1 fois », tile opened before Monter/Supprimer, `tiles.nth(1)` contains the moved text (saved-list assertion unchanged) |

## i18n (fr / en)
Changed (in place, P18): `editor.references.cited_one|other`: « citée {count} fois » -> « Citée {count} fois »; « cited {count} time(s) » -> « Cited {count} time(s) ».
Added: `editor.references.uncited` Non citée / Not cited; `citers_one|other` « Citée {count} fois, par : » / « Cited {count} time(s), by: »; `no_citers` « Aucun constat ni aucune famille ne cite cette référence. » / « No finding or family cites this reference. »; `family` famille / family; `go_to` Aller à / Go to; `edit` Modifier / Edit; `done` Terminer / Done; `edit_title` Modifier la référence / Edit the reference; `url_label` URL / URL; `none_doi` Aucun / None; `none_url` Aucune / None; `new_tab` (nouvel onglet) / (new tab) (sr-only); `delete_hint` (REVUE wording, fr and en).
Removed: none. R10 grep (src, tests, e2e incl. editor-equine) found no reader of the old lowercase wording left.
2026-11-12 20:50:25 +01:00

331 lines
11 KiB
TypeScript

/** R2.1: the citations panel of one finding (opened from its trigger only), non-modal layout. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
commitMove,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
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()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string, url = '', doi = '') =>
({
kind: 'reference',
value: {
id,
type: 'book',
citation,
url: url || null,
doi: doi || null,
},
}) as const
function sheetText(): string {
let text = baseText()
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
text = insert(text, ref('ref-b', 'Denoix', 'https://exemple.org/Épaule'))
text = insert(text, ref('ref-c', 'Code rural', '', '10.1000/ABC'))
text = insert(text, {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
return 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: ['ref-a', 'ref-b'],
review_status: 'to_confirm',
children: [],
},
},
})
}
/** The sheet plus one finding node under Cat A, citing ref-a and ref-c. */
function nodeText(): string {
return edit(sheetText(), {
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: {},
reference_ids: ['ref-a', 'ref-c'],
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
}
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const panel = () => screen.getByTestId('editor-citations-panel')
const cards = () => within(panel()).getAllByRole('listitem')
const trigger = () =>
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name: '2 références' },
)
async function mount(width = 1280) {
serverHas(nodeText(), 3)
const user = userEvent.setup()
mountDraft({ width })
await ready()
return user
}
type User = ReturnType<typeof userEvent.setup>
async function select(user: User, label: RegExp) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
const family = screen.getByRole('treeitem', { name: /Cat A/ })
if (!screen.queryByRole('treeitem', { name: /Node A/ })) {
await user.click(family)
await user.keyboard('{ArrowRight}')
}
await user.click(screen.getByRole('treeitem', { name: label }))
}
const openFromFinding = async (user: User) => {
await select(user, /Node A/)
await user.click(trigger())
}
describe('citations panel opening', () => {
it('has no header button, only a finding opens it on its heading', async () => {
const user = await mount()
expect(screen.queryByRole('button', { name: 'Références' })).toBeNull()
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
await select(user, /Node A/)
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
expect(trigger()).toHaveAttribute('aria-controls', 'editor-citations-panel')
await user.click(trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(
within(panel()).getByRole('heading', { name: 'Références' }),
)
})
it('a family keeps its inline list and has no trigger', async () => {
const user = await mount()
await select(user, /Cat A/)
const detail = screen.getByRole('tabpanel', { name: 'Constats' })
expect(
within(detail).queryByRole('button', { name: /références?$/ }),
).toBeNull()
expect(
within(detail).getAllByRole('button', { name: /^Retirer / }),
).toHaveLength(2)
})
it('lists only the references of the finding, each with its count', async () => {
const user = await mount()
await openFromFinding(user)
const chip = within(panel()).getByTestId('references-filter-chip')
expect(chip).toHaveTextContent('Citées par « Node A » (2)')
expect(cards()).toHaveLength(2)
expect(cards()[0].textContent).toContain('Citée 2 fois')
expect(cards()[1].textContent).toContain('Citée 1 fois')
})
it('has no search, no add form and no order buttons', async () => {
const user = await mount()
await openFromFinding(user)
expect(within(panel()).queryByRole('searchbox')).toBeNull()
expect(
within(panel()).queryByRole('button', { name: 'Ajouter la référence' }),
).toBeNull()
expect(
within(panel()).queryByRole('button', { name: 'Descendre' }),
).toBeNull()
})
it('field ids carry the panel prefix', async () => {
const user = await mount()
await openFromFinding(user)
expect(
panel().querySelector('#panel-reference-0-ref-a-citation'),
).not.toBeNull()
expect(document.querySelector('[id^="tab-reference-"]')).toBeNull()
})
it('« Tout afficher » closes the panel and shows the tab on its heading', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(
within(panel()).getByRole('button', { name: 'Tout afficher (3)' }),
)
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(screen.getByRole('tab', { name: 'Références' })).toHaveAttribute(
'aria-selected',
'true',
)
const tabPanel = screen.getByRole('tabpanel', { name: 'Références' })
expect(document.activeElement).toBe(
within(tabPanel).getByRole('heading', { name: 'Références' }),
)
expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(3)
})
it('undo removing the cited finding closes the panel, the tab takes the focus', async () => {
const user = await mount()
await openFromFinding(user)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(
screen.getByRole('tab', { name: 'Constats' }),
)
})
})
describe('closing and layout', () => {
it('Escape, ✕ and the scrim close it, the focus goes back to the trigger', async () => {
const user = await mount()
await openFromFinding(user)
await user.keyboard('{Escape}')
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(trigger())
await user.click(trigger())
await user.click(
within(panel()).getByRole('button', { name: 'Fermer les références' }),
)
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(trigger())
await user.click(trigger())
fireEvent.click(screen.getByTestId('references-scrim'))
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(trigger())
})
it('selecting a tab closes it, the new tab button takes the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(
screen.getByRole('tab', { name: 'Vérification' }),
)
})
it('makes the tab panels inert while it is open, the header stays usable', async () => {
const user = await mount()
const tabPanel = () => screen.getAllByRole('tabpanel', { hidden: true })[0]
act(() => void commitMove(40))
await openFromFinding(user)
expect(tabPanel().parentElement).toHaveAttribute('inert')
expect(screen.getByRole('button', { name: /Enregistrer/ })).toBeEnabled()
expect(panel().closest('header')).toBeNull()
await user.keyboard('{Escape}')
expect(tabPanel().parentElement).not.toHaveAttribute('inert')
})
it('Ctrl+Z reverts a reference edit while open', async () => {
const user = await mount()
await openFromFinding(user)
const field = within(panel()).getByLabelText('Citation', {
selector: '#panel-reference-0-ref-a-citation',
})
await user.clear(field)
await user.type(field, 'Neuf')
fireEvent.blur(field)
const doc = () => JSON.parse(store.getState().documentText)
expect(doc().references[0].citation).toBe('Neuf')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
})
describe('read-only modes', () => {
it('show the citations with no edit control', async () => {
const user = await mount(800)
await openFromFinding(user)
expect(
within(panel()).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
expect(within(panel()).queryByRole('textbox')).toBeNull()
})
})
describe('ids', () => {
it('stay unique with the Références tab mounted and the panel open (P14)', async () => {
const user = await mount()
await user.click(screen.getByRole('tab', { name: 'Références' }))
await user.click(screen.getByRole('button', { name: /^Barone/ }))
await user.click(screen.getByRole('button', { name: 'Modifier' }))
await openFromFinding(user)
const ids = [...document.querySelectorAll('[id]')].map((e) => e.id)
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([])
expect(ids).toContain('tab-reference-0-ref-a-citation')
expect(ids).toContain('panel-reference-0-ref-a-citation')
})
})
describe('focus fallbacks (P6)', () => {
it('below 640 px the active tab sits under « Plus »: the finding vanishing gives it the focus', async () => {
const user = await mount(375)
await user.click(screen.getByRole('button', { name: 'Plus' }))
await user.click(screen.getByRole('button', { name: 'Constats' }))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await user.click(trigger())
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Plus' }),
)
})
})