feat(editor): edit mode of the references dialog

« Modifier » turns the references dialog into a draft of adds and removes,
saved as one update on the current citations. A new layer, citations,
guards it between the finding and the reference dialogs: close, Back,
POP refusal and the leave cascade ask it. « Modifier la référence » and
« Nouvelle référence » stack the reference dialog over it; a creation it
started joins its draft.
This commit is contained in:
bchanot committed 2026-11-15 16:39:43 +01:00
1 parent d9dbcf1609
commit 3dc5820e3a
29 files changed
+1489 -243

No files matched your search

+2
View File
@@ -31,6 +31,8 @@ export default function FindingsHost({
onShowAll={() => undefined}
navigate={nav.navigate}
returnFocus={nav.citationsTrigger}
guards={nav.guards}
references={nav.references}
/>
</ReadOnlyContext>
)
@@ -0,0 +1,29 @@
/** Rev 5 Task 12: the citations draft, held as additions and removals. */
import { describe, expect, it } from 'vitest'
import {
addId,
applyEdits,
NO_EDITS,
removeId,
} from '@/editor/references/citationEdits'
describe('citation edits', () => {
it('applies removals and additions to the current list, each id once', () => {
const edits = addId(removeId(NO_EDITS, 'a'), 'b')
expect(applyEdits(['a', 'c'], edits)).toEqual(['c', 'b'])
expect(applyEdits(['a', 'b'], edits)).toEqual(['b'])
expect(applyEdits([], edits)).toEqual(['b'])
})
it('a removal then a citation of the same id is no change at all', () => {
expect(addId(removeId(NO_EDITS, 'a'), 'a')).toEqual(NO_EDITS)
expect(removeId(addId(NO_EDITS, 'n'), 'n')).toEqual(NO_EDITS)
})
it('a repeat is ignored', () => {
const once = addId(NO_EDITS, 'b')
expect(addId(once, 'b')).toBe(once)
const gone = removeId(NO_EDITS, 'a')
expect(removeId(gone, 'a')).toBe(gone)
})
})
@@ -0,0 +1,581 @@
/** Rev 5 Task 12: the references dialog's edit mode (draft, save, guards, stacked dialogs). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, 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 {
forgetSessionTag,
resolveSessionTag,
} from '@/editor/history/sessionTag'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
serverHas,
SHEET,
store,
USER,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import {
findingDialog,
inFindingDialog,
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]
let TAG: string
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
TAG = resolveSessionTag(USER)
})
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string) =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: null, doi: null },
}) as const
/** Barone (ref-a), Denoix (ref-b), Code rural (ref-c); Node A cites `ids`. */
function sheetText(ids = ['ref-a', 'ref-c']): string {
let text = baseText()
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
text = insert(text, ref('ref-b', 'Denoix'))
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: {},
reference_ids: ids,
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
}
const nodeKey = {
kind: 'finding' as const,
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
}
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280, text = sheetText()): Promise<User> {
serverHas(text, 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: 'Constats' }))
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
return user
}
const doc = () => JSON.parse(store.getState().documentText)
const nodeA = () =>
doc().finding_zones[0].categories[0].children[0] as {
name: { fr: string }
reference_ids: string[]
}
const library = () =>
(doc().references as { id: string; citation: string }[]).map(
(r) => r.citation,
)
const undos = () => store.getState().undo.length
const back = (steps = 1) => act(async () => navigate(-steps))
const question = 'Abandonner les modifications ?'
const openDialogs = () => [
...document.querySelectorAll<HTMLElement>('dialog[open][data-layer]'),
]
const citations = () =>
openDialogs().find((d) => d.querySelector('[data-place="citations"]'))
const inCitations = () => within(citations()!)
const referenceDialog = () =>
openDialogs().find((d) => d.querySelector('#reference-form-citation'))
const inReference = () => within(referenceDialog()!)
const button = (label: string | RegExp) =>
inCitations().getByRole('button', { name: label })
const rows = () =>
[...citations()!.querySelectorAll('[data-citation-row]')].map((row) =>
row.getAttribute('data-citation-row'),
)
/** Node A's dialog, then its references dialog. */
async function openCitations(user: User, trigger = '2 références') {
await openFinding(user, /Node A/)
await user.click(inFindingDialog().getByRole('button', { name: trigger }))
await waitFor(() => expect(citations()).toBeDefined())
}
/** The references dialog of Node A, in its edit mode. */
async function editCitations(user: User, trigger?: string) {
await openCitations(user, trigger)
await user.click(button('Modifier'))
await waitFor(() =>
expect(
inCitations().getByRole('heading', {
name: 'Modifier les références du constat',
}),
).toBeVisible(),
)
}
const removeRow = (user: User, citation: RegExp) =>
user.click(
inCitations().getByRole('button', {
name: new RegExp(`^Retirer ${citation.source}`),
}),
)
const cite = (user: User, id: string) =>
user.selectOptions(inCitations().getByLabelText('Citer une référence'), id)
describe('the « Modifier » of the references dialog', () => {
it('switches to the edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => {
const user = await mount()
await openCitations(user)
const before = written()!.id
await user.click(button('Modifier'))
expect(written()!.id).toBe(before)
expect(rows()).toEqual(['ref-a', 'ref-c'])
expect(
inCitations().queryByRole('button', { name: /Tout afficher/ }),
).toBeNull()
expect(inCitations().queryByRole('button', { name: 'Aller à' })).toBeNull()
})
it('is not offered read only (below 1 024 px)', async () => {
const user = await mount(900)
await openCitations(user)
expect(inCitations().queryByRole('button', { name: 'Modifier' })).toBeNull()
})
})
describe('the draft', () => {
it('stages a removal and a citation, writes nothing until « Enregistrer »', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await cite(user, 'ref-b')
expect(rows()).toEqual(['ref-c', 'ref-b'])
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(undos()).toBe(0)
})
it('one save is one update, one undo; back to the view mode, focus on « Modifier »', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await cite(user, 'ref-b')
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b'])
expect(undos()).toBe(1)
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(
inCitations().getByText('Modifications enregistrées'),
).toBeInTheDocument()
act(() => {
store.getState().undoStep()
})
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
it('a pristine save writes nothing', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Enregistrer'))
expect(undos()).toBe(0)
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(inCitations().queryByText('Modifications enregistrées')).toBeNull()
})
it('a dangling id is named and removable', async () => {
const user = await mount(1280, sheetText(['ref-a', 'ref-x']))
await editCitations(user)
expect(inCitations().getByText(/^Référence introuvable/)).toBeVisible()
await removeRow(user, /ref-x/)
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-a'])
})
it('a save keeps citations changed elsewhere: removals and additions on the current list', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
const node = doc().finding_zones[0].categories[0].children[0]
store.getState().commit({
op: 'update',
key: nodeKey,
element: {
kind: 'finding_node',
value: { ...node, reference_ids: ['ref-a', 'ref-c', 'ref-b'] },
},
})
})
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b'])
})
})
describe('leaving the edit mode with changes', () => {
it('« Annuler » asks; « Abandonner » goes back to the view, nothing written', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await user.click(button('Annuler'))
expect(inCitations().getByText(question)).toBeVisible()
await user.click(button('Abandonner'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
expect(citations()).toBeDefined()
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
it('« Annuler » without changes goes back at once', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Annuler'))
await waitFor(() => expect(button('Modifier')).toHaveFocus())
})
it('Escape and ✕ ask; the dialog stays', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await user.click(button('Fermer'))
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
await user.click(button('Continuer la saisie'))
act(() => button('Annuler').focus())
await user.keyboard('{Escape}')
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
})
it('a Back that closes only the references dialog asks; the draft stays', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
await back()
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
expect(rows()).toEqual(['ref-c'])
expect(written()!.view.finding).toMatchObject({ citations: true })
})
it('a flip to read only keeps the draft, every control off, only « Abandonner »', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(rows()).toEqual(['ref-c'])
expect(inCitations().getByText(/Élargissez la fenêtre/)).toBeVisible()
expect(button('Enregistrer')).toBeDisabled()
expect(button(/^Retirer/)).toBeDisabled()
expect(button(/^Modifier la référence/)).toBeDisabled()
expect(button('Nouvelle référence')).toBeDisabled()
expect(inCitations().queryByLabelText('Citer une référence')).toBeNull()
expect(inCitations().queryByRole('button', { name: 'Annuler' })).toBeNull()
await user.click(button('Abandonner'))
await waitFor(() =>
expect(
inCitations().getByRole('heading', { name: 'Références du constat' }),
).toBeVisible(),
)
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
})
describe('the reference dialog over the edit mode', () => {
it('« Modifier la référence » stacks it; closed, the draft and the focus are back', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Code rural/)
const opener = button(/^Modifier la référence Barone/)
await user.click(opener)
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(openDialogs()).toHaveLength(3)
expect(
inReference().getByRole('heading', { name: 'Modifier la référence' }),
).toBeVisible()
await user.click(inReference().getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(referenceDialog()).toBeUndefined())
await waitFor(() => expect(opener).toHaveFocus())
expect(rows()).toEqual(['ref-a'])
})
it('« Nouvelle référence » creates it and cites it in the draft only', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
await user.click(
inReference().getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(library()).toContain('Neuf')
const id = doc().references.find(
(r: { citation: string }) => r.citation === 'Neuf',
).id
expect(rows()).toEqual(['ref-a', 'ref-c', id])
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
await user.click(button('Enregistrer'))
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', id])
expect(undos()).toBe(2)
})
it('a reference created, then the draft abandoned, stays in the library uncited', async () => {
const user = await mount()
await editCitations(user)
await user.click(button('Nouvelle référence'))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
await user.click(
inReference().getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
await user.click(button('Annuler'))
await user.click(button('Abandonner'))
expect(library()).toContain('Neuf')
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(undos()).toBe(1)
})
})
describe('a finding draft and a references draft on the same element', () => {
it('are both saved; neither overwrites the other', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: 'Modifier' }),
)
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() => expect(citations()).toBeDefined())
await user.click(button('Modifier'))
await removeRow(user, /Barone/)
await user.click(button('Enregistrer'))
await user.click(button('Fermer'))
await waitFor(() => expect(citations()).toBeUndefined())
await user.click(
inFindingDialog().getByRole('button', { name: 'Enregistrer' }),
)
expect(nodeA().name.fr).toBe('Node A bis')
expect(nodeA().reference_ids).toEqual(['ref-c'])
expect(undos()).toBe(2)
})
})
describe('leaving the editor with a citations draft', () => {
it('a sign-out leaves the account flag of the citations layer', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
act(() => {
forgetSessionTag()
useAuthStore.setState({ user: null })
})
await waitFor(() => expect(citations()).toBeUndefined())
const flags = Object.keys(sessionStorage)
.filter((k) => k.startsWith('faunosteo:editor:left-draft-account:'))
.map((k) => JSON.parse(sessionStorage.getItem(k)!))
expect(flags).toHaveLength(1)
expect(flags[0]).toMatchObject({ kind: 'citations', key: nodeKey })
expect(JSON.stringify(flags)).not.toContain('Barone')
})
it('a plain leave flags the citations layer', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Barone/)
cleanup()
const flag = sessionStorage.getItem(
`faunosteo:editor:left-draft:${SHEET}:${TAG}`,
)
expect(JSON.parse(flag!)).toEqual({ kind: 'citations', key: nodeKey })
})
})
/** The Navigation API as the leave guard reads it: `navigate` events and `traverseTo`. */
class NavigationStub extends EventTarget {
traverseTo = vi.fn((key: string) => {
void key
return { committed: Promise.resolve(), finished: Promise.resolve() }
})
}
describe('a reference over the references dialog of a dirty finding (criterion 23)', () => {
let api: NavigationStub
beforeEach(() => {
api = new NavigationStub()
Object.defineProperty(window, 'navigation', {
value: api,
configurable: true,
})
})
afterEach(() => {
Reflect.deleteProperty(window, 'navigation')
})
function jump() {
const url = new URL('/app/admin/sheets', window.location.origin).href
const event = Object.assign(new Event('navigate', { cancelable: true }), {
navigationType: 'traverse',
destination: { url, key: 'list', sameDocument: true },
})
act(() => {
api.dispatchEvent(event)
})
return event
}
/** Node A in edit with a typed name, its references in edit, Barone in edit, typed. */
async function stacked(user: User) {
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: 'Modifier' }),
)
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() => expect(citations()).toBeDefined())
await user.click(button('Modifier'))
await user.click(button(/^Modifier la référence Barone/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await user.type(inReference().getByLabelText('Citation'), ' x')
}
it('the finding asks next with the references dialog closed, focused; the jump goes after it', async () => {
const user = await mount()
await stacked(user)
expect(jump().defaultPrevented).toBe(true)
expect(inReference().getByText(question)).toBeVisible()
await user.click(inReference().getByRole('button', { name: 'Abandonner' }))
await waitFor(() => expect(referenceDialog()).toBeUndefined())
await waitFor(() => expect(citations()).toBeUndefined())
const finding = within(findingDialog()!)
expect(finding.getByText(question)).toBeVisible()
const keep = finding.getByRole('button', { name: 'Continuer la saisie' })
await waitFor(() => expect(keep).toHaveFocus())
expect(api.traverseTo).not.toHaveBeenCalled()
await user.click(finding.getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).toHaveBeenCalledWith('list')
})
it('« Continuer la saisie » there keeps the finding draft and drops the jump', async () => {
const user = await mount()
await stacked(user)
jump()
await user.click(inReference().getByRole('button', { name: 'Abandonner' }))
await waitFor(() => expect(citations()).toBeUndefined())
const finding = within(findingDialog()!)
await user.click(
finding.getByRole('button', { name: 'Continuer la saisie' }),
)
expect(finding.getByLabelText('Nom (FR)')).toHaveValue('Node A bis')
expect(api.traverseTo).not.toHaveBeenCalled()
})
it('a citations draft under a clean reference dialog asks once the reference is closed', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Code rural/)
await user.click(button(/^Modifier la référence Barone/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
expect(jump().defaultPrevented).toBe(true)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(inCitations().getByText(question)).toBeVisible()
const keep = inCitations().getByRole('button', {
name: 'Continuer la saisie',
})
await waitFor(() => expect(keep).toHaveFocus())
await user.click(button('Abandonner'))
expect(api.traverseTo).toHaveBeenCalledWith('list')
})
})
describe('a Back over a citations draft under a clean reference dialog', () => {
it('the reference dialog closes, the draft asks, the view is pushed again', async () => {
const user = await mount()
await editCitations(user)
await removeRow(user, /Code rural/)
await user.click(button(/^Modifier la référence Barone/))
await waitFor(() => expect(referenceDialog()).toBeDefined())
await back(2)
await waitFor(() => expect(referenceDialog()).toBeUndefined())
expect(citations()).toBeDefined()
expect(inCitations().getByText(question)).toBeVisible()
expect(rows()).toEqual(['ref-a'])
expect(written()!.view).toMatchObject({
reference: null,
finding: { citations: true },
})
})
})
@@ -0,0 +1,172 @@
/** Rev 5 Task 12: the citations layer's guard (Back, refusal, close, order, creation). */
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render } from '@testing-library/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
MemoryRouter,
useLocation,
useNavigate,
type Location,
type NavigateFunction,
} from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import { LAYERS_TOP_DOWN, topDirtyLayer } from '@/editor/leftDraft'
import { defaultView } from '@/editor/navigation'
import {
useEditorNavigation,
type EditorNavigation,
type LayerName,
} from '@/editor/useEditorNavigation'
afterEach(cleanup)
const owner = { sheetId: 'S', tag: 'T' }
const node: ElementKey = {
kind: 'finding',
zone_id: 'zone',
path: ['family', 'node'],
}
let nav: EditorNavigation
let navigate: NavigateFunction
let location: Location
const entry = () => (location.state as Record<string, HistoryEntry>)[ENTRY_KEY]
function Page() {
nav = useEditorNavigation('findings')
navigate = useNavigate()
location = useLocation()
useEditorHistory(nav, owner, defaultView('findings'))
return null
}
function mount() {
render(
<MemoryRouter initialEntries={['/x']}>
<Page />
</MemoryRouter>,
)
}
/** A layer whose form holds changes: a user ask refuses, a forced one says the note. */
const dirty = vi.fn((forced: boolean) =>
forced ? { allowed: true, note: 'dropped' } : { allowed: false },
)
const register = (layer: LayerName) =>
act(() => nav.guards.register(layer, dirty))
/** Node's finding dialog, then its citations dialog: two entries. */
function cited() {
mount()
act(() => nav.openFinding(node))
act(() => nav.openCitations(node))
}
describe('the layer order', () => {
it('reference, citations, finding: asked top down', () => {
expect(LAYERS_TOP_DOWN).toEqual(['reference', 'citations', 'finding'])
mount()
const order: string[] = []
for (const layer of ['finding', 'citations', 'reference'] as const) {
nav.guards.register(layer, () => {
order.push(layer)
return { allowed: true }
})
}
nav.guards.askAll(false)
expect(order).toEqual(['reference', 'citations', 'finding'])
})
it('topDirtyLayer: citations over finding, reference over both', () => {
mount()
register('finding')
register('citations')
expect(topDirtyLayer(nav.guards)).toBe('citations')
expect(topDirtyLayer(nav.guards, 'citations')).toBe('finding')
register('reference')
expect(topDirtyLayer(nav.guards)).toBe('reference')
expect(topDirtyLayer(nav.guards, 'reference')).toBe('citations')
})
})
describe('a Back over a citations draft', () => {
it('closing only the citations dialog asks; the view and the entry stay', () => {
cited()
register('citations')
dirty.mockClear()
act(() => navigate(-1))
expect(dirty).toHaveBeenCalledWith(false)
expect(nav.state.finding).toMatchObject({ citations: true })
expect(entry().view.finding).toMatchObject({ citations: true })
})
it('a clean citations layer lets it close', () => {
cited()
act(() => nav.guards.register('citations', () => ({ allowed: true })))
act(() => navigate(-1))
expect(nav.state.finding).toMatchObject({ citations: false })
})
it('under a clean reference dialog: the reference closes, the draft asks', () => {
cited()
act(() => nav.references.open('ref-a'))
register('citations')
dirty.mockClear()
act(() => navigate(-2))
expect(dirty).toHaveBeenCalledWith(false)
expect(nav.state.reference).toBeNull()
expect(nav.state.finding).toMatchObject({ citations: true })
expect(entry().view).toMatchObject({
reference: null,
finding: { citations: true },
})
})
})
describe('closeCitations', () => {
it('a user close is refused by a draft; a forced one goes', () => {
cited()
register('citations')
let closed = true
act(() => {
closed = nav.closeCitations()
})
expect(closed).toBe(false)
expect(nav.state.finding).toMatchObject({ citations: true })
act(() => {
closed = nav.closeCitations(true)
})
expect(closed).toBe(true)
expect(nav.state.finding).toMatchObject({ citations: false })
})
})
describe('a creation started over the citations dialog', () => {
it('hands its id to the form that started it; no « added » notice', async () => {
cited()
const cite = vi.fn()
act(() => nav.references.start(null, cite))
expect(nav.state).toMatchObject({
tab: 'findings',
reference: { create: true },
})
await act(async () => nav.references.created('ref-new'))
expect(cite).toHaveBeenCalledWith('ref-new')
expect(nav.references.added).toBeNull()
expect(nav.state.reference).toBeNull()
expect(nav.state.finding).toMatchObject({ citations: true })
})
it('a later creation from the library sets the notice, cites nothing', async () => {
cited()
const cite = vi.fn()
act(() => nav.references.start(null, cite))
act(() => nav.references.close(true))
act(() => nav.selectTab('references'))
act(() => nav.references.start(null))
await act(async () => nav.references.created('ref-lib'))
expect(cite).not.toHaveBeenCalled()
expect(nav.references.added).toMatchObject({ id: 'ref-lib' })
})
})
+2 -2
View File
@@ -281,10 +281,10 @@ describe('Escape with the focus on the page', () => {
await select(user)
await openCitations(user)
const trigger = screen.getByRole('button', { name: '1 référence' })
expect(trigger).toHaveAttribute('aria-expanded', 'true')
expect(trigger).toHaveAttribute('aria-haspopup', 'dialog')
await user.keyboard('{Escape}')
await waitFor(() => expect(citations()).toBeNull())
expect(trigger).toHaveAttribute('aria-expanded', 'false')
await waitFor(() => expect(trigger).toHaveFocus())
// the finding dialog under the sheet is still there: a second Escape closes it
expect(document.querySelector('dialog[open]')).not.toBeNull()
await user.keyboard('{Escape}')
@@ -109,6 +109,10 @@ describe('sanitizeView', () => {
expect(sanitizeView(creation)?.reference).toEqual({ create: true })
const elsewhere = { ...view('general'), reference: { create: true } }
expect(sanitizeView(elsewhere)?.reference).toBeNull()
// Rev 5: a creation over the citations dialog is never read back (POP, reload).
const overCitations = { ...sheet, reference: { create: true } }
expect(sanitizeView(overCitations)?.reference).toBeNull()
expect(sanitizeView(overCitations)?.finding).toEqual(sheet.finding)
expect(
sanitizeView({ ...tab, reference: { edit: '' } })?.reference,
).toBeNull()
@@ -46,6 +46,7 @@ function Editor() {
return (
<>
<Layer guards={nav.guards} layer="finding" />
<Layer guards={nav.guards} layer="citations" />
<Layer guards={nav.guards} layer="reference" />
</>
)
@@ -93,23 +94,28 @@ const layer = (name: LayerName) => screen.queryByTestId(name)
const button = (name: LayerName, label: string) =>
within(layer(name)!).getByRole('button', { name: label })
describe('a reference dialog over a finding dialog, both dirty', () => {
it('asks the reference, then the finding, then the jump goes', async () => {
describe('reference, citations and finding dialogs, all dirty', () => {
it('asks the reference, the citations, then the finding, then the jump goes', async () => {
const user = userEvent.setup()
expect(jump().defaultPrevented).toBe(true)
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
expect(within(layer('citations')!).queryByRole('group')).toBeNull()
await user.click(button('reference', 'Abandonner'))
expect(layer('reference')).toBeNull()
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
await user.click(button('citations', 'Abandonner'))
expect(layer('citations')).toBeNull()
expect(api.traverseTo).not.toHaveBeenCalled()
await user.click(button('finding', 'Abandonner'))
expect(api.traverseTo).toHaveBeenCalledTimes(1)
expect(api.traverseTo).toHaveBeenCalledWith('list')
})
it('« Continuer la saisie » on the second keeps the finding, no jump', async () => {
it('« Continuer la saisie » on the last keeps the finding, no jump', async () => {
const user = userEvent.setup()
jump()
await user.click(button('reference', 'Abandonner'))
await user.click(button('citations', 'Abandonner'))
await user.click(button('finding', 'Continuer la saisie'))
expect(layer('finding')).not.toBeNull()
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
@@ -121,6 +127,7 @@ describe('a reference dialog over a finding dialog, both dirty', () => {
jump()
await user.click(button('reference', 'Continuer la saisie'))
expect(layer('reference')).not.toBeNull()
expect(layer('citations')).not.toBeNull()
expect(layer('finding')).not.toBeNull()
expect(api.traverseTo).not.toHaveBeenCalled()
})
@@ -180,6 +180,20 @@ describe('navigationReducer', () => {
})
})
it('a creation over the citations dialog keeps the tab and both dialogs under it', () => {
const created = run(
initialNavigation('findings'),
{ type: 'open_finding', key: node },
{ type: 'open_citations', citedBy: node },
{ type: 'create_reference' },
)
expect(created).toMatchObject({
tab: 'findings',
finding: { key: node, citations: true },
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',
@@ -223,7 +223,7 @@ describe('opening', () => {
expect(panel()).not.toHaveTextContent('Denoix')
})
it('view mode: an open tile marks the current finding, « Aller à » only, no edit control', async () => {
it('view mode: an open tile marks the current finding, « Aller à » only; « Modifier » is the dialog’s', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
@@ -239,9 +239,14 @@ describe('opening', () => {
'Monter',
'Descendre',
]) {
expect(within(tile).queryByRole('button', { name: absent })).toBeNull()
expect(
within(citationsDialog()).queryByRole('button', { name: absent }),
).toBeNull()
).toBe(
absent === 'Modifier'
? document.getElementById('citations-edit-button')
: null,
)
}
expect(within(citationsDialog()).queryByRole('searchbox')).toBeNull()
expect(within(citationsDialog()).queryByRole('textbox')).toBeNull()