chore(pdf): decompose addObservationPage (context object + sub-functions)
This commit is contained in:
1 parent
fe307e1d8d
commit
d702e9fb45
2 files changed
+180
-57
No files matched your search
+4
-4
@@ -140,17 +140,17 @@ export async function exportReportToPdf(
|
|||||||
const totalObs = report.observations.length
|
const totalObs = report.observations.length
|
||||||
|
|
||||||
for (let i = 0; i < totalObs; i += 1) {
|
for (let i = 0; i < totalObs; i += 1) {
|
||||||
await addObservationPage(
|
await addObservationPage({
|
||||||
pdfDoc,
|
pdfDoc,
|
||||||
report,
|
report,
|
||||||
report.observations[i],
|
observation: report.observations[i],
|
||||||
i,
|
obsIndex: i,
|
||||||
fonts,
|
fonts,
|
||||||
zoneLabels,
|
zoneLabels,
|
||||||
findingsTree,
|
findingsTree,
|
||||||
locale,
|
locale,
|
||||||
headerAssets,
|
headerAssets,
|
||||||
)
|
})
|
||||||
}
|
}
|
||||||
await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets)
|
await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets)
|
||||||
|
|
||||||
|
|||||||
@@ -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 { 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'
|
||||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
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 { getDict } from '@/i18n'
|
||||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||||
import type { ZoneLabelPair } from '@/pdf/export'
|
import type { ZoneLabelPair } from '@/pdf/export'
|
||||||
@@ -253,22 +254,52 @@ async function colorizedSvgString(
|
|||||||
return new XMLSerializer().serializeToString(root)
|
return new XMLSerializer().serializeToString(root)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function addObservationPage(
|
/** Parameters needed to render one observation page. */
|
||||||
pdfDoc: PDFDocument,
|
export interface ObservationPageContext {
|
||||||
report: Report,
|
pdfDoc: PDFDocument
|
||||||
observation: Observation,
|
report: Report
|
||||||
obsIndex: number,
|
observation: Observation
|
||||||
fonts: EmbeddedFonts,
|
obsIndex: number
|
||||||
zoneLabels: Map<string, ZoneLabelPair>,
|
fonts: EmbeddedFonts
|
||||||
findingsTree: SpeciesFindings | null,
|
zoneLabels: Map<string, ZoneLabelPair>
|
||||||
locale: Locale,
|
findingsTree: SpeciesFindings | null
|
||||||
headerAssets: HeaderAssets,
|
locale: Locale
|
||||||
): Promise<void> {
|
headerAssets: HeaderAssets
|
||||||
const dict = getDict(locale)
|
}
|
||||||
const page = pdfDoc.addPage(PageSizes.A4)
|
|
||||||
const { width, height } = page.getSize()
|
|
||||||
drawHeader(page, report, fonts, locale, 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 eyebrowY = height - EYEBROW_Y_OFFSET
|
||||||
const titleY = height - TITLE_Y_OFFSET
|
const titleY = height - TITLE_Y_OFFSET
|
||||||
const obsLabel = String(obsIndex + 1).padStart(2, '0')
|
const obsLabel = String(obsIndex + 1).padStart(2, '0')
|
||||||
@@ -286,9 +317,9 @@ export async function addObservationPage(
|
|||||||
font: fonts.headingRegular,
|
font: fonts.headingRegular,
|
||||||
color: COLOR_INK,
|
color: COLOR_INK,
|
||||||
})
|
})
|
||||||
if (observation.severity) {
|
if (severity) {
|
||||||
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
|
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
|
||||||
const sev = observation.severity
|
const sev = severity
|
||||||
const sevLabel = dict[`severity.${sev}`] ?? sev
|
const sevLabel = dict[`severity.${sev}`] ?? sev
|
||||||
const sevText = sevLabel.toUpperCase()
|
const sevText = sevLabel.toUpperCase()
|
||||||
const sevSize = 9
|
const sevSize = 9
|
||||||
@@ -320,10 +351,19 @@ export async function addObservationPage(
|
|||||||
thickness: 2,
|
thickness: 2,
|
||||||
color: COLOR_ACCENT,
|
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<RenderedImage[]> {
|
||||||
const hasMainZones = observation.zones.some((z) => !z.detailSourceId)
|
const hasMainZones = observation.zones.some((z) => !z.detailSourceId)
|
||||||
const detailIds = Array.from(
|
const detailIds = Array.from(
|
||||||
new Set(observation.zones.map((z) => z.detailSourceId).filter(Boolean) as string[]),
|
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) => {
|
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)
|
const png = await rasterizeSvg(svgStr)
|
||||||
@@ -352,8 +392,16 @@ export async function addObservationPage(
|
|||||||
return { label: it.label, img, aspect }
|
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<string, ZoneLabelPair>,
|
||||||
|
locale: Locale,
|
||||||
|
dict: Dict,
|
||||||
|
): string {
|
||||||
|
return zones
|
||||||
.map((z) => {
|
.map((z) => {
|
||||||
const pair = zoneLabels.get(z.boneId)
|
const pair = zoneLabels.get(z.boneId)
|
||||||
const label = pickLocaleLabel(pair?.fr, pair?.en, locale, z.boneId)
|
const label = pickLocaleLabel(pair?.fr, pair?.en, locale, z.boneId)
|
||||||
@@ -366,22 +414,28 @@ export async function addObservationPage(
|
|||||||
return `${label}${v}${side}`
|
return `${label}${v}${side}`
|
||||||
})
|
})
|
||||||
.join(' · ')
|
.join(' · ')
|
||||||
|
}
|
||||||
|
|
||||||
const sections: Array<{ label: string; value: string }> = [
|
/** Groups findings by zone+side, one label/value section entry per group. */
|
||||||
{ label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] },
|
function buildFindingsSections(
|
||||||
]
|
findings: Finding[],
|
||||||
const findingsByZoneSide = new Map<string, Finding[]>()
|
findingsTree: SpeciesFindings | null,
|
||||||
for (const f of observation.findings) {
|
locale: Locale,
|
||||||
|
dict: Dict,
|
||||||
|
): ObservationSection[] {
|
||||||
|
const byZoneSide = new Map<string, Finding[]>()
|
||||||
|
for (const f of findings) {
|
||||||
const key = f.side ? `${f.zoneId}:${f.side}` : f.zoneId
|
const key = f.side ? `${f.zoneId}:${f.side}` : f.zoneId
|
||||||
const list = findingsByZoneSide.get(key)
|
const list = byZoneSide.get(key)
|
||||||
if (list) {
|
if (list) {
|
||||||
list.push(f)
|
list.push(f)
|
||||||
} else {
|
} 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 zoneId = key.split(':')[0]
|
||||||
const side = group[0]?.side
|
const side = group[0]?.side
|
||||||
const zoneTree = findingsTree?.zones[zoneId]
|
const zoneTree = findingsTree?.zones[zoneId]
|
||||||
@@ -405,6 +459,22 @@ export async function addObservationPage(
|
|||||||
value,
|
value,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
return sections
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Assembles the ordered label/value sections drawn below the images. */
|
||||||
|
function buildObservationSections(
|
||||||
|
observation: Observation,
|
||||||
|
zoneLabels: Map<string, ZoneLabelPair>,
|
||||||
|
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) {
|
if (observation.freeTextFindings.length) {
|
||||||
sections.push({
|
sections.push({
|
||||||
@@ -419,10 +489,15 @@ export async function addObservationPage(
|
|||||||
if (observation.comment.trim()) {
|
if (observation.comment.trim()) {
|
||||||
sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() })
|
sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() })
|
||||||
}
|
}
|
||||||
|
return sections
|
||||||
|
}
|
||||||
|
|
||||||
const maxTextW = width - MARGIN_X * 2
|
/** Estimates the vertical space the given sections will occupy once drawn. */
|
||||||
|
function estimateSectionsHeight(
|
||||||
function estimateTextHeight(): number {
|
sections: ObservationSection[],
|
||||||
|
fonts: EmbeddedFonts,
|
||||||
|
maxTextW: number,
|
||||||
|
): number {
|
||||||
let h = TEXT_TOP_GAP
|
let h = TEXT_TOP_GAP
|
||||||
for (const { value } of sections) {
|
for (const { value } of sections) {
|
||||||
const lineCount = value.includes(' · ')
|
const lineCount = value.includes(' · ')
|
||||||
@@ -431,22 +506,32 @@ export async function addObservationPage(
|
|||||||
h += SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
|
h += SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
|
||||||
}
|
}
|
||||||
return h
|
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 isSingle = rendered.length === 1
|
||||||
const cols = isSingle ? 1 : 2
|
const cols = isSingle ? 1 : 2
|
||||||
const rows = Math.ceil(rendered.length / cols)
|
const rows = Math.ceil(rendered.length / cols)
|
||||||
const fullCellW =
|
const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
|
||||||
(width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
|
|
||||||
// Single-image observations get rendered at half the available width
|
// Single-image observations get rendered at half the available width
|
||||||
// and centered, so they don't dominate the page when the surrounding
|
// and centered, so they don't dominate the page when the surrounding
|
||||||
// text is short.
|
// text is short.
|
||||||
const cellW = isSingle ? fullCellW / 2 : fullCellW
|
const cellW = isSingle ? fullCellW / 2 : fullCellW
|
||||||
const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0
|
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 availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom)
|
||||||
const rowBudget = Math.max(
|
const rowBudget = Math.max(
|
||||||
IMAGE_MIN_CELL_H,
|
IMAGE_MIN_CELL_H,
|
||||||
@@ -455,9 +540,7 @@ export async function addObservationPage(
|
|||||||
|
|
||||||
for (let r = 0; r < rows; r += 1) {
|
for (let r = 0; r < rows; r += 1) {
|
||||||
const rowItems = rendered.slice(r * cols, r * cols + cols)
|
const rowItems = rendered.slice(r * cols, r * cols + cols)
|
||||||
const cellHs = rowItems.map((it) =>
|
const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget))
|
||||||
Math.min(cellW * it.aspect, rowBudget),
|
|
||||||
)
|
|
||||||
const rowH = Math.max(0, ...cellHs)
|
const rowH = Math.max(0, ...cellHs)
|
||||||
rowItems.forEach((it, c) => {
|
rowItems.forEach((it, c) => {
|
||||||
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
|
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
|
||||||
@@ -483,10 +566,18 @@ export async function addObservationPage(
|
|||||||
if (r < rows - 1) cursorY -= IMAGE_ROW_GAP
|
if (r < rows - 1) cursorY -= IMAGE_ROW_GAP
|
||||||
}
|
}
|
||||||
cursorY -= IMAGE_BOTTOM_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) {
|
for (const { label, value } of sections) {
|
||||||
page.drawText(label, {
|
page.drawText(label, {
|
||||||
x: MARGIN_X,
|
x: MARGIN_X,
|
||||||
@@ -506,12 +597,7 @@ export async function addObservationPage(
|
|||||||
fonts,
|
fonts,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
const lines = wrapLines(
|
const lines = wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW)
|
||||||
value,
|
|
||||||
fonts.bodyRegular,
|
|
||||||
SECTION_TEXT_SIZE,
|
|
||||||
maxTextW,
|
|
||||||
)
|
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
page.drawText(line, {
|
page.drawText(line, {
|
||||||
x: MARGIN_X,
|
x: MARGIN_X,
|
||||||
@@ -525,4 +611,41 @@ export async function addObservationPage(
|
|||||||
}
|
}
|
||||||
cursorY -= SECTION_BLOCK_GAP
|
cursorY -= SECTION_BLOCK_GAP
|
||||||
}
|
}
|
||||||
|
return cursorY
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addObservationPage(
|
||||||
|
ctx: ObservationPageContext,
|
||||||
|
): Promise<void> {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user