Administration page (board 10), species, rights, official sheets list with filters, creation from the core's empty document, overview with the working-copy action; catalogue list (search by sheet name), sheet and version pages through PreviewSheet with zoom and pan. App 650, typecheck, lint, build green.
336 lines
16 KiB
TypeScript
336 lines
16 KiB
TypeScript
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
|
import userEvent from '@testing-library/user-event'
|
|
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
|
import type { PreviewState } from '@faunosteo/core-wasm/types'
|
|
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
|
|
import { bundledSheet } from '../helpers/sheet'
|
|
|
|
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
|
|
vi.mock('@/lib/supabase', () => ({
|
|
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
|
|
isSupabaseConfigured: () => mocks.fake !== null,
|
|
}))
|
|
|
|
import CatalogRoute from '@/app/routes/app/anatomy/CatalogRoute'
|
|
import SheetRoute from '@/app/routes/app/anatomy/SheetRoute'
|
|
import { coreRuntime } from '@/core/runtime'
|
|
import { CataloguePreview } from '@/catalogue/preview'
|
|
import { coreFailure, serverFailure } from '@/catalogue/failure'
|
|
import { SheetFailure } from '@faunosteo/supabase'
|
|
import { useAuthStore } from '@/state/authStore'
|
|
import { useLocaleStore } from '@/state/localeStore'
|
|
import { fr } from '@/i18n/fr'
|
|
|
|
/**
|
|
* The catalogue screens (V1-2.5 slice I, boards 01 to 03) on a fake client and
|
|
* the real core: the equine draft stands for a published version, its
|
|
* drawing served as Storage would, so the core checks the hash, the
|
|
* fingerprint and the caps exactly as in the browser.
|
|
*/
|
|
const SHEET = '503dc301-0000-4000-8000-000000000001'
|
|
const OTHER = '503dc301-0000-4000-8000-000000000002'
|
|
const V1 = 'aaaaaaaa-0000-4000-8000-000000000001'
|
|
const V2 = 'aaaaaaaa-0000-4000-8000-000000000002'
|
|
const V3 = 'aaaaaaaa-0000-4000-8000-000000000003'
|
|
const DOG = 'bbbbbbbb-0000-4000-8000-000000000001'
|
|
|
|
let fake: FakeSupabase
|
|
let document: unknown
|
|
let assetId: string
|
|
let sha256: string
|
|
let bytes: Uint8Array<ArrayBuffer>
|
|
let fingerprint: string
|
|
|
|
beforeAll(async () => {
|
|
const bundle = await bundledSheet()
|
|
document = bundle.document
|
|
;[assetId] = Object.keys(bundle.assets)
|
|
sha256 = bundle.assetHashes[assetId]
|
|
bytes = new TextEncoder().encode(bundle.assets[assetId])
|
|
// The fingerprint a publication stores: the core's, read from a draft preview.
|
|
const draft = new CataloguePreview(
|
|
coreRuntime(),
|
|
{ status: 'draft', document: JSON.stringify(document) },
|
|
[{ assetId, sha256, bytes }],
|
|
)
|
|
const state = draft.state()
|
|
if (!state.ok || !state.value.fingerprint) throw new Error('draft preview refused')
|
|
fingerprint = state.value.fingerprint
|
|
draft.free()
|
|
})
|
|
|
|
function versionAnswer(id: string, status: 'published' | 'deprecated', patch: Record<string, unknown> = {}) {
|
|
return {
|
|
sheet_id: SHEET,
|
|
version_id: id,
|
|
version_number: Number(id.slice(-1)),
|
|
status,
|
|
species_id: 'equine',
|
|
document,
|
|
revision: 1,
|
|
// PreviewSheet requires the stored fingerprint for deprecated versions too, while
|
|
// `get_sheet_version` returns it for published ones only (gap reported at V1-2.5).
|
|
fingerprint,
|
|
drawings: [{ asset_id: assetId, sha256, byte_size: bytes.length }],
|
|
...patch,
|
|
}
|
|
}
|
|
|
|
/** `get_sheet_version` answers per id, as the server would; unknown ids are `not_found`. */
|
|
function serveVersions(answers: Record<string, unknown>) {
|
|
fake.rpcResults.get_sheet_version = () => {
|
|
const [, args] = fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').at(-1)!
|
|
const answer = answers[(args as { version_id: string }).version_id]
|
|
return answer ? { data: answer } : { error: { message: 'not_found', code: '42501' } }
|
|
}
|
|
}
|
|
|
|
function mount(path: string) {
|
|
return render(
|
|
<MemoryRouter initialEntries={[path]}>
|
|
<Routes>
|
|
<Route path="/app/anatomy" element={<CatalogRoute />} />
|
|
<Route path="/app/anatomy/:sheetId" element={<SheetRoute />} />
|
|
<Route path="/app/anatomy/:sheetId/versions/:number" element={<SheetRoute />} />
|
|
</Routes>
|
|
</MemoryRouter>,
|
|
)
|
|
}
|
|
|
|
beforeEach(() => {
|
|
useLocaleStore.setState({ locale: 'fr' })
|
|
useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), catalogGrants: [] })
|
|
fake = createFakeSupabase()
|
|
fake.tables.species = [
|
|
{ id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 1 },
|
|
{ id: 'canine', name_fr: 'Chien', name_en: 'Dog', sort_order: 2 },
|
|
]
|
|
fake.tables.anatomical_sheet_versions = [
|
|
{ sheet_id: SHEET, id: V3, version_number: 3, status: 'published', published_at: '2026-10-28T10:00:00Z', deprecated_at: null },
|
|
{ sheet_id: SHEET, id: V2, version_number: 2, status: 'deprecated', published_at: '2026-10-20T10:00:00Z', deprecated_at: '2026-10-28T10:00:00Z' },
|
|
{ sheet_id: SHEET, id: V1, version_number: 1, status: 'published', published_at: '2026-10-10T10:00:00Z', deprecated_at: null },
|
|
]
|
|
fake.rpcResults.list_official_catalog = {
|
|
data: [
|
|
{ sheet_id: SHEET, species_id: 'equine', slug: 'cheval', name: { fr: 'Cheval', en: 'Horse' }, description: {}, version_number: 3, version_id: V3 },
|
|
{ sheet_id: OTHER, species_id: 'canine', slug: 'chien', name: { fr: 'Chien, rachis', en: 'Dog spine' }, description: {}, version_number: 1, version_id: DOG },
|
|
],
|
|
}
|
|
serveVersions({ [V3]: versionAnswer(V3, 'published'), [V2]: versionAnswer(V2, 'deprecated'), [V1]: versionAnswer(V1, 'published') })
|
|
fake.storage.download.mockImplementation(async () => ({ data: new Blob([bytes]), error: null }))
|
|
mocks.fake = fake
|
|
})
|
|
afterEach(() => cleanup())
|
|
|
|
describe('/app/anatomy', () => {
|
|
it('shows each published sheet with its species, status, version line and link', async () => {
|
|
mount('/app/anatomy')
|
|
expect(await screen.findByRole('heading', { level: 1, name: fr['shell.nav.anatomy'] })).toBeInTheDocument()
|
|
const card = (await screen.findByRole('heading', { level: 2, name: 'Cheval' })).closest('article')!
|
|
expect(within(card).getByText(fr['catalogue.status.published'])).toBeInTheDocument()
|
|
expect(within(card).getByText('Cheval', { selector: 'span' })).toBeInTheDocument()
|
|
expect(
|
|
await within(card).findByText('Version 3 · publiée le 28/10/2026 · 2 vues, 27 zones de constats'),
|
|
).toBeInTheDocument()
|
|
// The thumbnail is the core's composed main view, as an image (never inserted as markup).
|
|
expect(card.querySelector('img')?.getAttribute('src')).toMatch(/^blob:/)
|
|
expect(within(card).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
|
|
// The card whose version cannot be read keeps its name, version and link.
|
|
const dog = screen.getByRole('heading', { level: 2, name: 'Chien, rachis' }).closest('article')!
|
|
expect(within(dog).getByText('Version 1')).toBeInTheDocument()
|
|
})
|
|
|
|
it('searches by sheet name in either language and filters by species', async () => {
|
|
mount('/app/anatomy')
|
|
await screen.findByRole('heading', { level: 2, name: 'Cheval' })
|
|
const search = screen.getByRole('searchbox', { name: fr['catalogue.search'] })
|
|
await userEvent.type(search, 'dog')
|
|
expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull()
|
|
expect(screen.getByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeInTheDocument()
|
|
await userEvent.clear(search)
|
|
await userEvent.type(search, 'thoracique')
|
|
expect(screen.getByText(fr['catalogue.no_results'])).toBeInTheDocument()
|
|
await userEvent.clear(search)
|
|
const chips = screen.getByRole('group', { name: fr['catalogue.species_filter'] })
|
|
expect(within(chips).getAllByRole('button').map((b) => b.textContent)).toEqual([
|
|
fr['catalogue.all_species'],
|
|
'Cheval',
|
|
'Chien',
|
|
])
|
|
await userEvent.click(within(chips).getByRole('button', { name: 'Cheval' }))
|
|
expect(screen.getByRole('heading', { level: 2, name: 'Cheval' })).toBeInTheDocument()
|
|
expect(screen.queryByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeNull()
|
|
})
|
|
|
|
it('says when no sheet is published', async () => {
|
|
fake.rpcResults.list_official_catalog = { data: [] }
|
|
mount('/app/anatomy')
|
|
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
|
|
})
|
|
|
|
it('shows « Accès non autorisé » on the server refusal', async () => {
|
|
fake.rpcResults.list_official_catalog = { error: { message: 'rights.catalog', code: '42501' } }
|
|
mount('/app/anatomy')
|
|
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
|
|
})
|
|
|
|
it('names an unavailable server and reads again on retry', async () => {
|
|
fake.rpcResults.list_official_catalog = { error: { message: 'boom' } }
|
|
mount('/app/anatomy')
|
|
expect(await screen.findByText(fr['catalogue.failure.unavailable'])).toBeInTheDocument()
|
|
fake.rpcResults.list_official_catalog = { data: [] }
|
|
await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
|
|
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
|
|
})
|
|
})
|
|
|
|
describe('/app/anatomy/:sheetId', () => {
|
|
it('shows the current version: views, zone panel, references and disclaimer', async () => {
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
expect(await screen.findByRole('heading', { level: 1, name: 'Cheval' })).toBeInTheDocument()
|
|
expect(screen.getByText('Version 3 · publiée le 28/10/2026')).toBeInTheDocument()
|
|
const tabs = screen.getAllByRole('tab')
|
|
expect(tabs.map((tab) => tab.textContent)).toEqual(['Vue latérale gauche', 'Tête (vue latérale gauche)'])
|
|
expect(tabs[0]).toHaveAttribute('aria-selected', 'true')
|
|
const canvas = screen.getByTestId('catalogue-canvas-drawing')
|
|
await waitFor(() => expect(canvas.querySelector('svg')).not.toBeNull())
|
|
fireEvent.click(canvas.querySelector('[data-anno-id="thoracic"]')!)
|
|
expect(screen.getByRole('heading', { name: 'Zone : Vertèbres thoraciques' })).toBeInTheDocument()
|
|
expect(screen.getByText('Catégorie : Segments vertébraux · vertèbres T1 à T18')).toBeInTheDocument()
|
|
expect(screen.getByRole('heading', { level: 3, name: 'Dysfonctions ostéopathiques' })).toBeInTheDocument()
|
|
expect(canvas.querySelector('[data-anno-id="thoracic"]')).toHaveAttribute('data-state', 'current')
|
|
expect(screen.getByRole('heading', { name: fr['catalogue.references.title'] })).toBeInTheDocument()
|
|
expect(screen.getByText(/Code rural et de la pêche maritime, art\. L\. 243-3/)).toBeInTheDocument()
|
|
expect(screen.getByText(/Aucun diagnostic médical n'est posé/)).toBeInTheDocument()
|
|
// No capability: no link to the administration.
|
|
expect(screen.queryByRole('link', { name: fr['catalogue.open_admin'] })).toBeNull()
|
|
})
|
|
|
|
it('opens the detail view from its link on the drawing', async () => {
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
const canvas = await screen.findByTestId('catalogue-canvas-drawing')
|
|
await waitFor(() => expect(canvas.querySelector('[data-anno-id="head-trigger"]')).not.toBeNull())
|
|
fireEvent.click(canvas.querySelector('[data-anno-id="head-trigger"]')!)
|
|
expect(screen.getByRole('tab', { name: 'Tête (vue latérale gauche)' })).toHaveAttribute('aria-selected', 'true')
|
|
})
|
|
|
|
it('lists the versions with the « Retirée » mark, each linking to its page', async () => {
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
await userEvent.click(await screen.findByRole('button', { name: '2 versions antérieures' }))
|
|
const list = screen.getByRole('list', { name: fr['catalogue.versions.title'] })
|
|
const links = within(list).getAllByRole('link')
|
|
expect(links.map((l) => l.getAttribute('href'))).toEqual([3, 2, 1].map((n) => `/app/anatomy/${SHEET}/versions/${n}`))
|
|
expect(links[0]).toHaveAttribute('aria-current', 'page')
|
|
expect(within(links[1]).getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
|
|
})
|
|
|
|
it('opens a retired version by number with its mark', async () => {
|
|
mount(`/app/anatomy/${SHEET}/versions/2`)
|
|
expect(await screen.findByText('Version 2 · publiée le 20/10/2026')).toBeInTheDocument()
|
|
expect(screen.getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
|
|
expect(fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').map(([, a]) => a)).toEqual([{ version_id: V2 }])
|
|
})
|
|
|
|
it('links an editor to the administration', async () => {
|
|
useAuthStore.setState({ catalogGrants: [{ kind: 'sheet_editor', expires_at: null, revoked_at: null }] })
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
expect(await screen.findByRole('link', { name: fr['catalogue.open_admin'] })).toHaveAttribute(
|
|
'href',
|
|
`/app/admin/sheets/${SHEET}`,
|
|
)
|
|
})
|
|
|
|
it.each([
|
|
['an unknown sheet', `/app/anatomy/${OTHER}`],
|
|
['a malformed id', '/app/anatomy/not-a-uuid'],
|
|
['an unknown number', `/app/anatomy/${SHEET}/versions/9`],
|
|
['a malformed number', `/app/anatomy/${SHEET}/versions/0`],
|
|
])('shows « Accès non autorisé » for %s', async (_case, path) => {
|
|
mount(path)
|
|
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
|
|
})
|
|
|
|
it('shows « Accès non autorisé » when the version read is refused', async () => {
|
|
serveVersions({})
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
|
|
})
|
|
|
|
it('zooms with the buttons and « Ajuster » brings the whole drawing back', async () => {
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
const drawing = await screen.findByTestId('catalogue-canvas-drawing')
|
|
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
|
|
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
|
|
expect(drawing.style.transform).toContain('scale(1.5)')
|
|
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
|
|
expect(drawing.style.transform).toContain('scale(2.25)')
|
|
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.out'] }))
|
|
expect(drawing.style.transform).toContain('scale(1.5)')
|
|
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.fit'] }))
|
|
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
|
|
// The keyboard on the focused box: + zooms, 0 fits.
|
|
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '+' })
|
|
expect(drawing.style.transform).toContain('scale(1.5)')
|
|
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '0' })
|
|
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
|
|
})
|
|
})
|
|
|
|
describe('failures', () => {
|
|
it.each([
|
|
[
|
|
'a drawing whose bytes do not hash to its row',
|
|
() => {
|
|
const altered = bytes.slice()
|
|
altered[200] ^= 1
|
|
fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null }))
|
|
},
|
|
'catalogue.failure.drawing_hash_mismatch',
|
|
],
|
|
[
|
|
'a stored fingerprint the core does not recompute',
|
|
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }),
|
|
'catalogue.failure.fingerprint_mismatch',
|
|
],
|
|
[
|
|
'a drawing Storage does not give',
|
|
() =>
|
|
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })),
|
|
'catalogue.failure.drawing_missing',
|
|
],
|
|
[
|
|
'an unreadable document',
|
|
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }),
|
|
'catalogue.failure.invalid_document',
|
|
],
|
|
])('names %s', async (_case, arrange, key) => {
|
|
arrange()
|
|
mount(`/app/anatomy/${SHEET}`)
|
|
expect(await screen.findByText(fr[key])).toBeInTheDocument()
|
|
expect(screen.getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
|
|
})
|
|
|
|
it('folds server and core kinds into the closed page kinds', () => {
|
|
expect(serverFailure(new SheetFailure('rights.catalog'))).toBe('denied')
|
|
expect(serverFailure(new SheetFailure('not_found'))).toBe('denied')
|
|
expect(serverFailure(new SheetFailure('network'))).toBe('network')
|
|
expect(serverFailure(new SheetFailure('draft_conflict'))).toBe('unavailable')
|
|
expect(coreFailure('caps')).toBe('caps')
|
|
expect(coreFailure('internal')).toBe('core_unavailable')
|
|
expect(coreFailure('invalid_json')).toBe('invalid_document')
|
|
})
|
|
|
|
it('a freed preview never rebuilds its handle', () => {
|
|
const preview = new CataloguePreview(
|
|
coreRuntime(),
|
|
{ status: 'published', document: JSON.stringify(document), fingerprint },
|
|
[{ assetId, sha256, bytes }],
|
|
)
|
|
const state = preview.state()
|
|
expect(state.ok && (state.value as PreviewState).status).toBe('published')
|
|
preview.free()
|
|
expect(preview.canvas('main')).toEqual({ ok: false, kind: 'core_unavailable' })
|
|
})
|
|
})
|