Files
faunosteo/packages/pdf/src/render/observationPage.ts
T

635 lines
16 KiB
TypeScript

import {
PageSizes,
rgb,
type PDFDocument,
type PDFImage,
type PDFPage,
} from 'pdf-lib'
import {
pickLabel,
type Finding,
type Observation,
type PdfLabels,
type Report,
type ReportZone,
type Severity,
type SheetIndex,
type SheetSnapshot,
} from '@faunosteo/domain'
import { renderHighlightedView } from '../svg/view'
import type { ExportWarning, Rasterizer } from '../types'
import {
COLOR_ACCENT,
COLOR_INK,
EYEBROW_Y_OFFSET,
MARGIN_X,
SECTION_LABEL_GAP,
TITLE_RULE_OFFSET,
TITLE_RULE_WIDTH,
TITLE_Y_OFFSET,
} from './constants'
import type { PdfLocale, RenderContext } from './context'
import type { EmbeddedFonts } from './fonts'
import { drawHeader, type HeaderAssets } from './header'
import { drawText, measure, wrapLines } from './text'
const MARGIN_BOTTOM = 48
const IMAGE_TOP_GAP = 32
const IMAGE_LABEL_GAP = 14
const IMAGE_BOTTOM_GAP = 14
const IMAGE_COL_GAP = 16
const IMAGE_ROW_GAP = 12
const IMAGE_MIN_CELL_H = 60
const TEXT_TOP_GAP = 10
const TEXT_LINE_HEIGHT = 13
const SECTION_BLOCK_GAP = 10
const COLOR_WHITE = rgb(1, 1, 1)
const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = {
mild: rgb(0.55, 0.65, 0.45),
moderate: rgb(0.85, 0.55, 0.18),
severe: rgb(0.78, 0.2, 0.2),
}
const SECTION_TEXT_SIZE = 10
const SEPARATOR_GLYPH = '•'
const SEPARATOR_SIZE = 14
const SEPARATOR_SIDE_GAP = 5
/** Items of a section joined by this print as a segmented line. */
const ITEM_JOIN = ' · '
/** Width of the visible separator block including the empty space on each side. */
function separatorWidth(fonts: EmbeddedFonts): number {
return (
measure(fonts.bodyBold, SEPARATOR_GLYPH, SEPARATOR_SIZE) +
SEPARATOR_SIDE_GAP * 2
)
}
/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */
function countSegmentedLines(
items: string[],
fonts: EmbeddedFonts,
maxWidth: number,
): number {
if (items.length === 0) return 1
const sepW = separatorWidth(fonts)
let lines = 1
let x = 0
for (let i = 0; i < items.length; i += 1) {
const itemW = measure(fonts.bodyRegular, items[i]!, SECTION_TEXT_SIZE)
if (x + itemW > maxWidth && x > 0) {
lines += 1
x = 0
}
x += itemW
if (i < items.length - 1) {
if (x + sepW > maxWidth) {
lines += 1
x = 0
} else {
x += sepW
}
}
}
return lines
}
interface SegmentCursor {
x: number
y: number
}
function drawSeparator(
page: PDFPage,
cursor: SegmentCursor,
fonts: EmbeddedFonts,
): void {
const baselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
drawText(page, SEPARATOR_GLYPH, {
x: cursor.x + SEPARATOR_SIDE_GAP,
y: cursor.y - baselineOffset,
size: SEPARATOR_SIZE,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
}
/**
* Renders a list of items separated by a visibly larger accent-coloured
* bullet. Returns the cursor y *below* the last line drawn.
*/
function drawSegmentedText(
page: PDFPage,
items: string[],
start: SegmentCursor,
maxWidth: number,
fonts: EmbeddedFonts,
): number {
if (items.length === 0) return start.y - TEXT_LINE_HEIGHT
const sepW = separatorWidth(fonts)
const cursor = { ...start }
for (let i = 0; i < items.length; i += 1) {
const item = items[i]!
const itemW = measure(fonts.bodyRegular, item, SECTION_TEXT_SIZE)
if (cursor.x + itemW > start.x + maxWidth && cursor.x > start.x) {
cursor.x = start.x
cursor.y -= TEXT_LINE_HEIGHT
}
drawText(page, item, {
x: cursor.x,
y: cursor.y,
size: SECTION_TEXT_SIZE,
font: fonts.bodyRegular,
color: COLOR_INK,
})
cursor.x += itemW
if (i === items.length - 1) continue
if (cursor.x + sepW > start.x + maxWidth) {
cursor.x = start.x
cursor.y -= TEXT_LINE_HEIGHT
} else {
drawSeparator(page, cursor, fonts)
cursor.x += sepW
}
}
return cursor.y - TEXT_LINE_HEIGHT
}
/** Parameters needed to render one observation page. */
export interface ObservationPageContext {
pdfDoc: PDFDocument
report: Report
observation: Observation
obsIndex: number
sheet: SheetIndex
snapshot: SheetSnapshot
ctx: RenderContext
headerAssets: HeaderAssets
rasterizer: Rasterizer
warnings: ExportWarning[]
}
interface PageDrawContext {
page: PDFPage
fonts: EmbeddedFonts
width: number
}
interface RenderedImage {
label: string
img: PDFImage
aspect: number
}
interface ObservationSection {
label: string
value: string
}
function drawSeverityPill(
draw: PageDrawContext,
severity: Severity,
labels: PdfLabels,
anchor: { numW: number; titleY: number },
): void {
const { page, fonts } = draw
const sevText = labels[`severity.${severity}`].toUpperCase()
const sevSize = 9
const padX = 8
const padY = 4
const pillW = measure(fonts.bodyBold, sevText, sevSize) + padX * 2
const pillH = sevSize + padY * 2
const pillX = MARGIN_X + anchor.numW + 14
const pillY = anchor.titleY + 4
page.drawRectangle({
x: pillX,
y: pillY,
width: pillW,
height: pillH,
color: SEVERITY_BG[severity],
})
drawText(page, sevText, {
x: pillX + padX,
y: pillY + padY,
size: sevSize,
font: fonts.bodyBold,
color: COLOR_WHITE,
})
}
function drawObservationTitleBlock(
draw: PageDrawContext,
labels: PdfLabels,
obsIndex: number,
severity: Severity | undefined,
): number {
const { page, fonts } = draw
const { height } = page.getSize()
const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET
const obsLabel = String(obsIndex + 1).padStart(2, '0')
drawText(page, labels['pdf.eyebrow.observation'], {
x: MARGIN_X,
y: eyebrowY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
drawText(page, obsLabel, {
x: MARGIN_X,
y: titleY,
size: 22,
font: fonts.headingRegular,
color: COLOR_INK,
})
if (severity) {
const numW = measure(fonts.headingRegular, obsLabel, 22)
drawSeverityPill(draw, severity, labels, { numW, titleY })
}
page.drawLine({
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
thickness: 2,
color: COLOR_ACCENT,
})
return titleY
}
/** Unique views the observation touches and the snapshot holds, main first. */
export function observationViewIds(
sheet: SheetIndex,
observation: Observation,
): string[] {
return [...new Set(observation.zones.map((z) => z.viewId))]
.filter((id) => sheet.view(id))
.sort(
(a, b) =>
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
)
}
function viewLabel(
sheet: SheetIndex,
viewId: string,
ctx: RenderContext,
): string {
const view = sheet.view(viewId)!
if (view.kind === 'main') return ctx.labels['pdf.view.general']
const name = pickLabel(view.name, ctx.locale).toUpperCase()
return `${ctx.labels['pdf.view.detail_prefix']}${name}`
}
interface RasterisedView {
viewId: string
png: Uint8Array | null
}
/** One view rasterised; a failure yields null and a warning, never a throw. */
async function rasteriseView(
page: ObservationPageContext,
viewId: string,
): Promise<RasterisedView> {
try {
const { svg, size } = renderHighlightedView(
page.snapshot,
viewId,
page.observation,
)
return { viewId, png: await page.rasterizer(svg, size) }
} catch {
page.warnings.push({
kind: 'view_raster_failed',
observationId: page.observation.id,
viewId,
})
return { viewId, png: null }
}
}
/** Rasterisation in parallel, embedding in view order so bytes stay stable. */
async function buildObservationImages(
page: ObservationPageContext,
): Promise<RenderedImage[]> {
const viewIds = observationViewIds(page.sheet, page.observation)
const rasters = await Promise.all(
viewIds.map((viewId) => rasteriseView(page, viewId)),
)
const rendered: RenderedImage[] = []
for (const { viewId, png } of rasters) {
if (!png) continue
try {
const img = await page.pdfDoc.embedPng(png)
rendered.push({
label: viewLabel(page.sheet, viewId, page.ctx),
img,
aspect: img.width > 0 ? img.height / img.width : 0.6,
})
} catch {
page.warnings.push({
kind: 'view_raster_failed',
observationId: page.observation.id,
viewId,
})
}
}
return rendered
}
/** Zone name: snapshot annotation, else the report's label snapshot, else the id. */
function zoneText(z: ReportZone, sheet: SheetIndex, locale: PdfLocale): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function sideLabel(side: 'left' | 'right', labels: PdfLabels): string {
return labels[side === 'left' ? 'lateral.left' : 'lateral.right']
}
function describeObservationZones(
zones: ReportZone[],
sheet: SheetIndex,
ctx: RenderContext,
): string {
return zones
.map((z) => {
const v = z.vertebrae?.length
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
: ''
const side = z.side ? ` (${sideLabel(z.side, ctx.labels)})` : ''
return `${zoneText(z, sheet, ctx.locale)}${v}${side}`
})
.join(ITEM_JOIN)
}
/** Finding group heading: snapshot finding-zone name, else the id as is. */
function findingZoneName(
zoneId: string,
sheet: SheetIndex,
locale: PdfLocale,
): string {
const zone = sheet.findingZone(zoneId)
return zone ? pickLabel(zone.name, locale) : zoneId
}
function findingText(f: Finding, locale: PdfLocale): string {
const label = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
return f.requiresVetReferral ? `(!) ${label}` : label
}
/** Groups findings by zone+side, one section per group; snapshots give the text. */
function buildFindingsSections(
findings: Finding[],
sheet: SheetIndex,
ctx: RenderContext,
): ObservationSection[] {
const byZoneSide = new Map<string, Finding[]>()
for (const f of findings) {
const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
}
const sections: ObservationSection[] = []
for (const [key, group] of byZoneSide) {
const zoneId = key.split(':')[0]!
const side = group[0]?.side
let zoneName = findingZoneName(zoneId, sheet, ctx.locale)
if (side) zoneName = `${zoneName} (${sideLabel(side, ctx.labels)})`
sections.push({
label: `${ctx.labels['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
value: group.map((f) => findingText(f, ctx.locale)).join(ITEM_JOIN),
})
}
return sections
}
function buildObservationSections(
observation: Observation,
sheet: SheetIndex,
ctx: RenderContext,
): ObservationSection[] {
const { labels } = ctx
const zonesText = describeObservationZones(observation.zones, sheet, ctx)
const sections: ObservationSection[] = [
{
label: labels['pdf.section.zones'],
value: zonesText || labels['pdf.empty'],
},
...buildFindingsSections(observation.findings, sheet, ctx),
]
if (observation.freeTextFindings.length) {
sections.push({
label: labels['pdf.section.free_findings'],
value: observation.freeTextFindings.join(ITEM_JOIN),
})
}
if (observation.severity) {
sections.push({
label: labels['pdf.section.severity'],
value: labels[`severity.${observation.severity}`],
})
}
if (observation.comment.trim()) {
sections.push({
label: labels['pdf.section.comment'],
value: observation.comment.trim(),
})
}
return sections
}
function estimateSectionsHeight(
sections: ObservationSection[],
fonts: EmbeddedFonts,
maxTextW: number,
): number {
let h = TEXT_TOP_GAP
for (const { value } of sections) {
const lineCount = value.includes(ITEM_JOIN)
? countSegmentedLines(value.split(ITEM_JOIN), 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
}
interface ImageGrid {
cols: number
rows: number
cellW: number
offsetX: number
rowBudget: number
}
function imageGridOf(
rendered: RenderedImage[],
width: number,
availH: number,
): ImageGrid {
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
const cellW = isSingle ? fullCellW / 2 : fullCellW
return {
cols,
rows,
cellW,
offsetX: isSingle ? (fullCellW - cellW) / 2 : 0,
rowBudget: Math.max(
IMAGE_MIN_CELL_H,
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
),
}
}
/** One row of the grid: labels above, then the images; returns the row height. */
function drawImageRow(
draw: PageDrawContext,
rowItems: RenderedImage[],
grid: ImageGrid,
topY: number,
): number {
const { page, fonts } = draw
const cellHs = rowItems.map((it) =>
Math.min(grid.cellW * it.aspect, grid.rowBudget),
)
const cellX = (c: number) =>
MARGIN_X + grid.offsetX + c * (grid.cellW + IMAGE_COL_GAP)
rowItems.forEach((it, c) => {
drawText(page, it.label, {
x: cellX(c),
y: topY,
size: 8,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
})
const imagesY = topY - IMAGE_LABEL_GAP
rowItems.forEach((it, c) => {
page.drawImage(it.img, {
x: cellX(c),
y: imagesY - cellHs[c]!,
width: grid.cellW,
height: cellHs[c]!,
})
})
return Math.max(0, ...cellHs)
}
/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
function drawObservationImageGrid(
draw: PageDrawContext,
rendered: RenderedImage[],
startY: number,
reservedBottom: number,
): number {
if (rendered.length === 0) return startY
const availH = Math.max(IMAGE_MIN_CELL_H, startY - reservedBottom)
const grid = imageGridOf(rendered, draw.width, availH)
let cursorY = startY
for (let r = 0; r < grid.rows; r += 1) {
const rowItems = rendered.slice(r * grid.cols, r * grid.cols + grid.cols)
const rowH = drawImageRow(draw, rowItems, grid, cursorY)
cursorY -= IMAGE_LABEL_GAP + rowH
if (r < grid.rows - 1) cursorY -= IMAGE_ROW_GAP
}
return cursorY - IMAGE_BOTTOM_GAP
}
function drawSectionValue(
draw: PageDrawContext,
value: string,
startY: number,
maxTextW: number,
): number {
const { page, fonts } = draw
if (value.includes(ITEM_JOIN)) {
return drawSegmentedText(
page,
value.split(ITEM_JOIN),
{ x: MARGIN_X, y: startY },
maxTextW,
fonts,
)
}
let cursorY = startY
for (const line of wrapLines(
value,
fonts.bodyRegular,
SECTION_TEXT_SIZE,
maxTextW,
)) {
drawText(page, line, {
x: MARGIN_X,
y: cursorY,
size: SECTION_TEXT_SIZE,
font: fonts.bodyRegular,
color: COLOR_INK,
})
cursorY -= TEXT_LINE_HEIGHT
}
return cursorY
}
function drawObservationSections(
draw: PageDrawContext,
sections: ObservationSection[],
startY: number,
maxTextW: number,
): number {
let cursorY = startY
for (const { label, value } of sections) {
drawText(draw.page, label, {
x: MARGIN_X,
y: cursorY,
size: 8,
font: draw.fonts.bodyBold,
color: COLOR_ACCENT,
})
cursorY -= SECTION_LABEL_GAP + 9
cursorY = drawSectionValue(draw, value, cursorY, maxTextW)
cursorY -= SECTION_BLOCK_GAP
}
return cursorY
}
export async function addObservationPage(
input: ObservationPageContext,
): Promise<void> {
const { pdfDoc, report, observation, obsIndex, sheet, ctx, headerAssets } =
input
const page = pdfDoc.addPage(PageSizes.A4)
const { width } = page.getSize()
drawHeader(page, report, ctx, headerAssets)
const draw: PageDrawContext = { page, fonts: ctx.fonts, width }
const titleY = drawObservationTitleBlock(
draw,
ctx.labels,
obsIndex,
observation.severity,
)
const rendered = await buildObservationImages(input)
const maxTextW = width - MARGIN_X * 2
const sections = buildObservationSections(observation, sheet, ctx)
const reservedBottom =
MARGIN_BOTTOM +
estimateSectionsHeight(sections, ctx.fonts, maxTextW) +
IMAGE_BOTTOM_GAP
let cursorY = drawObservationImageGrid(
draw,
rendered,
titleY - IMAGE_TOP_GAP,
reservedBottom,
)
cursorY -= TEXT_TOP_GAP
drawObservationSections(draw, sections, cursorY, maxTextW)
}