fix(editor,pdf): accordion observation cards + seed 1 obs + native SVG rasterization

Three issues from manual QA:

1. UX restructure — observations are now an accordion list. Each card has
   a header that's always visible (title + chips + chevron + action
   buttons) and a body that expands inline showing zones / pathologies /
   severity / comment. Click the header (or the chevron) to toggle.
   ObservationEditor has been merged into ObservationCard so each card
   owns its own details. Only one observation is expanded at a time; the
   chevron on the active card collapses everything. EditorRoute uses
   activeObservationIndex === -1 to represent "all collapsed".

2. App used to start with 2 observations instead of 1. Root cause:
   EditorRoute had a "seed first observation" useEffect that fired twice
   under React 19 StrictMode in dev, both invocations seeing length=0 and
   queueing addObservation(). Fixed by moving the seed into the store's
   initReport (synchronous, one-shot) and removing the useEffect entirely.
   Store tests updated to assert the seed behaviour (90/90 pass).

3. PDF export still failed with "The input is not a PNG file!" — canvg
   was returning bytes that pdf-lib rejected at embedPng(). Switched
   rasterizeSvg to the browser-native pipeline: serialize the SVG into a
   Blob URL, load it with an Image element, drawImage onto a 2D canvas,
   then toBlob → PNG bytes (with a toDataURL fallback). Validates the
   PNG signature before returning. Tree-shaking dropped canvg from the
   bundle (979 kB → 874 kB JS).

Tests updated for the new initReport behaviour and the new svgToPng
pipeline (Image mock + dataURL fallback case). lint + typecheck + build
all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bastien ChanotandClaude Opus 4.7 committed 2026-05-18 23:32:01 +02:00
1 parent bdf5e6475b
commit e8c29c1fdf
7 files changed
+449 -113

No files matched your search

