Files
faunosteo/apps/app/tests/unit/editor-no-loss-decisions.test.tsx
T
bchanot 4499bc740c feat(editor): fifth tab « Références », citations panel from a finding
The reference library moves into a fifth editor tab (Général,
Annotations, Constats, Références, Vérification; under « Plus » below
640 px with Général and Constats). The header « Références » button is
removed. The side panel becomes the citations list of one finding,
opened only from a finding's trigger (owner GO 2026-11-12: never from a
family; the family keeps its inline list with « Retirer »). Selecting a
tab closes it; every close records one pending move applied after the
panel is gone, focus back to the trigger else the active tab button.
Vérification's reference issues land on the tab. e2e seed gains a
reference cited by « Constat A ».

Gates: typecheck, lint, test:run (app 1396), build, e2e:ui 251 passed;
e2e:shell 15 specs on db:sandbox (editor-equine never listed): 107
passed / 95 skipped / 2 failed (test remap dropped its edit), fixed and
rerun: editor-shell.spec 11 passed; full-row data guard: no
pre-existing row changed in any table. editor-equine.spec.ts helper
calls updated, not run.

## R-24 table (removed or rewritten assertions; old = fc3fec7 line, new = current file)

Unit tests:

| file:old line | old | new |
|---|---|---|
| editor-verification.test.tsx:87-96 | `navigate` called with target AND `expect.any(HTMLElement)` | called with the target only (opener dropped) |
| editor-verification.test.tsx:238-241 | `references[0]` path -> `{place:'references', citedBy:null}` | `{place:'tab', tab:'references', section:null}` |
| editor-verification.test.tsx:262-264 | `placeKey(references[9])` = `editor.place.references` | `editor.tab.references` |
| editor-navigation.test.ts:63 | targetOfKey reference -> `{place:'references', key, citedBy:null}` | `{place:'tab', tab:'references', section:null, key}` |
| editor-navigation.test.ts:80 | `referencesMounted` false at start | `citationsOf` null and `libraryReset` 0 |
| editor-navigation.test.ts:95-110 | go_to a reference opens the panel over the place | go_to a reference shows the Références tab with its focus request |
| editor-navigation.test.ts:112-122 | go_to a tab closes the panel (`references` object) | same, via `citationsOf` null |
| editor-navigation.test.ts:124-136 | select_tab keeps the panel | select_tab CLOSES the panel (P21), keeps section, no request |
| editor-navigation.test.ts:138-146 | `clear_cited_by` drops the filter | removed (action gone); replaced by `open_citations` refuses family/zone/view, `show_all_references` (closes, tab, reset bump), plain go_to leaves reset alone |
| editor-navigation.test.ts:160-175 | open/close references keep tab and section | open/close citations, same assertions on `citationsOf` |
| editor-mode.test.ts:100-109 | tabsFor four tabs, small more = general, findings | five tabs, small more = general, findings, references |
| editor-route.test.tsx:46,50 | TABS four, title « four tabs » | five |
| editor-route.test.tsx:139-146 | 640-1023 px four tabs | five tabs, tablist has `flex-wrap` |
| editor-route.test.tsx:149-161 | « Plus » lists Général, Constats | lists Général, Constats, Références |
| editor-route.test.tsx:168-190 | header button opens panel, ✕ returns focus to button | no header button, panel not mounted at start (full panel flow moved to editor-references-panel.test.tsx) |
| editor-route.test.tsx:192-206 | Escape closes, panel content kept for next opening | removed: the panel is no longer kept mounted (design choice 3); Escape/close covered in editor-references-panel + editor-escape |
| editor-route.test.tsx:208-218 | read-only: panel lists references, no edit control | read-only: the Références tab lists them, no textbox, no add button; plus new: tab keeps mounted when left |
| editor-tabs-lists.test.tsx:47,75,114,130 | render `ReferencesPanel` | render `ReferencesTab` |
| editor-tabs-lists.test.tsx:77 | selector `#reference-ref-a-url` | `#tab-reference-ref-a-url` |
| editor-tabs-lists.test.tsx:131-135 | read-only buttons = only « Fermer les références » | no button at all |
| editor-focus-request.test.tsx:166-171,200-202,346 | `ReferencesPanel` with `panel` props and focus | `ReferenceLibrary` with focus (same assertions) |
| editor-focus-request.test.tsx:226 | `ownedBy(ref,'citations')` is the request | `ownedBy(ref,'references')` is the request, `'citations'` undefined |
| editor-focus-request.test.tsx (Probe) | none | new: Vérification « Aller à » reference -> tab + focused row; reference path naming no element -> tab heading |
| editor-keep-alive.test.tsx:71,178-190 | add form survives closing/reopening the panel | survives leaving/returning to the Références tab (`#tab-reference-new-citation`) |
| editor-keep-alive.test.tsx:300-326 | « Aller à » without focus move commits Références text | a tab click without focus move commits it (one undo entry): « Aller à » is not reachable from the Références tab in R2.1 |
| editor-keep-alive.test.tsx:333-347 | Escape in panel reference field commits, panel hides | same, panel opened from a finding node, field `#panel-reference-ref-1-citation` |
| editor-keep-alive.test.tsx:350-363 | header toggle (no focus move) closes after committing | scrim click (no focus move) closes after committing |
| editor-keep-alive.test.tsx:425 | `referencesButton` click in the all-places sweep | `Références` added to the tab loop |
| editor-escape.test.tsx:218-227 | header button toggle, Escape on body closes panel, annotation selection kept | trigger-opened panel (A5), Escape closes it, `aria-expanded` back to false, selection kept after returning to Annotations |
| editor-escape.test.tsx:255-266 | Escape from tab row closes panel | same from the Constats tab button |
| editor-no-loss.test.tsx:146-153 | reference creation form, in the panel | in the Références tab, id `tab-reference-new-citation` |
| editor-no-loss.test.tsx:285-291 | focused header button survives crossing | focused tab button (Constats) survives crossing: no header button left |
| editor-no-loss.test.tsx:293-307 | references search in panel keeps focus/text | same in the Références tab body |
| editor-no-loss.test.tsx:390-400 | `everyPlace` ends by opening the panel | visits Références in the tab loop, no panel open |
| editor-no-loss-decisions.test.tsx:248-259 | open references panel holds the decision back | REMOVED: the panel exists only over Constats, decisions live in Annotations (hidden then); « a widening on another tab opens nothing » (same file) covers the withholding |
| editor-route-recovery.test.tsx:93-97 | recovery offer: header button opens panel, `aria-labelledby` | tab Références shows `editor-tab-references` labelled by `editor-references-title` |
| editor-references-panel.test.tsx (all) | header-button-driven panel tests incl. search, order, add, « Aller à » | split: panel tests (finding path only) stay in this file; library tests moved to new editor-references-tab.test.tsx (search matching, ↑/↓ only without search, counts, Ctrl+Z, read-only, « Aller à », add clears search, refused add keeps it); new: reset signal, ids unique with both mounted (P14), P6 fallback under « Plus » |

