Files
faunosteo/apps/app/tests/unit/editor-tabs-views.test.tsx
T
bchanot bc2dba7c14 feat(editor): four tabs, Annotations sections, references from the header
U1 Lot B1. Four tabs (Général, Annotations, Constats, Vérification); views,
categories and regions become full-width Annotations sections opened from the
overview panel; references move to a header-toggled panel (minimal, Lot D
completes it); « Aller à » goes through EditorTarget and the navigation hook.
EditorWorkspace owns the navigation; DraftHeader split in HeaderActions and
SaveLine; EditorTabs split in TabList and MoreTabs.

R-24, assertions removed or rewritten (file: old -> new):
unit
- editor-route.test: seven tab names -> four; « Plus » at 800 px with
  Références clicked -> no « Plus »; below 640 px five others -> Général,
  Constats, and Constats opens the findings tab; + references panel cases
- editor-route-recovery.test: tab Références + editor-tab-references label ->
  header button + editor-references-panel labelled by its heading
- editor-mode.test: small tier `more` of five -> [general, findings]
- editor-focus-request.test: {key,serial} -> {target,serial}; ReferencesTab and
  VertebraeTab -> ReferencesPanel and RegionsSection; issueTarget tab/key ->
  target place/section/key (vertebrae tab -> annotations/regions); consumed
  context (serial) -> (serial, outcome); annotation case adds heading focus
- editor-verification.test: onGoTo('annotations', key) -> navigate(targetOfKey
  (key), opener); props onSelectTab/onGoTo -> navigate
- editor-annotations-tab.test: props onSelectTab -> navigate + section props;
  no_category text « (onglet Général) » -> « (Annotations, section
  Catégories) »
- editor-tabs-general.test: categories cases render GeneralTab ->
  CategoriesSection(doc); + Général holds no categories editor
- editor-tabs-lists.test: tab imports -> panel and section; read-only
  references « no button » -> only « Fermer les références »
- editor-tabs-views, editor-drawing-upload, editor-repair.test: ViewsTab ->
  ViewsSection import, assertions kept; editor-findings.test: navigate prop
e2e
- support/editor selectTab: exact name -> pattern (error badge in the name);
  + place, openSection, showDrawing, backToDrawing, openReferences, TABS
- support/warm-up: seven tabs -> four + sections + references panel
- editor-access: seven-tab axe loops -> four tabs + three sections + panel
  (edit and read-only); narrow widths add panel overflow and axe
- editor-drawings: tab Vues -> openSection views; tab Annotations ->
  showDrawing
- editor-structures: tab Général (categories) -> openSection categories, axe
  label « general tab » -> « categories section »; tab Références ->
  openReferences/closeReferences; tab Vertèbres -> openSection regions; tab
  Annotations -> showDrawing
- editor-geometry: three tab Vues -> openSection views
- editor-equine: tab Général (categories add) -> openSection categories; five
  tabs loop -> two tabs + sections + panel; tab Annotations -> showDrawing
- editor-journey: tab Vues, tab Général (category), tab Annotations ->
  openSection views/categories, showDrawing; frozen axe scrolls to the header
- lan/trial-lan (not run): tab Vues -> Annotations tab + views entry

Verified: typecheck, lint, vitest 107 files / 1125 tests, whole shell suite on
the sandbox 151 passed, 49 skipped, 0 failed.
2026-11-06 20:25:35 +01:00

384 lines
14 KiB
TypeScript

