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

584 lines
20 KiB
TypeScript

/** R2.3: search, sort, count, no-result notice, A1, the pin (the dialog's tile) and the reset. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ElementKey, ReferenceType } from '@faunosteo/core-wasm/types'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
store,
} from '../helpers/editorHarness'
import ReferencesHost from '../helpers/referencesHost'
import { PlaceVisibleContext } from '@/lib/placeVisibility'
import type { EditorNavigation } from '@/editor/useEditorNavigation'
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 = {}) => (
<ReferencesHost readOnly={readOnly} {...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('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('is announced once: the count line is the live region, the notice is not (M11)', async () => {
const { user } = await mount()
await user.type(search(), 'radiographie')
const live = document.querySelectorAll('[aria-live], [role="status"]')
expect(live).toHaveLength(1)
expect(live[0]).toHaveTextContent('0 référence sur 5')
})
it('writes the typed text as it is, `$&` and friends included (M5)', async () => {
const { user } = await mount()
await user.type(search(), "$& $` $'")
expect(screen.getByTestId('editor-references-no-result')).toHaveTextContent(
"Aucune référence ne contient « $& $` $' ».",
)
})
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.getByTestId('editor-references-no-result')
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 its « Modifier » dialog. */
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 screen.getByRole('dialog', { name: 'Modifier la référence' })
}
/** Types a new citation in the open dialog and saves it. */
async function saveCitation(user: User, text: string) {
const dialog = screen.getByRole('dialog', { name: 'Modifier la référence' })
const citation = within(dialog).getByLabelText('Citation')
await user.clear(citation)
await user.type(citation, text)
await user.click(within(dialog).getByRole('button', { name: 'Enregistrer' }))
await waitFor(() => expect(document.querySelector('dialog[open]')).toBeNull())
}
const cancelDialog = async (user: User) => {
await user.click(screen.getByRole('button', { name: 'Annuler' }))
await waitFor(() => expect(document.querySelector('dialog[open]')).toBeNull())
}
describe('the tile the dialog edits is pinned (P23)', () => {
it('keeps its index when the sort changes after the dialog closes', async () => {
const { user } = await mount()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r1')
await cancelDialog(user)
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
await user.selectOptions(sortBox(), 'count')
expect(order()).toEqual(['r2', 'r1', 'r5', 'r3', 'r4'])
})
it('stays shown under a search it stops matching, until the next search change (I1)', async () => {
const { user } = await mount()
await user.type(search(), 'alpha')
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
expect(order()).toEqual(['r5'])
await user.clear(search())
await user.type(search(), 'alpha')
expect(order()).toEqual([])
})
it('keeps the tile shown and the opener focused when its edit stops matching (I1)', async () => {
const { user } = await mount()
await user.type(search(), 'zèbre')
await startEdit(user, 'r1')
await saveCitation(user, 'Autre titre')
expect(order()).toEqual(['r1', 'r2'])
expect(search()).toHaveValue('zèbre')
expect(document.activeElement).toBe(
within(header('r1').closest('li')!).getByRole('button', {
name: 'Modifier',
}),
)
})
it('keeps its index across a sort made in read-only after the dialog', async () => {
const { user, view } = await mount()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r3')
await cancelDialog(user)
view.rerender(lib(true))
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
})
})
describe('the tile outside the search (C3)', () => {
const line = 'Ne correspond pas à la recherche'
const notice = () => screen.queryByTestId('editor-references-no-result')
const lineOf = (id: string) =>
within(header(id).closest('li')!).queryByText(line)
it('after the save shows the tile with its line and no notice', async () => {
const { user } = await mount()
await user.type(search(), 'alpha')
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
expect(order()).toEqual(['r5'])
expect(lineOf('r5')).toBeVisible()
expect(notice()).toBeNull()
expect(screen.getByText('0 référence sur 5')).toBeInTheDocument()
expect(header('r5')).toHaveAccessibleDescription(line)
})
it('the next search change drops the tile and shows the notice', async () => {
const { user } = await mount()
await user.type(search(), 'alpha')
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
await user.type(search(), 'x')
expect(order()).toEqual([])
expect(notice()).not.toBeNull()
})
it('a matching pinned tile has no line', async () => {
const { user } = await mount()
await user.type(search(), 'zebre')
await startEdit(user, 'r1')
await cancelDialog(user)
expect(lineOf('r1')).toBeNull()
})
it('a read-only flip keeps the tile and its line', async () => {
const { user, view } = await mount()
await user.type(search(), 'alpha')
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
view.rerender(lib(true))
expect(order()).toEqual(['r5'])
expect(lineOf('r5')).toBeVisible()
expect(notice()).toBeNull()
})
})
describe('no pin while a finding filter is set (R2F-6)', () => {
const category: ElementKey = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a'],
}
let nav: EditorNavigation
const hosted = async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
render(<ReferencesHost onNav={(n) => (nav = n)} />)
return user
}
it('the tile edited under a filter leaves no pin once the filter is removed', async () => {
const user = await hosted()
await user.selectOptions(sortBox(), 'citation')
act(() => nav.showAllReferences(category))
expect(order()).toEqual(['r5', 'r2', 'r1'])
await startEdit(user, 'r2')
await cancelDialog(user)
act(() => nav.references.clearFilter())
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
})
it('a pin from before the filter does not come back after it', async () => {
const user = await hosted()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r1')
await cancelDialog(user)
act(() => nav.showAllReferences(category))
act(() => nav.references.clearFilter())
await user.selectOptions(sortBox(), 'citation')
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
})
it('a tile edited out of the search is not kept under a filter', async () => {
const user = await hosted()
act(() => nav.showAllReferences(category))
await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
expect(order()).toEqual([])
})
})
describe('the added-reference notice', () => {
it('goes when the user leaves the References tab', async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
const { rerender } = render(
<PlaceVisibleContext value>
<ReferencesHost />
</PlaceVisibleContext>,
)
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
const dialog = screen.getByRole('dialog', { name: 'Nouvelle référence' })
await user.selectOptions(within(dialog).getByLabelText('Type'), 'book')
await user.type(within(dialog).getByLabelText('Citation'), 'Nouvelle')
await user.click(
within(dialog).getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() =>
expect(screen.getByText('Référence ajoutée : Nouvelle')).toBeVisible(),
)
rerender(
<PlaceVisibleContext value={false}>
<ReferencesHost />
</PlaceVisibleContext>,
)
rerender(
<PlaceVisibleContext value>
<ReferencesHost />
</PlaceVisibleContext>,
)
expect(screen.queryByText(/Référence ajoutée/)).toBeNull()
})
})
describe('after a dialog closes, the view is unchanged (R2F-5)', () => {
it('keeps scroll position inputs: search, sort, open tiles', async () => {
const { user } = await mount()
await user.click(header('r2'))
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'e')
await startEdit(user, 'r3')
await cancelDialog(user)
expect(search()).toHaveValue('e')
expect(sortBox()).toHaveValue('citation')
expect(header('r2')).toHaveAttribute('aria-expanded', 'true')
expect(header('r3')).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(
within(header('r3').closest('li')!).getByRole('button', {
name: 'Modifier',
}),
)
})
})
describe('the reset path (« Tout afficher »)', () => {
it('empties the search and keeps the sort, keeping open tiles (R2F-4)', async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
const view = render(lib(false, { libraryReset: 0 }))
await user.click(header('r2'))
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'e')
view.rerender(lib(false, { libraryReset: 1 }))
expect(search()).toHaveValue('')
expect(sortBox()).toHaveValue('citation')
expect(order()).toHaveLength(5)
expect(header('r2')).toHaveAttribute('aria-expanded', 'true')
})
})
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', async () => {
const { user } = await mount()
await user.click(header('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')
})
})