e2e (updated only, not run):

| file:old line | old | new |
|---|---|---|
| editor-shell.spec.ts:95-108 | panel keeps form text, no id repeats | Références tab keeps form text (`#tab-reference-new-citation`), ids unique with the panel open |
| editor-shell.spec.ts:121-142 | open panel leaves header and tab row clickable (incl. header Références button, add form) | `openCitations`; header button target and form steps dropped |
| editor-shell-journeys.spec.ts:113-123 | four tabs, `old` list includes « Références » | five tabs, « Références » removed from the old-layout list |
| editor-shell-journeys.spec.ts:246-249 | Aller à reference -> panel visible, close | `place('references')` visible, tab Références selected, row focus key, no close |
| editor-shell-layout.spec.ts:84-103 | overflow on four tabs + panel over drawing | five tabs + `openCitations`/`closeCitations` |
| editor-shell-layout.spec.ts:54-63 | local `goToTab` | removed, uses `openTab` |
| editor-shell-layout.spec.ts:140-158 | canvas width without/with panel over the drawing | E1: width measured before open and after a P21 switch to Annotations, asserted equal |
| editor-shell-layout.spec.ts:161-189 | axe on four tabs + open panel | five tabs + citations panel |
| editor-shell-layout.spec.ts:~255-310 | keyboard order began with `header` (the Références button) | `header` dropped from both orders (no focusable header control while the draft is clean); panel test selects Annotations before walking to `side` |
| editor-access.spec.ts:150-152,191-194,219-220 | axe/overflow with the panel at 320/375/768/800, 1024, read-only | same checks through `openCitations` (`showDrawing` calls dropped) |
| editor-shell-crossing.spec.ts:194-206 | references form with panel open, tab `annotations` | in the tab, focus expected on `editor-tab-references` |
| editor-shell-crossing.spec.ts:264-282 | panel open + add-form text across crossing | citations panel over a crossing, no typed-text step |
| editor-shell-crossing.spec.ts:~385-410 | decision withheld while panel open, Reprendre | REMOVED (state unreachable, see unit row) |
| editor-deselect.spec.ts:226-229 | Escape closes header-opened panel, selection kept | opened via Constats, Escape, back to Annotations, selection kept |
| editor-structures.spec.ts:80-122 | two references added, counts 2/1 | shape now holds `ref-a`: counts 3/2, `nth(1)` after move, saved list `['Référence A','Seconde référence']`, no panel |
| editor-equine.spec.ts:304-305,404-405 | openReferences/closeReferences | `openTab(page, dict, 'references')`: mis à jour, non exécuté, non vérifié |