/** Lot G: Vues et illustrations (states, detail views, crop group under the frame check). */
import { createHash } from 'node:crypto'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
NewElement,
} from '@faunosteo/core-wasm/types'
import ViewsSection from '@/components/editor/annotations/sections/ViewsSection'
import { useLocaleStore } from '@/state/localeStore'
import { ASSET, emptyText, insert, point } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
sb,
store,
versionAnswer,
} from '../helpers/editorHarness'
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(),
}))
const props = { readOnly: false, navigate: vi.fn(), reloadSheet: vi.fn() }
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const detail = (
viewBox: object | null = { min_x: 0, min_y: 0, width: 100, height: 100 },
) =>
({
kind: 'view',
value: {
kind: 'detail',
id: 'view-d',
name: { fr: 'Détail', en: 'Detail' },
svg_asset_id: null,
view_box: viewBox,
parent_view_id: 'view-main',
},
}) as NewElement
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
async function openCrop(text: string) {
await openReady({ text })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
await user.click(
screen.getByRole('button', { name: 'Modifier le recadrage' }),
)
return user
}
const CROP_IDS: Record<string, string> = {
'x minimum': 'min_x',
'y minimum': 'min_y',
largeur: 'width',
hauteur: 'height',
}
const cropField = (name: string) =>
document.getElementById(
`view-view-d-crop-${CROP_IDS[name]}`,
) as HTMLInputElement
describe('Vues et illustrations: drawing states', () => {
it('a valid main drawing shows its state and no hint', async () => {
await openReady()
render(<ViewsSection {...props} />)
expect(screen.getByText('Illustration valide')).toBeTruthy()
expect(
screen.queryByText(/Utilisez « Choisir une illustration »/),
).toBeNull()
})
it('a main view without drawing shows the hint pointing at the button', async () => {
await openReady({ text: emptyText() })
render(<ViewsSection {...props} />)
expect(screen.getByText('Aucune illustration')).toBeTruthy()
expect(
screen.getByText(/Utilisez « Choisir une illustration »/),
).toBeTruthy()
expect(screen.getByText(/n'est pas mesurable/)).toBeTruthy()
expect(
screen.getByRole('button', { name: 'Choisir une illustration' }),
).toBeTruthy()
})
it('a drawing the handle lacks reads as not found', async () => {
store.getState().close()
sb.getSheetVersion.mockResolvedValue(
versionAnswer(baseText(), 3, false) as never,
)
store.getState().open('ver-1', 'user-1', { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
render(<ViewsSection {...props} />)
expect(screen.getByText(/Illustration introuvable/)).toBeTruthy()
expect(
screen.getByText(/Utilisez « Choisir une illustration »/),
).toBeTruthy()
})
it('a rejected drawing shows the closed not-canonical message, no raw detail', async () => {
const bytes = new TextEncoder().encode(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <rect width="4" height="4"/></svg>',
)
const sha256 = createHash('sha256').update(bytes).digest('hex')
store.getState().close()
sb.getSheetVersion.mockResolvedValue({
...versionAnswer(baseText(), 3, false),
drawings: [{ asset_id: ASSET, sha256 }],
} as never)
sb.downloadSheetDrawing.mockResolvedValue(bytes)
store.getState().open('ver-1', 'user-1', { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
render(<ViewsSection {...props} />)
expect(
screen.getByText(
/Illustration refusée : elle n'est pas sous la forme enregistrée/,
),
).toBeTruthy()
expect(screen.queryByText(/not_canonical/)).toBeNull()
})
it('bytes that fail the hash check at load show their own message, not « introuvable »', async () => {
store.getState().close()
sb.getSheetVersion.mockResolvedValue(
versionAnswer(baseText(), 3, true) as never,
)
sb.downloadSheetDrawing.mockResolvedValue(
new TextEncoder().encode('<svg/>'),
)
store.getState().open('ver-1', 'user-1', { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
render(<ViewsSection {...props} />)
expect(
screen.getByText(/ne correspond pas à son empreinte SHA-256 enregistrée/),
).toBeTruthy()
expect(screen.queryByText(/introuvable/)).toBeNull()
})
it('use-parent asks first: cancel changes nothing, confirm commits once, undo restores', async () => {
const own = detail()
;(own.value as { svg_asset_id: string | null }).svg_asset_id = ASSET
await openReady({ text: insert(baseText(), own) })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
const open = () =>
user.click(
screen.getByRole('button', {
name: "Utiliser l'illustration de la vue parente",
}),
)
await open()
const dialog = screen.getByRole('dialog')
expect(dialog).toHaveTextContent(/reste enregistré/)
await user.click(within(dialog).getByRole('button', { name: 'Annuler' }))
expect(doc().views[1]).toMatchObject({ svg_asset_id: ASSET })
expect(store.getState().undo).toHaveLength(0)
await open()
await user.click(
within(screen.getByRole('dialog')).getByRole('button', {
name: "Utiliser l'illustration parente",
}),
)
expect(doc().views[1]).toMatchObject({ svg_asset_id: null })
expect(store.getState().undo).toHaveLength(1)
store.getState().undoStep()
expect(doc().views[1]).toMatchObject({ svg_asset_id: ASSET })
})
it('read-only shows states as text and no action', async () => {
await openReady({ text: insert(baseText(), detail()) })
render(<ViewsSection {...props} readOnly />)
expect(screen.getByText('Illustration valide')).toBeTruthy()
expect(screen.queryByRole('button')).toBeNull()
expect(screen.queryByRole('textbox')).toBeNull()
})
})
describe('Vues et illustrations: detail views', () => {
it('adds a detail view with names and a crop, in one insert', async () => {
await openReady()
const user = userEvent.setup()
render(<ViewsSection {...props} />)
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(screen.getByRole('alert')).toHaveTextContent('Renseignez les noms')
await user.type(document.getElementById('view-new-fr')!, 'Tête')
await user.type(document.getElementById('view-new-en')!, 'Head')
await user.type(document.getElementById('view-new-crop-min_x')!, '10')
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(screen.getByRole('alert')).toHaveTextContent('quatre valeurs')
expect(doc().views).toHaveLength(1)
for (const [key, value] of [
['min_y', '20'],
['width', '30'],
['height', '40'],
]) {
await user.type(document.getElementById(`view-new-crop-${key}`)!, value)
}
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(doc().views).toHaveLength(2)
expect(doc().views[1]).toMatchObject({
kind: 'detail',
name: { fr: 'Tête', en: 'Head' },
parent_view_id: 'view-main',
svg_asset_id: null,
view_box: { min_x: 10, min_y: 20, width: 30, height: 40 },
})
expect(doc().views[1].id).toMatch(/^view-[a-z2-7]{10}$/)
})
it('renames on blur and refuses a blank name locally', async () => {
await openReady({ text: insert(baseText(), detail()) })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
const name = document.getElementById('view-view-d-name-en')!
await user.clear(name)
await user.type(name, 'Lower leg')
await user.tab()
expect(doc().views[1].name).toEqual({ fr: 'Détail', en: 'Lower leg' })
await user.clear(document.getElementById('view-view-d-name-fr')!)
await user.tab()
expect(screen.getByText('Ce champ est obligatoire.')).toBeTruthy()
expect(doc().views[1].name.fr).toBe('Détail')
})
it('deleting a view that holds an annotation lists the dependents', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
await openReady({ text })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/ne peut pas être supprimé/)).toBeTruthy()
expect(doc().views).toHaveLength(2)
})
})
describe('Vues et illustrations: crop group under the frame check', () => {
it('refuses a crop that pushes a point out and keeps the typed values', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
const user = await openCrop(text)
const before = store.getState().documentText
await user.clear(cropField('x minimum'))
await user.type(cropField('x minimum'), '60{Enter}')
const alert = screen.getByRole('alert')
expect(alert).toHaveTextContent('Non appliqué')
expect(alert).toHaveTextContent(/géométrie de : N/)
expect(store.getState().documentText).toBe(before)
expect(store.getState().undo).toHaveLength(0)
expect(cropField('x minimum')).toHaveValue('60')
await user.click(
screen.getByRole('button', { name: 'Revenir aux valeurs enregistrées' }),
)
expect(cropField('x minimum')).toHaveValue('0')
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('applies the four fields as one group when they fit', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
const user = await openCrop(text)
await user.clear(cropField('x minimum'))
await user.type(cropField('x minimum'), '20')
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '60{Enter}')
expect(doc().views[1]).toMatchObject({
view_box: { min_x: 20, width: 60, height: 100 },
})
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('accepts a crop change when only an already invalid point is affected', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-bad', 150, 50, 5, 'view-d'),
)
const user = await openCrop(text)
expect(
store
.getState()
.previewState?.report.issues.some((i) => i.path.endsWith('.geometry')),
).toBe(true)
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '90{Enter}')
expect(doc().views[1]).toMatchObject({ view_box: { width: 90 } })
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('refuses a crop span the core cannot measure while the view holds annotations', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
const user = await openCrop(text)
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '0.5')
await user.clear(cropField('hauteur'))
await user.type(cropField('hauteur'), '0.5{Enter}')
expect(screen.getByRole('alert')).toHaveTextContent('Non appliqué')
expect(screen.getByRole('alert')).toHaveTextContent(
/non mesurable|géométrie de/,
)
expect(doc().views[1]).toMatchObject({ view_box: { width: 100 } })
})
it('a partial group is not applied and says so; an unchanged number commits nothing', async () => {
const user = await openCrop(insert(baseText(), detail()))
await user.clear(cropField('hauteur'))
await user.type(cropField('hauteur'), '{Enter}')
expect(screen.getByRole('alert')).toHaveTextContent(
'Indiquez les quatre valeurs',
)
await user.click(
screen.getByRole('button', { name: 'Revenir aux valeurs enregistrées' }),
)
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '100.0{Enter}')
expect(store.getState().undo).toHaveLength(0)
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('draws the crop rectangle over the parent canvas, numbers only', async () => {
await openCrop(
insert(
baseText(),
detail({ min_x: 10, min_y: 20, width: 30, height: 40 }),
),
)
const rect = screen.getByTestId('crop-overlay').querySelector('rect')!
expect(rect.getAttribute('x')).toBe('10')
expect(rect.getAttribute('height')).toBe('40')
expect(
screen.getByTestId('crop-canvas-drawing').querySelector('svg'),
).not.toBeNull()
})
it('a parent change commits through the frame check', async () => {
const text = insert(insert(baseText(), detail()), detail2())
await openReady({ text })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
await user.selectOptions(
document.getElementById('view-view-d-parent')!,
'view-e',
)
expect(doc().views[1]).toMatchObject({ parent_view_id: 'view-e' })
})
})
function detail2(): NewElement {
return {
kind: 'view',
value: {
kind: 'detail',
id: 'view-e',
name: { fr: 'Autre', en: 'Other' },
svg_asset_id: null,
view_box: { min_x: 0, min_y: 0, width: 50, height: 50 },
parent_view_id: 'view-main',
},
}
}