chore(workspace): move the app to apps/app under a pnpm workspace (step 2)
144 files moved with git mv (pure renames). Root package.json delegates dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager, root devDependency, engine-strict). Dockerfile builds @faunosteo/app on node:24-alpine and copies apps/app/dist; nginx and runtime config unchanged. CI workflow for Gitea Actions. packages/ reserved (README only). Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan. 271/271 tests, typecheck, lint, build green from the root.
This commit is contained in:
1 parent
c8d48ab4cc
commit
8673475293
164 files changed
+348
-128
No files matched your search
@@ -0,0 +1,132 @@
|
||||
import { AFRelationship, type PDFDocument } from 'pdf-lib'
|
||||
import { ReportSchema, type Report } from '@/domain/schema/report'
|
||||
|
||||
const FILENAME = 'osteo-report.json'
|
||||
|
||||
/**
|
||||
* Internal sentinel raised when the attached JSON's `version` field is
|
||||
* present but not 2. The UI-facing message is composed by the importer
|
||||
* caller against the active i18n dict — this error only carries the
|
||||
* discriminating data.
|
||||
*/
|
||||
export class IncompatibleReportVersionError extends Error {
|
||||
constructor(public readonly foundVersion: number) {
|
||||
super(`incompatible_version:${foundVersion}`)
|
||||
this.name = 'IncompatibleReportVersionError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
|
||||
await pdfDoc.attach(bytes, FILENAME, {
|
||||
mimeType: 'application/json',
|
||||
description: 'Faunosteo state v2',
|
||||
creationDate: new Date(),
|
||||
modificationDate: new Date(),
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
}
|
||||
|
||||
export async function extractReportJson(pdfDoc: PDFDocument): Promise<Report> {
|
||||
const maybeApi = pdfDoc as unknown as { getAttachments?: () => Array<{ name: string; data: Uint8Array }> }
|
||||
if (typeof maybeApi.getAttachments === 'function') {
|
||||
const list = maybeApi.getAttachments()
|
||||
if (list && list.length) {
|
||||
const hit = list.find((a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json')) ?? list[0]
|
||||
return parseAttachment(hit.data)
|
||||
}
|
||||
}
|
||||
const fallback = await traverseForJsonAttachment(pdfDoc)
|
||||
if (!fallback) throw new Error('No osteo-report attachment found')
|
||||
return parseAttachment(fallback)
|
||||
}
|
||||
|
||||
function parseAttachment(bytes: Uint8Array): Report {
|
||||
const text = new TextDecoder().decode(bytes)
|
||||
const data: unknown = JSON.parse(text)
|
||||
if (
|
||||
data !== null &&
|
||||
typeof data === 'object' &&
|
||||
'version' in data &&
|
||||
typeof (data as { version: unknown }).version === 'number' &&
|
||||
(data as { version: number }).version !== 2
|
||||
) {
|
||||
throw new IncompatibleReportVersionError((data as { version: number }).version)
|
||||
}
|
||||
return ReportSchema.parse(data)
|
||||
}
|
||||
|
||||
interface RawObj {
|
||||
contents?: Uint8Array
|
||||
dict?: { entries?: () => Array<[unknown, unknown]> }
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard ceiling on inflated attachment size. A valid report JSON is far
|
||||
* smaller; anything bigger is a decompression bomb or corruption.
|
||||
*/
|
||||
const MAX_INFLATED_BYTES = 16 * 1024 * 1024
|
||||
|
||||
/** Exported for tests. Returns null on failure or when the cap is exceeded. */
|
||||
export async function inflateFlate(bytes: Uint8Array): Promise<Uint8Array | null> {
|
||||
if (typeof DecompressionStream === 'undefined') return null
|
||||
try {
|
||||
const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate'))
|
||||
const reader = stream.getReader()
|
||||
const chunks: Uint8Array[] = []
|
||||
let total = 0
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
total += value.byteLength
|
||||
if (total > MAX_INFLATED_BYTES) {
|
||||
await reader.cancel()
|
||||
return null
|
||||
}
|
||||
chunks.push(value)
|
||||
}
|
||||
const out = new Uint8Array(total)
|
||||
let offset = 0
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset)
|
||||
offset += c.byteLength
|
||||
}
|
||||
return out
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean {
|
||||
for (const [k, v] of entries) {
|
||||
if (String(k).includes('Filter') && String(v).includes('FlateDecode')) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise<Uint8Array | null> {
|
||||
const ctx = (pdfDoc as unknown as { context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } }).context
|
||||
for (const [, obj] of ctx.enumerateIndirectObjects()) {
|
||||
if (!obj || typeof obj !== 'object') continue
|
||||
if (!(obj.contents instanceof Uint8Array)) continue
|
||||
const entries = obj.dict?.entries?.() ?? []
|
||||
let isEmbeddedFile = false
|
||||
let isJsonSubtype = false
|
||||
for (const [k, v] of entries) {
|
||||
const ks = String(k)
|
||||
const vs = String(v)
|
||||
if (ks.includes('Type') && vs.includes('EmbeddedFile')) isEmbeddedFile = true
|
||||
// PDF name syntax escapes '/' as '#2F': /application#2Fjson
|
||||
if (ks.includes('Subtype') && (vs.includes('application/json') || vs.includes('application#2Fjson'))) {
|
||||
isJsonSubtype = true
|
||||
}
|
||||
}
|
||||
if (!isEmbeddedFile && !isJsonSubtype) continue
|
||||
if (dictHasFlateFilter(entries)) {
|
||||
const inflated = await inflateFlate(obj.contents)
|
||||
if (inflated) return inflated
|
||||
}
|
||||
return obj.contents
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { embedFonts } from './fonts'
|
||||
import { addObservationPage } from './render/observationPage'
|
||||
import { addConclusionPage } from './render/conclusionPage'
|
||||
import { attachReportJson } from './attachment'
|
||||
import { drawFooter } from './render/footer'
|
||||
import { loadFaunosteoLogo, loadFaunosteoComLogo, loadZenqualityLogo } from './render/logo'
|
||||
import { rasterizeSvg } from './render/svgToPng'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||
import { getSpecies } from '@/domain/species/registry'
|
||||
|
||||
export interface PdfExportOptions {
|
||||
locale: Locale
|
||||
}
|
||||
|
||||
/** Bilingual label pair surfaced to the PDF render layer. */
|
||||
export interface ZoneLabelPair {
|
||||
fr: string
|
||||
en: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a `data-anno-id → { fr, en }` map by parsing every SVG the
|
||||
* species manifest knows about. Each SVG is loaded independently so a
|
||||
* failure on the detail asset never prevents the main labels (or vice
|
||||
* versa) from making it into the returned map. The PDF render layer
|
||||
* picks the locale-appropriate label at draw time (falls back to the
|
||||
* opposite language when one side is missing).
|
||||
*
|
||||
* Exported for unit testing — the editor calls it indirectly via
|
||||
* `exportReportToPdf`.
|
||||
*/
|
||||
export async function buildZoneLabels(
|
||||
report: Report,
|
||||
): Promise<Map<string, ZoneLabelPair>> {
|
||||
const labels = new Map<string, ZoneLabelPair>()
|
||||
const species = getSpecies(report.animal.speciesId)
|
||||
if (!species) return labels
|
||||
|
||||
const sources: string[] = [
|
||||
species.mainSvg,
|
||||
...Object.values(species.details),
|
||||
]
|
||||
await Promise.all(
|
||||
sources.map(async (src) => {
|
||||
try {
|
||||
const root = await loadSvg(src)
|
||||
parseSvgBones(root).forEach((b, id) => {
|
||||
const existing = labels.get(id)
|
||||
if (existing) {
|
||||
if (!existing.fr && b.fr) existing.fr = b.fr
|
||||
if (!existing.en && b.en) existing.en = b.en
|
||||
} else if (b.fr || b.en) {
|
||||
labels.set(id, { fr: b.fr, en: b.en })
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn(`buildZoneLabels: skipped ${src}`, err)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return labels
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the parsed findings catalog for a species so the PDF renderer
|
||||
* can resolve a Finding's `zoneId` (JSON catalog key) back to its
|
||||
* human-readable zone name.
|
||||
*/
|
||||
async function loadSpeciesFindings(
|
||||
speciesId: string,
|
||||
): Promise<SpeciesFindings | null> {
|
||||
const species = getSpecies(speciesId)
|
||||
if (!species) return null
|
||||
try {
|
||||
const m = await species.findings()
|
||||
return m.default
|
||||
} catch (err) {
|
||||
console.warn(`loadSpeciesFindings: failed for ${speciesId}`, err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportReportToPdf(
|
||||
report: Report,
|
||||
opts: PdfExportOptions,
|
||||
): Promise<Uint8Array> {
|
||||
const { locale } = opts
|
||||
const dict = getDict(locale)
|
||||
const pdfDoc = await PDFDocument.create()
|
||||
pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`)
|
||||
pdfDoc.setAuthor(report.practitioner.name)
|
||||
pdfDoc.setSubject(dict['pdf.subject'])
|
||||
pdfDoc.setCreationDate(new Date())
|
||||
pdfDoc.setModificationDate(new Date())
|
||||
|
||||
const fonts = await embedFonts(pdfDoc)
|
||||
const zoneLabels = await buildZoneLabels(report)
|
||||
const findingsTree = await loadSpeciesFindings(report.animal.speciesId)
|
||||
|
||||
let headerLogoPdf = null
|
||||
let footerLogoPdf = null
|
||||
let zqLogoPdfImage = null
|
||||
let pawsLogoPdf = null
|
||||
try {
|
||||
const bytes = await loadFaunosteoLogo()
|
||||
headerLogoPdf = await pdfDoc.embedPng(bytes)
|
||||
} catch (err) {
|
||||
console.warn('Faunosteo logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const bytes = await loadFaunosteoComLogo()
|
||||
footerLogoPdf = await pdfDoc.embedPng(bytes)
|
||||
} catch (err) {
|
||||
console.warn('Faunosteo -com logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const zqPngBytes = await loadZenqualityLogo()
|
||||
zqLogoPdfImage = await pdfDoc.embedPng(zqPngBytes)
|
||||
} catch (err) {
|
||||
console.warn('ZenQuality logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const resp = await fetch('/Paws_in_harmony.svg')
|
||||
if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`)
|
||||
const svgText = await resp.text()
|
||||
const pawsPngBytes = await rasterizeSvg(svgText)
|
||||
pawsLogoPdf = await pdfDoc.embedPng(pawsPngBytes)
|
||||
} catch (err) {
|
||||
console.warn('Paws in Harmony logo embed failed:', err)
|
||||
}
|
||||
|
||||
const headerAssets = { logoPng: headerLogoPdf }
|
||||
const totalObs = report.observations.length
|
||||
|
||||
for (let i = 0; i < totalObs; i += 1) {
|
||||
await addObservationPage({
|
||||
pdfDoc,
|
||||
report,
|
||||
observation: report.observations[i],
|
||||
obsIndex: i,
|
||||
fonts,
|
||||
zoneLabels,
|
||||
findingsTree,
|
||||
locale,
|
||||
headerAssets,
|
||||
})
|
||||
}
|
||||
await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets)
|
||||
|
||||
const pages = pdfDoc.getPages()
|
||||
const footerAssets = {
|
||||
logoPng: footerLogoPdf,
|
||||
zqLogoPng: zqLogoPdfImage,
|
||||
pawsLogoPng: pawsLogoPdf,
|
||||
}
|
||||
pages.forEach((page, idx) => {
|
||||
drawFooter(page, fonts, idx + 1, pages.length, locale, footerAssets)
|
||||
})
|
||||
|
||||
await attachReportJson(pdfDoc, report)
|
||||
return pdfDoc.save()
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
|
||||
|
||||
export interface EmbeddedFonts {
|
||||
bodyRegular: PDFFont
|
||||
bodyBold: PDFFont
|
||||
headingRegular: PDFFont
|
||||
}
|
||||
|
||||
export async function embedFonts(pdfDoc: PDFDocument): Promise<EmbeddedFonts> {
|
||||
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
|
||||
pdfDoc.embedFont(StandardFonts.Helvetica),
|
||||
pdfDoc.embedFont(StandardFonts.HelveticaBold),
|
||||
pdfDoc.embedFont(StandardFonts.TimesRoman),
|
||||
])
|
||||
return { bodyRegular, bodyBold, headingRegular }
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { extractReportJson, IncompatibleReportVersionError } from './attachment'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
|
||||
export type ImportErrorKind =
|
||||
| 'invalid_pdf'
|
||||
| 'incompatible_version'
|
||||
| 'no_attachment'
|
||||
|
||||
/**
|
||||
* Localization-agnostic import error. Carries a kind discriminant + an
|
||||
* optional foundVersion so the caller (UI layer) can resolve the
|
||||
* user-facing message via the active i18n dict.
|
||||
*/
|
||||
export class ImportError extends Error {
|
||||
constructor(
|
||||
public readonly kind: ImportErrorKind,
|
||||
public readonly foundVersion?: number,
|
||||
) {
|
||||
super(kind)
|
||||
this.name = 'ImportError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report> {
|
||||
let pdfDoc: PDFDocument
|
||||
try {
|
||||
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
|
||||
} catch {
|
||||
throw new ImportError('invalid_pdf')
|
||||
}
|
||||
try {
|
||||
return await extractReportJson(pdfDoc)
|
||||
} catch (err) {
|
||||
if (err instanceof IncompatibleReportVersionError) {
|
||||
throw new ImportError('incompatible_version', err.foundVersion)
|
||||
}
|
||||
throw new ImportError('no_attachment')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { PageSizes, type PDFDocument } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { wrapLines } from './text'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import {
|
||||
MARGIN_X,
|
||||
EYEBROW_Y_OFFSET,
|
||||
TITLE_Y_OFFSET,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
SECTION_LABEL_GAP,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
COLOR_ACCENT,
|
||||
} from './constants'
|
||||
|
||||
const SECTION_TOP_GAP = 28
|
||||
const SECTION_BLOCK_GAP = 18
|
||||
const TEXT_LINE_HEIGHT = 14
|
||||
|
||||
export async function addConclusionPage(
|
||||
pdfDoc: PDFDocument,
|
||||
report: Report,
|
||||
fonts: EmbeddedFonts,
|
||||
locale: Locale,
|
||||
headerAssets: HeaderAssets,
|
||||
): Promise<void> {
|
||||
const dict = getDict(locale)
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width, height } = page.getSize()
|
||||
const max = width - MARGIN_X * 2
|
||||
|
||||
drawHeader(page, report, fonts, locale, headerAssets)
|
||||
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
page.drawText(dict['pdf.eyebrow.synthesis'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
page.drawText(dict['pdf.title.conclusion'], {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
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,
|
||||
})
|
||||
|
||||
let cursorY = titleY - SECTION_TOP_GAP
|
||||
|
||||
const sections: Array<{ label: string; body: string; color?: typeof COLOR_INK }> = [
|
||||
{ label: dict['pdf.section.conclusion'], body: report.conclusion || dict['pdf.empty'] },
|
||||
{ label: dict['pdf.section.recommendations'], body: report.recommendations || dict['pdf.empty'] },
|
||||
]
|
||||
if (report.nextAppointment) {
|
||||
const txt =
|
||||
report.nextAppointment.kind === 'date'
|
||||
? formatDate(report.nextAppointment.date, locale)
|
||||
: report.nextAppointment.text
|
||||
sections.push({
|
||||
label: dict['pdf.section.next_appointment'],
|
||||
body: txt || dict['pdf.empty'],
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
|
||||
for (const { label, body, color } of sections) {
|
||||
page.drawText(label, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 10
|
||||
wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 11,
|
||||
font: fonts.bodyRegular,
|
||||
color: color ?? COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
})
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { rgb } from 'pdf-lib'
|
||||
|
||||
/**
|
||||
* Layout and color constants shared across PDF page renderers (header,
|
||||
* footer, observation page, conclusion page). Only values that are
|
||||
* byte-identical across all callers live here — a same-named constant
|
||||
* with a different value per file stays local to that file.
|
||||
*/
|
||||
|
||||
export const MARGIN_X = 36
|
||||
export const EYEBROW_Y_OFFSET = 95
|
||||
export const TITLE_Y_OFFSET = 122
|
||||
export const TITLE_RULE_OFFSET = 12
|
||||
export const TITLE_RULE_WIDTH = 48
|
||||
export const SECTION_LABEL_GAP = 4
|
||||
|
||||
export const COLOR_INK = rgb(0.12, 0.11, 0.09)
|
||||
export const COLOR_MUTED = rgb(0.42, 0.39, 0.35)
|
||||
export const COLOR_ACCENT = rgb(0.72, 0.35, 0.25)
|
||||
@@ -0,0 +1,173 @@
|
||||
import { rgb, type PDFPage, type PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { MARGIN_X, COLOR_MUTED } from './constants'
|
||||
|
||||
const FOOTER_BASE_Y = 20
|
||||
const FONT_SIZE = 8
|
||||
|
||||
export interface FooterAssets {
|
||||
logoPng: PDFImage | null
|
||||
zqLogoPng: PDFImage | null
|
||||
pawsLogoPng: PDFImage | null
|
||||
}
|
||||
|
||||
export function drawFooter(
|
||||
page: PDFPage,
|
||||
fonts: EmbeddedFonts,
|
||||
pageNumber: number,
|
||||
totalPages: number,
|
||||
locale: Locale,
|
||||
assets: FooterAssets,
|
||||
): void {
|
||||
const dict = getDict(locale)
|
||||
const { width } = page.getSize()
|
||||
const accent = rgb(0.28, 0.56, 0.42)
|
||||
|
||||
const logoW = 80
|
||||
const logoH = 30
|
||||
const rowY = FOOTER_BASE_Y + 14
|
||||
const separatorY = rowY + logoH + 6
|
||||
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: rgb(0.85, 0.83, 0.8),
|
||||
})
|
||||
|
||||
if (assets.logoPng) {
|
||||
page.drawImage(assets.logoPng, {
|
||||
x: MARGIN_X,
|
||||
y: rowY,
|
||||
width: logoW,
|
||||
height: logoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: MARGIN_X,
|
||||
y: rowY,
|
||||
width: logoW,
|
||||
height: logoH,
|
||||
url: 'https://faunosteo.com',
|
||||
})
|
||||
}
|
||||
|
||||
const poweredLabel = `${dict['footer.powered_by']} `
|
||||
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(poweredLabel, FONT_SIZE)
|
||||
const zqLogoW = 70
|
||||
const zqLogoH = 16
|
||||
const zqFallback = 'zenquality.fr'
|
||||
const zqFallbackW = fonts.bodyRegular.widthOfTextAtSize(zqFallback, FONT_SIZE)
|
||||
const poweredBlockW = assets.zqLogoPng
|
||||
? poweredLabelW + zqLogoW
|
||||
: poweredLabelW + zqFallbackW
|
||||
const poweredX = (width - poweredBlockW) / 2
|
||||
const textBaseY = rowY + 6
|
||||
|
||||
page.drawText(poweredLabel, {
|
||||
x: poweredX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
const zqX = poweredX + poweredLabelW
|
||||
if (assets.zqLogoPng) {
|
||||
page.drawImage(assets.zqLogoPng, {
|
||||
x: zqX,
|
||||
y: rowY + 2,
|
||||
width: zqLogoW,
|
||||
height: zqLogoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: zqX,
|
||||
y: rowY + 2,
|
||||
width: zqLogoW,
|
||||
height: zqLogoH,
|
||||
url: 'https://zenquality.fr',
|
||||
})
|
||||
} else {
|
||||
page.drawText(zqFallback, {
|
||||
x: zqX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: accent,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: zqX,
|
||||
y: textBaseY - 2,
|
||||
width: zqFallbackW,
|
||||
height: FONT_SIZE + 4,
|
||||
url: 'https://zenquality.fr',
|
||||
})
|
||||
}
|
||||
|
||||
const partnerLabel = `${dict['footer.in_partnership']} `
|
||||
const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(partnerLabel, FONT_SIZE)
|
||||
const partnerUrl = 'https://www.instagram.com/paws.iin.harmony'
|
||||
|
||||
if (assets.pawsLogoPng) {
|
||||
const pawsLogoH = 16
|
||||
const pawsLogoW = pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height)
|
||||
const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW
|
||||
page.drawText(partnerLabel, {
|
||||
x: partnerX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
const pawsX = partnerX + partnerLabelW
|
||||
page.drawImage(assets.pawsLogoPng, {
|
||||
x: pawsX,
|
||||
y: rowY + 2,
|
||||
width: pawsLogoW,
|
||||
height: pawsLogoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: pawsX,
|
||||
y: rowY + 2,
|
||||
width: pawsLogoW,
|
||||
height: pawsLogoH,
|
||||
url: partnerUrl,
|
||||
})
|
||||
} else {
|
||||
const handle = '@paws.iin.harmony'
|
||||
const handleW = fonts.bodyRegular.widthOfTextAtSize(handle, FONT_SIZE)
|
||||
const partnerX = width - MARGIN_X - partnerLabelW - handleW
|
||||
page.drawText(partnerLabel, {
|
||||
x: partnerX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
page.drawText(handle, {
|
||||
x: partnerX + partnerLabelW,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: accent,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: partnerX + partnerLabelW,
|
||||
y: textBaseY - 2,
|
||||
width: handleW,
|
||||
height: FONT_SIZE + 4,
|
||||
url: partnerUrl,
|
||||
})
|
||||
}
|
||||
|
||||
const pageText = `${pageNumber} / ${totalPages}`
|
||||
const pageW = fonts.bodyRegular.widthOfTextAtSize(pageText, FONT_SIZE)
|
||||
page.drawText(pageText, {
|
||||
x: (width - pageW) / 2,
|
||||
y: FOOTER_BASE_Y + 2,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { PDFPage, PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { MARGIN_X, COLOR_INK, COLOR_MUTED } from './constants'
|
||||
|
||||
const TOP_Y = 800
|
||||
const LOGO_WIDTH = 100
|
||||
const LOGO_HEIGHT = 38
|
||||
|
||||
export interface HeaderAssets {
|
||||
logoPng: PDFImage | null
|
||||
}
|
||||
|
||||
export function drawHeader(
|
||||
page: PDFPage,
|
||||
report: Report,
|
||||
fonts: EmbeddedFonts,
|
||||
locale: Locale,
|
||||
assets: HeaderAssets,
|
||||
): void {
|
||||
const dict = getDict(locale)
|
||||
const { width } = page.getSize()
|
||||
|
||||
const y = TOP_Y
|
||||
|
||||
const left = [
|
||||
report.practitioner.name,
|
||||
report.practitioner.cabinet,
|
||||
report.practitioner.contact,
|
||||
report.practitioner.siret
|
||||
? `${dict['pdf.siret_prefix']}${report.practitioner.siret}`
|
||||
: undefined,
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
left.forEach((line, i) => {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: y - i * 12,
|
||||
size: i === 0 ? 11 : 9,
|
||||
font: i === 0 ? fonts.bodyBold : fonts.bodyRegular,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
|
||||
if (assets.logoPng) {
|
||||
const logoX = (width - LOGO_WIDTH) / 2
|
||||
const logoY = y - LOGO_HEIGHT + 10
|
||||
page.drawImage(assets.logoPng, {
|
||||
x: logoX,
|
||||
y: logoY,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: logoX,
|
||||
y: logoY,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
url: 'https://faunosteo.com',
|
||||
})
|
||||
}
|
||||
|
||||
const animalLine = [
|
||||
report.animal.name,
|
||||
report.animal.breed ? `(${report.animal.breed})` : '',
|
||||
report.animal.age ? `· ${report.animal.age}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
|
||||
const right = [
|
||||
animalLine,
|
||||
`${dict['pdf.owner_prefix']}${report.owner.name}`,
|
||||
formatDate(report.date, locale),
|
||||
]
|
||||
right.forEach((line, i) => {
|
||||
const size = i === 0 ? 11 : 9
|
||||
const font = i === 0 ? fonts.bodyBold : fonts.bodyRegular
|
||||
const w = font.widthOfTextAtSize(line, size)
|
||||
page.drawText(line, {
|
||||
x: width - MARGIN_X - w,
|
||||
y: y - i * 12,
|
||||
size,
|
||||
font,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
|
||||
const separatorY = y - Math.max(left.length * 12, LOGO_HEIGHT) - 8
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
|
||||
|
||||
export interface LinkRect {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
url: string
|
||||
}
|
||||
|
||||
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
|
||||
const context = page.doc.context
|
||||
|
||||
const actionDict = context.obj({
|
||||
Type: 'Action',
|
||||
S: 'URI',
|
||||
URI: PDFString.of(rect.url),
|
||||
})
|
||||
|
||||
const annotDict = context.obj({
|
||||
Type: 'Annot',
|
||||
Subtype: 'Link',
|
||||
Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height],
|
||||
Border: [0, 0, 0],
|
||||
A: actionDict,
|
||||
})
|
||||
|
||||
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
|
||||
if (annots) {
|
||||
annots.push(context.register(annotDict))
|
||||
} else {
|
||||
const arr = context.obj([context.register(annotDict)])
|
||||
page.node.set(PDFName.of('Annots'), arr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
const FAUNOSTEO_LOGO = '/assets/faunosteo_logo_horizontal-512.png'
|
||||
const FAUNOSTEO_COM_LOGO = '/assets/faunosteo-horizontal-com-512.png'
|
||||
const ZENQUALITY_LOGO = '/brand/zenquality-logo-fr.png'
|
||||
|
||||
async function fetchPngBytes(path: string): Promise<Uint8Array> {
|
||||
const resp = await fetch(path)
|
||||
if (!resp.ok) throw new Error(`Logo fetch failed: HTTP ${resp.status}`)
|
||||
return new Uint8Array(await resp.arrayBuffer())
|
||||
}
|
||||
|
||||
export async function loadFaunosteoLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(FAUNOSTEO_LOGO)
|
||||
}
|
||||
|
||||
export async function loadFaunosteoComLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(FAUNOSTEO_COM_LOGO)
|
||||
}
|
||||
|
||||
export async function loadZenqualityLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(ZENQUALITY_LOGO)
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
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 { 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'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { rasterizeSvg } from './svgToPng'
|
||||
import { wrapLines } from './text'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||
import { getSpecies } from '@/domain/species/registry'
|
||||
import {
|
||||
MARGIN_X,
|
||||
EYEBROW_Y_OFFSET,
|
||||
TITLE_Y_OFFSET,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
SECTION_LABEL_GAP,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
COLOR_ACCENT,
|
||||
} from './constants'
|
||||
|
||||
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<string, ReturnType<typeof rgb>> = {
|
||||
'légère': rgb(0.55, 0.65, 0.45),
|
||||
'modérée': rgb(0.85, 0.55, 0.18),
|
||||
'sévère': rgb(0.78, 0.20, 0.20),
|
||||
}
|
||||
|
||||
const SECTION_TEXT_SIZE = 10
|
||||
const SEPARATOR_GLYPH = '•'
|
||||
const SEPARATOR_SIZE = 14
|
||||
const SEPARATOR_SIDE_GAP = 5
|
||||
|
||||
/** Width of the visible separator block including the empty space on each side. */
|
||||
function separatorWidth(fonts: EmbeddedFonts): number {
|
||||
return (
|
||||
fonts.bodyBold.widthOfTextAtSize(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 = fonts.bodyRegular.widthOfTextAtSize(
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a list of items separated by a visibly larger accent-coloured
|
||||
* bullet. Returns the cursor y *below* the last line drawn so the
|
||||
* caller can keep advancing the page cursor like a plain wrapLines run.
|
||||
*/
|
||||
function drawSegmentedText(
|
||||
page: PDFPage,
|
||||
items: string[],
|
||||
startX: number,
|
||||
startY: number,
|
||||
maxWidth: number,
|
||||
fonts: EmbeddedFonts,
|
||||
): number {
|
||||
if (items.length === 0) return startY - TEXT_LINE_HEIGHT
|
||||
const sepW = separatorWidth(fonts)
|
||||
// The bullet's larger size pushes its baseline above the surrounding
|
||||
// text. Shift it down a touch so it visually centers on the x-height
|
||||
// of the items it separates.
|
||||
const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
|
||||
|
||||
let x = startX
|
||||
let y = startY
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const item = items[i]
|
||||
const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE)
|
||||
if (x + itemW > startX + maxWidth && x > startX) {
|
||||
x = startX
|
||||
y -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
page.drawText(item, {
|
||||
x,
|
||||
y,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
x += itemW
|
||||
if (i < items.length - 1) {
|
||||
if (x + sepW > startX + maxWidth) {
|
||||
x = startX
|
||||
y -= TEXT_LINE_HEIGHT
|
||||
} else {
|
||||
page.drawText(SEPARATOR_GLYPH, {
|
||||
x: x + SEPARATOR_SIDE_GAP,
|
||||
y: y - sepBaselineOffset,
|
||||
size: SEPARATOR_SIZE,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
x += sepW
|
||||
}
|
||||
}
|
||||
}
|
||||
return y - TEXT_LINE_HEIGHT
|
||||
}
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
const HALO_FILTER_ID = 'osteo-halo'
|
||||
|
||||
/**
|
||||
* Adds a Gaussian-blur "halo" filter to the SVG defs the first time it
|
||||
* is called on a root. The filter widens the visible footprint of the
|
||||
* highlighted zones on the whole-animal view, where individual point
|
||||
* markers are otherwise tiny relative to the full body silhouette.
|
||||
*/
|
||||
function ensureHaloFilter(root: SVGSVGElement): void {
|
||||
const doc = root.ownerDocument
|
||||
if (!doc) return
|
||||
if (doc.getElementById(HALO_FILTER_ID)) return
|
||||
|
||||
let defs = root.querySelector('defs')
|
||||
if (!defs) {
|
||||
defs = doc.createElementNS(SVG_NS, 'defs')
|
||||
root.insertBefore(defs, root.firstChild)
|
||||
}
|
||||
|
||||
const filter = doc.createElementNS(SVG_NS, 'filter')
|
||||
filter.setAttribute('id', HALO_FILTER_ID)
|
||||
filter.setAttribute('x', '-100%')
|
||||
filter.setAttribute('y', '-100%')
|
||||
filter.setAttribute('width', '300%')
|
||||
filter.setAttribute('height', '300%')
|
||||
filter.setAttribute('filterUnits', 'userSpaceOnUse')
|
||||
|
||||
// Two-stage blur: a wide outer halo for "spotted from across the
|
||||
// room" visibility, plus a tighter inner halo that keeps the
|
||||
// selection anchored to the original point so it doesn't dissolve.
|
||||
const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur')
|
||||
wide.setAttribute('in', 'SourceGraphic')
|
||||
wide.setAttribute('stdDeviation', '18')
|
||||
wide.setAttribute('result', 'haloWide')
|
||||
filter.appendChild(wide)
|
||||
|
||||
const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur')
|
||||
tight.setAttribute('in', 'SourceGraphic')
|
||||
tight.setAttribute('stdDeviation', '8')
|
||||
tight.setAttribute('result', 'haloTight')
|
||||
filter.appendChild(tight)
|
||||
|
||||
const merge = doc.createElementNS(SVG_NS, 'feMerge')
|
||||
// Stack the wide halo three times so its contribution survives the
|
||||
// SVG → PNG → pdf-lib pipeline (each pass attenuates alpha) and
|
||||
// still reads as a strong glow at print scale.
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
n.setAttribute('in', 'haloWide')
|
||||
merge.appendChild(n)
|
||||
}
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
n.setAttribute('in', 'haloTight')
|
||||
merge.appendChild(n)
|
||||
}
|
||||
const source = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
source.setAttribute('in', 'SourceGraphic')
|
||||
merge.appendChild(source)
|
||||
filter.appendChild(merge)
|
||||
|
||||
defs.appendChild(filter)
|
||||
}
|
||||
|
||||
async function colorizedSvgString(
|
||||
speciesSvgPath: string,
|
||||
observation: Observation,
|
||||
sourceDetailId: string | undefined,
|
||||
): Promise<string> {
|
||||
const root = await loadSvg(speciesSvgPath)
|
||||
const bones = parseSvgBones(root)
|
||||
const selectedIds = new Set(
|
||||
observation.zones
|
||||
.filter((z) => z.detailSourceId === sourceDetailId)
|
||||
.map((z) => z.boneId),
|
||||
)
|
||||
|
||||
// Whole-animal view: zone hitboxes are tiny markers on a big
|
||||
// silhouette, so we apply a blurred halo to make selections pop.
|
||||
// Detail views are already zoomed in and don't need it.
|
||||
const applyHalo = sourceDetailId === undefined
|
||||
if (applyHalo) ensureHaloFilter(root)
|
||||
|
||||
bones.forEach((bone, id) => {
|
||||
const selected = selectedIds.has(id)
|
||||
bone.els.forEach((el) => {
|
||||
if (selected) {
|
||||
el.setAttribute('fill', '#b85a3f')
|
||||
el.setAttribute('fill-opacity', '0.85')
|
||||
if (applyHalo) {
|
||||
el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
|
||||
}
|
||||
} else {
|
||||
el.setAttribute('display', 'none')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
root.querySelectorAll('[data-anno-id]').forEach((el) => {
|
||||
Array.from(el.attributes)
|
||||
.filter((a) => a.name.startsWith('data-anno-'))
|
||||
.forEach((a) => el.removeAttribute(a.name))
|
||||
})
|
||||
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
/** Parameters needed to render one observation page. */
|
||||
export interface ObservationPageContext {
|
||||
pdfDoc: PDFDocument
|
||||
report: Report
|
||||
observation: Observation
|
||||
obsIndex: number
|
||||
fonts: EmbeddedFonts
|
||||
zoneLabels: Map<string, ZoneLabelPair>
|
||||
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')
|
||||
page.drawText(dict['pdf.eyebrow.observation'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
page.drawText(obsLabel, {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
if (severity) {
|
||||
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
|
||||
const sev = severity
|
||||
const sevLabel = dict[`severity.${sev}`] ?? sev
|
||||
const sevText = sevLabel.toUpperCase()
|
||||
const sevSize = 9
|
||||
const sevTextW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize)
|
||||
const padX = 8
|
||||
const padY = 4
|
||||
const pillW = sevTextW + padX * 2
|
||||
const pillH = sevSize + padY * 2
|
||||
const pillX = MARGIN_X + numW + 14
|
||||
const pillY = titleY + 4
|
||||
page.drawRectangle({
|
||||
x: pillX,
|
||||
y: pillY,
|
||||
width: pillW,
|
||||
height: pillH,
|
||||
color: SEVERITY_BG[sev] ?? COLOR_MUTED,
|
||||
})
|
||||
page.drawText(sevText, {
|
||||
x: pillX + padX,
|
||||
y: pillY + padY,
|
||||
size: sevSize,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_WHITE,
|
||||
})
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 detailIds = Array.from(
|
||||
new Set(observation.zones.map((z) => z.detailSourceId).filter(Boolean) as string[]),
|
||||
)
|
||||
|
||||
const items: Array<{ label: string; src: string; sourceId: string | undefined }> = []
|
||||
if (hasMainZones) {
|
||||
items.push({ label: dict['pdf.view.general'], src: species.mainSvg, sourceId: undefined })
|
||||
}
|
||||
for (const detailId of detailIds) {
|
||||
const detailPath = species.details[detailId]
|
||||
if (!detailPath) continue
|
||||
items.push({
|
||||
label: `${dict['pdf.view.detail_prefix']}${detailId.toUpperCase()}`,
|
||||
src: detailPath,
|
||||
sourceId: detailId,
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.all(
|
||||
items.map(async (it) => {
|
||||
const svgStr = await colorizedSvgString(it.src, observation, it.sourceId)
|
||||
const png = await rasterizeSvg(svgStr)
|
||||
const img = await pdfDoc.embedPng(png)
|
||||
const aspect = img.width > 0 ? img.height / img.width : 0.6
|
||||
return { label: it.label, img, aspect }
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/** 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) => {
|
||||
const pair = zoneLabels.get(z.boneId)
|
||||
const label = pickLocaleLabel(pair?.fr, pair?.en, locale, z.boneId)
|
||||
const v = z.vertebrae?.length
|
||||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
||||
: ''
|
||||
const side = z.side
|
||||
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
|
||||
: ''
|
||||
return `${label}${v}${side}`
|
||||
})
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
/** 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<string, Finding[]>()
|
||||
for (const f of findings) {
|
||||
const key = f.side ? `${f.zoneId}:${f.side}` : f.zoneId
|
||||
const list = byZoneSide.get(key)
|
||||
if (list) {
|
||||
list.push(f)
|
||||
} else {
|
||||
byZoneSide.set(key, [f])
|
||||
}
|
||||
}
|
||||
|
||||
const sections: ObservationSection[] = []
|
||||
for (const [key, group] of byZoneSide) {
|
||||
const zoneId = key.split(':')[0]
|
||||
const side = group[0]?.side
|
||||
const zoneTree = findingsTree?.zones[zoneId]
|
||||
let zoneName = zoneTree
|
||||
? locale === 'en'
|
||||
? zoneTree.name_en
|
||||
: zoneTree.name_fr
|
||||
: zoneId
|
||||
if (side) {
|
||||
const sideLabel = dict[side === 'left' ? 'lateral.left' : 'lateral.right']
|
||||
zoneName = `${zoneName} (${sideLabel})`
|
||||
}
|
||||
const value = group
|
||||
.map((f) => {
|
||||
const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
|
||||
return f.requiresVetReferral ? `(!) ${lbl}` : lbl
|
||||
})
|
||||
.join(' · ')
|
||||
sections.push({
|
||||
label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
|
||||
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) {
|
||||
sections.push({
|
||||
label: dict['pdf.section.free_findings'],
|
||||
value: observation.freeTextFindings.join(' · '),
|
||||
})
|
||||
}
|
||||
if (observation.severity) {
|
||||
const sevLabel = dict[`severity.${observation.severity}`] ?? observation.severity
|
||||
sections.push({ label: dict['pdf.section.severity'], value: sevLabel })
|
||||
}
|
||||
if (observation.comment.trim()) {
|
||||
sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() })
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
/** 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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
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,
|
||||
})
|
||||
})
|
||||
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
|
||||
return cursorY
|
||||
}
|
||||
|
||||
/** 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,
|
||||
y: cursorY,
|
||||
size: 8,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 9
|
||||
if (value.includes(' · ')) {
|
||||
cursorY = drawSegmentedText(
|
||||
page,
|
||||
value.split(' · '),
|
||||
MARGIN_X,
|
||||
cursorY,
|
||||
maxTextW,
|
||||
fonts,
|
||||
)
|
||||
} else {
|
||||
const lines = wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW)
|
||||
for (const line of lines) {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
const TARGET_WIDTH = 1200
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
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,
|
||||
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 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')
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, widthPx, heightPx)
|
||||
ctx.drawImage(img, 0, 0, widthPx, heightPx)
|
||||
return canvas
|
||||
}
|
||||
|
||||
async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> {
|
||||
const blob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob((b) => resolve(b), 'image/png')
|
||||
})
|
||||
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 a data URL without a payload')
|
||||
}
|
||||
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`)
|
||||
*/
|
||||
export async function rasterizeSvg(svgString: string): Promise<Uint8Array> {
|
||||
const { widthPx, heightPx } = readViewBox(svgString)
|
||||
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
|
||||
return canvasToPngBytes(canvas)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user