Files
faunosteo/apps/app/tests/unit/components.AnatomyCanvas.test.tsx
T

196 lines
8.0 KiB
TypeScript

import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import { buildViewSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { bundledSheet, loadTestSheet, sheetFromBundle } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
afterEach(cleanup)
/** The composed view, or a test failure naming why it is missing. */
function svgOf(index: SheetIndex, viewId: string): SVGSVGElement {
const build = buildViewSvg(index, viewId)
if (!build.ok) throw new Error(`${viewId}: ${build.failure}`)
return build.svg
}
/** The bundled sheet with its drawing replaced by `svg` (a hostile asset). */
async function sheetDrawing(svg: string): Promise<SheetIndex> {
const bundle = await bundledSheet()
const assets = Object.fromEntries(Object.keys(bundle.assets).map((id) => [id, svg]))
return sheetFromBundle({ ...bundle, assets })
}
describe('buildViewSvg', () => {
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
const main = svgOf(sheet, 'main')
const head = svgOf(sheet, 'head')
expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
expect(main.querySelectorAll('path').length).toBe(
head.querySelectorAll('path').length,
)
expect(main.querySelectorAll('[data-layer="annotations"]')).toHaveLength(1)
expect(main.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(2)
expect(head.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(0)
expect(head.querySelectorAll('[data-anno-id="atm"]')).toHaveLength(2)
expect(main.hasAttribute('width')).toBe(false)
})
it('composes the view once per sheet (a constant text) and carries no state', () => {
expect(sheet.canvasSvg('main')).toEqual(sheet.canvasSvg('main'))
expect(svgOf(sheet, 'main').querySelector('[data-state]')).toBeNull()
})
it('refuses a drawing the core would have to alter: nothing of it reaches the page (LRN-025)', async () => {
const hostile = await sheetDrawing(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><script>alert(1)</script><g onclick="x()"><a href="javascript:void(0)"><path d="M0 0"/></a></g><foreignObject/></svg>',
)
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
expect(buildViewSvg(hostile, 'main')).toEqual({ ok: false, failure: 'view' })
const malformed = await sheetDrawing('<not svg')
expect(malformed.canvasSvg('main')).toMatchObject({
ok: false,
kind: 'svg_rejected',
detail: 'malformed',
})
})
})
describe('AnatomyCanvas', () => {
it('renders the view and delegates clicks on the generated markers to onZoneClick with the view id', async () => {
const onZoneClick = vi.fn()
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={onZoneClick}
/>,
)
await waitFor(() =>
expect(
container.querySelector('[data-anno-id="head-trigger"]'),
).not.toBeNull(),
)
const hip = container.querySelector('circle[data-anno-id="hip"]')!
hip.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledWith('hip', 'main')
container
.querySelector('path')!
.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledTimes(1)
})
it('applies the states right after the build, on both elements of a point', async () => {
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['stifle', 'current']])}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="stifle"]')).not.toBeNull(),
)
const marked = Array.from(
container.querySelectorAll('[data-state="current"]'),
).map((el) => el.getAttribute('data-anno-id'))
expect(marked).toEqual(['stifle', 'stifle'])
})
it('names a view it cannot draw, offers no retry and keeps the drawing and the draft as they are', async () => {
useLocaleStore.setState({ locale: 'fr' })
const drawing = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
const hostile = await sheetDrawing(drawing)
sessionStorage.setItem('osteo:draft', '{"kept":true}')
const { container } = render(
<AnatomyCanvas index={hostile} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(fr['canvas.view_unavailable']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
expect(container.querySelector('script, [data-layer], [data-anno-id]')).toBeNull()
// The refused drawing stays the bundle's own text; the session is untouched.
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
expect(sessionStorage.getItem('osteo:draft')).toBe('{"kept":true}')
})
it('offers a retry when the engine did not run, and draws the view once it does', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
let engineDown = true
const flaky = Object.create(sheet) as SheetIndex
flaky.canvasSvg = (viewId: string) =>
engineDown ? { ok: false, kind: 'core_unavailable' } : sheet.canvasSvg(viewId)
const { container } = render(
<AnatomyCanvas index={flaky} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.queryByText(fr['canvas.view_unavailable']!)).toBeNull()
engineDown = false
await user.click(screen.getByRole('button', { name: fr['sheet.core_retry'] }))
await waitFor(() => expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull())
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
})
it('words both failures in English too', async () => {
useLocaleStore.setState({ locale: 'en' })
const hostile = await sheetDrawing('<svg xmlns="http://www.w3.org/2000/svg"><script/></svg>')
const first = render(
<AnatomyCanvas index={hostile} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(en['canvas.view_unavailable']!)
first.unmount()
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(en['sheet.core_unavailable']!)
expect(screen.getByRole('button', { name: en['sheet.core_retry'] })).toBeInTheDocument()
useLocaleStore.setState({ locale: 'fr' })
})
it('restyles in place when the states change', async () => {
const { container, rerender } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull(),
)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['hip', 'current']])}
onZoneClick={() => undefined}
/>,
)
expect(
container.querySelectorAll('[data-anno-id="hip"][data-state="current"]'),
).toHaveLength(2)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
expect(container.querySelectorAll('[data-state="current"]')).toHaveLength(0)
})
})