Files
faunosteo/apps/app/tests/unit/editor-references-panel.test.tsx
T

670 lines
23 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 {
findingDialog,
inFindingDialog,
openFinding,
} from '../helpers/findingDialog'
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') =>
inFindingDialog().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 removeNodeA = () =>
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'fnode-a'] },
})
})
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>
/** The finding dialog of `label` (a row activation opens it, R2F-3). */
async function select(user: User, label: RegExp) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, label)
}
/** The sheet of Node A, open over its dialog: its first control (✕) 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(closeButton)
}
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(closeButton)
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; « Modifier » opens the reference dialog over the sheet', 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(document.querySelectorAll('dialog[open]')).toHaveLength(3)
expect(
screen.getByRole('dialog', { name: 'Modifier la référence' }),
).toBeVisible()
expect(panel().querySelector('[id$="-citation"]')).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 openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
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-header')
expect(ids).toContain('panel-reference-0-ref-a-header')
})
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() 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(closeButton)
await waitFor(() => 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(closeButton)
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(closeButton)
await user.keyboard('{Escape}')
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(closeButton)
fireEvent.click(screen.getByTestId('references-scrim'))
await closed()
await focusIs(() => trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('the platform close request closes it with nothing focused (no key reaches the page)', async () => {
const user = await mount()
await openFromFinding(user)
;(document.activeElement as HTMLElement).blur()
fireEvent(
panel().closest('dialog')!,
new Event('cancel', { cancelable: true }),
)
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' }),
)
// Filtered by the finding the sheet belonged to: its two citations (R2F-6).
expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(2)
expect(
within(tabPanel).getByText('Références du constat : Node A'),
).toBeVisible()
})
it('« Aller à » a citer from a panel tile closes the sheet and opens that finding in its dialog', 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 waitFor(() =>
expect(
inFindingDialog().getByRole('heading', { name: 'Cat A' }),
).toBeVisible(),
)
// Closed, the dialog hands the focus back to the row of that finding.
await user.click(inFindingDialog().getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(findingDialog()).toBeNull())
await focusIs(() => screen.getByRole('treeitem', { name: /Cat A/ }))
})
it('the finding vanishing closes both layers and says so once the dialogs are gone', async () => {
const user = await mount()
await openFromFinding(user)
removeNodeA()
await closed()
await waitFor(() => expect(findingDialog()).toBeNull())
await waitFor(() =>
expect(live()).toHaveTextContent("Ce constat n'existe plus"),
)
expect(document.activeElement).not.toBe(document.body)
})
it('below 640 px the sheet opens from « Plus » > Constats and closes on its own', async () => {
const user = await mount(375)
await user.click(screen.getByRole('button', { name: 'Plus' }))
await user.click(screen.getByRole('button', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(trigger())
await focusIs(closeButton)
await user.click(closeButton())
await closed()
await focusIs(() => trigger())
})
})
describe('the exit', () => {
it('a sheet playing its exit is inert, its trigger reads « expanded » until it is gone', async () => {
const user = await mount()
await openFromFinding(user)
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(panel().closest('dialog')).toHaveAttribute('inert')
await closed()
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('a second close during the exit finds no layer and does nothing', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
fireEvent.keyDown(layer(), { key: 'Escape' })
fireEvent.click(screen.getByTestId('references-scrim'))
await closed()
expect(findingDialog()).not.toBeNull()
await focusIs(() => trigger())
})
it('Ctrl+Z is ignored while the sheet is open: Défaire is unreachable under a dialog', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
const before = store.getState().undo.length
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(store.getState().undo.length).toBe(before)
expect(hasPanel()).toBe(true)
})
})
describe('the library and the history around the panel', () => {
it('« Tout afficher » clears the search of the tab and keeps its sort, 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('citation')
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 both layers (gone rule)', 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(closeButton)
act(() => void store.getState().undoStep())
await closed()
await waitFor(() => expect(findingDialog()).toBeNull())
expect(document.activeElement).not.toBe(document.body)
})
})
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 focus stays inside the finding dialog
expect(findingDialog()!.contains(document.activeElement)).toBe(true)
})
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')!)
})
})
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')
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('the panel review fixes', () => {
it('the sheet is a modal dialog named by its title (M4: no announcement needed)', async () => {
const user = await mount()
await openFromFinding(user)
const dialog = panel().closest('dialog')!
expect(dialog).toHaveAttribute('aria-labelledby', 'editor-citations-title')
expect(dialog).toHaveAttribute('open')
})
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)
})
})