chore: remove dead code and duplicate logic

- drop unused assertNever, canvg dependency (never imported),
  readonly re-export shim in VertebraPicker, stale equine named export
- unexport validateBoneElement (internal only)
- getBoneIdFromEvent now delegates to getAnnotatedElement (dup walk-up)
- rasterizeSvg: drop ignored _scale param (2 call sites + tests)
- extract byte-identical word-wrap into pdf/render/text.ts
- extract mergeBones helper in EditorRoute (block duplicated twice)
- fix stale canvg comment in observationPage
Checks: typecheck, lint, 174/174 tests, build all green
This commit is contained in:
Bastien Chanot committed 2026-07-12 04:47:54 +02:00
1 parent c55da07697
commit bbdc0e851a
14 files changed
+55 -141

No files matched your search

-1
View File
@@ -20,7 +20,6 @@
"scaffold:species": "node scripts/scaffold-species.mjs" "scaffold:species": "node scripts/scaffold-species.mjs"
}, },
"dependencies": { "dependencies": {
"canvg": "^4.0.2",
"motion": "^11.11.17", "motion": "^11.11.17",
"pdf-lib": "^1.17.1", "pdf-lib": "^1.17.1",
"react": "^19.0.0", "react": "^19.0.0",
-50
View File
@@ -8,9 +8,6 @@ importers:
.: .:
dependencies: dependencies:
canvg:
specifier: ^4.0.2
version: 4.0.3
motion: motion:
specifier: ^11.11.17 specifier: ^11.11.17
version: 11.18.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6) version: 11.18.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
@@ -719,9 +716,6 @@ packages:
'@types/node@20.19.41': '@types/node@20.19.41':
resolution: {integrity: sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==} resolution: {integrity: sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==}
'@types/raf@3.4.3':
resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==}
'@types/react-dom@19.2.3': '@types/react-dom@19.2.3':
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
peerDependencies: peerDependencies:
@@ -942,10 +936,6 @@ packages:
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'} engines: {node: '>=6'}
canvg@4.0.3:
resolution: {integrity: sha512-fKzMoMBwus3CWo1Uy8XJc4tqqn98RoRrGV6CsIkaNiQT5lOeHuMh4fOt+LXLzn2Wqtr4p/c2TOLz4xtu4oBlFA==}
engines: {node: '>=12.0.0'}
chai@5.3.3: chai@5.3.3:
resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
engines: {node: '>=18'} engines: {node: '>=18'}
@@ -1674,9 +1664,6 @@ packages:
pdf-lib@1.17.1: pdf-lib@1.17.1:
resolution: {integrity: sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==} resolution: {integrity: sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==}
performance-now@2.1.0:
resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
picocolors@1.1.1: picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -1712,9 +1699,6 @@ packages:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'} engines: {node: '>=6'}
raf@3.4.1:
resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==}
react-dom@19.2.6: react-dom@19.2.6:
resolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==} resolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==}
peerDependencies: peerDependencies:
@@ -1768,10 +1752,6 @@ packages:
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
hasBin: true hasBin: true
rgbcolor@1.0.1:
resolution: {integrity: sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==}
engines: {node: '>= 0.8.15'}
rollup@4.60.4: rollup@4.60.4:
resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==} resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'} engines: {node: '>=18.0.0', npm: '>=8.0.0'}
@@ -1850,10 +1830,6 @@ packages:
stackback@0.0.2: stackback@0.0.2:
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
stackblur-canvas@2.7.0:
resolution: {integrity: sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==}
engines: {node: '>=0.1.14'}
std-env@3.10.0: std-env@3.10.0:
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
@@ -1899,10 +1875,6 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
svg-pathdata@6.0.3:
resolution: {integrity: sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==}
engines: {node: '>=12.0.0'}
tailwindcss@4.3.0: tailwindcss@4.3.0:
resolution: {integrity: sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==} resolution: {integrity: sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==}
@@ -2569,8 +2541,6 @@ snapshots:
dependencies: dependencies:
undici-types: 6.21.0 undici-types: 6.21.0
'@types/raf@3.4.3': {}
'@types/react-dom@19.2.3(@types/react@19.2.14)': '@types/react-dom@19.2.3(@types/react@19.2.14)':
dependencies: dependencies:
'@types/react': 19.2.14 '@types/react': 19.2.14
@@ -2858,14 +2828,6 @@ snapshots:
callsites@3.1.0: {} callsites@3.1.0: {}
canvg@4.0.3:
dependencies:
'@types/raf': 3.4.3
raf: 3.4.1
rgbcolor: 1.0.1
stackblur-canvas: 2.7.0
svg-pathdata: 6.0.3
chai@5.3.3: chai@5.3.3:
dependencies: dependencies:
assertion-error: 2.0.1 assertion-error: 2.0.1
@@ -3691,8 +3653,6 @@ snapshots:
pako: 1.0.11 pako: 1.0.11
tslib: 1.14.1 tslib: 1.14.1
performance-now@2.1.0: {}
picocolors@1.1.1: {} picocolors@1.1.1: {}
picomatch@4.0.4: {} picomatch@4.0.4: {}
@@ -3723,10 +3683,6 @@ snapshots:
punycode@2.3.1: {} punycode@2.3.1: {}
raf@3.4.1:
dependencies:
performance-now: 2.1.0
react-dom@19.2.6(react@19.2.6): react-dom@19.2.6(react@19.2.6):
dependencies: dependencies:
react: 19.2.6 react: 19.2.6
@@ -3788,8 +3744,6 @@ snapshots:
path-parse: 1.0.7 path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0 supports-preserve-symlinks-flag: 1.0.0
rgbcolor@1.0.1: {}
rollup@4.60.4: rollup@4.60.4:
dependencies: dependencies:
'@types/estree': 1.0.8 '@types/estree': 1.0.8
@@ -3910,8 +3864,6 @@ snapshots:
stackback@0.0.2: {} stackback@0.0.2: {}
stackblur-canvas@2.7.0: {}
std-env@3.10.0: {} std-env@3.10.0: {}
stop-iteration-iterator@1.1.0: stop-iteration-iterator@1.1.0:
@@ -3979,8 +3931,6 @@ snapshots:
supports-preserve-symlinks-flag@1.0.0: {} supports-preserve-symlinks-flag@1.0.0: {}
svg-pathdata@6.0.3: {}
tailwindcss@4.3.0: {} tailwindcss@4.3.0: {}
tapable@2.3.3: {} tapable@2.3.3: {}
+2 -8
View File
@@ -12,7 +12,7 @@ import type { Bone, BoneCategory } from './types'
* string is accepted. New SVGs are free to introduce new categories * string is accepted. New SVGs are free to introduce new categories
* without touching this parser. * without touching this parser.
*/ */
export function validateBoneElement(el: Element): void { function validateBoneElement(el: Element): void {
const boneId = el.getAttribute('data-anno-id') ?? '' const boneId = el.getAttribute('data-anno-id') ?? ''
if (!boneId) { if (!boneId) {
throw new SvgConventionError( throw new SvgConventionError(
@@ -94,13 +94,7 @@ export function parseSvgBones(svgRoot: SVGSVGElement): Map<string, Bone> {
* annotated element. * annotated element.
*/ */
export function getBoneIdFromEvent(event: Event): string | null { export function getBoneIdFromEvent(event: Event): string | null {
let node = event.target as Element | null return getAnnotatedElement(event)?.getAttribute('data-anno-id') || null
while (node && node.nodeType === 1) {
const id = node.getAttribute?.('data-anno-id')
if (id) return id
node = node.parentElement
}
return null
} }
export function getAnnotatedElement(event: Event): Element | null { export function getAnnotatedElement(event: Event): Element | null {
+13 -17
View File
@@ -3,9 +3,8 @@ import { useNavigate } from 'react-router-dom'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import DetailModal from '@/components/canvas/DetailModal' import DetailModal from '@/components/canvas/DetailModal'
import ObservationList from '@/components/observation/ObservationList' import ObservationList from '@/components/observation/ObservationList'
import VertebraPicker, { import VertebraPicker from '@/components/observation/VertebraPicker'
regionFromLabel, import { regionFromLabel } from '@/lib/spineZones'
} from '@/components/observation/VertebraPicker'
import LateralityPicker from '@/components/observation/LateralityPicker' import LateralityPicker from '@/components/observation/LateralityPicker'
import type { LateralSide } from '@/domain/schema/observation' import type { LateralSide } from '@/domain/schema/observation'
import ConclusionPanel from '@/components/report/ConclusionPanel' import ConclusionPanel from '@/components/report/ConclusionPanel'
@@ -32,6 +31,15 @@ import { boneLabel } from '@/anatomy/labels'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
/** Merges newly parsed bones into the accumulated map without overwriting. */
function mergeBones(prev: Map<string, Bone>, parsed: Map<string, Bone>) {
const merged = new Map(prev)
parsed.forEach((b, id) => {
if (!merged.has(id)) merged.set(id, b)
})
return merged
}
export default function EditorRoute() { export default function EditorRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const t = useT() const t = useT()
@@ -135,13 +143,7 @@ export default function EditorRoute() {
loadSvg(path) loadSvg(path)
.then((root) => { .then((root) => {
const parsed = parseSvgBones(root) const parsed = parseSvgBones(root)
setDetailBones((prev) => { setDetailBones((prev) => mergeBones(prev, parsed))
const merged = new Map(prev)
parsed.forEach((b, id) => {
if (!merged.has(id)) merged.set(id, b)
})
return merged
})
}) })
.catch((err) => { .catch((err) => {
console.warn(`EditorRoute: failed to preload detail SVG ${path}`, err) console.warn(`EditorRoute: failed to preload detail SVG ${path}`, err)
@@ -162,13 +164,7 @@ export default function EditorRoute() {
loadSvg(detail.src).then((root) => { loadSvg(detail.src).then((root) => {
if (cancelled) return if (cancelled) return
const parsed = parseSvgBones(root) const parsed = parseSvgBones(root)
setDetailBones((prev) => { setDetailBones((prev) => mergeBones(prev, parsed))
const merged = new Map(prev)
parsed.forEach((b, id) => {
if (!merged.has(id)) merged.set(id, b)
})
return merged
})
}) })
return () => { return () => {
cancelled = true cancelled = true
@@ -6,8 +6,6 @@ import type { Vertebra, VertebralRegion } from '@/domain/schema/observation'
import type { VertebralFormula } from '@/domain/species/types' import type { VertebralFormula } from '@/domain/species/types'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export { regionFromLabel } from '@/lib/spineZones'
const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd'] const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd']
const REGION_KEY: Record<VertebralRegion, string> = { const REGION_KEY: Record<VertebralRegion, string> = {
C: 'vertebra.region.C', C: 'vertebra.region.C',
+2 -3
View File
@@ -1,7 +1,7 @@
import type { SpeciesManifest } from '@/domain/species/types' import type { SpeciesManifest } from '@/domain/species/types'
import { EQUINE_VERTEBRAL_FORMULA } from './vertebrae' import { EQUINE_VERTEBRAL_FORMULA } from './vertebrae'
export const equine: SpeciesManifest = { const equine: SpeciesManifest = {
id: 'equine', id: 'equine',
labelFr: 'Cheval', labelFr: 'Cheval',
mainSvg: '/species/equine/Horse.svg', mainSvg: '/species/equine/Horse.svg',
@@ -13,6 +13,5 @@ export const equine: SpeciesManifest = {
} }
// Default export is the convention picked up by the registry's // Default export is the convention picked up by the registry's
// import.meta.glob() auto-discovery. Keep the named export for any // import.meta.glob() auto-discovery.
// code that still imports the manifest by name.
export default equine export default equine
-8
View File
@@ -7,11 +7,3 @@ export function assert(condition: unknown, message: string): asserts condition {
throw new Error(`Assertion failed: ${message}`) throw new Error(`Assertion failed: ${message}`)
} }
} }
/**
* Marks a code path as unreachable for exhaustive switch coverage.
* TypeScript will error at compile time if the path is reachable.
*/
export function assertNever(value: never, message?: string): never {
throw new Error(message ?? `Unexpected value: ${JSON.stringify(value)}`)
}
+1 -1
View File
@@ -130,7 +130,7 @@ export async function exportReportToPdf(
const resp = await fetch('/Paws_in_harmony.svg') const resp = await fetch('/Paws_in_harmony.svg')
if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`) if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`)
const svgText = await resp.text() const svgText = await resp.text()
const pawsPngBytes = await rasterizeSvg(svgText, 1) const pawsPngBytes = await rasterizeSvg(svgText)
pawsLogoPdf = await pdfDoc.embedPng(pawsPngBytes) pawsLogoPdf = await pdfDoc.embedPng(pawsPngBytes)
} catch (err) { } catch (err) {
console.warn('Paws in Harmony logo embed failed:', err) console.warn('Paws in Harmony logo embed failed:', err)
+3 -19
View File
@@ -1,9 +1,10 @@
import { rgb, PageSizes, type PDFDocument, type PDFFont } from 'pdf-lib' import { rgb, PageSizes, type PDFDocument } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import type { Locale } from '@/i18n/types' import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n' import { getDict } from '@/i18n'
import { drawHeader, type HeaderAssets } from './header' import { drawHeader, type HeaderAssets } from './header'
import { wrapLines } from './text'
import { formatDate } from '@/lib/dates' import { formatDate } from '@/lib/dates'
const MARGIN_X = 36 const MARGIN_X = 36
@@ -20,23 +21,6 @@ const COLOR_INK = rgb(0.12, 0.11, 0.09)
const COLOR_MUTED = rgb(0.42, 0.39, 0.35) const COLOR_MUTED = rgb(0.42, 0.39, 0.35)
const COLOR_ACCENT = rgb(0.72, 0.35, 0.25) const COLOR_ACCENT = rgb(0.72, 0.35, 0.25)
function wrap(text: string, font: PDFFont, size: number, max: number): string[] {
const words = text.split(/\s+/)
const lines: string[] = []
let line = ''
for (const w of words) {
const test = line ? `${line} ${w}` : w
if (font.widthOfTextAtSize(test, size) > max && line) {
lines.push(line)
line = w
} else {
line = test
}
}
if (line) lines.push(line)
return lines
}
export async function addConclusionPage( export async function addConclusionPage(
pdfDoc: PDFDocument, pdfDoc: PDFDocument,
report: Report, report: Report,
@@ -101,7 +85,7 @@ export async function addConclusionPage(
color: COLOR_ACCENT, color: COLOR_ACCENT,
}) })
cursorY -= SECTION_LABEL_GAP + 10 cursorY -= SECTION_LABEL_GAP + 10
wrap(body, fonts.bodyRegular, 11, max).forEach((line) => { wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => {
page.drawText(line, { page.drawText(line, {
x: MARGIN_X, x: MARGIN_X,
y: cursorY, y: cursorY,
+4 -20
View File
@@ -1,4 +1,4 @@
import { rgb, PageSizes, type PDFDocument, type PDFFont, type PDFPage } from 'pdf-lib' import { rgb, PageSizes, type PDFDocument, type PDFPage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import type { Finding, Observation } from '@/domain/schema/observation' import type { Finding, Observation } from '@/domain/schema/observation'
@@ -8,6 +8,7 @@ import { getDict } from '@/i18n'
import type { ZoneLabelPair } from '@/pdf/export' import type { ZoneLabelPair } from '@/pdf/export'
import { drawHeader, type HeaderAssets } from './header' import { drawHeader, type HeaderAssets } from './header'
import { rasterizeSvg } from './svgToPng' import { rasterizeSvg } from './svgToPng'
import { wrapLines } from './text'
import { loadSvg } from '@/anatomy/svgLoader' import { loadSvg } from '@/anatomy/svgLoader'
import { parseSvgBones } from '@/anatomy/svgConvention' import { parseSvgBones } from '@/anatomy/svgConvention'
import { getSpecies } from '@/domain/species/registry' import { getSpecies } from '@/domain/species/registry'
@@ -141,23 +142,6 @@ function drawSegmentedText(
return y - TEXT_LINE_HEIGHT return y - TEXT_LINE_HEIGHT
} }
function wrapLines(text: string, font: PDFFont, size: number, max: number): string[] {
const words = text.split(/\s+/)
const lines: string[] = []
let line = ''
for (const w of words) {
const test = line ? `${line} ${w}` : w
if (font.widthOfTextAtSize(test, size) > max && line) {
lines.push(line)
line = w
} else {
line = test
}
}
if (line) lines.push(line)
return lines
}
const SVG_NS = 'http://www.w3.org/2000/svg' const SVG_NS = 'http://www.w3.org/2000/svg'
const HALO_FILTER_ID = 'osteo-halo' const HALO_FILTER_ID = 'osteo-halo'
@@ -203,7 +187,7 @@ function ensureHaloFilter(root: SVGSVGElement): void {
const merge = doc.createElementNS(SVG_NS, 'feMerge') const merge = doc.createElementNS(SVG_NS, 'feMerge')
// Stack the wide halo three times so its contribution survives the // Stack the wide halo three times so its contribution survives the
// canvg → PNG → pdf-lib pipeline (each pass attenuates alpha) and // SVG → PNG → pdf-lib pipeline (each pass attenuates alpha) and
// still reads as a strong glow at print scale. // still reads as a strong glow at print scale.
for (let i = 0; i < 3; i += 1) { for (let i = 0; i < 3; i += 1) {
const n = doc.createElementNS(SVG_NS, 'feMergeNode') const n = doc.createElementNS(SVG_NS, 'feMergeNode')
@@ -359,7 +343,7 @@ export async function addObservationPage(
const rendered = await Promise.all( const rendered = await Promise.all(
items.map(async (it) => { items.map(async (it) => {
const svgStr = await colorizedSvgString(it.src, observation, it.sourceId) const svgStr = await colorizedSvgString(it.src, observation, it.sourceId)
const png = await rasterizeSvg(svgStr, 2) const png = await rasterizeSvg(svgStr)
const img = await pdfDoc.embedPng(png) const img = await pdfDoc.embedPng(png)
const aspect = img.width > 0 ? img.height / img.width : 0.6 const aspect = img.width > 0 ? img.height / img.width : 0.6
return { label: it.label, img, aspect } return { label: it.label, img, aspect }
+1 -7
View File
@@ -113,14 +113,8 @@ async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array>
* the inline anatomy canvas. * the inline anatomy canvas.
* *
* @param svgString Serialized SVG (must declare `xmlns`) * @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( export async function rasterizeSvg(svgString: string): Promise<Uint8Array> {
svgString: string,
_scale: number,
): Promise<Uint8Array> {
const { widthPx, heightPx } = readViewBox(svgString) const { widthPx, heightPx } = readViewBox(svgString)
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx) const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
return canvasToPngBytes(canvas) return canvasToPngBytes(canvas)
+27
View File
@@ -0,0 +1,27 @@
import type { PDFFont } from 'pdf-lib'
/**
* Greedy word-wrap: splits `text` into lines whose rendered width at
* `size` points stays within `max` for the given font.
*/
export function wrapLines(
text: string,
font: PDFFont,
size: number,
max: number,
): string[] {
const words = text.split(/\s+/)
const lines: string[] = []
let line = ''
for (const w of words) {
const test = line ? `${line} ${w}` : w
if (font.widthOfTextAtSize(test, size) > max && line) {
lines.push(line)
line = w
} else {
line = test
}
}
if (line) lines.push(line)
return lines
}
@@ -1,9 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react' import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import VertebraPicker, { import VertebraPicker from '@/components/observation/VertebraPicker'
regionFromLabel, import { regionFromLabel } from '@/lib/spineZones'
} from '@/components/observation/VertebraPicker'
import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae' import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
-2
View File
@@ -48,7 +48,6 @@ describe('rasterizeSvg', () => {
const out = await rasterizeSvg( const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>', '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
2,
) )
expect(out).toBeInstanceOf(Uint8Array) expect(out).toBeInstanceOf(Uint8Array)
expect(out[0]).toBe(0x89) expect(out[0]).toBe(0x89)
@@ -79,7 +78,6 @@ describe('rasterizeSvg', () => {
const out = await rasterizeSvg( const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>', '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
2,
) )
expect(out[0]).toBe(0x89) expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50) expect(out[1]).toBe(0x50)