Files
faunosteo/apps/app/tests/unit/editor-references-flip.test.tsx
T
bchanot 18085cecf8 feat(editor): finding dialog and citations side sheet in the history
Constats opens each element in one modal dialog (view, edit with a
local draft, creation) driven by the editor view layer of the browser
history. The citations panel becomes a modal side sheet stacked over
it; its geometry, exit machinery and page inertness are removed.
Back and Forward restore the layers, a dirty form asks first.
2026-11-13 18:51:35 +01:00

621 lines
21 KiB
TypeScript

/**
* C1: a read-only flip never drops a draft silently, writes nothing, and keeps the tile.
* I1: a user leave with several refused fields focuses the first one, with its own error.
*/
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 {
findingDialog,
inFindingDialog,
openFinding,
} from '../helpers/findingDialog'
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' }))
/** Every watcher made by `watchNotes`: stopped after each test, even a failing one. */
const watchers: { stop: () => void }[] = []
afterEach(() => {
watchers.splice(0).forEach((watch) => watch.stop())
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)
/** The prototype object that owns a property, so a wrapper can be put back exactly. */
function ownerOf(target: object, property: string): object {
let owner: object | null = target
while (owner && !Object.hasOwn(owner, property)) {
owner = Object.getPrototypeOf(owner)
}
return owner!
}
/**
* Counts the live region's updates that carry the drop note. It wraps the two DOM setters
* React uses for a text change (`textContent`, `nodeValue`) instead of using a
* MutationObserver: happy-dom keeps an observer's callback in a WeakRef, so a garbage
* collection under load silently ends the observation (seen as a missed announcement).
*/
function watchNotes() {
const seen: string[] = []
const restore: (() => void)[] = []
const wrap = (target: object, property: string) => {
const owner = ownerOf(target, property)
const original = Object.getOwnPropertyDescriptor(owner, property)!
Object.defineProperty(owner, property, {
...original,
set(this: Node, value: string) {
original.set!.call(this, value)
const region = live()
if (region.contains(this) && region.textContent?.includes(NOTE)) {
seen.push(region.textContent)
}
},
})
restore.push(() => Object.defineProperty(owner, property, original))
}
wrap(live(), 'textContent')
wrap(document.createTextNode(''), 'nodeValue')
const watch = { seen, stop: () => restore.forEach((undo) => undo()) }
watchers.push(watch)
return watch
}
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, says it once, writes nothing, focuses 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; Terminer removes it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
await flush()
const watch = watchNotes()
cross(1280)
await flush()
expect(watch.seen).toHaveLength(0)
watch.stop()
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('the note ends on the next action', () => {
/** ref-b flipped with a refused URL and back: in edit again, note shown. */
async function flippedBack() {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
cross(1280)
expect(
within(tile('ref-b')).getByText(/Saisie non appliquée/),
).toBeVisible()
return user
}
const noted = () => within(tabPanel()).queryAllByText(/Saisie non appliquée/)
it("ends on another tile's « Modifier » (this tile leaves edit)", async () => {
const user = await flippedBack()
await user.click(
within(tabPanel()).getByRole('button', { name: /^Barone/ }),
)
await user.click(
within(tile('ref-a')).getByRole('button', { name: 'Modifier' }),
)
expect(noted()).toHaveLength(0)
})
it('ends on « Ajouter une référence »', async () => {
const user = await flippedBack()
await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' }),
)
expect(noted()).toHaveLength(0)
})
it('is replaced by a newer drop of the same tile, announced again', async () => {
const user = await flippedBack()
const watch = watchNotes()
await user.clear(field('ref-b', 'citation'))
await typeBadUrl(user, 'ref-b')
cross(800)
await flush()
const items = noted()
expect(items).toHaveLength(1)
expect(items[0]).toHaveTextContent(`${NOTE} : Citation, Adresse web (URL)`)
expect(watch.seen).toHaveLength(1)
watch.stop()
})
})
describe('a read-only flip without a refused draft', () => {
it('adds only the typed change when a valid draft has the focus', 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('an undo that removes a tile holding a refused draft (V1)', () => {
const added = (name: string) =>
document.querySelector<HTMLInputElement>(`#tab-reference-3-ref-d-${name}`)!
/** ref-d inserted by one history entry, then its tile in edit. */
async function editInserted() {
const user = await mount()
act(() => {
store
.getState()
.commit({ op: 'insert', element: ref('ref-d', 'Nouvelle') })
})
expect(history()).toEqual({ undo: 1, redo: 0 })
await editTile(user, 'ref-d', /^Nouvelle/)
return user
}
/** From a valid place: « Défaire » pressed from a refused field only refocuses it. */
async function undoInsertion(user: User) {
await user.tab()
expect(document.activeElement).not.toHaveAttribute('aria-invalid', 'true')
const watch = watchNotes()
await user.click(screen.getByRole('button', { name: /Défaire/ }))
await flush()
expect(header('ref-d')).toBeNull()
expect(doc().references.map((r: { id: string }) => r.id)).toEqual([
'ref-a',
'ref-b',
'ref-c',
])
expect(history()).toEqual({ undo: 0, redo: 1 })
return watch
}
it('says the dropped Citation once', async () => {
const user = await editInserted()
await user.clear(added('citation'))
const watch = await undoInsertion(user)
expect(watch.seen).toEqual([`${NOTE} : Citation`])
watch.stop()
})
it('names both refused fields, once', async () => {
const user = await editInserted()
await user.clear(added('citation'))
await user.click(added('url'))
await user.type(added('url'), 'exemple.org')
const watch = await undoInsertion(user)
expect(watch.seen).toEqual([`${NOTE} : Citation, Adresse web (URL)`])
watch.stop()
})
})
/** The citations panel of Node A, its Denoix tile in edit. */
async function openPanel(user: User) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Fermer les références' }),
),
)
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
}
/** The sheet, then the finding dialog under it, closed with their ✕. */
async function closeLayers(user: User) {
await user.click(
screen.getByRole('button', { name: 'Fermer les références' }),
)
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
await user.click(
within(findingDialog()!).getByRole('button', { name: 'Fermer' }),
)
await waitFor(() => expect(document.querySelector('dialog[open]')).toBeNull())
}
describe('a read-only flip in the citations 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()
// the page is inert under the two dialogs: the announcement waits for them
expect(watch.seen).toHaveLength(0)
expect(document.activeElement).toBe(header('ref-b', 'panel'))
expect(history()).toEqual({ undo: 0, redo: 0 })
await closeLayers(user)
await waitFor(() => expect(watch.seen).toHaveLength(1))
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(),
)
// The forced close announces in a later commit than the panel's exit: wait for
// the text itself, then let any second announcement land before counting.
await waitFor(() =>
expect(live().textContent).toContain(
`${NOTE} : Citation, Adresse web (URL)`,
),
)
await flush()
expect(watch.seen).toHaveLength(1)
watch.stop()
})
})
describe('an undo that takes a tile holding a refused draft out of the panel (V1)', () => {
it('says the dropped Citation once, the panel stays', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'update',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
element: {
kind: 'finding_node',
value: {
...doc().finding_zones[0].categories[0].children[0],
reference_ids: ['ref-a', 'ref-b', 'ref-c'],
},
},
})
})
expect(history()).toEqual({ undo: 1, redo: 0 })
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: '3 références' }),
)
const panel = await screen.findByTestId('editor-citations-panel')
await user.click(within(panel).getByRole('button', { name: /^Code rural/ }))
await user.click(within(panel).getByRole('button', { name: 'Modifier' }))
await user.clear(field('ref-c', 'citation', 'panel'))
await user.tab()
const watch = watchNotes()
await user.click(screen.getByRole('button', { name: /Défaire/ }))
await flush()
expect(header('ref-c', 'panel')).toBeNull()
expect(screen.getByTestId('editor-citations-panel')).toBe(panel)
expect(history()).toEqual({ undo: 0, redo: 1 })
// said once the sheet and the finding dialog under it are closed
expect(watch.seen).toEqual([])
await closeLayers(user)
await waitFor(() => expect(watch.seen).toEqual([`${NOTE} : Citation`]))
watch.stop()
})
})
async function typeBadUrlIn(user: User) {
const url = field('ref-b', 'url', 'panel')
await user.clear(url)
await user.type(url, 'exemple.org')
}
const REQUIRED = 'Ce champ est obligatoire.'
/** Citation cleared then a schemeless URL, both refused, in the tile `id` of `host`. */
async function twoRefused(user: User, id: string, host = 'tab') {
await user.clear(field(id, 'citation', host))
await user.tab()
const url = field(id, 'url', host)
await user.clear(url)
await user.type(url, 'exemple.org')
}
/** I1: the field focused by a refused leave shows its own refusal; no draft is lost. */
function expectCitationRefused(id: string, host = 'tab') {
const citation = field(id, 'citation', host)
expect(document.activeElement).toBe(citation)
expect(citation).toHaveAttribute('aria-invalid', 'true')
expect(citation).toHaveAccessibleDescription(REQUIRED)
expect(citation).toHaveValue('')
}
describe('a user leave with several refused fields (I1)', () => {
it('keyboard « Terminer » focuses Citation with its own error', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await twoRefused(user, 'ref-b')
const done = within(tile('ref-b')).getByRole('button', { name: 'Terminer' })
for (let step = 0; step < 6 && document.activeElement !== done; step++) {
await user.tab()
}
expect(document.activeElement).toBe(done)
await user.keyboard('{Enter}')
expect(done).toBeInTheDocument()
expectCitationRefused('ref-b')
expect(field('ref-b', 'url')).toHaveValue('exemple.org')
expect(history()).toEqual({ undo: 0, redo: 0 })
})
it("another tile's « Modifier » focuses Citation with its own error", async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await twoRefused(user, 'ref-b')
await user.click(
within(tabPanel()).getByRole('button', { name: /^Barone/ }),
)
await user.click(
within(tile('ref-a')).getByRole('button', { name: 'Modifier' }),
)
expect(field('ref-a', 'citation')).toBeNull()
expectCitationRefused('ref-b')
expect(field('ref-b', 'url')).toHaveValue('exemple.org')
})
it('the panel ✕ is cancelled, Citation focused with its own error', async () => {
const user = await mount()
const panel = await openPanel(user)
await twoRefused(user, 'ref-b', 'panel')
await user.click(
within(panel).getByRole('button', { name: 'Fermer les références' }),
)
expect(screen.getByTestId('editor-citations-panel')).toBe(panel)
expectCitationRefused('ref-b', 'panel')
expect(field('ref-b', 'url', 'panel')).toHaveValue('exemple.org')
expect(history()).toEqual({ undo: 0, redo: 0 })
})
it('a mouse « Terminer » with a valid URL focused keeps edit on Citation', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.clear(field('ref-b', 'citation'))
await user.tab()
const url = field('ref-b', 'url')
await user.clear(url)
await user.type(url, 'https://exemple.org/neuf')
const done = within(tile('ref-b')).getByRole('button', { name: 'Terminer' })
await user.click(done)
expect(done).toBeInTheDocument()
expectCitationRefused('ref-b')
expect(doc().references[1].url).toBe('https://exemple.org/neuf')
expect(history()).toEqual({ undo: 1, redo: 0 })
})
})