Files
faunosteo/apps/app/tests/unit/editor-references-panel.test.tsx
T
bchanot 1bf27014b3 fix(editor): one history entry per reference edit, focus kept
Final review fixes. « Terminer » and every panel close re-committed the
edited field against a stale value, adding a second identical history
entry so the first « Défaire » seemed to do nothing: the tile now reads
the latest applied value (tests assert the undo-length delta). A tile
leaving the search on « Terminer » stays pinned until the next view
change and keeps focus; « Ajouter la référence » resets search and sort
and focuses the new tile. Also: refused draft dropped on a read-only
flip is announced; arrow keys respect a refused tab switch; pinned
index kept across read-only; the panel announces « Références citées »;
search text inserted literally; « Aller à » names its citer; the edit
header's name starts with « Terminer. »; undo removing the focused panel
tile moves focus per P20; no-result announced once; docs corrected.

Gates: typecheck, lint, test:run (app 1510), build, e2e:ui 251;
e2e:shell 16 specs (admin and editor-equine excluded): 117 passed / 108
skipped / 1 failed (crossing:211 stuck on the MFA step-up screen before
the editor), rerun alone 11 passed; full-row guard: no pre-existing row
changed in any table.
2026-11-13 01:08:00 +01:00

855 lines
30 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** R2.4: the citations panel of one finding (board 25): contents, « Retirer », motion, closes, focus. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { 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'
import { setReducedMotion } from '../helpers/motion'
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)
setReducedMotion(false)
})
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 (default: citing ref-a and ref-c). */
function nodeText(ids = ['ref-a', 'ref-c']): 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: ids,
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 hasPanel = () => screen.queryByTestId('editor-citations-panel') !== null
const layer = () => panel().closest('[data-place="citations"]')!
const tiles = () => [...panel().querySelectorAll('ul > li')]
const trigger = (name = '2 références') =>
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name },
)
const heading = () =>
within(panel()).getByRole('heading', { name: 'Références citées' })
const doc = () => JSON.parse(store.getState().documentText)
const nodeA = () =>
doc().finding_zones[0].categories[0].children[0] as {
reference_ids: string[]
review_status: string
}
const closed = () => waitFor(() => expect(hasPanel()).toBe(false))
const focusIs = (element: () => Element) =>
waitFor(() => expect(document.activeElement).toBe(element()))
async function mount(width = 1280, text = nodeText()) {
serverHas(text, 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 }))
}
/** The panel of Node A, open and in place: its heading holds the focus. */
async function openFromFinding(user: User, name = '2 références') {
await select(user, /Node A/)
await user.click(trigger(name))
await focusIs(heading)
}
const link = () =>
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
})
const closeButton = () =>
within(panel()).getByRole('button', { name: 'Fermer les références' })
describe('opening', () => {
it('has no header button; only a finding opens it, its heading takes the focus after the slide', async () => {
const user = await mount()
expect(screen.queryByRole('button', { name: 'Références' })).toBeNull()
expect(hasPanel()).toBe(false)
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).not.toBe(heading())
await focusIs(heading)
expect(panel()).toHaveAttribute('aria-labelledby', 'editor-citations-title')
})
it('a family keeps its inline list: no trigger, no panel', 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)
expect(hasPanel()).toBe(false)
})
it('shows the path, the count, and only the references of the finding as tiles', async () => {
const user = await mount()
await openFromFinding(user)
expect(panel()).toHaveTextContent('Zone A › Cat A › Node A')
expect(panel()).toHaveTextContent('2 références citées par ce constat')
expect(tiles()).toHaveLength(2)
expect(tiles()[0].textContent).toContain('Barone')
expect(tiles()[0].textContent).toContain('Citée 2 fois')
expect(tiles()[1].textContent).toContain('Code rural')
expect(tiles()[1].textContent).toContain('Citée 1 fois')
expect(panel()).not.toHaveTextContent('Denoix')
})
it('an open tile marks the current finding and offers Modifier and « Retirer de ce constat »', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
const tile = tiles()[0] as HTMLElement
expect(within(tile).getByText('ce constat')).toBeInTheDocument()
expect(
within(tile).getAllByRole('button', { name: /^Aller à / }),
).toHaveLength(2)
expect(within(tile).getByRole('button', { name: 'Modifier' })).toBeVisible()
expect(
within(tile).getByRole('button', { name: 'Retirer de ce constat' }),
).toBeVisible()
for (const absent of ['Supprimer', 'Monter', 'Descendre']) {
expect(within(panel()).queryByRole('button', { name: absent })).toBeNull()
}
})
it('has no search, no add control; field ids carry the panel prefix', async () => {
const user = await mount()
await openFromFinding(user)
expect(within(panel()).queryByRole('searchbox')).toBeNull()
expect(
within(panel()).queryByRole('button', { name: /Ajouter/ }),
).toBeNull()
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
expect(
panel().querySelector('#panel-reference-0-ref-a-citation'),
).not.toBeNull()
expect(document.querySelector('[id^="tab-reference-"]')).toBeNull()
})
it('ids 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)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
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')
})
it('read-only: the tiles show, no Modifier, no Retirer, no field', async () => {
const user = await mount(800)
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
expect(
within(panel()).queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(
within(panel()).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
expect(within(panel()).queryByRole('textbox')).toBeNull()
})
})
describe('motion', () => {
const slid = () => (layer().firstElementChild as HTMLElement).style.transform
it('slides in from the right and fades the scrim, the page behind inert', async () => {
const user = await mount()
await select(user, /Node A/)
await user.click(trigger())
expect(slid()).toMatch(/translateX\(/)
expect(screen.getByTestId('references-scrim')).toBeInTheDocument()
expect(panel().closest('header')).toBeNull()
await focusIs(heading)
expect(slid()).not.toMatch(/translateX\([1-9]/)
})
it('reduced motion: no slide, the same lifecycle', async () => {
setReducedMotion(true)
const user = await mount()
await select(user, /Node A/)
await user.click(trigger())
expect(slid()).not.toMatch(/translateX\(/)
await focusIs(heading)
await user.click(closeButton())
await closed()
await focusIs(() => trigger())
})
})
const MODES = [
['motion', false],
['reduced motion', true],
] as const
describe.each(MODES)('closing, %s', (_label, reduced) => {
beforeEach(() => setReducedMotion(reduced))
it('✕, Escape and the scrim each close it after the exit: the trigger holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(heading)
await user.keyboard('{Escape}')
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(heading)
fireEvent.click(screen.getByTestId('references-scrim'))
await closed()
await focusIs(() => trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('Escape with nothing focused closes it too', async () => {
const user = await mount()
await openFromFinding(user)
;(document.activeElement as HTMLElement).blur()
await user.keyboard('{Escape}')
await closed()
await focusIs(() => trigger())
})
it('« Tout afficher » closes it, shows the tab, the heading holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
await closed()
expect(screen.getByRole('tab', { name: 'Références' })).toHaveAttribute(
'aria-selected',
'true',
)
const tabPanel = screen.getByRole('tabpanel', { name: 'Références' })
await focusIs(() =>
within(tabPanel).getByRole('heading', { name: 'Références' }),
)
expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(3)
})
it('selecting a tab closes it, the new tab button holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
await focusIs(() => screen.getByRole('tab', { name: 'Vérification' }))
})
it('« Aller à » a citer from a panel tile closes it and lands on that finding', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
const go = within(panel()).getAllByRole('button', { name: /^Aller à / })
await user.click(go[0])
await closed()
await focusIs(() => screen.getByRole('treeitem', { name: /Cat A/ }))
})
it('the finding vanishing closes it, the active tab button holds 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'],
},
})
})
await closed()
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
})
it('below 640 px the active tab sits under « Plus »: it holds 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())
await focusIs(heading)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await closed()
await focusIs(() => screen.getByRole('button', { name: 'Plus' }))
})
})
describe('the exit', () => {
it('keeps the page and the panel inert until it is over, then lifts it', async () => {
const user = await mount()
const page = () =>
screen.getAllByRole('tabpanel', { hidden: true })[0].parentElement
await openFromFinding(user)
expect(page()).toHaveAttribute('inert')
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(layer()).toHaveAttribute('inert')
expect(page()).toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
await closed()
expect(page()).not.toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('a second close is a no-op, a tab choice replaces the pending move', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
fireEvent.keyDown(layer(), { key: 'Escape' })
fireEvent.click(screen.getByTestId('references-scrim'))
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
await focusIs(() => screen.getByRole('tab', { name: 'Vérification' }))
})
it('leaves a focus the user placed elsewhere during the exit alone', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
await user.click(closeButton())
const save = screen.getByRole('button', { name: /Enregistrer/ })
act(() => save.focus())
await closed()
await new Promise((resolve) => setTimeout(resolve, 50))
expect(document.activeElement).toBe(save)
})
it('Défaire and Refaire stay usable while it is open', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
const undo = screen.getByRole('button', { name: /Défaire/ })
await waitFor(() => expect(undo).toBeEnabled())
await user.click(undo)
expect(hasPanel()).toBe(true)
expect(screen.getByRole('button', { name: /Refaire/ })).toBeEnabled()
})
})
describe('the library and the history around the panel', () => {
it('« Tout afficher » resets the search and the sort of the tab, open tiles kept (P4)', async () => {
const user = await mount()
await user.click(screen.getByRole('tab', { name: 'Références' }))
const tab = () => screen.getByRole('tabpanel', { name: 'Références' })
await user.type(within(tab()).getByRole('searchbox'), 'Barone')
await user.click(within(tab()).getByRole('button', { name: /^Barone/ }))
await user.selectOptions(
within(tab()).getByLabelText('Trier par'),
'citation',
)
await openFromFinding(user)
await user.click(link())
await closed()
expect(within(tab()).getByRole('searchbox')).toHaveValue('')
expect(within(tab()).getByLabelText('Trier par')).toHaveValue('sheet')
expect(within(tab()).getAllByRole('listitem').length).toBeGreaterThan(2)
expect(
within(tab()).getByRole('button', { name: /^Barone/ }),
).toHaveAttribute('aria-expanded', 'true')
await focusIs(() =>
within(tab()).getByRole('heading', { name: 'Références' }),
)
})
it('an undo that removes the finding closes it: the active tab button holds the focus (P6)', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
element: {
kind: 'finding_node',
value: {
id: 'fnode-b',
name: name('Node B'),
description: {},
reference_ids: ['ref-b'],
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
})
await select(user, /Node B/)
await user.click(trigger('1 référence'))
await focusIs(heading)
act(() => void store.getState().undoStep())
await closed()
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
})
})
describe('« Retirer de ce constat »', () => {
const retire = (user: User, at = 0) =>
user.click(
within(panel()).getAllByRole('button', { name: 'Retirer de ce constat' })[
at
],
)
async function openTile(user: User, citation: RegExp) {
await user.click(within(panel()).getByRole('button', { name: citation }))
}
it('removes only that id, the reference stays, one undo restores it with the status', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'set_status',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
status: 'reviewed',
})
})
expect(nodeA().review_status).toBe('reviewed')
await openFromFinding(user)
const history = store.getState().undo.length
await openTile(user, /^Barone/)
await retire(user)
expect(nodeA().reference_ids).toEqual(['ref-c'])
expect(nodeA().review_status).toBe('to_confirm')
expect(doc().references).toHaveLength(3)
expect(store.getState().undo.length).toBe(history + 1)
expect(tiles()).toHaveLength(1)
expect(panel()).toHaveTextContent('1 référence citée par ce constat')
act(() => void store.getState().undoStep())
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(nodeA().review_status).toBe('reviewed')
expect(tiles()).toHaveLength(2)
})
it('the focus goes to the next tile, else the previous, else the heading', async () => {
const ids = ['ref-a', 'ref-b', 'ref-c']
const user = await mount(1280, nodeText(ids))
await openFromFinding(user, '3 références')
const header = (at: number) => () =>
tiles()[at].querySelector('button') as HTMLElement
await openTile(user, /^Barone/)
await retire(user)
await focusIs(header(0))
expect(header(0)().textContent).toContain('Denoix')
await openTile(user, /^Code rural/)
await retire(user, 0)
await focusIs(header(0))
expect(tiles()).toHaveLength(1)
await openTile(user, /^Denoix/)
await retire(user)
await focusIs(heading)
})
it('the last citation gone: the panel stays with its line and « Tout afficher »', async () => {
const user = await mount(1280, nodeText(['ref-a']))
await openFromFinding(user, '1 référence')
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await retire(user)
expect(panel()).toHaveTextContent(
'Ce constat ne cite plus aucune référence.',
)
expect(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
).toBeVisible()
expect(hasPanel()).toBe(true)
await user.click(closeButton())
await closed()
// the trigger is gone with its count: the active tab button takes the focus (P6)
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
})
it('a dangling id is a « Référence introuvable » row with Retirer, counted like the rest', async () => {
const user = await mount(1280, nodeText(['ref-a', 'ref-gone']))
await openFromFinding(user)
expect(panel()).toHaveTextContent('2 références citées par ce constat')
expect(tiles()).toHaveLength(2)
expect(tiles()[1]).toHaveTextContent('Référence introuvable')
await user.click(
within(tiles()[1] as HTMLElement).getByRole('button', {
name: /^Retirer/,
}),
)
expect(nodeA().reference_ids).toEqual(['ref-a'])
expect(tiles()).toHaveLength(1)
await focusIs(() => tiles()[0].querySelector('button')!)
})
})
describe("a tile in edit when the panel closes (P22'')", () => {
async function edit(user: User) {
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
return panel().querySelector(
'#panel-reference-0-ref-a-citation',
) as HTMLTextAreaElement
}
it('a valid draft is committed before the close, then the panel closes', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
await user.click(closeButton())
expect(doc().references[0].citation).toBe('Neuf')
await closed()
await focusIs(() => trigger())
})
it('a refused draft cancels a user close: panel open, field focused, message shown', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(layer()).not.toHaveAttribute('inert')
expect(document.activeElement).toBe(field)
expect(within(panel()).getByRole('alert')).toBeVisible()
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('a refused draft cancels a tab switch and « Tout afficher »', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
await user.click(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
expect(hasPanel()).toBe(true)
})
it('a forced close (finding vanished) drops a refused draft and says so', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await closed()
expect(
screen.getByText(/Saisie non appliquée : Citation/),
).toBeInTheDocument()
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('Escape in a field of the tile neither closes nor commits', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
await user.keyboard('{Escape}')
expect(hasPanel()).toBe(true)
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('Ctrl+Z reverts a reference edit while the panel is open', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
fireEvent.blur(field)
expect(doc().references[0].citation).toBe('Neuf')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
})
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')
const entries = () => store.getState().undo.length
const undo = () => act(() => store.getState().undoStep())
const nodeKey: ElementKey = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
}
/** The finding node cites `ids` from now on (one history entry). */
function cite(ids: string[]) {
act(() => {
store.getState().commit({
op: 'update',
key: nodeKey,
element: {
kind: 'finding_node',
value: {
...doc().finding_zones[0].categories[0].children[0],
reference_ids: ids,
},
},
})
})
}
describe('one user edit, one history entry in the panel (C1)', () => {
/** Opens Barone, enters edit and types a URL; the field keeps the focus. */
async function typeUrl(user: User) {
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
const url = panel().querySelector<HTMLInputElement>(
'#panel-reference-0-ref-a-url',
)!
await user.type(url, 'https://a.org/')
expect(document.activeElement).toBe(url)
return entries()
}
it('✕ pressed with the field still focused (iPadOS) adds one entry', async () => {
const user = await mount()
const before = await typeUrl(user)
fireEvent.click(closeButton())
await closed()
expect(entries() - before).toBe(1)
expect(doc().references[0].url).toBe('https://a.org/')
undo()
expect(doc().references[0].url).toBeNull()
})
it('a tab switch with the field still focused adds one entry', async () => {
const user = await mount()
const before = await typeUrl(user)
fireEvent.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(entries() - before).toBe(1)
undo()
expect(doc().references[0].url).toBeNull()
})
it('a forced close (finding vanished) adds the edit once, besides the removal', async () => {
const user = await mount()
const before = await typeUrl(user)
act(() => {
store.getState().commit({ op: 'remove', key: nodeKey })
})
await closed()
expect(entries() - before).toBe(2)
expect(doc().references[0].url).toBe('https://a.org/')
})
})
describe('the panel review fixes', () => {
it('opening announces the panel title, not the tab name (M4)', async () => {
const user = await mount()
await openFromFinding(user)
expect(live()?.textContent?.trim()).toBe('Références citées')
})
it('every « Aller à » names its citer (M6)', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
const names = within(panel())
.getAllByRole('button', { name: /^Aller à / })
.map((button) => button.getAttribute('aria-label'))
expect(new Set(names).size).toBe(names.length)
expect(names).toEqual([
'Aller à Zone A › Cat A',
'Aller à Zone A › Cat A › Node A',
])
})
it('an undo that removes the focused tile moves the focus to the next one (M8)', async () => {
const user = await mount(1280, nodeText(['ref-c']))
cite(['ref-a', 'ref-c'])
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
expect(document.activeElement).toBe(tiles()[0].querySelector('button'))
undo()
expect(tiles()).toHaveLength(1)
await focusIs(() => tiles()[0].querySelector('button')!)
expect(tiles()[0]).toHaveTextContent('Code rural')
})
it('an undo that removes the last focused tile moves the focus to the previous one (M8)', async () => {
const user = await mount(1280, nodeText(['ref-a']))
cite(['ref-a', 'ref-c'])
await openFromFinding(user)
await user.click(
within(panel()).getByRole('button', { name: /^Code rural/ }),
)
undo()
expect(tiles()).toHaveLength(1)
await focusIs(() => tiles()[0].querySelector('button')!)
expect(tiles()[0]).toHaveTextContent('Barone')
})
it('an undo that removes the only tile puts the focus on the heading (M8)', async () => {
const user = await mount(1280, nodeText([]))
cite(['ref-a'])
await openFromFinding(user, '1 référence')
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
undo()
expect(tiles()).toHaveLength(0)
await focusIs(heading)
})
it('an arrow key in the tab row leaves the focus on the refused field (M2)', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
const field = panel().querySelector<HTMLTextAreaElement>(
'#panel-reference-0-ref-a-citation',
)!
await user.clear(field)
const tab = screen.getByRole('tab', { name: 'Constats' })
fireEvent.keyDown(tab, { key: 'ArrowRight' })
expect(hasPanel()).toBe(true)
expect(document.activeElement).toBe(field)
expect(tab).toHaveAttribute('aria-selected', 'true')
})
})