Files
faunosteo/apps/app/tests/unit/editor-keep-alive.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

647 lines
22 KiB
TypeScript

/** U1 Lot B2a: tabs, Annotations sections and the Références tab stay mounted. */
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 { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import EditorTabBody from '@/components/editor/EditorTabBody'
import KeptPlace from '@/components/editor/KeptPlace'
import { useSheetDocument } from '@/editor/sheetDocument'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { FocusConsumedContext } from '@/editor/focusRequest'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { cleanSvg } from '@/editor/core/cleaning'
import {
ASSET,
drawnText,
edit,
emptyText,
insert,
point,
} from '../helpers/editorFixtures'
import {
baseText,
resetStore,
sb,
serverHas,
store,
versionAnswer,
} 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 ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const tab = (name: string | RegExp) => screen.getByRole('tab', { name })
const entry = (name: string | RegExp) => screen.getByRole('button', { name })
const place = (name: string) =>
document.querySelector<HTMLElement>(`[data-place="${name}"]`)!
const inPlace = (name: string) => within(place(name))
const name = (n: string) => ({ fr: n, en: n })
function findingsText(from = baseText(), nodeRefs?: string[]): string {
const text = insert(from, {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
const family = 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: [],
},
},
})
if (!nodeRefs) return family
return edit(family, {
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: nodeRefs,
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
}
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 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' }))
}
async function mount(text = baseText()) {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft()
await ready()
return user
}
describe('KeptPlace', () => {
function Probe() {
return <p>{usePlaceVisible() ? 'yes' : 'no'}</p>
}
it('hides its children and composes with the places around it', () => {
render(
<KeptPlace name="outer" visible>
<KeptPlace name="inner" visible={false}>
<Probe />
</KeptPlace>
<KeptPlace name="other" visible>
<Probe />
</KeptPlace>
</KeptPlace>,
)
expect(place('inner')).not.toBeVisible()
expect(place('other')).toBeVisible()
expect(screen.getAllByText('yes')).toHaveLength(1)
})
it('an own visible place inside a hidden one is not visible', () => {
render(
<KeptPlace name="outer" visible={false}>
<KeptPlace name="inner" visible>
<Probe />
</KeptPlace>
</KeptPlace>,
)
expect(screen.getByText('no')).toBeInTheDocument()
})
it('is visible outside any place', () => {
render(<Probe />)
expect(screen.getByText('yes')).toBeInTheDocument()
})
})
describe('text typed in a place that is left', () => {
it('the category add form survives Général ↔ Annotations and a section round trip', async () => {
const user = await mount()
await user.click(tab('Annotations'))
await user.click(entry('Modifier les catégories'))
const field = inPlace('annotations.categories').getByLabelText(
'Nom de la catégorie (FR)',
{ selector: '#category-new-fr' },
)
await user.type(field, 'Brouillon')
await user.click(tab('Général'))
expect(place('annotations.categories')).not.toBeVisible()
await user.click(tab('Annotations'))
expect(place('annotations.categories')).toBeVisible()
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
await user.click(entry('Modifier les catégories'))
expect(document.querySelector('#category-new-fr')).toBe(field)
expect(field).toHaveValue('Brouillon')
expect(store.getState().unsaved).toBe(false)
})
it('the reference add form 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',
})
await user.type(field, '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(store.getState().unsaved).toBe(false)
})
})
describe('findings and canvas state across a tab change', () => {
it('the findings selection and expansion survive', async () => {
const user = await mount(findingsText())
await user.click(tab('Constats'))
const zone = inPlace('findings').getByRole('treeitem', { name: /Zone A/ })
const cat = inPlace('findings').getByRole('treeitem', { name: /Cat A/ })
await user.click(cat)
expect(zone).toHaveAttribute('aria-expanded', 'true')
await user.click(tab('Général'))
await user.click(tab('Constats'))
expect(inPlace('findings').getByRole('treeitem', { name: /Cat A/ })).toBe(
cat,
)
expect(cat).toHaveAttribute('aria-selected', 'true')
expect(zone).toHaveAttribute('aria-expanded', 'true')
})
it('the canvas tool, selection and zoom survive a tab change and a section round trip', async () => {
const text = insert(drawnText(), point('anno-a', 50, 50, 5))
const user = await mount(text)
await waitFor(() =>
expect(
inPlace('annotations.drawing').getByRole('button', { name: 'Zone' }),
).toBeEnabled(),
)
const drawing = inPlace('annotations.drawing')
await user.click(drawing.getByRole('button', { name: 'Zone' }))
await user.click(drawing.getByRole('button', { name: 'Zoom avant' }))
const layer = () =>
drawing.getByTestId('annotation-canvas').firstElementChild as HTMLElement
const zoomed = layer().style.transform
expect(zoomed).not.toContain('scale(1)')
await user.click(tab('Général'))
await user.click(tab('Annotations'))
await user.click(entry('Gérer les vues'))
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
expect(drawing.getByRole('button', { name: 'Zone' })).toHaveAttribute(
'aria-pressed',
'true',
)
expect(layer().style.transform).toBe(zoomed)
const list = drawing.getByRole('list', { name: 'Annotations de la vue' })
await user.click(within(list).getAllByRole('button')[0])
const marker = () =>
drawing
.getByTestId('annotation-canvas-drawing')
.querySelector('[data-anno-id="anno-a"]')
const stillSelected = () =>
waitFor(() => expect(marker()).toHaveAttribute('data-state', 'current'))
await stillSelected()
await user.click(tab('Général'))
await user.click(tab('Annotations'))
await stillSelected()
expect(drawing.getByTestId('annotation-properties')).toBeVisible()
})
it('the unmeasured hint opens the views section and « Retour au dessin » restores the same canvas', async () => {
serverHas(emptyText(), 3, false)
const user = userEvent.setup()
mountDraft()
await ready()
await user.click(tab('Annotations'))
const drawing = inPlace('annotations.drawing')
const canvas = drawing.getByTestId('annotation-canvas')
await user.click(drawing.getByRole('button', { name: 'Vues' }))
expect(place('annotations.views')).toBeVisible()
expect(place('annotations.drawing')).not.toBeVisible()
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
expect(place('annotations.drawing')).toBeVisible()
expect(drawing.getByTestId('annotation-canvas')).toBe(canvas)
})
})
describe('a field still focused while a place is left', () => {
async function generalNameField(user: ReturnType<typeof userEvent.setup>) {
await user.click(tab('Général'))
const field = inPlace('general').getByLabelText('Nom (FR)', {
exact: true,
selector: '#general-name-fr',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Nom saisi' } })
return field
}
it('a click that moves no focus (Safari) still commits it, as one undo entry', async () => {
const user = await mount()
const before = store.getState().documentText
const field = await generalNameField(user)
expect(document.activeElement).toBe(field)
fireEvent.click(tab('Annotations'))
expect(JSON.parse(store.getState().documentText).name.fr).toBe('Nom saisi')
expect(store.getState().unsaved).toBe(true)
act(() => void store.getState().undoStep())
expect(store.getState().documentText).toBe(before)
})
it('an arrow key on the tab list commits it first, as one undo entry', async () => {
const user = await mount()
const before = store.getState().documentText
const field = await generalNameField(user)
fireEvent.keyDown(tab('Général'), { key: 'ArrowRight' })
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
expect(JSON.parse(store.getState().documentText).name.fr).toBe('Nom saisi')
expect(field).toHaveValue('Nom saisi')
expect(store.getState().unsaved).toBe(true)
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', () => {
const detail = {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 20, width: 40, height: 60 },
parent_view_id: 'view-main',
},
} as const
/** A drawing whose own elements carry ids, so a second composed copy would repeat them. */
function serveDrawingWithIds(text: string): void {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">' +
'<defs><linearGradient id="fade"><stop offset="0"/></linearGradient></defs>' +
'<rect id="body" width="4" height="4" fill="url(#fade)"/></svg>'
const cleaned = cleanSvg(new TextEncoder().encode(svg))
if (!cleaned.ok || !cleaned.value.stored) throw new Error('uncleanable')
const bytes = new TextEncoder().encode(cleaned.value.stored)
const answer = versionAnswer(text, 3)
answer.drawings = [{ asset_id: ASSET, sha256: cleaned.value.sha256! }]
sb.getSheetVersion.mockResolvedValue(answer as never)
sb.downloadSheetDrawing.mockResolvedValue(bytes)
}
const composedHosts = () =>
[
...document.querySelectorAll(
'[data-testid="annotation-canvas-drawing"], [data-testid="crop-canvas-drawing"]',
),
].filter((host) => host.querySelector('svg'))
it('every place visited, a crop group open: one composed copy, no id repeats', async () => {
serveDrawingWithIds(insert(drawnText(), detail))
const user = userEvent.setup()
mountDraft()
await ready()
await waitFor(() => expect(composedHosts()).toHaveLength(1))
await user.click(entry('Gérer les vues'))
await user.click(
inPlace('annotations.views').getByRole('button', {
name: 'Modifier le recadrage',
}),
)
await waitFor(() => expect(composedHosts()).toHaveLength(1))
expect(composedHosts()[0]).toHaveAttribute(
'data-testid',
'crop-canvas-drawing',
)
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
await user.click(entry('Modifier les catégories'))
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
await user.click(entry(/^Régions vertébrales/))
for (const name of ['Général', 'Constats', 'Références', /Vérification/]) {
await user.click(tab(name))
}
expect(composedHosts()).toHaveLength(0)
await user.click(tab('Annotations'))
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
await waitFor(() => expect(composedHosts()).toHaveLength(1))
const ids = [...document.querySelectorAll('[id]')].map((e) => e.id)
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([])
expect(ids.some((id) => id.includes('body'))).toBe(true)
})
it('every place reads the same parsed document per text', async () => {
await mount()
const seen: unknown[] = []
function Probe() {
seen.push(useSheetDocument())
return null
}
const first = render(
<>
<Probe />
<Probe />
</>,
)
expect(seen[0]).not.toBeNull()
expect(seen[1]).toBe(seen[0])
first.unmount()
act(() => {
store.getState().commit({
op: 'insert',
element: {
kind: 'category',
value: { id: 'cat-z', name: name('Z'), color: null },
},
})
})
seen.length = 0
render(
<>
<Probe />
<Probe />
</>,
)
expect(seen[1]).toBe(seen[0])
expect(seen[0]).toMatchObject({
categories: expect.arrayContaining([
expect.objectContaining({ id: 'cat-z' }),
]),
})
})
})
describe('a request reaches only its owner', () => {
it('a finding request focuses the findings place while others are mounted', async () => {
await mount(findingsText())
await userEvent.setup().click(tab('Constats'))
await userEvent.setup().click(tab('Général'))
const consumed = vi.fn()
const { unmount } = render(
<FocusConsumedContext value={consumed}>
<EditorTabBody
tab="findings"
visited={['general', 'annotations', 'findings']}
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
focus={{
target: targetOfKey({
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a'],
}),
serial: 9,
}}
annotations={{
section: 'drawing',
visited: ['drawing'],
onOpenSection: vi.fn(),
onBack: vi.fn(),
}}
/>
</FocusConsumedContext>,
)
await waitFor(() => expect(consumed).toHaveBeenCalledTimes(1))
expect(consumed).toHaveBeenCalledWith(9, 'found')
unmount()
})
it('after « Aller à » a finding, arrowing back onto Constats keeps the focus on the tab', async () => {
const text = insert(findingsText(), {
...point('anno-bare', 10, 10, 2),
})
const user = await mount(text)
await user.click(tab('Constats'))
await user.click(
inPlace('findings').getByRole('treeitem', { name: /Cat A/ }),
)
await user.click(tab('Annotations'))
tab('Annotations').focus()
await user.keyboard('{ArrowRight}')
expect(tab('Constats')).toHaveAttribute('aria-selected', 'true')
expect(document.activeElement).toBe(tab('Constats'))
})
})
describe('« Aller à » while a creation or a tracing is in progress', () => {
const liveText = () =>
document.querySelector('p[aria-live="polite"]')?.textContent ?? ''
function bareAnnotationText(): string {
const bare = point('anno-bare', 10, 10, 2)
const value = { ...bare.value, geometry: null, name: name('Sans tracé') }
return insert(drawnText(), { kind: 'annotation', value } as typeof bare)
}
async function gotoBare(
user: ReturnType<typeof userEvent.setup>,
start: () => Promise<void>,
) {
await waitFor(() =>
expect(
inPlace('annotations.drawing').getByRole('button', { name: 'Zone' }),
).toBeEnabled(),
)
await start()
await user.click(tab(/Vérification/))
await user.click(
inPlace('verification').getAllByRole('button', {
name: 'Aller à Sans tracé',
})[0],
)
}
it('a tracing from the Zone tool is kept and focused', async () => {
const user = await mount(bareAnnotationText())
await gotoBare(user, async () => {
await user.click(
inPlace('annotations.drawing').getByRole('button', { name: 'Zone' }),
)
fireEvent.click(screen.getByTestId('annotation-canvas'), {
clientX: 20,
clientY: 20,
})
})
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
const bar = within(place('annotations.drawing')).getByTestId('tracing-bar')
expect(bar).toBeVisible()
await waitFor(() => expect(document.activeElement).toBe(bar))
expect(liveText()).toContain('tracé est en cours')
})
it('a « Remplacer par un polygone » tracing is kept and focused (it cannot coexist with a pending creation)', async () => {
const zone = point('zone-a', 0, 0, 1)
const zoneValue = {
...zone.value,
kind: 'zone',
geometry: { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' },
}
const text = insert(bareAnnotationText(), {
kind: 'annotation',
value: zoneValue,
} as typeof zone)
const user = await mount(text)
await gotoBare(user, async () => {
const drawing = inPlace('annotations.drawing')
const list = drawing.getByRole('list', { name: 'Annotations de la vue' })
await user.click(within(list).getAllByRole('button')[0])
await user.click(
await drawing.findByRole('button', {
name: 'Remplacer par un polygone',
}),
)
expect(drawing.getByTestId('tracing-bar')).toBeVisible()
})
const bar = within(place('annotations.drawing')).getByTestId('tracing-bar')
await waitFor(() => expect(document.activeElement).toBe(bar))
expect(liveText()).toContain('tracé est en cours')
})
it('a pending creation is kept and focused', async () => {
const user = await mount(bareAnnotationText())
await gotoBare(user, async () => {
await user.click(
inPlace('annotations.drawing').getByRole('button', {
name: 'Ajouter un point',
}),
)
})
const panel = within(place('annotations.drawing')).getByTestId(
'annotation-creation',
)
expect(panel).toBeVisible()
await waitFor(() =>
expect(document.activeElement).toHaveAttribute('data-creation-heading'),
)
expect(liveText()).toContain('création est en cours')
})
})