Fix round 1: 1. e2e/shell/editor-shell.spec.ts « the open citations panel leaves the header and the tab row clickable »: before `openCitations`, the test now opens the Références tab and adds a reference through the library form (`#tab-reference-new-type` book, `#tab-reference-new-citation` « Smith 1999 », « Ajouter la référence »), so the draft is dirty and Save is enabled. All original assertion
2026-11-12 20:29:27 +01:00

399 lines
13 KiB
TypeScript

/** U1 Lot B2b: the drawing actions of the views section across a crossing and a held decision. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation } from '@faunosteo/core-wasm/types'
import { cleanSvg } from '@/editor/core/cleaning'
import { useLocaleStore } from '@/state/localeStore'
import { emptyText, insert, point, svgBytes } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
sb,
serverHas,
store,
} from '../helpers/editorHarness'
import {
adminAnswer,
mountDraft,
round,
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(),
registerSheetAsset: vi.fn(),
listSheetAssets: vi.fn(),
uploadSheetDrawing: vi.fn(),
confirmSheetAssetUpload: vi.fn(),
}))
const NEW_ASSET = '22222222-2222-4222-8222-222222222222'
const svg = (inner = '<rect width="4" height="4"/>') =>
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">${inner}</svg>`
const CLEAN = svg()
const DIRTY = svg(
'<style>.a{fill:red}</style><rect class="a" width="4" height="4"/>',
)
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 tab = (name: string | RegExp) => screen.getByRole('tab', { name })
const button = (name: string | RegExp) => screen.getByRole('button', { name })
const maybeButton = (name: string | RegExp) =>
screen.queryByRole('button', { name })
const dialogs = () => document.querySelectorAll('dialog[open]').length
const doc = () => JSON.parse(store.getState().documentText)
const mainAsset = () => doc().views[0].svg_asset_id
const fileInput = (view = 'main') =>
screen.getByTestId(`view-view-${view}-file`) as HTMLInputElement
function cross(width: number) {
act(() => {
setWidth(width)
window.dispatchEvent(new Event('resize'))
})
}
function serverGets(text: string) {
const cleaned = cleanSvg(new TextEncoder().encode(text))
if (!cleaned.ok || !cleaned.value.stored) throw new Error('bad svg')
const bytes = new TextEncoder().encode(cleaned.value.stored)
sb.registerSheetAsset.mockResolvedValue(NEW_ASSET)
sb.listSheetAssets.mockResolvedValue([
{
id: NEW_ASSET,
sha256: cleaned.value.sha256!,
byte_size: cleaned.value.byte_size!,
uploaded_at: null,
},
])
sb.uploadSheetDrawing.mockResolvedValue('uploaded')
sb.confirmSheetAssetUpload.mockResolvedValue(NEW_ASSET)
sb.downloadSheetDrawing.mockImplementation(async (_c, hash) =>
hash === cleaned.value.sha256 ? bytes : svgBytes().bytes,
)
}
/** A file whose bytes arrive when `release` runs: the decision settles at a chosen time. */
function heldFile(text: string) {
let release: () => void = () => undefined
const gate = new Promise<void>((resolve) => (release = resolve))
const file = new File([text], 'd.svg', { type: 'image/svg+xml' })
Object.defineProperty(file, 'arrayBuffer', {
value: async () => {
await gate
return new TextEncoder().encode(text).buffer
},
})
return { file, release }
}
const pick = (file: File, view = 'main') =>
fireEvent.change(fileInput(view), { target: { files: [file] } })
const plain = (text: string) =>
new File([text], 'd.svg', { type: 'image/svg+xml' })
async function mountViews(text = baseText()) {
serverHas(text, 3)
serverGets(CLEAN)
const user = userEvent.setup()
mountDraft()
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
await user.click(tab('Annotations'))
await user.click(button('Gérer les vues'))
return user
}
const PENDING = /nettoyage de l'illustration attend votre décision/
const RESUME = 'Reprendre'
describe('a cleaning decision across a crossing', () => {
it('closes with the editor, shows as pending, reopens only through « Reprendre »', async () => {
const user = await mountViews()
serverGets(DIRTY)
pick(plain(DIRTY))
await screen.findByRole('dialog')
cross(800)
await waitFor(() => expect(dialogs()).toBe(0))
expect(screen.getByText(PENDING)).toBeVisible()
expect(maybeButton(RESUME)).toBeNull()
cross(1280)
expect(dialogs()).toBe(0)
expect(screen.getByText(PENDING)).toBeVisible()
await user.click(button(RESUME))
const dialog = within(await screen.findByRole('dialog'))
expect(dialog.getByText('style')).toBeVisible()
await user.click(
dialog.getByRole('button', {
name: 'Nettoyer et utiliser cette version',
}),
)
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(screen.queryByText(PENDING)).toBeNull()
})
it('disables the picker, the file input and the parent button while it is pending', async () => {
const user = await mountViews()
pick(plain(DIRTY))
await screen.findByRole('dialog')
cross(800)
cross(1280)
const picker = button('Choisir une illustration')
expect(picker).toBeDisabled()
expect(fileInput()).toBeDisabled()
const note = screen.getByText(PENDING).closest('[id]')!
expect(picker).toHaveAttribute('aria-describedby', note.id)
await user.click(button(RESUME))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Annuler',
}),
)
expect(button('Choisir une illustration')).toBeEnabled()
expect(fileInput()).toBeEnabled()
})
it('a new decision opens on its own once the held one has ended', async () => {
const user = await mountViews()
pick(plain(DIRTY))
await screen.findByRole('dialog')
cross(800)
cross(1280)
await user.click(button(RESUME))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Annuler',
}),
)
pick(plain(DIRTY))
expect(await screen.findByRole('dialog')).toBeVisible()
expect(screen.queryByText(PENDING)).toBeNull()
})
it('narrow with a held decision: the pending text, no « Reprendre »; none after widening until clicked', async () => {
const user = await mountViews()
pick(plain(DIRTY))
await screen.findByRole('dialog')
cross(800)
await waitFor(() => expect(dialogs()).toBe(0))
expect(screen.getByText(PENDING)).toBeVisible()
expect(maybeButton(RESUME)).toBeNull()
expect(
screen.queryByRole('button', { name: 'Choisir une illustration' }),
).toBeNull()
cross(1280)
expect(dialogs()).toBe(0)
await user.click(button(RESUME))
expect(await screen.findByRole('dialog')).toBeVisible()
})
})
describe('a decision that settles in a place that is not shown', () => {
it('an offer settling with the section hidden opens nothing until « Reprendre »', async () => {
const user = await mountViews()
const held = heldFile(DIRTY)
pick(held.file)
await user.click(button('Retour au dessin'))
await act(async () => held.release())
await waitFor(() => expect(sb.registerSheetAsset).not.toHaveBeenCalled())
expect(dialogs()).toBe(0)
await user.click(button('Gérer les vues'))
expect(dialogs()).toBe(0)
expect(screen.getByText(PENDING)).toBeVisible()
await user.click(button(RESUME))
expect(await screen.findByRole('dialog')).toBeVisible()
})
it('a widening on another tab opens nothing; the tab keeps its focus', async () => {
const user = await mountViews()
const held = heldFile(DIRTY)
pick(held.file)
await user.click(tab('Général'))
await act(async () => held.release())
cross(800)
cross(1280)
expect(dialogs()).toBe(0)
await user.click(tab('Annotations'))
expect(document.activeElement).toBe(tab('Annotations'))
expect(dialogs()).toBe(0)
expect(screen.getByText(PENDING)).toBeVisible()
})
it('an upload settling while read-only lands in the live hook, its notice shown', async () => {
const user = await mountViews()
let finish: (value: string) => void = () => undefined
sb.registerSheetAsset.mockReturnValue(
new Promise<string>((resolve) => (finish = resolve)),
)
pick(plain(CLEAN))
expect(await screen.findByText(/Vérification et envoi/)).toBeVisible()
cross(800)
expect(screen.getByText(/Vérification et envoi/)).toBeVisible()
await act(async () => finish(NEW_ASSET))
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(store.getState().unsaved).toBe(true)
cross(1280)
expect(await screen.findByText(/est ajoutée à la vue/)).toBeVisible()
void user
})
})
const detailOwn = (assetId: string | null) =>
({
kind: 'view',
value: {
kind: 'detail',
id: 'view-d',
name: { fr: 'Détail', en: 'Detail' },
svg_asset_id: assetId,
view_box: { min_x: 0, min_y: 0, width: 50, height: 50 },
parent_view_id: 'view-main',
},
}) as Parameters<typeof insert>[1]
describe('the parent choice', () => {
const USE_PARENT = "Utiliser l'illustration de la vue parente"
async function mountDetail() {
const user = await mountViews(insert(baseText(), detailOwn(NEW_ASSET)))
return user
}
it('is a decision per click: held across a crossing, a new click opens on its own', async () => {
const user = await mountDetail()
await user.click(button(USE_PARENT))
expect(await screen.findByRole('dialog')).toBeVisible()
cross(800)
await waitFor(() => expect(dialogs()).toBe(0))
expect(
screen.getByText(/retour à l'illustration de la vue parente/),
).toBeVisible()
cross(1280)
expect(button(USE_PARENT)).toBeDisabled()
await user.click(button(RESUME))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Annuler',
}),
)
await user.click(button(USE_PARENT))
expect(await screen.findByRole('dialog')).toBeVisible()
})
})
/** An unmeasured main view with annotations far outside a 100 x 100 frame. */
function unmeasuredText(): string {
let text = insert(emptyText(), {
kind: 'category',
value: { id: 'cat-a', name: { fr: 'N', en: 'N' }, color: null },
})
text = insert(text, point('anno-a', 500, 400, 5))
const zone = {
...(point('anno-z', 0, 0, 1).value as Annotation),
kind: 'zone' as const,
geometry: {
type: 'polygon' as const,
points: [
[10, 10],
[400, 10],
[400, 400],
] as [number, number][],
},
}
return insert(text, { kind: 'annotation', value: zone as Annotation })
}
describe('the repair offer', () => {
it('keeps its typed geometries across a crossing and « Reprendre »', async () => {
const user = await mountViews(unmeasuredText())
pick(plain(CLEAN))
const first = await screen.findByRole('dialog')
const row = within(within(first).getByTestId('repair-anno-a'))
const x = row.getByLabelText('Centre x')
await user.clear(x)
await user.type(x, '60{Enter}')
cross(800)
await waitFor(() => expect(dialogs()).toBe(0))
expect(screen.getByText(/réparation des annotations attend/)).toBeVisible()
cross(1280)
expect(dialogs()).toBe(0)
await user.click(button(RESUME))
const again = within(await screen.findByRole('dialog'))
expect(
within(again.getByTestId('repair-anno-a')).getByLabelText('Centre x'),
).toHaveValue('60')
expect(mainAsset()).toBeNull()
})
})
describe('limits of a held decision', () => {
it('is lost with its view (undo), redo does not bring it back', async () => {
const user = await mountViews(baseText())
const added = store.getState().commit({
op: 'insert',
element: detailOwn(null) as never,
} as never)
expect(added.ok).toBe(true)
await screen.findByTestId('view-view-d-file')
pick(plain(DIRTY), 'd')
await screen.findByRole('dialog')
cross(800)
cross(1280)
expect(screen.getByText(PENDING)).toBeVisible()
act(() => void store.getState().undoStep())
await waitFor(() => expect(screen.queryByText(PENDING)).toBeNull())
act(() => void store.getState().redoStep())
await screen.findByTestId('view-view-d-file')
expect(screen.queryByText(PENDING)).toBeNull()
expect(maybeButton(RESUME)).toBeNull()
void user
})
it('stays a pending line without action once the draft is frozen by a submission', async () => {
const user = await mountViews()
const held = heldFile(DIRTY)
pick(held.file)
await user.click(tab(/Vérification/))
await act(async () => held.release())
sb.submitSheetReview.mockResolvedValue('review-1' as never)
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
'Prête',
)
sb.getOfficialSheetAdmin.mockResolvedValue(
adminAnswer({ rounds: [round('open')] }) as never,
)
await user.click(button('Soumettre à la revue'))
await user.click(tab('Annotations'))
await waitFor(() => expect(screen.getByText(PENDING)).toBeVisible())
expect(maybeButton(RESUME)).toBeNull()
expect(dialogs()).toBe(0)
})
})