From d702e9fb45b974b37528d652f5eb6a0208128d0d Mon Sep 17 00:00:00 2001 From: Bastien Chanot Date: Sun, 12 Jul 2026 17:52:50 +0200 Subject: [PATCH] chore(pdf): decompose addObservationPage (context object + sub-functions) --- src/pdf/export.ts | 8 +- src/pdf/render/observationPage.ts | 317 +++++++++++++++++++++--------- 2 files changed, 224 insertions(+), 101 deletions(-) diff --git a/src/pdf/export.ts b/src/pdf/export.ts index 02c51aa3..fe5c3c3a 100644 --- a/src/pdf/export.ts +++ b/src/pdf/export.ts @@ -140,17 +140,17 @@ export async function exportReportToPdf( const totalObs = report.observations.length for (let i = 0; i < totalObs; i += 1) { - await addObservationPage( + await addObservationPage({ pdfDoc, report, - report.observations[i], - i, + observation: report.observations[i], + obsIndex: i, fonts, zoneLabels, findingsTree, locale, headerAssets, - ) + }) } await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets) diff --git a/src/pdf/render/observationPage.ts b/src/pdf/render/observationPage.ts index c5eeb859..c731eb5b 100644 --- a/src/pdf/render/observationPage.ts +++ b/src/pdf/render/observationPage.ts @@ -1,9 +1,10 @@ -import { rgb, PageSizes, type PDFDocument, type PDFPage } from 'pdf-lib' +import { rgb, PageSizes, type PDFDocument, type PDFPage, type PDFImage } from 'pdf-lib' import type { EmbeddedFonts } from '@/pdf/fonts' import type { Report } from '@/domain/schema/report' import type { Finding, Observation } from '@/domain/schema/observation' import type { SpeciesFindings } from '@/domain/schema/findings' -import type { Locale } from '@/i18n/types' +import type { SpeciesManifest } from '@/domain/species/types' +import type { Locale, Dict } from '@/i18n/types' import { getDict } from '@/i18n' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' import type { ZoneLabelPair } from '@/pdf/export' @@ -253,22 +254,52 @@ async function colorizedSvgString( return new XMLSerializer().serializeToString(root) } -export async function addObservationPage( - pdfDoc: PDFDocument, - report: Report, - observation: Observation, - obsIndex: number, - fonts: EmbeddedFonts, - zoneLabels: Map, - findingsTree: SpeciesFindings | null, - locale: Locale, - headerAssets: HeaderAssets, -): Promise { - const dict = getDict(locale) - const page = pdfDoc.addPage(PageSizes.A4) - const { width, height } = page.getSize() - drawHeader(page, report, fonts, locale, headerAssets) +/** Parameters needed to render one observation page. */ +export interface ObservationPageContext { + pdfDoc: PDFDocument + report: Report + observation: Observation + obsIndex: number + fonts: EmbeddedFonts + zoneLabels: Map + findingsTree: SpeciesFindings | null + locale: Locale + headerAssets: HeaderAssets +} +/** Shared draw handles threaded through the observation-page sub-renderers. */ +interface PageDrawContext { + page: PDFPage + fonts: EmbeddedFonts + width: number +} + +/** One rasterized anatomy view (main body or a detail popup) ready to embed. */ +interface RenderedImage { + label: string + img: PDFImage + aspect: number +} + +/** One label/value block drawn under the images (zones, findings, comment...). */ +interface ObservationSection { + label: string + value: string +} + +/** + * Draws the eyebrow, index/severity title, and accent rule for an + * observation page. Returns titleY so callers can lay out the content + * below it. + */ +function drawObservationTitleBlock( + ctx: PageDrawContext, + dict: Dict, + obsIndex: number, + severity: Observation['severity'], +): number { + const { page, fonts } = ctx + const { height } = page.getSize() const eyebrowY = height - EYEBROW_Y_OFFSET const titleY = height - TITLE_Y_OFFSET const obsLabel = String(obsIndex + 1).padStart(2, '0') @@ -286,9 +317,9 @@ export async function addObservationPage( font: fonts.headingRegular, color: COLOR_INK, }) - if (observation.severity) { + if (severity) { const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22) - const sev = observation.severity + const sev = severity const sevLabel = dict[`severity.${sev}`] ?? sev const sevText = sevLabel.toUpperCase() const sevSize = 9 @@ -320,10 +351,19 @@ export async function addObservationPage( thickness: 2, color: COLOR_ACCENT, }) + return titleY +} - const species = getSpecies(report.animal.speciesId) - if (!species) return - +/** + * Resolves the main-body view plus every detail-popup view referenced by + * the observation, rasterizing each to a PNG ready for pdf-lib. + */ +async function buildObservationImages( + pdfDoc: PDFDocument, + species: SpeciesManifest, + observation: Observation, + dict: Dict, +): Promise { const hasMainZones = observation.zones.some((z) => !z.detailSourceId) const detailIds = Array.from( new Set(observation.zones.map((z) => z.detailSourceId).filter(Boolean) as string[]), @@ -343,7 +383,7 @@ export async function addObservationPage( }) } - const rendered = await Promise.all( + return Promise.all( items.map(async (it) => { const svgStr = await colorizedSvgString(it.src, observation, it.sourceId) const png = await rasterizeSvg(svgStr) @@ -352,8 +392,16 @@ export async function addObservationPage( return { label: it.label, img, aspect } }), ) +} - const zonesText = observation.zones +/** Renders the "Zones" section value: bilingual labels + vertebra/side suffixes. */ +function describeObservationZones( + zones: Observation['zones'], + zoneLabels: Map, + locale: Locale, + dict: Dict, +): string { + return zones .map((z) => { const pair = zoneLabels.get(z.boneId) const label = pickLocaleLabel(pair?.fr, pair?.en, locale, z.boneId) @@ -366,22 +414,28 @@ export async function addObservationPage( return `${label}${v}${side}` }) .join(' · ') +} - const sections: Array<{ label: string; value: string }> = [ - { label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] }, - ] - const findingsByZoneSide = new Map() - for (const f of observation.findings) { +/** Groups findings by zone+side, one label/value section entry per group. */ +function buildFindingsSections( + findings: Finding[], + findingsTree: SpeciesFindings | null, + locale: Locale, + dict: Dict, +): ObservationSection[] { + const byZoneSide = new Map() + for (const f of findings) { const key = f.side ? `${f.zoneId}:${f.side}` : f.zoneId - const list = findingsByZoneSide.get(key) + const list = byZoneSide.get(key) if (list) { list.push(f) } else { - findingsByZoneSide.set(key, [f]) + byZoneSide.set(key, [f]) } } - for (const [key, group] of findingsByZoneSide) { + const sections: ObservationSection[] = [] + for (const [key, group] of byZoneSide) { const zoneId = key.split(':')[0] const side = group[0]?.side const zoneTree = findingsTree?.zones[zoneId] @@ -405,6 +459,22 @@ export async function addObservationPage( value, }) } + return sections +} + +/** Assembles the ordered label/value sections drawn below the images. */ +function buildObservationSections( + observation: Observation, + zoneLabels: Map, + findingsTree: SpeciesFindings | null, + locale: Locale, + dict: Dict, +): ObservationSection[] { + const zonesText = describeObservationZones(observation.zones, zoneLabels, locale, dict) + const sections: ObservationSection[] = [ + { label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] }, + ] + sections.push(...buildFindingsSections(observation.findings, findingsTree, locale, dict)) if (observation.freeTextFindings.length) { sections.push({ @@ -419,74 +489,95 @@ export async function addObservationPage( if (observation.comment.trim()) { sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() }) } + return sections +} - const maxTextW = width - MARGIN_X * 2 - - function estimateTextHeight(): number { - let h = TEXT_TOP_GAP - for (const { value } of sections) { - const lineCount = value.includes(' · ') - ? countSegmentedLines(value.split(' · '), fonts, maxTextW) - : wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length - h += SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP - } - return h +/** Estimates the vertical space the given sections will occupy once drawn. */ +function estimateSectionsHeight( + sections: ObservationSection[], + fonts: EmbeddedFonts, + maxTextW: number, +): number { + let h = TEXT_TOP_GAP + for (const { value } of sections) { + const lineCount = value.includes(' · ') + ? countSegmentedLines(value.split(' · '), fonts, maxTextW) + : wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length + h += SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP } + return h +} - let cursorY = titleY - IMAGE_TOP_GAP +/** + * Lays out and draws the (up to 2-column) image grid for an observation + * page. Returns the cursor y directly below the images — unchanged from + * startY when there is nothing to draw. + */ +function drawObservationImageGrid( + ctx: PageDrawContext, + rendered: RenderedImage[], + startY: number, + reservedBottom: number, +): number { + const { page, fonts, width } = ctx + let cursorY = startY + if (rendered.length === 0) return cursorY - if (rendered.length > 0) { - const isSingle = rendered.length === 1 - const cols = isSingle ? 1 : 2 - const rows = Math.ceil(rendered.length / cols) - const fullCellW = - (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols - // Single-image observations get rendered at half the available width - // and centered, so they don't dominate the page when the surrounding - // text is short. - const cellW = isSingle ? fullCellW / 2 : fullCellW - const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0 - const reservedBottom = MARGIN_BOTTOM + estimateTextHeight() + IMAGE_BOTTOM_GAP - const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom) - const rowBudget = Math.max( - IMAGE_MIN_CELL_H, - (availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows, - ) + const isSingle = rendered.length === 1 + const cols = isSingle ? 1 : 2 + const rows = Math.ceil(rendered.length / cols) + const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols + // Single-image observations get rendered at half the available width + // and centered, so they don't dominate the page when the surrounding + // text is short. + const cellW = isSingle ? fullCellW / 2 : fullCellW + const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0 + const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom) + const rowBudget = Math.max( + IMAGE_MIN_CELL_H, + (availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows, + ) - for (let r = 0; r < rows; r += 1) { - const rowItems = rendered.slice(r * cols, r * cols + cols) - const cellHs = rowItems.map((it) => - Math.min(cellW * it.aspect, rowBudget), - ) - const rowH = Math.max(0, ...cellHs) - rowItems.forEach((it, c) => { - const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) - page.drawText(it.label, { - x, - y: cursorY, - size: 8, - font: fonts.bodyBold, - color: COLOR_ACCENT, - }) + for (let r = 0; r < rows; r += 1) { + const rowItems = rendered.slice(r * cols, r * cols + cols) + const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget)) + const rowH = Math.max(0, ...cellHs) + rowItems.forEach((it, c) => { + const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) + page.drawText(it.label, { + x, + y: cursorY, + size: 8, + font: fonts.bodyBold, + color: COLOR_ACCENT, }) - cursorY -= IMAGE_LABEL_GAP - rowItems.forEach((it, c) => { - const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) - page.drawImage(it.img, { - x, - y: cursorY - cellHs[c], - width: cellW, - height: cellHs[c], - }) + }) + cursorY -= IMAGE_LABEL_GAP + rowItems.forEach((it, c) => { + const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) + page.drawImage(it.img, { + x, + y: cursorY - cellHs[c], + width: cellW, + height: cellHs[c], }) - cursorY -= rowH - if (r < rows - 1) cursorY -= IMAGE_ROW_GAP - } - cursorY -= IMAGE_BOTTOM_GAP + }) + cursorY -= rowH + if (r < rows - 1) cursorY -= IMAGE_ROW_GAP } + cursorY -= IMAGE_BOTTOM_GAP + return cursorY +} - cursorY -= TEXT_TOP_GAP - +/** Draws each label/value section, returns the cursor y below the last one. */ +function drawObservationSections( + ctx: PageDrawContext, + sections: ObservationSection[], + startY: number, + maxTextW: number, +): number { + const { page, fonts } = ctx + let cursorY = startY for (const { label, value } of sections) { page.drawText(label, { x: MARGIN_X, @@ -506,12 +597,7 @@ export async function addObservationPage( fonts, ) } else { - const lines = wrapLines( - value, - fonts.bodyRegular, - SECTION_TEXT_SIZE, - maxTextW, - ) + const lines = wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW) for (const line of lines) { page.drawText(line, { x: MARGIN_X, @@ -525,4 +611,41 @@ export async function addObservationPage( } cursorY -= SECTION_BLOCK_GAP } + return cursorY +} + +export async function addObservationPage( + ctx: ObservationPageContext, +): Promise { + const { + pdfDoc, + report, + observation, + obsIndex, + fonts, + zoneLabels, + findingsTree, + locale, + headerAssets, + } = ctx + const dict = getDict(locale) + const page = pdfDoc.addPage(PageSizes.A4) + const { width } = page.getSize() + drawHeader(page, report, fonts, locale, headerAssets) + + const drawCtx: PageDrawContext = { page, fonts, width } + const titleY = drawObservationTitleBlock(drawCtx, dict, obsIndex, observation.severity) + + const species = getSpecies(report.animal.speciesId) + if (!species) return + + const rendered = await buildObservationImages(pdfDoc, species, observation, dict) + + const maxTextW = width - MARGIN_X * 2 + const sections = buildObservationSections(observation, zoneLabels, findingsTree, locale, dict) + const reservedBottom = MARGIN_BOTTOM + estimateSectionsHeight(sections, fonts, maxTextW) + IMAGE_BOTTOM_GAP + + let cursorY = drawObservationImageGrid(drawCtx, rendered, titleY - IMAGE_TOP_GAP, reservedBottom) + cursorY -= TEXT_TOP_GAP + drawObservationSections(drawCtx, sections, cursorY, maxTextW) }