test(editor): reference dialog, filter and the owner journey, specs follow the dialog

This commit is contained in:
bchanot committed 2026-11-13 20:27:01 +01:00
1 parent 7a64daf251
commit 8b42816270
20 files changed
+1546 -1171

No files matched your search

+2 -2
View File
@@ -28,10 +28,10 @@ export default function FindingsHost({
<CitationsSheet
citedBy={citationsOfView(nav.state)}
readOnly={readOnly}
guards={nav.guards}
onClose={nav.closeCitations}
onShowAll={nav.showAllReferences}
onShowAll={() => undefined}
navigate={nav.navigate}
onEdit={nav.references.open}
returnFocus={nav.citationsTrigger}
/>
</ReadOnlyContext>
+55
View File
@@ -0,0 +1,55 @@
import { vi } from 'vitest'
import ReferenceDialog from '@/components/editor/references/ReferenceDialog'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import { ReadOnlyContext } from '@/editor/editingContext'
import { referenceLayerOf } from '@/editor/findingLayer'
import { AnnounceContext } from '@/editor/focusRequest'
import { defaultView, type EditorView } from '@/editor/navigation'
import type { EditorPlaceProps } from '@/editor/tabs'
import {
useEditorNavigation,
type EditorNavigation,
} from '@/editor/useEditorNavigation'
interface Props extends Partial<EditorPlaceProps> {
/** The view the editor starts on (a filter, a dialog); the References tab by default. */
view?: EditorView
/** Reads the navigation each render, for a test that drives or inspects it. */
onNav?: (nav: EditorNavigation) => void
/** Renders the polite live region (the workspace's), for a test that reads announcements. */
live?: boolean
}
/**
* The References tab with the navigation that drives its dialog and its filter (what the
* workspace gives it), without the rest of the editor.
*/
export default function ReferencesHost({
readOnly = false,
view,
onNav,
live = false,
...extra
}: Props) {
const nav = useEditorNavigation(
'references',
view ?? defaultView('references'),
)
onNav?.(nav)
const references = referenceLayerOf(nav)
return (
<ReadOnlyContext value={readOnly}>
<AnnounceContext value={nav.announce}>
<ReferencesTab
readOnly={readOnly}
navigate={vi.fn()}
reloadSheet={vi.fn()}
{...extra}
references={references}
/>
<ReferenceDialog layer={references} readOnly={readOnly} />
</AnnounceContext>
{live && <p aria-live="polite">{nav.live}</p>}
</ReadOnlyContext>
)
}
@@ -13,13 +13,13 @@ import type {
AnatomicalSheetDocument,
ElementKey,
} from '@faunosteo/core-wasm/types'
import { findingLayerOf } from '@/editor/findingLayer'
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
import { testLayer } from '../helpers/findingsHost'
import ReferencesHost from '../helpers/referencesHost'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import RegionsSection from '@/components/editor/annotations/sections/RegionsSection'
import EditorTabBody from '@/components/editor/EditorTabBody'
import EditorTabs from '@/components/editor/EditorTabs'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import {
FocusConsumedContext,
@@ -164,7 +164,7 @@ describe('focus requests', () => {
})
await openReady({ text })
render(
<ReferencesTab
<ReferencesHost
{...base}
focus={request({ kind: 'reference', id: 'ref-a' })}
/>,
@@ -200,9 +200,9 @@ describe('focus requests', () => {
})
await openReady({ text })
const focus = request({ kind: 'reference', id: 'ref-a' })
const view = render(<ReferencesTab {...base} focus={focus} />)
const view = render(<ReferencesHost {...base} focus={focus} />)
;(document.activeElement as HTMLElement).blur()
view.rerender(<ReferencesTab {...base} focus={focus} />)
view.rerender(<ReferencesHost {...base} focus={focus} />)
expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull()
})
@@ -271,6 +271,7 @@ function Probe({ go, tier }: { go: EditorTarget; tier: 'wide' | 'small' }) {
{...base}
navigate={nav.navigate}
layer={findingLayerOf(nav)}
references={referenceLayerOf(nav)}
focus={state.focus}
annotations={{
section: state.section,
@@ -288,7 +289,17 @@ function ShowAllProbe() {
return (
<>
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
<button onClick={nav.showAllReferences}>show all</button>
<button
onClick={() =>
nav.showAllReferences({
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
})
}
>
show all
</button>
</>
)
}
@@ -419,7 +430,7 @@ function Harness() {
switch
</button>
{shown === 'references' ? (
<ReferencesTab {...base} focus={focus} />
<ReferencesHost {...base} focus={focus} />
) : (
<RegionsSection {...base} focus={focus} />
)}
@@ -86,6 +86,43 @@ describe('sanitizeView', () => {
expect(sanitizeView(odd)?.finding).toBeNull()
})
it('the reference dialog is a form: over References or the sheet, never at a reload', () => {
const edit = { edit: 'ref-a' }
const tab = { ...view('references'), reference: edit }
expect(sanitizeView(tab)?.reference).toEqual(edit)
expect(sanitizeView(tab, false)?.reference).toBeNull()
const sheet = {
...view('findings'),
finding: { key: node, citations: true },
reference: edit,
}
expect(sanitizeView(sheet)?.reference).toEqual(edit)
const noSheet = { ...sheet, finding: { key: node, citations: false } }
expect(sanitizeView(noSheet)?.reference).toBeNull()
const creation = { ...view('references'), reference: { create: true } }
expect(sanitizeView(creation)?.reference).toEqual({ create: true })
const elsewhere = { ...view('general'), reference: { create: true } }
expect(sanitizeView(elsewhere)?.reference).toBeNull()
expect(
sanitizeView({ ...tab, reference: { edit: '' } })?.reference,
).toBeNull()
})
it('the finding filter names a finding node and lives on the References tab only', () => {
const filtered = view('references', { referenceFilter: node })
expect(sanitizeView(filtered)?.referenceFilter).toEqual(node)
expect(sanitizeView(filtered, false)?.referenceFilter).toEqual(node)
expect(
sanitizeView({ ...view('general'), referenceFilter: node })
?.referenceFilter,
).toBeNull()
const zone = { kind: 'zone', id: 'z' }
expect(
sanitizeView({ ...view('references'), referenceFilter: zone })
?.referenceFilter,
).toBeNull()
})
it('drops what is no view: an unknown tab, a non-object', () => {
expect(sanitizeView({ tab: 'nowhere', section: 'views' })).toBeNull()
expect(sanitizeView('general')).toBeNull()
@@ -211,6 +248,46 @@ describe('planWrite', () => {
})
})
describe('planWrite and the reference layers', () => {
const sheet = view('findings', { finding: { key: node, citations: true } })
const dialog = { ...sheet, reference: { edit: 'ref-a' } }
const top = (v: EditorView, below: EditorView | null) =>
entry({ view: v, below })
it('the reference dialog is a layer: added pushes, removed goes back to the view below', () => {
expect(planWrite(top(sheet, null), dialog, false)).toBe('push')
expect(planWrite(top(dialog, sheet), sheet, false)).toBe('back')
expect(planWrite(top(dialog, view('general')), sheet, false)).toBe(
'replace',
)
expect(layerCount(dialog)).toBe(3)
})
it('a creation turned into its element is a replace; the filter removal is a replace hint', () => {
const creating = view('references', { reference: { create: true } })
const editing = view('references', { reference: { edit: 'ref-n' } })
expect(planWrite(top(creating, null), editing, true)).toBe('replace')
const filtered = view('references', { referenceFilter: node })
expect(planWrite(top(filtered, sheet), view('references'), true)).toBe(
'replace',
)
})
it('« Revenir au constat » goes back when the entry below shows that finding, else pushes', () => {
const filtered = view('references', { referenceFilter: node })
const dialogOnly = view('findings', {
finding: { key: node, citations: false },
})
expect(planWrite(top(filtered, sheet), dialogOnly, false, node)).toBe(
'back',
)
expect(
planWrite(top(filtered, view('general')), dialogOnly, false, node),
).toBe('push')
expect(planWrite(top(filtered, sheet), dialogOnly, false)).toBe('push')
})
})
describe('createWriteBudget', () => {
it('lets the limit through per window, then refuses until the window slides', () => {
const take = createWriteBudget(3, 1000)
@@ -131,19 +131,23 @@ describe('the guard stack', () => {
const { result } = renderHook(() => useEditorNavigation('general'))
const { guards } = result.current
const order: string[] = []
guards.register('citations', () => {
order.push('citations')
guards.register('reference', () => {
order.push('reference')
return { allowed: true, note: 'a' }
})
guards.register('finding', () => {
order.push('finding')
return { allowed: false, note: 'b' }
})
expect(guards.ask('reference', false)).toEqual({ allowed: true })
expect(guards.ask('reference', false)).toEqual({
allowed: true,
note: 'a',
})
expect(guards.ask('finding', true).allowed).toBe(false)
order.length = 0
expect(guards.askAll(false)).toEqual({ allowed: false, note: 'b. a' })
expect(order).toEqual(['finding', 'citations'])
// The reference dialog is the top layer: it is asked first.
expect(guards.askAll(false)).toEqual({ allowed: false, note: 'a. b' })
expect(order).toEqual(['reference', 'finding'])
guards.register('finding', null)
expect(guards.askAll(false).allowed).toBe(true)
})
+5 -93
View File
@@ -10,7 +10,6 @@ import {
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import EditorTabBody from '@/components/editor/EditorTabBody'
import KeptPlace from '@/components/editor/KeptPlace'
import { useSheetDocument } from '@/editor/sheetDocument'
@@ -36,7 +35,6 @@ import {
versionAnswer,
} from '../helpers/editorHarness'
import { testLayer } from '../helpers/findingsHost'
import { openFinding } from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
@@ -112,26 +110,6 @@ function findingsText(from = baseText(), nodeRefs?: string[]): string {
})
}
function referenceText(): string {
return insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-1',
type: 'journal',
citation: 'Doe 2020',
url: null,
doi: null,
},
})
}
/** Constats, the node selected, its « 1 référence » trigger pressed. */
async function openCitations(user: Awaited<ReturnType<typeof mount>>) {
await user.click(tab('Constats'))
await openFinding(user, /Node A/)
await user.click(screen.getByRole('button', { name: '1 référence' }))
}
async function mount(text = baseText()) {
serverHas(text, 3)
const user = userEvent.setup()
@@ -199,22 +177,17 @@ describe('text typed in a place that is left', () => {
expect(store.getState().unsaved).toBe(false)
})
it('the reference add form survives leaving and returning to the Références tab', async () => {
it('the references search survives leaving and returning to the Références tab', async () => {
const user = await mount()
await user.click(tab('Références'))
await user.click(
inPlace('references').getByRole('button', {
name: 'Ajouter une référence',
}),
)
const field = inPlace('references').getByLabelText('Citation', {
selector: '#tab-reference-new-citation',
const box = inPlace('references').getByRole('searchbox', {
name: 'Rechercher une référence',
})
await user.type(field, 'Smith 1999')
await user.type(box, 'Smith 1999')
await user.click(tab('Annotations'))
expect(place('references')).not.toBeVisible()
await user.click(tab('Références'))
expect(field).toHaveValue('Smith 1999')
expect(box).toHaveValue('Smith 1999')
expect(store.getState().unsaved).toBe(false)
})
})
@@ -328,67 +301,6 @@ describe('a field still focused while a place is left', () => {
act(() => void store.getState().undoStep())
expect(store.getState().documentText).toBe(before)
})
it('a tab click without a focus move commits the Références text, as one undo entry', async () => {
const user = await mount(referenceText())
const before = store.getState().documentText
await user.click(tab('Références'))
await user.click(inPlace('references').getByRole('button', { name: /Doe/ }))
await user.click(
inPlace('references').getByRole('button', { name: 'Modifier' }),
)
const field = inPlace('references').getByLabelText('Citation', {
selector: '#tab-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2023' } })
fireEvent.click(tab(/Vérification/))
expect(
JSON.parse(store.getState().documentText).references[0].citation,
).toBe('Doe 2023')
expect(store.getState().unsaved).toBe(true)
expect(place('references')).not.toBeVisible()
act(() => void store.getState().undoStep())
expect(store.getState().documentText).toBe(before)
})
/** The panel's first tile opened in edit, its citation field typed in (not blurred). */
async function typeInPanelTile(user: Awaited<ReturnType<typeof mount>>) {
await openCitations(user)
const panel = inPlace('citations')
await user.click(panel.getByRole('button', { name: /Doe/ }))
await user.click(panel.getByRole('button', { name: 'Modifier' }))
const field = panel.getByLabelText('Citation', {
selector: '#panel-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2021' } })
return field
}
const savedCitation = () =>
(JSON.parse(store.getState().documentText) as AnatomicalSheetDocument)
.references[0].citation
it('Escape in a field of a panel tile neither closes the panel nor commits the text (A5)', async () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
const before = store.getState().documentText
await typeInPanelTile(user)
await user.keyboard('{Escape}')
expect(screen.getByTestId('editor-citations-panel')).toBeInTheDocument()
expect(store.getState().documentText).toBe(before)
})
it('the scrim (no focus move) commits the typed text, then closes the panel after its exit', async () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
await typeInPanelTile(user)
fireEvent.click(screen.getByTestId('references-scrim'))
expect(savedCitation()).toBe('Doe 2021')
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
expect(store.getState().unsaved).toBe(true)
})
})
describe('ids and parses', () => {
+55 -2
View File
@@ -147,16 +147,69 @@ describe('navigationReducer', () => {
const state = run(
initialNavigation('findings'),
{ type: 'open_citations', citedBy: node },
{ type: 'show_all_references' },
{ type: 'show_all_references', filter: node },
)
expect(state).toMatchObject({
tab: 'references',
finding: null,
referenceFilter: node,
libraryReset: 1,
focus: undefined,
})
expect(state.visitedTabs).toEqual(['findings', 'references'])
expect(run(state, { type: 'show_all_references' }).libraryReset).toBe(2)
const again = run(state, { type: 'show_all_references', filter: node })
expect(again.libraryReset).toBe(2)
})
it('the reference dialog is a layer above the place and the sheet', () => {
const open = run(
initialNavigation('findings'),
{ type: 'open_citations', citedBy: node },
{ type: 'open_reference', id: 'ref-a' },
)
expect(open).toMatchObject({
tab: 'findings',
finding: { key: node, citations: true },
reference: { edit: 'ref-a' },
})
expect(run(open, { type: 'close_reference' }).reference).toBeNull()
const created = run(initialNavigation('general'), {
type: 'create_reference',
})
expect(created).toMatchObject({
tab: 'references',
reference: { create: true },
})
})
it('the filter belongs to the References tab: any move to another tab drops it', () => {
const filtered = run(initialNavigation('findings'), {
type: 'show_all_references',
filter: node,
})
expect(
run(filtered, { type: 'select_tab', tab: 'references' }),
).toMatchObject({
referenceFilter: node,
})
expect(run(filtered, { type: 'select_tab', tab: 'general' })).toMatchObject(
{
referenceFilter: null,
},
)
expect(run(filtered, { type: 'open_finding', key: node })).toMatchObject({
tab: 'findings',
referenceFilter: null,
finding: { key: node, citations: false },
})
const toReference = run(filtered, {
type: 'go_to',
target: targetOfKey({ kind: 'reference', id: 'x' }),
})
expect(toReference.referenceFilter).toBeNull()
expect(
run(filtered, { type: 'clear_reference_filter' }).referenceFilter,
).toBeNull()
})
it('a plain go_to a reference leaves the library reset alone', () => {
@@ -143,18 +143,6 @@ describe('typed values come back after a 1 024 px crossing', () => {
)
})
it('the reference creation form, in the Références tab', async () => {
const user = await mount()
await user.click(tab('Références'))
await user.click(button('Ajouter une référence'))
await keepsTypedValue(
user,
'tab-reference-new-citation',
'Citation',
'Ajouter la référence',
)
})
it('the region creation form', async () => {
const user = await mount()
await user.click(tab('Annotations'))
@@ -0,0 +1,534 @@
/** R2F-5 and R2F-6: the reference dialog, the reading tiles, the finding filter, their history. */
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 { Location, NavigateFunction } from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import { findingDialog, openFinding } from '../helpers/findingDialog'
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(),
}))
let navigate: NavigateFunction
let location: Location
const probe = (n: NavigateFunction, l: Location) => {
navigate = n
location = l
}
const written = () =>
(location.state as Record<string, HistoryEntry> | null)?.[ENTRY_KEY]
const back = () => act(async () => navigate(-1))
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 = '') =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: url || null, doi: null },
}) as const
/** Three references; Node A (under Cat A) cites ref-a and ref-b. */
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/p'))
text = insert(text, ref('ref-c', 'Code rural'))
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: [],
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: ['ref-a', 'ref-b'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280): Promise<User> {
serverHas(sheetText(), 3)
const user = userEvent.setup()
mountDraft({ width, probe })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
await user.click(screen.getByRole('tab', { name: 'Références' }))
await waitFor(() => expect(written()?.view.tab).toBe('references'))
return user
}
const doc = () => JSON.parse(store.getState().documentText)
const entries = () => store.getState().undo.length
const dialogs = () => document.querySelectorAll('dialog[open]')
const refDialog = () =>
[...dialogs()].find((d) => d.querySelector('[data-draft-form]')) as
| HTMLElement
| undefined
const inRef = () => within(refDialog()!)
const closed = () => waitFor(() => expect(refDialog()).toBeUndefined())
const tab = () => screen.getByRole('tabpanel', { name: 'Références' })
const header = (citation: string) =>
within(tab()).getByRole('button', { name: new RegExp(`^${citation}`) })
const modify = async (user: User, citation: string) => {
if (header(citation).getAttribute('aria-expanded') === 'false') {
await user.click(header(citation))
}
const tile = header(citation).closest('li')!
await user.click(within(tile).getByRole('button', { name: 'Modifier' }))
await waitFor(() => expect(refDialog()).toBeDefined())
}
const field = (label: string) => inRef().getByLabelText(label)
const save = (user: User) =>
user.click(
inRef().getByRole('button', {
name: /^(Enregistrer|Ajouter la référence)$/,
}),
)
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
describe('the dialog', () => {
it('opens from « Modifier » with the first control focused, one entry on top', async () => {
const user = await mount()
const first = written()!.id
await modify(user, 'Barone')
expect(
inRef().getByRole('heading', { name: 'Modifier la référence' }),
).toBeVisible()
expect(refDialog()!.contains(document.activeElement)).toBe(true)
expect(field('Citation')).toHaveValue('Barone, Ostéologie')
await waitFor(() => expect(written()?.id).not.toBe(first))
expect(written()?.view.reference).toEqual({ edit: 'ref-a' })
expect(written()?.below?.reference).toBeNull()
})
it('a pristine « Enregistrer » closes with no command; a changed one is one entry', async () => {
const user = await mount()
await modify(user, 'Barone')
const before = entries()
await save(user)
await closed()
expect(entries()).toBe(before)
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1000/x')
await user.clear(field('Citation'))
await user.type(field('Citation'), 'Neuf')
await user.type(field('Adresse web (URL)'), 'https://a.org/')
await save(user)
await closed()
expect(entries()).toBe(before + 1)
expect(doc().references[0]).toMatchObject({
citation: 'Neuf',
doi: '10.1000/x',
url: 'https://a.org/',
})
act(() => void store.getState().undoStep())
expect(doc().references[0]).toMatchObject({
citation: 'Barone, Ostéologie',
doi: null,
url: null,
})
})
it('a double click on « Enregistrer » writes once and pops at most one entry', async () => {
const user = await mount()
const mounted = written()!.id
await modify(user, 'Barone')
await user.clear(field('Citation'))
await user.type(field('Citation'), 'Neuf')
const button = inRef().getByRole('button', { name: 'Enregistrer' })
fireEvent.click(button)
fireEvent.click(button)
await closed()
expect(entries()).toBe(1)
await waitFor(() => expect(written()?.id).toBe(mounted))
})
it('a blank citation and a non-http address are refused on their field', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.clear(field('Citation'))
await save(user)
expect(field('Citation')).toHaveFocus()
expect(field('Citation')).toHaveAccessibleDescription(
'Ce champ est obligatoire.',
)
await user.type(field('Citation'), 'Barone')
await user.type(field('Adresse web (URL)'), 'exemple.org')
await save(user)
expect(field('Adresse web (URL)')).toHaveFocus()
expect(field('Adresse web (URL)')).toHaveAccessibleDescription(
/http:\/\/ ou https:\/\//,
)
expect(entries()).toBe(0)
expect(refDialog()).toBeDefined()
})
it('« Annuler » with changes asks, « Abandonner » writes nothing', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
await user.click(inRef().getByRole('button', { name: 'Annuler' }))
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible()
expect(
inRef().getByRole('button', { name: 'Continuer la saisie' }),
).toHaveFocus()
await user.click(
inRef().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(field('DOI')).toHaveValue('10.1/x')
await user.click(inRef().getByRole('button', { name: 'Annuler' }))
await user.click(inRef().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(entries()).toBe(0)
})
it('a real dialog.close() on a dirty dialog keeps it, with its confirmation', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
act(() => (refDialog() as HTMLDialogElement).close())
await waitFor(() =>
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible(),
)
expect(refDialog()!.hasAttribute('open')).toBe(true)
expect(field('DOI')).toHaveValue('10.1/x')
})
it('Escape asks once when dirty; a held Escape (repeat) is ignored', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
fireEvent.keyDown(field('DOI'), { key: 'Escape', repeat: true })
expect(inRef().queryByText('Abandonner les modifications ?')).toBeNull()
fireEvent.keyDown(field('DOI'), { key: 'Escape' })
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible()
})
it('Défaire is unreachable under the dialog and a mode flip leaves the draft untouched', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(field('DOI')).toHaveValue('10.1/x')
const same = field('DOI')
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(field('DOI')).toBe(same)
expect(same).toHaveAttribute('readonly')
expect(inRef().getByText(/Élargissez la fenêtre/)).toBeVisible()
expect(inRef().getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
expect(entries()).toBe(0)
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(same).not.toHaveAttribute('readonly')
expect(same).toHaveValue('10.1/x')
})
it('a reference that vanishes closes its dialog by replace and says so', async () => {
const user = await mount()
await modify(user, 'Code rural')
const open = written()!
act(() => {
store
.getState()
.commit({ op: 'remove', key: { kind: 'reference', id: 'ref-c' } })
})
await closed()
await waitFor(() =>
expect(live()).toHaveTextContent("Cette référence n'existe plus"),
)
expect(written()?.id).toBe(open.id)
expect(written()?.view.reference).toBeNull()
})
})
describe('creation', () => {
const add = () =>
screen.getByRole('button', { name: 'Ajouter une référence' })
it('needs a type and a citation, creates in one command, leaves the list and says so', async () => {
const user = await mount()
await user.click(add())
await waitFor(() => expect(refDialog()).toBeDefined())
expect(written()?.view.reference).toEqual({ create: true })
await save(user)
expect(field('Type')).toHaveFocus()
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
await save(user)
await closed()
expect(entries()).toBe(1)
expect(doc().references).toHaveLength(4)
// Appended after the three, the sheet order untouched: nothing moved.
expect(within(tab()).getAllByRole('listitem')).toHaveLength(4)
expect(
within(tab()).getByText('Référence ajoutée : Nouvelle source'),
).toBeVisible()
await waitFor(() =>
expect(live()).toHaveTextContent('Référence ajoutée : Nouvelle source'),
)
expect(add()).toHaveFocus()
})
it('« Afficher » shows the new tile open and focuses it', async () => {
const user = await mount()
await user.click(add())
await waitFor(() => expect(refDialog()).toBeDefined())
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
await save(user)
await closed()
await user.click(within(tab()).getByRole('button', { name: 'Afficher' }))
expect(within(tab()).queryByText(/Référence ajoutée/)).toBeNull()
await waitFor(() =>
expect(header('Nouvelle source')).toHaveAttribute(
'aria-expanded',
'true',
),
)
await waitFor(() => expect(header('Nouvelle source')).toHaveFocus())
})
it('the entry becomes the reference’s own: Back, then Forward, reopens an edit, never a creation', async () => {
const user = await mount()
const first = written()!.id
await user.click(add())
await waitFor(() =>
expect(written()?.view.reference).toEqual({ create: true }),
)
const entry = written()!.id
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
await save(user)
await closed()
await waitFor(() => expect(written()?.id).toBe(first))
await act(async () => navigate(1))
await waitFor(() => expect(written()?.id).toBe(entry))
const created = doc().references[3].id
expect(written()?.view.reference).toEqual({ edit: created })
})
it('a dirty creation asks before it closes and writes nothing', async () => {
const user = await mount()
await user.click(add())
await waitFor(() => expect(refDialog()).toBeDefined())
await user.type(field('Citation'), 'x')
await user.keyboard('{Escape}')
await user.click(inRef().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(entries()).toBe(0)
await waitFor(() => expect(add()).toHaveFocus())
})
})
describe('history', () => {
it('Back closes the dialog and the opener holds the focus; Forward reopens it', async () => {
const user = await mount()
await modify(user, 'Barone')
const opener = within(header('Barone').closest('li')!).getByRole('button', {
name: 'Modifier',
})
await back()
await closed()
await waitFor(() => expect(opener).toHaveFocus())
await act(async () => navigate(1))
await waitFor(() => expect(refDialog()).toBeDefined())
expect(field('Citation')).toHaveValue('Barone, Ostéologie')
})
it('a dirty dialog keeps its draft when Back asks, then Abandonner pops once', async () => {
const user = await mount()
await modify(user, 'Barone')
await user.type(field('DOI'), '10.1/x')
await back()
expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible()
fireEvent.click(
inRef().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(field('DOI')).toHaveValue('10.1/x')
fireEvent.click(inRef().getByRole('button', { name: 'Annuler' }))
await user.click(inRef().getByRole('button', { name: 'Abandonner' }))
await closed()
await waitFor(() => expect(written()?.view.reference).toBeNull())
expect(entries()).toBe(0)
}, 20_000)
it('a reload keeps the tab but never reopens the form', async () => {
const user = await mount()
await modify(user, 'Barone')
const entry = written()!
cleanup()
serverHas(sheetText(), 3)
mountDraft({
probe,
entries: [{ pathname: location.pathname, state: { [ENTRY_KEY]: entry } }],
})
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await waitFor(() => expect(written()?.view.reference).toBeNull())
expect(written()?.view.tab).toBe('references')
expect(refDialog()).toBeUndefined()
})
})
describe('the finding filter', () => {
const chip = () => screen.getByTestId('editor-references-filter')
/** Node A's dialog, its sheet, then « Tout afficher »: the tab filtered by Node A. */
async function filtered(user: User) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(screen.getByRole('button', { name: '2 références' }))
await user.click(
await screen.findByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
await waitFor(() => expect(written()?.view.tab).toBe('references'))
}
it('« Tout afficher » lists the finding’s references, counts within the filter, no reorder', async () => {
const user = await mount()
await filtered(user)
expect(written()?.view.referenceFilter).toMatchObject({ kind: 'finding' })
expect(chip()).toHaveTextContent('Références du constat : Node A')
expect(within(tab()).getAllByRole('listitem')).toHaveLength(2)
expect(within(tab()).getByText('2 références')).toBeVisible()
await user.click(header('Barone'))
expect(
within(tab()).queryByRole('button', { name: 'Descendre' }),
).toBeNull()
await user.type(
within(tab()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'Code',
)
expect(within(tab()).getByText('0 référence sur 2')).toBeVisible()
expect(screen.getByTestId('editor-references-no-result')).toBeVisible()
})
it('the × removes the filter by replace; the search text is never in the entry', async () => {
const user = await mount()
await filtered(user)
const id = written()!.id
await user.type(
within(tab()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'Code',
)
await user.click(
within(chip()).getByRole('button', {
name: 'Retirer le filtre du constat Node A',
}),
)
await waitFor(() => expect(written()?.view.referenceFilter).toBeNull())
expect(written()?.id).toBe(id)
expect(JSON.stringify(location.state)).not.toContain('Code')
expect(within(tab()).getAllByRole('listitem').length).toBeGreaterThan(0)
})
it('« Revenir au constat » pops to the finding with its sheet open when the entry below shows it', async () => {
const user = await mount()
await filtered(user)
await user.click(screen.getByRole('button', { name: 'Revenir au constat' }))
await waitFor(() => expect(dialogs()).toHaveLength(2))
expect(written()?.view.finding).toMatchObject({ citations: true })
expect(written()?.view.referenceFilter).toBeNull()
})
it('a finding that vanishes clears the filter and says so', async () => {
const user = await mount()
await filtered(user)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await waitFor(() => expect(written()?.view.referenceFilter).toBeNull())
expect(screen.queryByTestId('editor-references-filter')).toBeNull()
await waitFor(() =>
expect(live()).toHaveTextContent(
"Le constat n'existe plus : le filtre est retiré",
),
)
})
it('the finding dialog and the sheet come back by Back, the filtered tab by Forward', async () => {
const user = await mount()
await filtered(user)
await back()
await waitFor(() => expect(dialogs()).toHaveLength(2))
expect(findingDialog()).not.toBeNull()
await act(async () => navigate(1))
await waitFor(() => expect(dialogs()).toHaveLength(0))
expect(chip()).toBeVisible()
})
})
@@ -222,7 +222,7 @@ describe('opening', () => {
}
})
it('has no search, no add control; field ids carry the panel prefix', async () => {
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()
@@ -231,24 +231,23 @@ describe('opening', () => {
).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(
panel().querySelector('#panel-reference-0-ref-a-citation'),
).not.toBeNull()
expect(document.querySelector('[id^="tab-reference-"]')).toBeNull()
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 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')
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 () => {
@@ -348,7 +347,11 @@ describe.each(MODES)('closing, %s', (_label, reduced) => {
await focusIs(() =>
within(tabPanel).getByRole('heading', { name: 'Références' }),
)
expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(3)
// 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 () => {
@@ -581,90 +584,7 @@ describe('« Retirer de ce constat »', () => {
})
})
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 « Tout afficher »', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
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)
removeNodeA()
await closed()
await waitFor(() => expect(findingDialog()).toBeNull())
await waitFor(() =>
expect(live()).toHaveTextContent(/Saisie non appliquée : Citation/),
)
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('a committed tile edit is one entry, reverted by Défaire once the sheet is closed', 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')
await user.click(closeButton())
await closed()
act(() => void store.getState().undoStep())
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',
@@ -689,44 +609,6 @@ function cite(ids: string[]) {
})
}
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 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)
await waitFor(() => expect(findingDialog()).toBeNull())
expect(doc().references[0].url).toBe('https://a.org/')
})
})
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()
@@ -1,16 +1,15 @@
/** 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 {
act,
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 ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import { useLocaleStore } from '@/state/localeStore'
import { targetOfKey } from '@/editor/navigation'
import { edit, insert } from '../helpers/editorFixtures'
@@ -22,6 +21,7 @@ import {
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) => ({
@@ -188,19 +188,19 @@ describe('the Références tab', () => {
).toBeNull()
})
it('Ctrl+Z reverts a reference edit', async () => {
it('Ctrl+Z reverts a reference edit made in the dialog, once it is closed', async () => {
const user = await mount()
await user.click(header('Barone'))
await user.click(
within(tabPanel()).getByRole('button', { name: 'Modifier' }),
)
const field = within(tabPanel()).getByLabelText('Citation', {
selector: '#tab-reference-0-ref-a-citation',
})
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')
fireEvent.blur(field)
const doc = () => JSON.parse(store.getState().documentText)
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')
@@ -228,13 +228,7 @@ describe('« Aller à » a reference', () => {
serverHas(sheetText(), 3)
await openReady({ text: sheetText() })
const user = userEvent.setup()
const view = render(
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
/>,
)
const view = render(<ReferencesHost />)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
@@ -244,14 +238,7 @@ describe('« Aller à » a reference', () => {
target: targetOfKey({ kind: 'reference', id: 'ref-a' }),
serial: 1,
}
view.rerender(
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
focus={focus}
/>,
)
view.rerender(<ReferencesHost focus={focus} />)
expect(box).toHaveValue('')
expect(document.querySelectorAll('button[aria-controls]')).toHaveLength(3)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
@@ -265,45 +252,17 @@ 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(
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={0}
/>,
)
const view = render(<ReferencesHost libraryReset={0} />)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
await user.type(box, 'Code')
view.rerender(
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={0}
/>,
)
view.rerender(<ReferencesHost libraryReset={0} />)
expect(box).toHaveValue('Code')
view.rerender(
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={1}
/>,
)
view.rerender(<ReferencesHost libraryReset={1} />)
expect(box).toHaveValue('')
await user.type(box, 'a')
view.rerender(
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={1}
/>,
)
view.rerender(<ReferencesHost libraryReset={1} />)
expect(box).toHaveValue('a')
})
})
@@ -311,182 +270,50 @@ describe('the reset signal', () => {
describe('adding a reference', () => {
const addButton = () =>
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' })
async function add(user: User) {
await user.click(addButton())
const byId = (id: string) => tabPanel().querySelector<HTMLElement>(id)!
await user.selectOptions(byId('#tab-reference-new-type'), 'book')
await user.type(byId('#tab-reference-new-citation'), 'Nouvelle source')
await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }),
)
}
it('resets the search, shows the new tile open and focuses its button', async () => {
const user = await mount()
await user.type(search(), 'Barone')
expect(cards()).toHaveLength(1)
await add(user)
expect(search()).toHaveValue('')
expect(cards()).toHaveLength(4)
expect(header('Nouvelle source')).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(header('Nouvelle source'))
expect(within(tabPanel()).queryByLabelText('Citation')).toBeNull()
})
it('opens a draft tile with the citation focused, and a refused add keeps it', async () => {
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())
expect(search()).toHaveValue('')
expect(document.activeElement).toBe(
tabPanel().querySelector('#tab-reference-new-citation'),
)
await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }),
)
expect(within(tabPanel()).getByRole('alert')).toHaveTextContent(
'Choisissez un type',
)
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)
})
})
describe("« Annuler l'ajout » (C2)", () => {
const addButton = () =>
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' })
const field = (id: string) =>
tabPanel().querySelector<HTMLElement>(`#tab-reference-new-${id}`)!
const draftTile = () =>
within(tabPanel()).queryByLabelText('Nouvelle référence')
const cancelButton = () =>
within(tabPanel()).getByRole('button', { name: "Annuler l'ajout" })
const history = () => ({
undo: store.getState().undo.length,
redo: store.getState().redo.length,
})
const refs = () => JSON.parse(store.getState().documentText).references
/** One real change undone, so a redo is pending; then the draft is opened. */
async function openWithPendingRedo() {
it('creates the reference in one modification and leaves the list where it was', async () => {
const user = await mount()
await startEditAndType(user)
act(() => store.getState().undoStep())
await user.type(search(), 'Barone')
await user.click(addButton())
return user
}
async function startEditAndType(user: User) {
await user.click(header('Barone, Ostéologie'))
const item = header('Barone, Ostéologie').closest('li')!
await user.click(within(item).getByRole('button', { name: 'Modifier' }))
await user.type(within(item).getByLabelText('DOI'), '10.1/x')
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
}
function expectCancelled(before: { refs: unknown; history: object }) {
expect(draftTile()).toBeNull()
expect(refs()).toEqual(before.refs)
expect(history()).toEqual(before.history)
expect(document.activeElement).toBe(addButton())
}
const snapshot = () => ({ refs: refs(), history: history() })
it('the button removes the tile, writes nothing, keeps a pending redo', async () => {
const user = await openWithPendingRedo()
expect(history().redo).toBe(1)
const before = snapshot()
await user.click(cancelButton())
expectCancelled(before)
})
it('Escape on the type select and on a button does the same', async () => {
const user = await openWithPendingRedo()
const before = snapshot()
await user.type(field('citation'), 'Brouillon')
fireEvent.keyDown(field('type'), { key: 'Escape' })
expectCancelled(before)
await user.click(addButton())
await user.type(field('citation'), 'Brouillon')
fireEvent.keyDown(cancelButton(), { key: 'Escape' })
expectCancelled(before)
})
it('Escape in a field cancels while the form is pristine, not once typed', async () => {
const user = await openWithPendingRedo()
const before = snapshot()
fireEvent.keyDown(field('citation'), { key: 'Escape' })
expectCancelled(before)
await user.click(addButton())
await user.type(field('citation'), 'Brouillon')
fireEvent.keyDown(field('citation'), { key: 'Escape' })
expect(draftTile()).not.toBeNull()
expect(field('citation')).toHaveValue('Brouillon')
})
it('Escape while composing, or already handled, does nothing', async () => {
const user = await mount()
await user.click(addButton())
fireEvent.keyDown(field('type'), { key: 'Escape', isComposing: true })
fireEvent.keyDown(field('type'), { key: 'Escape', keyCode: 229 })
expect(draftTile()).not.toBeNull()
const handled = new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
})
handled.preventDefault()
act(() => void field('type').dispatchEvent(handled))
expect(draftTile()).not.toBeNull()
})
it('Escape that cancels is marked handled', async () => {
const user = await mount()
await user.click(addButton())
const event = new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
})
act(() => void field('type').dispatchEvent(event))
expect(event.defaultPrevented).toBe(true)
})
it('goes with its refusal message, and a new add starts from an empty form', async () => {
const user = await mount()
await user.click(addButton())
await user.type(field('citation'), 'Brouillon')
await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter la 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 source',
)
expect(within(tabPanel()).getByRole('alert')).toBeInTheDocument()
await user.click(cancelButton())
expect(within(tabPanel()).queryByRole('alert')).toBeNull()
await user.click(addButton())
expect(field('citation')).toHaveValue('')
expect(field('type')).toHaveValue('')
expect(within(tabPanel()).queryByRole('alert')).toBeNull()
})
it('« Défaire » after a cancel undoes the previous real change', async () => {
const user = await mount()
await startEditAndType(user)
expect(history().undo).toBe(1)
await user.click(addButton())
await user.click(cancelButton())
expect(history().undo).toBe(1)
act(() => store.getState().undoStep())
expect(history()).toEqual({ undo: 0, redo: 1 })
expect(refs()[0].doi).toBeNull()
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 enters edit; answers the tile, whose header then names the edit. */
/** Opens the tile and its « Modifier » dialog. */
async function startEdit(user: User, citation: string) {
const item = tile(citation)
await user.click(header(citation))
await user.click(within(item).getByRole('button', { name: 'Modifier' }))
return item
await user.click(
within(tile(citation)).getByRole('button', { name: 'Modifier' }),
)
}
describe('the tile disclosure', () => {
@@ -593,198 +420,6 @@ describe('an open tile', () => {
})
})
describe('a tile in edit', () => {
it('shows the fields, the citers and « Terminer », and hides the other actions', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
expect(view.getByText('Modifier la référence')).toBeInTheDocument()
expect(document.activeElement).toBe(view.getByLabelText('Citation'))
expect(view.getByText('Citée 2 fois, par :')).toBeInTheDocument()
expect(view.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2)
for (const name of ['Modifier', 'Supprimer', 'Monter', 'Descendre']) {
expect(view.queryByRole('button', { name })).toBeNull()
}
await user.click(view.getByRole('button', { name: 'Terminer' }))
expect(view.queryByLabelText('Citation')).toBeNull()
expect(document.activeElement).toBe(
item.querySelector('button[aria-expanded]'),
)
expect(view.getByRole('button', { name: 'Modifier' })).toBeInTheDocument()
})
it('keeps edit and focuses the field when the URL is refused', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
const url = view.getByLabelText('Adresse web (URL)')
await user.type(url, 'exemple.org')
await user.click(view.getByRole('button', { name: 'Terminer' }))
expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument()
expect(document.activeElement).toBe(url)
expect(view.getByRole('alert')).toBeInTheDocument()
expect(doc().references[0].url).toBeNull()
})
it('keeps edit and focuses the citation when it is left blank', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
const citation = view.getByLabelText('Citation')
await user.clear(citation)
await user.click(view.getByRole('button', { name: 'Terminer' }))
expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument()
expect(document.activeElement).toBe(citation)
expect(view.getByText('Ce champ est obligatoire.')).toBeInTheDocument()
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('a refused field A, then B applied, then « Terminer » keeps edit', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
const url = view.getByLabelText('Adresse web (URL)')
await user.type(url, 'exemple.org')
await user.tab()
await user.type(view.getByLabelText('DOI'), '10.1000/xyz')
await user.tab()
expect(doc().references[0].doi).toBe('10.1000/xyz')
await user.click(view.getByRole('button', { name: 'Terminer' }))
expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument()
expect(document.activeElement).toBe(url)
})
it('a press on « Terminer » keeps the focus in the field (no refusal shifts it), the click keeps edit', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
const url = view.getByLabelText('Adresse web (URL)')
await user.type(url, 'exemple.org')
const done = view.getByRole('button', { name: 'Terminer' })
await user.pointer({ keys: '[MouseLeft>]', target: done })
expect(view.queryByRole('alert')).toBeNull()
expect(document.activeElement).toBe(url)
await user.pointer({ keys: '[/MouseLeft]', target: done })
expect(view.getByRole('alert')).toBeInTheDocument()
expect(document.activeElement).toBe(url)
expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument()
})
it('applies every pending field on « Terminer », as one history entry each', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
const before = store.getState().undo.length
await user.type(view.getByLabelText('DOI'), '10.1000/xyz')
await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/')
await user.click(view.getByRole('button', { name: 'Terminer' }))
expect(store.getState().undo.length - before).toBe(2)
expect(doc().references[0]).toMatchObject({
doi: '10.1000/xyz',
url: 'https://a.org/',
})
expect(view.queryByLabelText('Citation')).toBeNull()
})
it('switching to another tile leaves edit only when the fields apply', async () => {
const user = await mount()
const barone = await startEdit(user, 'Barone')
const denoix = tile('Denoix')
const url = within(barone).getByLabelText('Adresse web (URL)')
await user.type(url, 'exemple.org')
await user.click(header('Denoix'))
const modify = () =>
within(denoix).getByRole('button', { name: 'Modifier' })
await user.click(modify())
expect(within(barone).getByLabelText('Citation')).toBeInTheDocument()
expect(within(denoix).queryByLabelText('Citation')).toBeNull()
await user.clear(url)
await user.click(modify())
expect(within(barone).queryByLabelText('Citation')).toBeNull()
expect(within(denoix).getByLabelText('Citation')).toBeInTheDocument()
})
it('survives a tab change with the typed text', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
await user.type(within(item).getByLabelText('DOI'), '10.1000/kept')
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('tab', { name: 'Références' }))
const view = within(item)
expect(view.getByLabelText('DOI')).toHaveValue('10.1000/kept')
expect(doc().references[0].doi).toBe('10.1000/kept')
})
})
describe('the disclosure button in edit (M7)', () => {
it('is named for what it does, and pressing it ends the edit', async () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const button = within(item).getByRole('button', {
name: /^Terminer\. Modifier la référence/,
})
expect(button).toHaveAttribute('aria-expanded', 'true')
await user.click(button)
expect(within(item).queryByLabelText('Citation')).toBeNull()
})
})
describe('one user edit, one history entry (C1)', () => {
const entries = () => store.getState().undo.length
const undo = () => act(() => store.getState().undoStep())
it('« Terminer » after one typed field adds one entry, the first « Défaire » undoes it', async () => {
const user = await mount()
const view = within(await startEdit(user, 'Barone'))
const before = entries()
await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/')
await user.click(view.getByRole('button', { name: 'Terminer' }))
expect(entries() - before).toBe(1)
expect(doc().references[0].url).toBe('https://a.org/')
undo()
expect(doc().references[0].url).toBeNull()
})
it('« Terminer » pressed with the field still focused (no pointer) adds one entry', async () => {
const user = await mount()
const view = within(await startEdit(user, 'Barone'))
const before = entries()
const url = view.getByLabelText('Adresse web (URL)')
await user.type(url, 'https://a.org/')
expect(document.activeElement).toBe(url)
fireEvent.click(view.getByRole('button', { name: 'Terminer' }))
expect(entries() - before).toBe(1)
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 view = within(await startEdit(user, 'Barone'))
const before = entries()
await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/')
fireEvent.click(screen.getByRole('tab', { name: 'Constats' }))
expect(entries() - before).toBe(1)
undo()
expect(doc().references[0].url).toBeNull()
})
it('a blur after the field was applied adds nothing; a changed text adds one more', async () => {
const user = await mount()
const view = within(await startEdit(user, 'Barone'))
const before = entries()
const url = view.getByLabelText('Adresse web (URL)')
await user.type(url, 'https://a.org/')
await user.tab()
await user.click(url)
await user.tab()
expect(entries() - before).toBe(1)
await user.type(url, 'x')
await user.tab()
expect(entries() - before).toBe(2)
})
})
describe('read-only tiles', () => {
it('keep DOI, URL and « Aller à », and offer no edit control', async () => {
const user = await mount(800)
@@ -805,9 +440,8 @@ describe('read-only tiles', () => {
})
describe('reopening the editor', () => {
it('starts with every tile closed and none in edit', async () => {
it('starts with every tile closed', async () => {
const user = await mount()
await startEdit(user, 'Barone')
await user.click(header('Denoix'))
cleanup()
await mount()
@@ -815,10 +449,5 @@ describe('reopening the editor', () => {
expanded: true,
})
expect(opened).toHaveLength(0)
expect(
within(tabPanel()).queryByLabelText('Citation', {
selector: '#tab-reference-0-ref-a-citation',
}),
).toBeNull()
})
})
@@ -1,10 +1,15 @@
/** R2.3: search, sort, count, no-result notice, A1, the add flow, the pin and the reset. */
/** 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, within } from '@testing-library/react'
import {
act,
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import { AnnounceContext } from '@/editor/focusRequest'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
@@ -14,6 +19,7 @@ import {
resetStore,
store,
} from '../helpers/editorHarness'
import ReferencesHost from '../helpers/referencesHost'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -87,12 +93,7 @@ function sortText(): string {
type User = ReturnType<typeof userEvent.setup>
const doc = () => JSON.parse(store.getState().documentText)
const lib = (readOnly = false, extra = {}) => (
<ReferencesTab
readOnly={readOnly}
navigate={vi.fn()}
reloadSheet={vi.fn()}
{...extra}
/>
<ReferencesHost readOnly={readOnly} {...extra} />
)
async function mount(readOnly = false) {
await openReady({ text: sortText() })
@@ -183,16 +184,6 @@ describe('the count line', () => {
})
})
describe('the count with a pinned tile', () => {
it('counts the matches only, the pinned tile stays shown', async () => {
const { user } = await mount()
await startEdit(user, 'r1')
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
expect(screen.getByText('1 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()
@@ -303,96 +294,72 @@ describe('the move buttons (A1)', () => {
})
})
/** Opens the tile of `id` and enters edit. */
/** 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 item
return screen.getByRole('dialog', { name: 'Modifier la référence' })
}
describe('the tile in edit is pinned (P23)', () => {
it('keeps its index when the sort changes', async () => {
/** 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', 'r5', 'r3', 'r4', 'r1'])
await user.selectOptions(sortBox(), 'sheet')
expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5'])
expect(order()).toEqual(['r2', 'r1', 'r5', 'r3', 'r4'])
})
it('starts in sheet order and holds its place under a later sort', async () => {
it('stays shown under a search it stops matching, until the next search change (I1)', async () => {
const { user } = await mount()
await startEdit(user, 'r3')
await user.selectOptions(sortBox(), 'citation')
expect(order()).toEqual(['r5', 'r4', 'r3', 'r2', 'r1'])
})
it('stays shown under a search that does not match it, also after « Terminer », until the next search change (I1)', async () => {
const { user } = await mount()
const item = await startEdit(user, 'r1')
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
expect(within(item).getByLabelText('Citation')).toBeInTheDocument()
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
expect(order()).toEqual(['r1', 'r5'])
expect(document.activeElement).toBe(header('r1'))
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(['r5'])
expect(order()).toEqual([])
})
it('keeps the tile shown and focused when its edit stops matching the search (I1)', async () => {
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')
const item = await startEdit(user, 'r1')
const citation = within(item).getByLabelText('Citation')
await user.clear(citation)
await user.type(citation, 'Autre titre')
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
await startEdit(user, 'r1')
await saveCitation(user, 'Autre titre')
expect(order()).toEqual(['r1', 'r2'])
expect(document.activeElement).toBe(header('r1'))
expect(search()).toHaveValue('zèbre')
expect(document.activeElement).toBe(
within(header('r1').closest('li')!).getByRole('button', {
name: 'Modifier',
}),
)
})
it('keeps the tile in edit at its index across a sort change made while read-only (M3)', async () => {
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'])
view.rerender(lib(true))
await user.selectOptions(sortBox(), 'count')
view.rerender(lib(false))
expect(order()).toEqual(['r2', 'r3', 'r1', 'r5', 'r4'])
})
it('stays pinned in read-only: the read view of the tile, still shown after a search', async () => {
const { user, view } = await mount()
await startEdit(user, 'r1')
await user.selectOptions(sortBox(), 'citation')
view.rerender(lib(true))
expect(screen.queryByLabelText('Citation')).toBeNull()
expect(order()).toEqual(['r1', 'r5', 'r3', 'r4', 'r2'])
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
view.rerender(lib(false))
expect(order()).toEqual(['r1', 'r5'])
expect(
within(header('r1').closest('li')!).getByLabelText('Citation'),
).toBeVisible()
})
it('a read-only toggle ends the edit state and collapses the tile', async () => {
const { user, view } = await mount()
await startEdit(user, 'r1')
view.rerender(lib(true))
expect(header('r1')).toHaveAttribute('aria-expanded', 'true')
await user.click(header('r1'))
expect(header('r1')).toHaveAttribute('aria-expanded', 'false')
view.rerender(lib(false))
expect(header('r1')).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByLabelText('Citation')).toBeNull()
})
})
@@ -402,194 +369,74 @@ describe('the tile outside the search (C3)', () => {
const lineOf = (id: string) =>
within(header(id).closest('li')!).queryByText(line)
async function editedOut(user: User) {
await user.type(search(), 'zèbre')
const item = await startEdit(user, 'r1')
const citation = within(item).getByLabelText('Citation')
await user.clear(citation)
await user.type(citation, 'Autre titre')
return item
}
it('after « Terminer » shows the tile with its line, no notice, focus on its header', async () => {
it('after the save shows the tile with its line and no notice', async () => {
const { user } = await mount()
await user.clear(search())
await user.type(search(), 'alpha')
const item = await startEdit(user, 'r5')
await user.clear(within(item).getByLabelText('Citation'))
await user.type(within(item).getByLabelText('Citation'), 'Autre titre')
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
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(document.activeElement).toBe(header('r5'))
expect(header('r5').getAttribute('aria-describedby')).toBe(lineOf('r5')!.id)
expect(header('r5')).toHaveAccessibleDescription(line)
expect(
screen.getByRole('button', { name: 'Effacer la recherche' }),
).toBeVisible()
})
it('the next search change drops the tile and shows the notice', async () => {
const { user } = await mount()
await user.type(search(), 'alpha')
const item = await startEdit(user, 'r5')
await user.clear(within(item).getByLabelText('Citation'))
await user.type(within(item).getByLabelText('Citation'), 'Autre titre')
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
await user.type(search(), 'x')
expect(order()).toEqual([])
expect(notice()).not.toBeNull()
})
it('a tile in edit that does not match carries the line', async () => {
const { user } = await mount()
const item = await editedOut(user)
expect(lineOf('r1')).toBeNull()
await user.type(search(), 'x')
expect(within(item).getByLabelText('Citation')).toBeVisible()
expect(lineOf('r1')).toBeVisible()
})
it('a matching pinned tile has no line', async () => {
const { user } = await mount()
await user.type(search(), 'zebre')
await startEdit(user, 'r1')
await user.type(search(), 'alpha')
expect(lineOf('r1')).toBeVisible()
expect(lineOf('r5')).toBeNull()
await user.clear(search())
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 startEdit(user, 'r1')
await user.type(search(), 'alpha')
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
view.rerender(lib(true))
expect(order()).toEqual(['r1', 'r5'])
expect(lineOf('r1')).toBeVisible()
expect(order()).toEqual(['r5'])
expect(lineOf('r5')).toBeVisible()
expect(notice()).toBeNull()
})
it('an open draft tile does not hide the notice for a search matching nothing', async () => {
const { user } = await mount()
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
await user.type(search(), 'radiographie')
expect(order()).toEqual([])
expect(notice()).not.toBeNull()
})
})
describe('adding (P24)', () => {
const add = () =>
screen.getByRole('button', { name: 'Ajouter une référence' })
const draftCitation = () =>
document.querySelector<HTMLElement>('#tab-reference-new-citation')
it('resets search and sort, appends a draft tile in edit, citation focused', async () => {
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.selectOptions(sortBox(), 'count')
await user.click(header('r2'))
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'e')
await user.click(add())
expect(search()).toHaveValue('')
expect(sortBox()).toHaveValue('sheet')
expect(order()).toHaveLength(5)
expect(document.activeElement).toBe(draftCitation())
expect(screen.getByLabelText('Type')).toHaveValue('')
expect(
within(screen.getByLabelText('Type')).getByText('Choisir…'),
).toBeInTheDocument()
expect(
screen.getByText('Type et citation obligatoires.'),
).toBeInTheDocument()
expect(snapshot().history).toBe(0)
})
it('creates the reference in one modification; the tile stays open, out of edit, focused', async () => {
const { user } = await mount()
await user.click(add())
await user.selectOptions(screen.getByLabelText('Type'), 'book')
await user.type(draftCitation()!, 'Nouvelle source')
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
expect(store.getState().undo.length).toBe(1)
expect(doc().references).toHaveLength(6)
const id = doc().references[5].id
expect(order()).toHaveLength(6)
expect(header(id)).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(header(id))
expect(draftCitation()).toBeNull()
expect(
within(header(id).closest('li')!).getByRole('button', {
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',
}),
).toBeInTheDocument()
})
it('a search typed after « Ajouter une référence » is cleared by the add, the new tile takes the focus (I1)', async () => {
const { user } = await mount()
await user.click(add())
await user.selectOptions(screen.getByLabelText('Type'), 'book')
await user.type(draftCitation()!, 'Nouvelle source')
await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
const id = doc().references[5].id
expect(search()).toHaveValue('')
expect(order()).toHaveLength(6)
expect(document.activeElement).toBe(header(id))
})
it('a second click on the button takes the focus back to the citation', async () => {
const { user } = await mount()
await user.click(add())
await user.click(search())
await user.click(add())
expect(document.activeElement).toBe(draftCitation())
expect(
document.querySelectorAll('#tab-reference-new-citation'),
).toHaveLength(1)
})
it('leaves the tile in edit first: a refused field cancels the add (P22)', async () => {
const { user } = await mount()
const item = await startEdit(user, 'r1')
const url = within(item).getByLabelText('Adresse web (URL)')
await user.type(url, 'exemple.org')
await user.click(add())
expect(draftCitation()).toBeNull()
expect(document.activeElement).toBe(url)
await user.clear(url)
await user.click(add())
expect(draftCitation()).not.toBeNull()
expect(within(item).queryByLabelText('Citation')).toBeNull()
})
it('keeps the draft hidden in read-only and resumes it when editable again', async () => {
const { user, view } = await mount()
await user.click(add())
await user.type(draftCitation()!, 'En cours')
view.rerender(lib(true))
expect(draftCitation()).not.toBeVisible()
view.rerender(lib(false))
expect(draftCitation()).toBeVisible()
expect(draftCitation()).toHaveValue('En cours')
})
})
describe('the reset path (« Tout afficher »)', () => {
it('empties the search and keeps the sort, keeping open tiles and the tile in edit (R2F-4)', async () => {
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'))
const item = await startEdit(user, 'r1')
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'e')
view.rerender(lib(false, { libraryReset: 1 }))
@@ -597,10 +444,6 @@ describe('the reset path (« Tout afficher »)', () => {
expect(sortBox()).toHaveValue('citation')
expect(order()).toHaveLength(5)
expect(header('r2')).toHaveAttribute('aria-expanded', 'true')
expect(within(item).getByLabelText('Citation')).toBeInTheDocument()
// The tile in edit stays pinned through the reset: a new search does not hide it.
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
})
})
@@ -638,9 +481,9 @@ describe('« Aller à » a reference hidden by the search (P3, P8)', () => {
})
describe('state of a reference that left the document (P23-prime)', () => {
it('is dropped: undoing the removal brings the tile back closed and out of edit', async () => {
it('is dropped: undoing the removal brings the tile back closed', async () => {
const { user } = await mount()
await startEdit(user, 'r4')
await user.click(header('r4'))
act(() => {
store
.getState()
@@ -652,58 +495,5 @@ describe('state of a reference that left the document (P23-prime)', () => {
})
expect(order()).toContain('r4')
expect(header('r4')).toHaveAttribute('aria-expanded', 'false')
expect(
within(header('r4').closest('li')!).queryByLabelText('Citation'),
).toBeNull()
})
})
describe('a read-only flip with a tile in edit (M1)', () => {
const ui = (announce: (text: string) => void, readOnly: boolean) => (
<AnnounceContext value={announce}>{lib(readOnly)}</AnnounceContext>
)
async function refusedUrl() {
await openReady({ text: sortText() })
const user = userEvent.setup()
const announce = vi.fn()
const view = render(ui(announce, false))
const item = await startEdit(user, 'r1')
await user.type(
within(item).getByLabelText('Adresse web (URL)'),
'exemple.org',
)
await user.tab()
return { view, announce, item, user }
}
it('says which refused draft is dropped, once', async () => {
const { view, announce } = await refusedUrl()
view.rerender(ui(announce, true))
expect(announce).toHaveBeenCalledTimes(1)
expect(announce).toHaveBeenCalledWith(
'Saisie non appliquée : Adresse web (URL)',
)
view.rerender(ui(announce, false))
expect(announce).toHaveBeenCalledTimes(1)
})
it('does not move the focus to Citation when editing is possible again', async () => {
const { view, announce } = await refusedUrl()
view.rerender(ui(announce, true))
view.rerender(ui(announce, false))
const citation = screen.getByLabelText('Citation')
expect(document.activeElement).not.toBe(citation)
expect(screen.getByLabelText('Adresse web (URL)')).toHaveValue('')
})
it('says nothing when no draft is lost', async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
const announce = vi.fn()
const view = render(ui(announce, false))
await startEdit(user, 'r1')
view.rerender(ui(announce, true))
expect(announce).not.toHaveBeenCalled()
})
})
+28 -13
View File
@@ -1,9 +1,14 @@
/** Lot F: the Références tab and Vertèbres. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import RegionsSection from '@/components/editor/annotations/sections/RegionsSection'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert, point } from '../helpers/editorFixtures'
@@ -13,6 +18,7 @@ import {
resetStore,
store,
} from '../helpers/editorHarness'
import ReferencesHost from '../helpers/referencesHost'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -44,16 +50,24 @@ describe('Références', () => {
it('adds a reference only with a type and a citation', async () => {
await openReady()
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
render(<ReferencesHost {...props} />)
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
expect(screen.getByRole('alert')).toHaveTextContent('Choisissez un type')
expect(screen.getByLabelText('Type')).toHaveAccessibleDescription(
'Ce champ est obligatoire.',
)
expect(doc().references).toEqual([])
await user.selectOptions(screen.getByLabelText('Type'), 'web')
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
expect(screen.getByLabelText('Citation')).toHaveAccessibleDescription(
'Ce champ est obligatoire.',
)
await user.type(screen.getByLabelText('Citation'), 'Anatomie du cheval')
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
@@ -68,23 +82,24 @@ describe('Références', () => {
expect(doc().references[0].id).toMatch(/^ref-[a-z2-7]{10}$/)
})
it('edits a field in a tile, applies it on blur, and reorders with the arrows', async () => {
it('edits a reference in its dialog, one command on « Enregistrer », and reorders with the arrows', async () => {
const text = insert(
insert(baseText(), reference('ref-a', 'Alpha')),
reference('ref-b', 'Beta'),
)
await openReady({ text })
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
render(<ReferencesHost {...props} />)
await user.click(screen.getByRole('button', { name: /^Alpha/ }))
await user.click(screen.getByRole('button', { name: 'Modifier' }))
const url = screen.getByLabelText('Adresse web (URL)', {
selector: '#tab-reference-0-ref-a-url',
})
const url = screen.getByLabelText('Adresse web (URL)')
await user.type(url, 'https://example.org')
await user.tab()
expect(doc().references[0].url).toBeNull()
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
expect(doc().references[0].url).toBe('https://example.org')
await user.click(screen.getByRole('button', { name: 'Terminer' }))
await user.click(screen.getByRole('button', { name: /^Beta/ }))
await user.click(screen.getAllByRole('button', { name: 'Monter' })[1])
expect(doc().references.map((r) => r.id)).toEqual(['ref-b', 'ref-a'])
@@ -118,7 +133,7 @@ describe('Références', () => {
})
await openReady({ text })
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
render(<ReferencesHost {...props} />)
await user.click(screen.getByRole('button', { name: /^Alpha/ }))
expect(screen.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(screen.getByText(/Pour supprimer cette référence/)).toBeTruthy()
@@ -133,7 +148,7 @@ describe('Références', () => {
it('read-only shows the facts and no control that changes the draft', async () => {
await openReady({ text: insert(baseText(), reference('ref-a', 'Alpha')) })
const user = userEvent.setup()
render(<ReferencesTab {...props} readOnly />)
render(<ReferencesHost {...props} readOnly />)
await user.click(screen.getByRole('button', { name: /^Alpha/ }))
expect(screen.getByText('Aucun')).toBeTruthy()
expect(screen.queryByRole('textbox', { name: 'Citation' })).toBeNull()