Files
faunosteo/apps/app/tests/unit/editor-escape.test.tsx
T
bchanot 8db6f4287f feat(editor): contextual citations panel of a finding (board 25)
The panel opens only from a finding's « {n} références » trigger: 34 rem
at most, never wider than the room, a scrim, slide in 180 ms and out
140 ms (motion/react; none under reduced motion, callbacks still fire).
It lists the finding's references as tiles with « Modifier », « Retirer
de ce constat » (one « Défaire » restores it and the review status) and
« Aller à »; dangling ids read « Référence introuvable »; zero left
reads « Ce constat ne cite plus aucune référence. ». « Tout afficher
dans l'onglet Références » resets search and sort, keeps open tiles and
edits. Every close (✕, Escape outside fields, scrim, tab, « Aller à »,
« Tout afficher », element gone) records one pending move applied
after the exit, page inert until then; focus back to the trigger, else
the active tab button. A refused draft cancels a user close; a forced
close drops it and announces « Saisie non appliquée : {field} ». Places
keeps a permanent dvh min-height; the panel fits the visible viewport
at every scroll position, document size unchanged.

Gates: typecheck, lint, test:run (app 1488), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (admin and editor-equine excluded):
117 passed / 107 skipped / 0 failed, rerun after the fix rounds: 118
passed / 108 skipped / 0 failed; layout spec 13 passed after round 2;
full-row guard: no pre-existing row changed in any table. Known limit:
landscape 667 x 375 at scroll 0 leaves ~13 px of panel (the trigger is
below the fold there).

## R-24 (removed or rewritten assertions)

| file | old | new |
|---|---|---|
| editor-references-panel.test.tsx (whole file) | R2.1 interim-panel tests, synchronous closes | rewritten: 39 tests (opening, motion, close matrix in both modes, exit, Retirer, P22'', library + history) |
| same, opening | heading `Références` focused right after the click | heading `Références citées` focused after the enter (`waitFor`), `aria-expanded` only after click |
| same | chip `references-filter-chip` « Citées par « Node A » (2) » | REMOVED (REVUE: path line + count line « 2 références citées par ce constat ») |
| same | `listitem` cards « Citée 2 fois » | tiles (`ul > li`) with the same counts, in the finding's order |
| same | field id `#panel-reference-0-ref-a-citation` present at once | tile opened + « Modifier » first (tiles since R2.2) |
| same | « Tout afficher (3) », sync | « Tout afficher dans l'onglet Références », after exit, heading focus asserted |
| same | Escape / ✕ / scrim / tab / vanish: sync null panel | all `await closed()` + `document.activeElement` checks, `describe.each` normal / reduced motion |
| same | « makes the tab panels inert while open, header usable » | split: inert page + inert panel until the exit ends then lifted; « Défaire / Refaire usable »; the `Enregistrer` enabled check dropped (covered by the focus-moved-off test) |
| same | Ctrl+Z test on an always-open field | open tile + Modifier first |
| same | read-only: no Supprimer, no textbox | open tile: no Modifier, no Retirer, no textbox |
| same | P6 under « Plus »: sync | in the close matrix, awaited |
| editor-escape.test.tsx (2 tests) | `expect(citations()).toBeNull()` right after Escape | `await waitFor(...)`; trigger `aria-expanded` false after exit |
| editor-keep-alive.test.tsx | « Escape in a citations panel field commits the text before the panel closes » | REPLACED by « Escape in a field of a panel tile neither closes nor commits » (A5, P27) |
| same | scrim click closes the panel after committing, sync, id on a closed tile | tile opened in edit first, close awaited, commit asserted before the exit |
| editor-focus-request.test.tsx | `ReferenceLibrary` with `resetSignal`; `ownedBy(ref,'citations')` undefined | `ReferencesTab` (+ `reloadSheet`); the `'citations'` assertion removed with the type |
| editor-references-tab / -view.test.tsx | `ReferenceLibrary`, `resetSignal` | `ReferencesTab`, `libraryReset` (+ `reloadSheet`) |
| e2e support `openCitations` | waited for the panel visible | also waits for the heading focus (slide over) |

New unit coverage: editor-citations-exit.test.tsx (hook, fake timers), editor-findings (aria-expanded per finding),
`useDecisionsOpen` gate, panel file (Retirer + status + one undo, P20 chain, zero state, dangling id, P4 reset, P6 after undo,
P22'' four paths, reduced motion, inert/exit, second close, tab replace, focus-moved-off).

## i18n (FR / EN)

