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

705 lines
24 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, Rev 5: the references dialog of one finding: contents, view mode, 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(family = ['ref-a', 'ref-b']): 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: family,
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'], family?: string[]): string {
return edit(sheetText(family), {
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 citationsDialog = () => panel().closest('dialog')!
const tiles = () => [...panel().querySelectorAll('ul > li')]
const trigger = (name = '2 références') =>
inFindingDialog().getByRole('button', { name })
const heading = () =>
within(citationsDialog()).getByRole('heading', {
name: 'Références du constat',
})
const backdrop = () => within(citationsDialog()).getByTestId('dialog-backdrop')
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 references dialog of Node A, 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(citationsDialog()).getByRole('button', { name: 'Fermer' })
describe('opening', () => {
it('has no header button; « X références » opens a modal dialog over the finding, ✕ focused', 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-haspopup', 'dialog')
expect(trigger()).not.toHaveAttribute('aria-expanded')
expect(trigger()).not.toHaveAttribute('aria-controls')
await user.click(trigger())
expect(trigger()).not.toHaveAttribute('aria-expanded')
await focusIs(closeButton)
expect(heading()).toHaveAttribute('id', 'editor-citations-title')
expect(citationsDialog()).toHaveAttribute(
'aria-labelledby',
'editor-citations-title',
)
expect(citationsDialog()).toHaveAttribute('data-layer')
expect(panel()).toHaveAttribute('data-place', 'citations')
expect(document.querySelectorAll('dialog[open]')).toHaveLength(2)
expect(findingDialog()).not.toBe(citationsDialog())
})
it('a family opens the same dialog with its citations', async () => {
const user = await mount()
await select(user, /Cat A/)
expect(inFindingDialog().queryByText('Barone, Ostéologie')).toBeNull()
await user.click(trigger())
await focusIs(closeButton)
expect(panel()).toHaveTextContent('Zone A › Cat A')
expect(tiles()).toHaveLength(2)
expect(tiles()[0].textContent).toContain('Barone')
expect(tiles()[1].textContent).toContain('Denoix')
})
it('« 0 référence » is offered at zero and opens the empty dialog', async () => {
const user = await mount(1280, nodeText([]))
await select(user, /Node A/)
await user.click(trigger('0 référence'))
await focusIs(closeButton)
expect(tiles()).toHaveLength(0)
expect(panel()).toHaveTextContent('Ce constat ne cite aucune référence.')
})
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('a tile marks the finding, « Aller à » only; « Modifier » on the dialog', 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)
for (const absent of [
'Modifier',
'Retirer de ce constat',
'Supprimer',
'Monter',
'Descendre',
]) {
expect(within(tile).queryByRole('button', { name: absent })).toBeNull()
expect(
within(citationsDialog()).queryByRole('button', { name: absent }),
).toBe(
absent === 'Modifier'
? document.getElementById('citations-edit-button')
: null,
)
}
expect(within(citationsDialog()).queryByRole('searchbox')).toBeNull()
expect(within(citationsDialog()).queryByRole('textbox')).toBeNull()
expect(within(citationsDialog()).queryByRole('combobox')).toBeNull()
})
it('ids stay unique with the Références tab mounted and the dialog 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('reduced motion', () => {
it('the same lifecycle: open, close, the trigger takes the focus back', async () => {
setReducedMotion(true)
const user = await mount()
await select(user, /Node A/)
await user.click(trigger())
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 backdrop 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(backdrop())
await closed()
await focusIs(() => trigger())
})
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 dialog 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 tile closes the dialog 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 dialog 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 dialog playing its exit is inert until it is gone', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(panel().closest('dialog')).toHaveAttribute('inert')
await closed()
})
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(citationsDialog(), { key: 'Escape' })
fireEvent.click(backdrop())
await closed()
expect(findingDialog()).not.toBeNull()
await focusIs(() => trigger())
})
it('Ctrl+Z is ignored while the dialog 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 dialog', () => {
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('the view mode cannot remove a citation', () => {
it('no tile offers « Retirer de ce constat »', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
expect(
within(panel()).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
it('a dangling id is a « Référence introuvable » row, counted, without Retirer', 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')
expect(
within(panel()).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
})
})
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 dialog is modal and 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)
})
})
describe('the family wording (Rev 6)', () => {
const familyHeading = (name: string) =>
within(citationsDialog()).getByRole('heading', { name })
const chip = () => screen.getByTestId('editor-references-filter')
const showAll = (user: User) =>
user.click(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
it('a family: dialog title, count, its own tile row, edit title', async () => {
const user = await mount()
await select(user, /Cat A/)
await user.click(trigger())
await focusIs(closeButton)
expect(familyHeading('Références de la famille')).toBeVisible()
expect(panel()).toHaveTextContent('2 références citées par cette famille')
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
const tile = tiles()[0] as HTMLElement
expect(within(tile).getByText('cette famille')).toBeInTheDocument()
expect(within(tile).queryByText('famille')).toBeNull()
await user.click(
within(citationsDialog()).getByRole('button', { name: 'Modifier' }),
)
await waitFor(() =>
expect(
familyHeading('Modifier les références de la famille'),
).toBeVisible(),
)
})
it('a finding keeps the finding wording', async () => {
const user = await mount()
await openFromFinding(user)
expect(heading()).toBeVisible()
expect(panel()).toHaveTextContent('2 références citées par ce constat')
})
it('an empty family: the empty line, then the filtered tab names the family', async () => {
const user = await mount(1280, nodeText(['ref-a', 'ref-c'], []))
await select(user, /Cat A/)
await user.click(trigger('0 référence'))
await focusIs(closeButton)
expect(panel()).toHaveTextContent('Cette famille ne cite aucune référence.')
await showAll(user)
await closed()
expect(chip()).toHaveTextContent('Références de la famille : Cat A')
expect(
within(chip()).getByRole('button', {
name: 'Retirer le filtre de la famille Cat A',
}),
).toBeVisible()
expect(
within(chip()).getByRole('button', { name: 'Revenir à la famille' }),
).toBeVisible()
expect(screen.getByTestId('editor-references-no-result')).toHaveTextContent(
'Cette famille ne cite aucune référence.',
)
})
it('a filtered family removed by an undo says the family is gone', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-b',
kind: 'dysfunction',
name: name('Cat B'),
description: {},
reference_ids: ['ref-c'],
review_status: 'to_confirm',
children: [],
},
},
})
})
await select(user, /Cat B/)
await user.click(trigger('1 référence'))
await showAll(user)
await closed()
expect(chip()).toHaveTextContent('Références de la famille : Cat B')
act(() => {
store.getState().undoStep()
})
await waitFor(() =>
expect(live()).toHaveTextContent(
"La famille n'existe plus : le filtre est retiré",
),
)
})
it('a family that vanishes closes its dialog and says the family is gone', async () => {
const user = await mount()
await select(user, /Cat A/)
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
})
})
await waitFor(() => expect(findingDialog()).toBeNull())
await waitFor(() =>
expect(live()).toHaveTextContent("Cette famille n'existe plus"),
)
})
})