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

454 lines
15 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.1 and R2.2: the Références tab, the library (search, order, counts, add, « Aller à »). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ReferenceFacts from '@/components/editor/references/ReferenceFacts'
import { useLocaleStore } from '@/state/localeStore'
import { targetOfKey } from '@/editor/navigation'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import ReferencesHost from '../helpers/referencesHost'
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 with a finding under « Cat A » that cites ref-a too (ref-a: two citers). */
function citedTwiceText(): 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: {},
requires_vet_referral: false,
reference_ids: ['ref-a'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const tabPanel = () => screen.getByRole('tabpanel', { name: 'Références' })
const cards = () => within(tabPanel()).getAllByRole('listitem')
const header = (citation: string) =>
within(tabPanel()).getByRole('button', { name: new RegExp(`^${citation}`) })
const openAll = async (user: User) => {
for (const button of within(tabPanel()).getAllByRole('button', {
expanded: false,
})) {
if (button.hasAttribute('aria-controls')) await user.click(button)
}
}
const search = () =>
within(tabPanel()).getByRole('searchbox', {
name: 'Rechercher une référence',
})
async function mount(width = 1280, text = citedTwiceText()) {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft({ width })
await ready()
await user.click(screen.getByRole('tab', { name: 'Références' }))
return user
}
describe('the Références tab', () => {
it('is the fifth tab, there is no header button, and it lists every card', async () => {
await mount()
const tabs = screen.getAllByRole('tab').map((tab) => tab.textContent)
expect(tabs).toEqual([
'Général',
'Annotations',
'Constats',
'Références',
'Vérification',
])
expect(screen.queryByRole('button', { name: 'Références' })).toBeNull()
expect(cards()).toHaveLength(3)
expect(
within(tabPanel()).getByRole('heading', { name: 'Références' }),
).toBeInTheDocument()
})
it('each card says how often it is cited, the ids carry the tab prefix', async () => {
await mount()
const texts = cards().map((card) => card.textContent)
expect(texts[0]).toContain('Citée 2 fois')
expect(texts[1]).toContain('Citée 1 fois')
expect(texts[2]).toContain('Non citée')
expect(
tabPanel().querySelector('#tab-reference-0-ref-a-header'),
).not.toBeNull()
expect(tabPanel().querySelector('#tab-reference-new-citation')).toBeNull()
})
it('matches the citation, the DOI and the URL, ignoring case and accents', async () => {
const user = await mount()
await user.type(search(), 'OSTEOLOGIE')
expect(cards()).toHaveLength(1)
await user.clear(search())
await user.type(search(), '10.1000/abc')
expect(cards()).toHaveLength(1)
await user.clear(search())
await user.type(search(), 'epaule')
expect(cards()).toHaveLength(1)
await user.clear(search())
await user.type(search(), 'zzz')
expect(
within(tabPanel()).getByText('Aucune référence ne contient « zzz ».'),
).toBeInTheDocument()
})
it('shows ↑ / ↓ in open tiles, and only without a search', async () => {
const user = await mount()
await openAll(user)
expect(
within(tabPanel()).getAllByRole('button', { name: 'Descendre' }).length,
).toBe(3)
await user.type(search(), 'a')
expect(
within(tabPanel()).queryByRole('button', { name: 'Descendre' }),
).toBeNull()
})
it('Ctrl+Z reverts a reference edit made in the dialog, once it is closed', async () => {
const user = await mount()
await startEdit(user, 'Barone')
const dialog = screen.getByRole('dialog', { name: 'Modifier la référence' })
const field = within(dialog).getByLabelText('Citation')
await user.clear(field)
await user.type(field, 'Neuf')
await user.click(
within(dialog).getByRole('button', { name: 'Enregistrer' }),
)
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
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 no edit control, only the search', async () => {
const user = await mount(800)
await openAll(user)
expect(
within(tabPanel()).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
expect(
within(tabPanel()).queryByRole('button', {
name: 'Ajouter la référence',
}),
).toBeNull()
expect(search()).toBeInTheDocument()
})
})
describe('« Aller à » a reference', () => {
it('clears the search that hides it, opens its tile and focuses its button', async () => {
serverHas(sheetText(), 3)
await openReady({ text: sheetText() })
const user = userEvent.setup()
const view = render(<ReferencesHost />)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
await user.type(box, 'Code')
expect(screen.getAllByRole('listitem')).toHaveLength(1)
const focus = {
target: targetOfKey({ kind: 'reference', id: 'ref-a' }),
serial: 1,
}
view.rerender(<ReferencesHost focus={focus} />)
expect(box).toHaveValue('')
expect(document.querySelectorAll('button[aria-controls]')).toHaveLength(3)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
)
expect(document.activeElement).toHaveAttribute('aria-expanded', 'true')
})
})
describe('the reset signal', () => {
it('empties the search once per bump and leaves other state alone', async () => {
await openReady({ text: sheetText() })
const user = userEvent.setup()
const view = render(<ReferencesHost libraryReset={0} />)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
await user.type(box, 'Code')
view.rerender(<ReferencesHost libraryReset={0} />)
expect(box).toHaveValue('Code')
view.rerender(<ReferencesHost libraryReset={1} />)
expect(box).toHaveValue('')
await user.type(box, 'a')
view.rerender(<ReferencesHost libraryReset={1} />)
expect(box).toHaveValue('a')
})
})
describe('adding a reference', () => {
const addButton = () =>
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' })
it('opens the creation dialog with the type to choose, the search untouched', async () => {
const user = await mount()
await user.type(search(), 'Barone')
await user.click(addButton())
const dialog = screen.getByRole('dialog', { name: 'Nouvelle référence' })
expect(within(dialog).getByLabelText('Type')).toHaveValue('')
expect(search()).toHaveValue('Barone')
expect(doc().references).toHaveLength(3)
})
it('creates the reference in one modification and leaves the list where it was', async () => {
const user = await mount()
await user.type(search(), 'Barone')
await user.click(addButton())
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 source',
)
await user.click(
within(dialog).getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
expect(store.getState().undo.length).toBe(1)
expect(doc().references).toHaveLength(4)
expect(search()).toHaveValue('Barone')
expect(cards()).toHaveLength(1)
expect(document.activeElement).toBe(addButton())
})
})
const tile = (citation: string) => header(citation).closest('li')!
const doc = () => JSON.parse(store.getState().documentText)
/** Opens the tile and its « Modifier » dialog. */
async function startEdit(user: User, citation: string) {
await user.click(header(citation))
await user.click(
within(tile(citation)).getByRole('button', { name: 'Modifier' }),
)
}
describe('the tile disclosure', () => {
it('opens and closes from the keyboard, and several stay open', async () => {
const user = await mount()
const first = header('Barone')
expect(first).toHaveAttribute('aria-expanded', 'false')
expect(first).toHaveAttribute('aria-controls', 'tab-reference-0-ref-a-body')
first.focus()
await user.keyboard('{Enter}')
expect(first).toHaveAttribute('aria-expanded', 'true')
header('Denoix').focus()
await user.keyboard(' ')
expect(first).toHaveAttribute('aria-expanded', 'true')
expect(header('Denoix')).toHaveAttribute('aria-expanded', 'true')
first.focus()
await user.keyboard('{Enter}')
expect(first).toHaveAttribute('aria-expanded', 'false')
expect(tabPanel().querySelector('#tab-reference-0-ref-a-body')).toBeNull()
})
it('is a natural tab stop that carries only the focus key', async () => {
await mount()
const button = header('Barone')
expect(button).not.toHaveAttribute('tabindex')
expect(button.closest('[data-focus-key]')).toBe(button)
})
})
describe('an open tile', () => {
it('shows type, DOI and URL as safe links, « Aucun » / « Aucune » when absent', async () => {
const user = await mount()
await user.click(header('Code rural'))
await user.click(header('Denoix'))
const doi = within(tile('Code rural')).getByRole('link', {
name: /10\.1000\/ABC/,
})
expect(doi).toHaveAttribute('href', 'https://doi.org/10.1000/ABC')
expect(doi).toHaveAttribute('target', '_blank')
expect(doi).toHaveAttribute('rel', 'noopener noreferrer')
expect(within(tile('Code rural')).getByText('Aucune')).toBeInTheDocument()
const url = within(tile('Denoix')).getByRole('link', {
name: /exemple\.org/,
})
expect(url).toHaveAttribute('href', 'https://exemple.org/%C3%89paule')
expect(within(tile('Denoix')).getByText('Aucun')).toBeInTheDocument()
})
it('lists the citers, a family marked, and the count is the list length', async () => {
const user = await mount()
await user.click(header('Barone'))
const open = within(tile('Barone'))
expect(open.getByText('Citée 2 fois, par :')).toBeInTheDocument()
expect(open.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2)
expect(open.getAllByText('famille')).toHaveLength(1)
expect(open.getByText(/Zone A › Cat A ›/)).toBeInTheDocument()
})
it('says so when nothing cites it, and offers « Supprimer » only then', async () => {
const user = await mount()
await user.click(header('Barone'))
await user.click(header('Code rural'))
const cited = within(tile('Barone'))
expect(cited.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(
cited.getByText(/Pour supprimer cette référence/),
).toBeInTheDocument()
const uncited = within(tile('Code rural'))
expect(
uncited.getByText(
'Aucun constat ni aucune famille ne cite cette référence.',
),
).toBeInTheDocument()
expect(
uncited.getByRole('button', { name: 'Supprimer' }),
).toBeInTheDocument()
expect(uncited.queryByText(/Pour supprimer cette référence/)).toBeNull()
})
it('« Aller à » on a citer opens the Constats tab on it', async () => {
const user = await mount()
await user.click(header('Barone'))
const [family] = within(tile('Barone')).getAllByRole('button', {
name: /^Aller à /,
})
await user.click(family)
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
})
it('never links a javascript: address', () => {
const risky = {
id: 'ref-x',
type: 'web',
citation: 'X',
url: 'javascript:alert(1)',
doi: 'javascript:alert(2)',
} as const
render(<ReferenceFacts reference={risky} />)
expect(screen.queryByRole('link')).toBeNull()
expect(screen.getByText('javascript:alert(1)')).toBeInTheDocument()
})
})
describe('read-only tiles', () => {
it('keep DOI, URL and « Aller à », and offer no edit control', async () => {
const user = await mount(800)
await user.click(header('Barone'))
await user.click(header('Denoix'))
const cited = within(tile('Barone'))
expect(cited.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2)
expect(
within(tile('Denoix')).getByRole('link', { name: /exemple\.org/ }),
).toBeInTheDocument()
expect(
within(tabPanel()).queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(
within(tabPanel()).queryByRole('textbox', { name: 'Citation' }),
).toBeNull()
})
})
describe('reopening the editor', () => {
it('starts with every tile closed', async () => {
const user = await mount()
await user.click(header('Denoix'))
cleanup()
await mount()
const opened = within(tabPanel()).queryAllByRole('button', {
expanded: true,
})
expect(opened).toHaveLength(0)
})
})