Added: `editor.references.panel_title` Références citées / Cited references; `panel_count_one|other` « {count} référence citée par
ce constat » / « {count} références citées par ce constat » and « {count} reference cited by this finding » / « … references … »;
`panel_show_all` Tout afficher dans l'onglet Références / Show all in the References tab; `panel_empty` Ce constat ne cite plus
aucune référence. / This finding no longer cites any reference.; `remove_citation` Retirer de ce constat / Remove from this finding;
`this_finding` ce constat / this finding; `missing` Référence introuvable / Reference not found; `draft_dropped`
Saisie non appliquée : {field} / Entry not applied: {field}.
Changed: none. Removed: `editor.references.cited_by` (« Citées par « {name} » ({count}) » / « Cited by « {name} » ({count}) »),
`editor.references.show_all` (« Tout afficher ({count}) » / « Show all ({count}) »). R10 grep over src, tests and e2e including
editor-equine: no reader left. `editor-equine` has no panel reference: « updated, not run » (nothing to update). The three
provisional FR labels are exactly as listed in the brief; `…` = the refused field's label.
2026-11-12 22:27:32 +01:00

360 lines
12 KiB
TypeScript

/** R1 (A5, A6): the Escape priority across the whole editor workspace. */
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 type { Annotation } from '@faunosteo/core-wasm/types'
import ModalDialog from '@/components/ui/ModalDialog'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, edit, insert, point } from '../helpers/editorFixtures'
import { 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' })
const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }
Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', {
configurable: true,
value: () => ({ ...identity, inverse: () => identity }),
})
})
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const TWO = () =>
insert(
insert(drawnText(), point('anno-a', 50, 50, 5)),
point('anno-b', 20, 20, 3),
)
const ZONE = () =>
insert(drawnText(), {
kind: 'annotation',
value: {
...(point('zone-a', 0, 0, 1).value as Annotation),
kind: 'zone',
geometry: { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' },
} as Annotation,
})
/** TWO plus a finding node that cites one reference: the citations panel has a trigger. */
const WITH_NODE = () => {
const name = (n: string) => ({ fr: n, en: n })
let text = insert(TWO(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
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: ['ref-a'],
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
}
const shown = (selector: string) =>
[...document.querySelectorAll<HTMLElement>(selector)].find(
(element) => !element.closest('[hidden]'),
)
const panel = () => shown('[data-testid="annotation-properties"]')
const rowOf = (id: string) =>
shown(`[data-focus-key='{"kind":"annotation","id":"${id}"}']`)
const live = () => document.querySelector('[aria-live="polite"]')!
const escape = (target: Element | Window = document.body) =>
fireEvent.keyDown(target, { key: 'Escape' })
async function mount(text = TWO(), width?: number) {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft({ width })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
await waitFor(() =>
expect(shown('[data-testid$="canvas-drawing"] svg')).toBeDefined(),
)
return user
}
/** Selects through the overview row (the visible body's). */
async function select(user: ReturnType<typeof userEvent.setup>, id = 'anno-a') {
await waitFor(() => expect(rowOf(id)).toBeDefined())
await user.click(rowOf(id)!)
await waitFor(() => expect(panel()).toBeDefined())
}
const canvasBox = () =>
shown('[data-place="annotations.drawing"] [role="group"][tabindex="0"]')!
const citations = () => screen.queryByTestId('editor-citations-panel')
/** Constats, the node selected, its « 1 référence » trigger pressed. */
async function openCitations(user: ReturnType<typeof userEvent.setup>) {
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(screen.getByRole('button', { name: '1 référence' }))
expect(citations()).not.toBeNull()
}
const inPanel = (name: string) => within(panel()!).getByRole('button', { name })
describe('Escape deselects', () => {
it('from the canvas box: deselected, the focus stays, announced', async () => {
const user = await mount()
await select(user)
canvasBox().focus()
escape(canvasBox())
expect(panel()).toBeUndefined()
expect(document.activeElement).toBe(canvasBox())
await waitFor(() =>
expect(live()).toHaveTextContent('Aucune annotation sélectionnée.'),
)
})
it('from a button of the panel: deselected, the focus on the row', async () => {
const user = await mount()
await select(user)
inPanel('Marquer comme relu').focus()
escape(document.activeElement!)
expect(panel()).toBeUndefined()
expect(document.activeElement).toBe(rowOf('anno-a'))
})
it("after A then B, from the panel: the focus on B's row", async () => {
const user = await mount()
await select(user, 'anno-a')
await user.click(inPanel('Toutes les annotations'))
await select(user, 'anno-b')
inPanel('Marquer comme relu').focus()
escape(document.activeElement!)
expect(document.activeElement).toBe(rowOf('anno-b'))
})
it('from body and from the history button of the tab row', async () => {
const user = await mount()
await select(user)
escape(document.body)
expect(panel()).toBeUndefined()
await select(user)
act(
() =>
void store
.getState()
.commit({ op: 'remove', key: { kind: 'annotation', id: 'anno-b' } }),
)
const undo = screen.getByRole('button', { name: /Défaire/ })
await waitFor(() => expect(undo).toBeEnabled())
undo.focus()
escape(undo)
expect(panel()).toBeUndefined()
expect(document.activeElement).toBe(undo)
})
})
describe('Escape leaves alone', () => {
it('a text field', async () => {
const user = await mount()
await select(user)
const field = within(panel()!).getByLabelText('Nom (FR)')
field.focus()
escape(field)
expect(panel()).toBeDefined()
})
it('a target outside the workspace', async () => {
const user = await mount()
await select(user)
const outside = document.createElement('button')
document.body.append(outside)
outside.focus()
escape(outside)
outside.remove()
expect(panel()).toBeDefined()
})
it('nothing selected, or the selected annotation deleted: no announcement', async () => {
const user = await mount()
escape(document.body)
expect(live()).toBeEmptyDOMElement()
await select(user)
act(
() =>
void store
.getState()
.commit({ op: 'remove', key: { kind: 'annotation', id: 'anno-a' } }),
)
const before = store.getState().documentText
escape(document.body)
expect(live()).toBeEmptyDOMElement()
expect(store.getState().documentText).toBe(before)
})
it('a tracing: the TracingBar keeps its Escape, the canvas box cancels the tracing only', async () => {
const user = await mount(ZONE())
await select(user, 'zone-a')
await user.click(inPanel('Remplacer par un polygone'))
const bar = await screen.findByTestId('tracing-bar')
bar.focus()
escape(bar)
expect(screen.queryByTestId('tracing-bar')).not.toBeNull()
canvasBox().focus()
escape(canvasBox())
await waitFor(() => expect(screen.queryByTestId('tracing-bar')).toBeNull())
expect(panel()).toBeDefined()
})
it('a modal dialog open: only its own handling (wiring proof)', async () => {
const user = await mount()
await select(user)
await user.click(inPanel('Supprimer'))
const dialog = document.querySelector('dialog')!
expect(dialog).not.toBeNull()
escape(dialog)
expect(panel()).toBeDefined()
})
})
describe('Escape with the focus on the page', () => {
it('a delete dialog open: the selection is kept', async () => {
const user = await mount()
await select(user)
await user.click(inPanel('Supprimer'))
expect(document.querySelector('dialog[open]')).not.toBeNull()
document.body.focus()
escape(document.body)
expect(panel()).toBeDefined()
})
it('the citations panel open: it closes, the annotation selection is kept', async () => {
const user = await mount(WITH_NODE())
await select(user)
await openCitations(user)
const trigger = screen.getByRole('button', { name: '1 référence' })
expect(trigger).toHaveAttribute('aria-expanded', 'true')
escape(document.body)
await waitFor(() => expect(citations()).toBeNull())
expect(trigger).toHaveAttribute('aria-expanded', 'false')
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(panel()).toBeDefined()
})
it('a dialog outside the workspace open: the selection is kept', async () => {
const user = await mount()
await select(user)
render(
<ModalDialog onClose={() => undefined} label="Outside">
<p>Outside</p>
</ModalDialog>,
)
escape(document.body)
expect(panel()).toBeDefined()
})
it('« Plus » open, Escape in the twin filter: the menu and the field stay', async () => {
const user = await mount(TWO(), 500)
const more = screen.getByRole('button', { name: 'Plus' })
await user.click(more)
const filter = within(
shown('[data-testid="annotation-overview"]')!,
).getByRole('searchbox', { name: 'Filtrer par nom' })
filter.focus()
escape(filter)
expect(more).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(filter)
})
})
describe('Escape and the other layers', () => {
it('closes the citations panel from the tab row, the selection kept', async () => {
const user = await mount(WITH_NODE())
await select(user)
await openCitations(user)
escape(screen.getByRole('tab', { name: 'Constats' }))
await waitFor(() => expect(citations()).toBeNull())
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(panel()).toBeDefined()
})
it('closes « Plus » first (small tier), the twin selection kept', async () => {
const user = await mount(TWO(), 500)
await select(user)
const more = screen.getByRole('button', { name: 'Plus' })
await user.click(more)
expect(more).toHaveAttribute('aria-expanded', 'true')
canvasBox().focus()
escape(canvasBox())
expect(more).toHaveAttribute('aria-expanded', 'false')
expect(document.activeElement).toBe(more)
expect(panel()).toBeDefined()
})
it('read-only width: only the visible twin deselects, the hidden body keeps its own', async () => {
const user = await mount()
await select(user)
setWidth(500)
act(() => void window.dispatchEvent(new Event('resize')))
await waitFor(() =>
expect(shown('[data-testid="catalogue-canvas"]')).toBeDefined(),
)
await select(user)
escape(document.body)
expect(panel()).toBeUndefined()
const hidden = [
...document.querySelectorAll('[data-testid="annotation-properties"]'),
].filter((element) => element.closest('[hidden]'))
expect(hidden).toHaveLength(1)
})
})