+56 -38
View File
@@ -3,7 +3,6 @@ import { useNavigate } from 'react-router-dom'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import DetailModal from '@/components/canvas/DetailModal'
import ObservationList from '@/components/observation/ObservationList'
import ObservationEditor from '@/components/observation/ObservationEditor'
import VertebraPicker from '@/components/observation/VertebraPicker'
import ConclusionPanel from '@/components/report/ConclusionPanel'
import ReportHeader from '@/components/report/ReportHeader'
@@ -33,7 +32,11 @@ export default function EditorRoute() {
const [bones, setBones] = useState<Map<string, Bone>>(new Map())
const [pathologies, setPathologies] = useState<Pathology[]>([])
const [detail, setDetail] = useState<{ id: string; src: string; title: string } | null>(null)
const [detail, setDetail] = useState<{
id: string
src: string
title: string
} | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
const [exporting, setExporting] = useState(false)
@@ -52,12 +55,8 @@ export default function EditorRoute() {
species.pathologies().then((m) => setPathologies(m.default))
}, [species])
const observationsCount = report?.observations.length ?? -1
useEffect(() => {
if (observationsCount === 0) addObservation()
}, [observationsCount, addObservation])
const activeObs = report?.observations[activeIndex]
const activeObs =
activeIndex >= 0 ? report?.observations[activeIndex] : undefined
const boneStates = useMemo<Map<string, BoneState>>(() => {
const map = new Map<string, BoneState>()
@@ -77,8 +76,12 @@ export default function EditorRoute() {
return map
}, [report, activeIndex])
function onToggleCard(index: number) {
setActiveObservation(activeIndex === index ? -1 : index)
}
function onZoneClick(boneId: string, detailSourceId?: string) {
if (!report || !activeObs) return
if (!report) return
const bone = bones.get(boneId)
if (!bone) return
@@ -91,6 +94,17 @@ export default function EditorRoute() {
return
}
if (!activeObs || activeIndex < 0) {
// No expanded observation — auto-expand the most recent one (or the
// first if no rows yet) so the click lands somewhere.
const fallbackIndex =
report.observations.length > 0 ? report.observations.length - 1 : -1
if (fallbackIndex < 0) return
setActiveObservation(fallbackIndex)
// Defer the actual zone add to the next render where activeObs is set.
return
}
const newZone: ObservationZone = {
boneId,
...(detailSourceId ? { detailSourceId } : {}),
@@ -132,7 +146,7 @@ export default function EditorRoute() {
}
}
if (!report || !species || !activeObs) return null
if (!report || !species) return null
return (
<main className="min-h-screen flex flex-col">
@@ -149,22 +163,23 @@ export default function EditorRoute() {
<ObservationList
observations={report.observations}
activeIndex={activeIndex}
onSelect={setActiveObservation}
onToggle={onToggleCard}
onAdd={addObservation}
onDelete={removeObservation}
onMoveUp={moveObservationUp}
onMoveDown={moveObservationDown}
/>
<ObservationEditor
observation={activeObs}
bones={bones}
speciesId={species.id}
pathologyPool={pathologies}
onChange={(next: Observation) => updateObservation(activeIndex, next)}
onOpenVertebraPicker={(zoneIndex) => setVertebraTarget(zoneIndex)}
onRemoveZone={(zoneIndex) => {
const zones = activeObs.zones.filter((_, i) => i !== zoneIndex)
updateObservation(activeIndex, { ...activeObs, zones })
onChange={(i, next: Observation) => updateObservation(i, next)}
onOpenVertebraPicker={(_i, zoneIndex) =>
setVertebraTarget(zoneIndex)
}
onRemoveZone={(i, zoneIndex) => {
const obs = report.observations[i]
if (!obs) return
const zones = obs.zones.filter((_, k) => k !== zoneIndex)
updateObservation(i, { ...obs, zones })
}}
/>
<ConclusionPanel
@@ -195,26 +210,29 @@ export default function EditorRoute() {
/>
)}
{vertebraTarget !== null && activeObs.zones[vertebraTarget] && (
<VertebraPicker
open
onClose={() => setVertebraTarget(null)}
onConfirm={(vertebrae) => {
const fresh = useReportStore.getState().report?.observations[activeIndex]
if (!fresh?.zones[vertebraTarget]) {
{vertebraTarget !== null &&
activeObs &&
activeObs.zones[vertebraTarget] && (
<VertebraPicker
open
onClose={() => setVertebraTarget(null)}
onConfirm={(vertebrae) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (!fresh?.zones[vertebraTarget]) {
setVertebraTarget(null)
return
}
const next = [...fresh.zones]
next[vertebraTarget] = { ...next[vertebraTarget], vertebrae }
updateObservation(activeIndex, { ...fresh, zones: next })
setVertebraTarget(null)
return
}
const next = [...fresh.zones]
next[vertebraTarget] = { ...next[vertebraTarget], vertebrae }
updateObservation(activeIndex, { ...fresh, zones: next })
setVertebraTarget(null)
}}
initial={activeObs.zones[vertebraTarget].vertebrae ?? []}
formula={species.vertebralFormula}
title={`Préciser les vertèbres — ${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`}
/>
)}
}}
initial={activeObs.zones[vertebraTarget].vertebrae ?? []}
formula={species.vertebralFormula}
title={`Préciser les vertèbres — ${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`}
/>
)}
</main>
)
}
+160 -16
View File
@@ -1,39 +1,72 @@
import type { Observation } from '@/domain/schema/observation'
import type { Observation, ObservationZone, Vertebra } from '@/domain/schema/observation'
import type { Pathology } from '@/domain/schema/pathology'
import type { Bone } from '@/anatomy/types'
import { AnimatePresence, motion } from 'motion/react'
import Card from '@/components/ui/Card'
import Badge from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea'
import PathologyPicker from './PathologyPicker'
import FreeTextPathologyInput from './FreeTextPathologyInput'
import SeveritySelector from './SeveritySelector'
export interface ObservationCardProps {
observation: Observation
index: number
active: boolean
onSelect: () => void
expanded: boolean
onToggle: () => void
onDelete: () => void
onMoveUp: () => void
onMoveDown: () => void
canMoveUp: boolean
canMoveDown: boolean
// Editor body props (used only when expanded)
bones: Map<string, Bone>
speciesId: string
pathologyPool: Pathology[]
onChange: (next: Observation) => void
onOpenVertebraPicker: (zoneIndex: number) => void
onRemoveZone: (zoneIndex: number) => void
}
function describeZone(z: ObservationZone, bones: Map<string, Bone>): string {
const b = bones.get(z.boneId)
const label = b?.fr ?? z.boneId
if (z.vertebrae?.length) {
const vs = z.vertebrae
.map((v: Vertebra) => `${v.region}${v.index}`)
.join(', ')
return `${label} (${vs})`
}
return label
}
export default function ObservationCard({
observation,
index,
active,
onSelect,
expanded,
onToggle,
onDelete,
onMoveUp,
onMoveDown,
canMoveUp,
canMoveDown,
bones,
speciesId,
pathologyPool,
onChange,
onOpenVertebraPicker,
onRemoveZone,
}: ObservationCardProps) {
const zoneCount = observation.zones.length
const patCount =
observation.pathologyIds.length + observation.freeTextPathologies.length
function onCardKey(event: React.KeyboardEvent<HTMLDivElement>) {
function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onSelect()
onToggle()
}
}
@@ -44,11 +77,13 @@ export default function ObservationCard({
}
}
const zoneBoneIds = observation.zones.map((z) => z.boneId)
return (
<Card
className={[
'cursor-pointer p-4 transition',
active
'transition',
expanded
? 'ring-2 ring-[var(--color-accent)]'
: 'hover:bg-[var(--color-surface-strong)]',
].join(' ')}
@@ -56,11 +91,11 @@ export default function ObservationCard({
<div
role="button"
tabIndex={0}
aria-label={`Sélectionner l'observation ${index + 1}`}
aria-pressed={active}
onClick={onSelect}
onKeyDown={onCardKey}
className="flex items-start justify-between gap-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-lg"
aria-expanded={expanded}
aria-label={`${expanded ? 'Réduire' : 'Développer'} l'observation ${index + 1}`}
onClick={onToggle}
onKeyDown={onHeaderKey}
className="flex items-start justify-between gap-3 p-4 cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-2xl"
>
<div className="flex-1 min-h-[60px] text-left">
<div className="flex items-center gap-2 mb-2">
@@ -83,14 +118,14 @@ export default function ObservationCard({
{zoneCount} zone{zoneCount > 1 ? 's' : ''} · {patCount} pathologie
{patCount > 1 ? 's' : ''}
</div>
{observation.comment && (
{!expanded && observation.comment && (
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">
{observation.comment}
</p>
)}
</div>
<div
className="flex flex-col gap-1"
className="flex items-start gap-1"
onClick={(event) => event.stopPropagation()}
>
<Button
@@ -119,8 +154,117 @@ export default function ObservationCard({
>
🗑
</Button>
<Button
size="sm"
variant="ghost"
onClick={stop(onToggle)}
aria-label={expanded ? 'Réduire' : 'Développer'}
>
{expanded ? '▲' : '▼'}
</Button>
</div>
</div>
<AnimatePresence initial={false}>
{expanded && (
<motion.div
key="body"
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="overflow-hidden"
>
<div className="px-4 pb-4 pt-2 border-t border-[var(--color-border)] space-y-6">
<section>
<Label>Zones sélectionnées</Label>
{observation.zones.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
Cliquez sur les zones du schéma pour les ajouter à cette
observation.
</p>
) : (
<ul className="flex flex-wrap gap-2">
{observation.zones.map((z, i) => {
const b = bones.get(z.boneId)
const isSpine = b?.category === 'spine-zone'
return (
<li key={`${z.boneId}-${i}`}>
<Badge tone="accent" className="gap-2">
{describeZone(z, bones)}
{isSpine && (
<button
type="button"
onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]"
>
Préciser…
</button>
)}
<button
type="button"
aria-label={`Retirer ${b?.fr ?? z.boneId}`}
onClick={() => onRemoveZone(i)}
className="ml-1 text-[var(--color-accent-strong)]"
>
✕
</button>
</Badge>
</li>
)
})}
</ul>
)}
</section>
<section>
<Label>Pathologies (référence)</Label>
<PathologyPicker
pool={pathologyPool}
speciesId={speciesId}
boneIds={zoneBoneIds}
selected={observation.pathologyIds}
onChange={(ids) =>
onChange({ ...observation, pathologyIds: ids })
}
/>
</section>
<section>
<Label>Pathologies (texte libre)</Label>
<FreeTextPathologyInput
items={observation.freeTextPathologies}
onChange={(items) =>
onChange({ ...observation, freeTextPathologies: items })
}
/>
</section>
<section>
<Label>Sévérité</Label>
<SeveritySelector
value={observation.severity}
onChange={(s) => onChange({ ...observation, severity: s })}
/>
</section>
<section>
<Label htmlFor={`obs-comment-${observation.id}`}>
Commentaire
</Label>
<Textarea
id={`obs-comment-${observation.id}`}
value={observation.comment}
onChange={(e) =>
onChange({ ...observation, comment: e.target.value })
}
placeholder="Notes cliniques détaillées…"
/>
</section>
</div>
</motion.div>
)}
</AnimatePresence>
</Card>
)
}
+35 -7
View File
@@ -1,35 +1,55 @@
import type { Observation } from '@/domain/schema/observation'
import type { Pathology } from '@/domain/schema/pathology'
import type { Bone } from '@/anatomy/types'
import ObservationCard from './ObservationCard'
import Button from '@/components/ui/Button'
export interface ObservationListProps {
observations: Observation[]
activeIndex: number
onSelect: (i: number) => void
onToggle: (i: number) => void
onAdd: () => void
onDelete: (i: number) => void
onMoveUp: (i: number) => void
onMoveDown: (i: number) => void
// Editor body props forwarded to each card
bones: Map<string, Bone>
speciesId: string
pathologyPool: Pathology[]
onChange: (i: number, next: Observation) => void
onOpenVertebraPicker: (i: number, zoneIndex: number) => void
onRemoveZone: (i: number, zoneIndex: number) => void
}
export default function ObservationList({
observations,
activeIndex,
onSelect,
onToggle,
onAdd,
onDelete,
onMoveUp,
onMoveDown,
bones,
speciesId,
pathologyPool,
onChange,
onOpenVertebraPicker,
onRemoveZone,
}: ObservationListProps) {
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-serif text-xl text-[var(--color-ink)]">Observations</h2>
<Button size="sm" onClick={onAdd}>+ Nouvelle observation</Button>
<h2 className="font-serif text-xl text-[var(--color-ink)]">
Observations
</h2>
<Button size="sm" onClick={onAdd}>
+ Nouvelle observation
</Button>
</div>
{observations.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
Aucune observation. Cliquez sur &quot;+ Nouvelle observation&quot; puis sur les zones du schéma.
Aucune observation. Cliquez sur &quot;+ Nouvelle observation&quot;
puis sur les zones du schéma.
</p>
) : (
<ul className="space-y-2">
@@ -38,13 +58,21 @@ export default function ObservationList({
<ObservationCard
observation={obs}
index={i}
active={i === activeIndex}
onSelect={() => onSelect(i)}
expanded={i === activeIndex}
onToggle={() => onToggle(i)}
onDelete={() => onDelete(i)}
onMoveUp={() => onMoveUp(i)}
onMoveDown={() => onMoveDown(i)}
canMoveUp={i > 0}
canMoveDown={i < observations.length - 1}
bones={bones}
speciesId={speciesId}
pathologyPool={pathologyPool}
onChange={(next) => onChange(i, next)}
onOpenVertebraPicker={(zoneIndex) =>
onOpenVertebraPicker(i, zoneIndex)
}
onRemoveZone={(zoneIndex) => onRemoveZone(i, zoneIndex)}
/>
</li>
))}
+98 -32
View File
@@ -1,61 +1,127 @@
import { Canvg } from 'canvg'
const TARGET_WIDTH = 1200
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
export async function rasterizeSvg(
function startsWithPngSignature(bytes: Uint8Array): boolean {
if (bytes.length < PNG_SIGNATURE.length) return false
for (let i = 0; i < PNG_SIGNATURE.length; i += 1) {
if (bytes[i] !== PNG_SIGNATURE[i]) return false
}
return true
}
function ensureSvgAttributes(
svgString: string,
scale: number,
): Promise<Uint8Array> {
const tmp = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const root = tmp.documentElement
const vb = (root.getAttribute('viewBox') ?? '0 0 1000 600')
widthPx: number,
heightPx: number,
): string {
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const root = doc.documentElement
if (root.namespaceURI !== 'http://www.w3.org/2000/svg') {
// Some serializers strip xmlns; force the SVG namespace so
// browsers will rasterize the blob URL as an image.
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
}
if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx))
if (!root.getAttribute('height')) root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
function readViewBox(svgString: string): {
widthPx: number
heightPx: number
} {
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const vb = (doc.documentElement.getAttribute('viewBox') ?? '0 0 1000 600')
.split(/\s+/)
.map(Number)
const widthPx = Math.max(
1,
Math.round(TARGET_WIDTH * Math.max(1, scale) * 0.5),
)
const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6
const widthPx = Math.max(1, Math.round(TARGET_WIDTH))
const heightPx = Math.max(1, Math.round(ratio * widthPx))
return { widthPx, heightPx }
}
async function rasterizeWithImageElement(
svgString: string,
widthPx: number,
heightPx: number,
): Promise<HTMLCanvasElement> {
const normalized = ensureSvgAttributes(svgString, widthPx, heightPx)
const svgBlob = new Blob([normalized], {
type: 'image/svg+xml;charset=utf-8',
})
const url = URL.createObjectURL(svgBlob)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
try {
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve()
img.onerror = () =>
reject(new Error('Browser failed to render the SVG into an Image'))
img.src = url
})
} finally {
// The Blob URL is single-use — release it once the Image has loaded
// (or failed).
URL.revokeObjectURL(url)
}
const canvas = document.createElement('canvas')
canvas.width = widthPx
canvas.height = heightPx
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
// White background so the resulting PNG is opaque (some PDF viewers
// ignore transparent canvases when embedded).
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, widthPx, heightPx)
ctx.drawImage(img, 0, 0, widthPx, heightPx)
return canvas
}
try {
const canv = await Canvg.from(ctx, svgString, {
anonymousCrossOrigin: true,
})
await canv.render()
} catch (err) {
console.error('canvg render failed; falling back to blank canvas', err)
}
async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> {
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/png')
})
if (blob) return new Uint8Array(await blob.arrayBuffer())
// toBlob can return null in some browsers when the canvas state is
// unusual; fall back to toDataURL which is synchronous and broadly
// available.
if (blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
if (startsWithPngSignature(bytes)) return bytes
}
const dataUrl = canvas.toDataURL('image/png')
if (!dataUrl.startsWith('data:image/png')) {
throw new Error(
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
)
}
const comma = dataUrl.indexOf(',')
if (comma < 0) {
throw new Error('canvas.toDataURL returned an unexpected payload')
throw new Error('canvas.toDataURL returned a data URL without a payload')
}
const base64 = dataUrl.slice(comma + 1)
const binary = atob(base64)
const binary = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i)
}
if (!startsWithPngSignature(bytes)) {
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
}
return bytes
}
/**
* Rasterizes an SVG string to a PNG byte array using the browser's native
* SVG-to-Image pipeline. The browser parses + draws the SVG via an
* Image/Blob URL pair, which renders identically to what the user sees in
* the inline anatomy canvas.
*
* @param svgString Serialized SVG (must declare `xmlns`)
* @param _scale Reserved — current implementation renders at a fixed
* TARGET_WIDTH derived from the viewBox; kept for API
* compatibility.
*/
export async function rasterizeSvg(
svgString: string,
_scale: number,
): Promise<Uint8Array> {
const { widthPx, heightPx } = readViewBox(svgString)
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
return canvasToPngBytes(canvas)
}
+10 -1
View File
@@ -37,7 +37,16 @@ export const useReportStore = create<ReportStore>((set) => ({
initReport: (draft) =>
set({
report: { ...draft, version: 1, id: generateId(), createdAt: nowIso() },
report: {
...draft,
version: 1,
id: generateId(),
createdAt: nowIso(),
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
},
activeObservationIndex: 0,
}),
+73 -10
View File
@@ -1,24 +1,87 @@
import { describe, it, expect, vi } from 'vitest'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { rasterizeSvg } from '@/pdf/render/svgToPng'
vi.mock('canvg', () => ({
Canvg: { from: vi.fn(async () => ({ render: vi.fn(async () => {}) })) },
}))
const PNG_BYTES = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00,
])
class MockImage {
decoding: 'sync' | 'async' | 'auto' = 'auto'
crossOrigin: string | null = null
onload: (() => void) | null = null
onerror: ((err?: unknown) => void) | null = null
private _src = ''
get src(): string {
return this._src
}
set src(value: string) {
this._src = value
queueMicrotask(() => this.onload?.())
}
}
describe('rasterizeSvg', () => {
it('returns a Uint8Array', async () => {
beforeEach(() => {
vi.stubGlobal('Image', MockImage)
vi.stubGlobal('URL', {
createObjectURL: () => 'blob:mock',
revokeObjectURL: () => undefined,
})
})
it('returns PNG bytes for a valid SVG', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => {},
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = ((cb: BlobCallback) => {
cb(new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }))
cb(new Blob([PNG_BYTES], { type: 'image/png' }))
}) as HTMLCanvasElement['toBlob']
vi.spyOn(document, 'createElement').mockImplementationOnce(() => canvas)
vi.spyOn(document, 'createElement').mockImplementation(
((tag: string) =>
tag === 'canvas'
? canvas
: ({}) as HTMLElement) as typeof document.createElement,
)
const out = await rasterizeSvg('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"/>', 2)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
2,
)
expect(out).toBeInstanceOf(Uint8Array)
expect(out.length).toBeGreaterThan(0)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
expect(out[2]).toBe(0x4e)
expect(out[3]).toBe(0x47)
})
it('falls back to toDataURL when toBlob returns null', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = ((cb: BlobCallback) => {
cb(null)
}) as HTMLCanvasElement['toBlob']
canvas.toDataURL = () =>
'data:image/png;base64,' +
Buffer.from(PNG_BYTES).toString('base64')
vi.spyOn(document, 'createElement').mockImplementation(
((tag: string) =>
tag === 'canvas'
? canvas
: ({}) as HTMLElement) as typeof document.createElement,
)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
2,
)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
})
})
+17 -9
View File
@@ -25,6 +25,14 @@ describe('reportStore.initReport', () => {
expect(r.practitioner.name).toBe('Dr. Dupont')
})
it('seeds a single empty observation when the draft has none', () => {
useReportStore.getState().initReport(draft)
const r = useReportStore.getState().report!
expect(r.observations.length).toBe(1)
expect(r.observations[0].zones).toEqual([])
expect(r.observations[0].comment).toBe('')
})
it('resets activeObservationIndex to 0', () => {
useReportStore.getState().initReport(draft)
expect(useReportStore.getState().activeObservationIndex).toBe(0)
@@ -44,8 +52,8 @@ describe('reportStore.addObservation', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().addObservation()
const s = useReportStore.getState()
expect(s.report!.observations.length).toBe(1)
expect(s.activeObservationIndex).toBe(0)
expect(s.report!.observations.length).toBe(2)
expect(s.activeObservationIndex).toBe(1)
})
})
@@ -65,21 +73,21 @@ describe('reportStore.updateObservation', () => {
describe('reportStore.removeObservation', () => {
it('drops the observation at the given index', () => {
const store = useReportStore.getState()
store.initReport(draft)
store.initReport(draft) // seeds 1
store.addObservation()
store.addObservation()
store.removeObservation(0)
expect(useReportStore.getState().report!.observations.length).toBe(1)
expect(useReportStore.getState().report!.observations.length).toBe(2)
})
it('clamps activeObservationIndex within bounds', () => {
const store = useReportStore.getState()
store.initReport(draft)
store.initReport(draft) // seeds 1
store.addObservation()
store.addObservation()
store.setActiveObservation(1)
store.removeObservation(1)
expect(useReportStore.getState().activeObservationIndex).toBe(0)
store.addObservation() // total 3
store.setActiveObservation(2)
store.removeObservation(2)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
})
})