fix(editor): never drop a refused draft silently on a read-only flip

Drop slot is tile-local state; the edit view cleanup reports every pending
field (FIELDS order) only when some are pending. The tile shows a warning
note and says it once in the live region; it ends on toggle, Terminer or a
newer drop. LeaveGuard returns all refused fields (forced panel close names
them all). Pin follows editingKey through read-only; reset re-pins it.
Read-only toggle ends edit and collapses. Flip focus goes to the tile header.

R-24 mapping:
- view test "keeps its index ... read-only (M3)": renamed, same assertion
- view test "is suspended in read-only ...": rewritten as "stays pinned in
  read-only" (pin kept, tile still shown after a search); toggle test added
- reset test extended: tile in edit stays pinned through the reset
- new editor-references-flip.test.tsx covers (a)-(g); (h) is a stated limit
This commit is contained in:
bchanot committed 2026-11-13 11:11:51 +01:00
1 parent 52aac41472
commit 3303530717
15 files changed
+543 -94

No files matched your search

+6 -2
View File
@@ -1,3 +1,4 @@
import { StrictMode } from 'react'
import { render } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import {
@@ -89,6 +90,8 @@ export interface MountOptions {
answer?: Record<string, unknown>
/** The admin read is refused with this closed kind. */
adminFailure?: SheetFailureKind
/** Renders inside <StrictMode>: effects run twice on mount, as in development. */
strict?: boolean
}
/** Mounts the draft route as an editor with the admin role, at a wide screen, by default. */
@@ -111,7 +114,7 @@ export function mountDraft(options: MountOptions = {}) {
(options.answer ?? adminAnswer()) as never,
)
}
return render(
const page = (
<MemoryRouter initialEntries={[`/app/admin/sheets/${SHEET}/draft`]}>
<Routes>
<Route
@@ -123,6 +126,7 @@ export function mountDraft(options: MountOptions = {}) {
element={<p>overview page</p>}
/>
</Routes>
</MemoryRouter>,
</MemoryRouter>
)
return render(options.strict ? <StrictMode>{page}</StrictMode> : page)
}
@@ -0,0 +1,331 @@
/** C1: a read-only flip never drops a draft silently, writes nothing, and keeps the tile. */
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 { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string, url = '') =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: url || null, doi: null },
}) as const
/** Three references (ref-b has a URL) and Node A citing 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/Épaule'))
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>
const NOTE = 'Saisie non appliquée'
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
const doc = () => JSON.parse(store.getState().documentText)
const history = () => ({
undo: store.getState().undo.length,
redo: store.getState().redo.length,
})
const cross = (width: number) =>
act(() => {
setWidth(width)
window.dispatchEvent(new Event('resize'))
})
const flush = () => act(async () => undefined)
/** Counts the live region's updates that carry the drop note. */
function watchNotes() {
const seen: string[] = []
const observer = new MutationObserver(() => {
if (live().textContent?.includes(NOTE)) seen.push(live().textContent!)
})
observer.observe(live(), {
childList: true,
characterData: true,
subtree: true,
})
return { seen, stop: () => observer.disconnect() }
}
async function mount(width = 1280) {
serverHas(sheetText(), 3)
const user = userEvent.setup()
mountDraft({ width, strict: true })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
return user
}
const tabPanel = () => screen.getByRole('tabpanel', { name: 'Références' })
const header = (id: string, host = 'tab') =>
document.querySelector<HTMLElement>(
`button[id^="${host}-reference-"][id$="-${id}-header"]`,
)!
const tile = (id: string, host = 'tab') => header(id, host).closest('li')!
const field = (id: string, name: string, host = 'tab') =>
document.querySelector<HTMLInputElement>(
`#${host}-reference-${id === 'ref-a' ? 0 : id === 'ref-b' ? 1 : 2}-${id}-${name}`,
)!
/** « Références », the tile open and in edit; the focus on its Citation field. */
async function editTile(user: User, id: string, label: RegExp) {
await user.click(screen.getByRole('tab', { name: 'Références' }))
await user.click(within(tabPanel()).getByRole('button', { name: label }))
await user.click(within(tile(id)).getByRole('button', { name: 'Modifier' }))
}
/** Types a schemeless URL (refused) in the focused-then-kept URL field of `id`. */
async function typeBadUrl(user: User, id: string) {
const url = field(id, 'url')
await user.clear(url)
await user.type(url, 'exemple.org')
return url
}
describe('a read-only flip with a refused draft (tab tile)', () => {
it('shows the note in the tile, says it once, writes nothing, keeps the focus on the tile', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
const before = { references: doc().references, ...history() }
const watch = watchNotes()
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Adresse web (URL)`),
).toBeVisible()
expect(within(tile('ref-b')).queryByRole('textbox')).toBeNull()
expect(
within(tile('ref-b')).getByText('https://exemple.org/Épaule'),
).toBeVisible()
await flush()
expect(watch.seen).toHaveLength(1)
expect(live().textContent).toBe(`${NOTE} : Adresse web (URL)`)
expect({ references: doc().references, ...history() }).toEqual(before)
expect(document.activeElement).toBe(header('ref-b'))
watch.stop()
})
it('keeps the note across the flip back, URL field on the document value; Terminer removes it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
cross(1280)
const item = tile('ref-b')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
expect(field('ref-b', 'url')).toHaveValue('https://exemple.org/Épaule')
expect(history()).toEqual({ undo: 0, redo: 0 })
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
expect(within(item).queryByText(new RegExp(NOTE))).toBeNull()
})
it('the read-only toggle ends the edit state, collapses and clears the note', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
await user.click(header('ref-b'))
expect(header('ref-b')).toHaveAttribute('aria-expanded', 'false')
expect(within(tile('ref-b')).queryByText(new RegExp(NOTE))).toBeNull()
cross(1280)
expect(header('ref-b')).toHaveAttribute('aria-expanded', 'false')
expect(within(tile('ref-b')).queryByRole('textbox')).toBeNull()
})
it('names both refused fields, in field order', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.clear(field('ref-b', 'citation'))
await typeBadUrl(user, 'ref-b')
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Citation, Adresse web (URL)`),
).toBeVisible()
expect(doc().references[1].citation).toBe('Denoix')
})
it('keeps the tile in edit shown when the search does not match it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.type(
within(tabPanel()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'rural',
)
expect(header('ref-b')).not.toBeNull()
await typeBadUrl(user, 'ref-b')
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Adresse web (URL)`),
).toBeVisible()
expect(header('ref-c')).not.toBeNull()
})
})
describe('a read-only flip without a refused draft', () => {
it('adds exactly the typed change when a valid draft has the focus, nothing on the way back', async () => {
const user = await mount()
await editTile(user, 'ref-a', /^Barone/)
const citation = field('ref-a', 'citation')
await user.clear(citation)
await user.type(citation, 'Neuf')
const watch = watchNotes()
cross(800)
expect(history()).toEqual({ undo: 1, redo: 0 })
expect(doc().references[0].citation).toBe('Neuf')
expect(within(tile('ref-a')).queryByText(new RegExp(NOTE))).toBeNull()
expect(document.activeElement).toBe(header('ref-a'))
cross(1280)
await flush()
expect(history()).toEqual({ undo: 1, redo: 0 })
expect(watch.seen).toHaveLength(0)
watch.stop()
})
it('writes nothing, says nothing and shows no note when nothing is pending', async () => {
const user = await mount()
await editTile(user, 'ref-a', /^Barone/)
const watch = watchNotes()
cross(800)
cross(1280)
await flush()
expect(history()).toEqual({ undo: 0, redo: 0 })
expect(watch.seen).toHaveLength(0)
expect(screen.queryByText(new RegExp(NOTE))).toBeNull()
watch.stop()
})
})
describe('a read-only flip in the citations panel', () => {
async function openPanel(user: User) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await user.click(
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name: '2 références' },
),
)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('heading', { name: 'Références citées' }),
),
)
const panel = screen.getByTestId('editor-citations-panel')
await user.click(within(panel).getByRole('button', { name: /^Denoix/ }))
await user.click(within(panel).getByRole('button', { name: 'Modifier' }))
return panel
}
it('shows the note in the panel tile, says it once, focuses the tile header', async () => {
const user = await mount()
await openPanel(user)
await typeBadUrlIn(user)
const watch = watchNotes()
cross(800)
const item = tile('ref-b', 'panel')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
await flush()
expect(watch.seen).toHaveLength(1)
expect(document.activeElement).toBe(header('ref-b', 'panel'))
expect(history()).toEqual({ undo: 0, redo: 0 })
watch.stop()
})
it('a forced close names every refused field and says it once', async () => {
const user = await mount()
await openPanel(user)
await user.clear(field('ref-b', 'citation', 'panel'))
await typeBadUrlIn(user)
const watch = watchNotes()
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
expect(watch.seen).toHaveLength(1)
expect(live().textContent).toContain(
`${NOTE} : Citation, Adresse web (URL)`,
)
watch.stop()
})
})
async function typeBadUrlIn(user: User) {
const url = field('ref-b', 'url', 'panel')
await user.clear(url)
await user.type(url, 'exemple.org')
}
@@ -356,7 +356,7 @@ describe('the tile in edit is pinned (P23)', () => {
expect(document.activeElement).toBe(header('r1'))
})
it('keeps its index across a search or sort change made while read-only (M3)', async () => {
it('keeps the tile in edit at its index across a sort change made while read-only (M3)', async () => {
const { user, view } = await mount()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r3')
@@ -367,15 +367,32 @@ describe('the tile in edit is pinned (P23)', () => {
expect(order()).toEqual(['r2', 'r3', 'r1', 'r5', 'r4'])
})
it('is suspended in read-only: the tile renders its read view', async () => {
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(['r5', 'r3', 'r4', 'r2', 'r1'])
expect(order()).toEqual(['r1', 'r5', 'r3', 'r4', 'r2'])
await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
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()
})
})
@@ -494,6 +511,9 @@ describe('the reset path (« Tout afficher »)', () => {
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'])
})
})