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:
1 parent
bdf5e6475b
commit
e8c29c1fdf
7 files changed
+449
-113
No files matched your search
+98
-32
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user