feat(app): application on the canonical sheet — report v3 store with v2 draft migration, bundled SheetProvider (SHEET_BUNDLE), annotation layer rendered from the document, zone interaction service, pickers and cards on the sheet index, PDF v3 export with v2 archive import; legacy registry, matchers, editors and assets removed

This commit is contained in:
bchanot committed 2026-10-10 11:36:14 +02:00
1 parent 0a17e390cf
commit ce2ec26112
114 files changed
+3560 -14637

No files matched your search

+81 -33
View File
@@ -1,59 +1,92 @@
import { AFRelationship, type PDFDocument } from 'pdf-lib'
import { ReportSchema, type Report } from '@/domain/schema/report'
import {
readReportDocument,
REPORT_VERSION,
UnsupportedReportVersionError,
type MigrationOutcome,
type Report,
type ReportMigrationMap,
} from '@faunosteo/domain'
/**
* The report document travels inside the PDF as a native attachment.
* Written as v3; read back as v3, or as v2 migrated through the sheet's
* migration map (the practitioner's archive). Any other version is refused
* with the found version.
*/
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}`)
constructor(public readonly foundVersion: number | null) {
super(`incompatible_version:${foundVersion ?? 'unknown'}`)
this.name = 'IncompatibleReportVersionError'
}
}
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> {
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',
description: `Faunosteo state v${REPORT_VERSION}`,
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 }> }
export interface ExtractedReport extends MigrationOutcome {
/** True when the attachment was an older version lifted to v3. */
migrated: boolean
}
export async function extractReportJson(
pdfDoc: PDFDocument,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
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 hit =
list.find(
(a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json'),
) ?? list[0]
return parseAttachment(hit.data, map)
}
}
const fallback = await traverseForJsonAttachment(pdfDoc)
if (!fallback) throw new Error('No osteo-report attachment found')
return parseAttachment(fallback)
return parseAttachment(fallback, map)
}
function parseAttachment(bytes: Uint8Array): Report {
const text = new TextDecoder().decode(bytes)
const data: unknown = JSON.parse(text)
if (
function parseAttachment(
bytes: Uint8Array,
map: ReportMigrationMap,
): ExtractedReport {
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
const version =
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)
typeof (data as { version?: unknown }).version === 'number'
? (data as { version: number }).version
: null
try {
return {
...readReportDocument(data, map),
migrated: version !== REPORT_VERSION,
}
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new IncompatibleReportVersionError(err.foundVersion)
}
throw err
}
return ReportSchema.parse(data)
}
interface RawObj {
@@ -68,10 +101,14 @@ interface RawObj {
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> {
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 stream = new Blob([bytes as BlobPart])
.stream()
.pipeThrough(new DecompressionStream('deflate'))
const reader = stream.getReader()
const chunks: Uint8Array[] = []
let total = 0
@@ -99,13 +136,20 @@ export async function inflateFlate(bytes: Uint8Array): Promise<Uint8Array | 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
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
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
@@ -115,9 +159,13 @@ async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise<Uint8Arra
for (const [k, v] of entries) {
const ks = String(k)
const vs = String(v)
if (ks.includes('Type') && vs.includes('EmbeddedFile')) isEmbeddedFile = true
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'))) {
if (
ks.includes('Subtype') &&
(vs.includes('application/json') || vs.includes('application#2Fjson'))
) {
isJsonSubtype = true
}
}
+18 -90
View File
@@ -1,94 +1,32 @@
import { PDFDocument } from 'pdf-lib'
import type { Report } from '@/domain/schema/report'
import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import type { SheetIndex } from '@/services/sheetIndex'
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 {
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`.
* Exports a report to PDF from the in-memory document and the loaded sheet:
* labels and drawings come from the sheet, nothing is fetched except the
* partner logos. The v3 document is attached for re-import.
*/
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,
sheet: SheetIndex,
opts: PdfExportOptions,
): Promise<Uint8Array> {
const { locale } = opts
@@ -101,53 +39,43 @@ export async function exportReportToPdf(
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)
headerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoLogo())
} catch (err) {
console.warn('Faunosteo logo embed failed:', err)
}
try {
const bytes = await loadFaunosteoComLogo()
footerLogoPdf = await pdfDoc.embedPng(bytes)
footerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoComLogo())
} catch (err) {
console.warn('Faunosteo -com logo embed failed:', err)
}
try {
const zqPngBytes = await loadZenqualityLogo()
zqLogoPdfImage = await pdfDoc.embedPng(zqPngBytes)
zqLogoPdfImage = await pdfDoc.embedPng(await loadZenqualityLogo())
} 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)
pawsLogoPdf = await pdfDoc.embedPng(await rasterizeSvg(await resp.text()))
} 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) {
for (let i = 0; i < report.observations.length; i += 1) {
await addObservationPage({
pdfDoc,
report,
observation: report.observations[i],
observation: report.observations[i]!,
obsIndex: i,
fonts,
zoneLabels,
findingsTree,
sheet,
locale,
headerAssets,
})
+17 -5
View File
@@ -1,6 +1,10 @@
import { PDFDocument } from 'pdf-lib'
import { extractReportJson, IncompatibleReportVersionError } from './attachment'
import type { Report } from '@/domain/schema/report'
import type { ReportMigrationMap } from '@faunosteo/domain'
import {
extractReportJson,
IncompatibleReportVersionError,
type ExtractedReport,
} from './attachment'
export type ImportErrorKind =
| 'invalid_pdf'
@@ -15,14 +19,22 @@ export type ImportErrorKind =
export class ImportError extends Error {
constructor(
public readonly kind: ImportErrorKind,
public readonly foundVersion?: number,
public readonly foundVersion?: number | null,
) {
super(kind)
this.name = 'ImportError'
}
}
export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report> {
/**
* Reads a Faunosteo PDF back into a report document (v3, or v2 migrated
* through the reference sheet's map). The outcome says whether a migration
* happened and how many zones or findings it could not place.
*/
export async function importReportFromPdf(
pdfBytes: Uint8Array,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
let pdfDoc: PDFDocument
try {
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
@@ -30,7 +42,7 @@ export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report>
throw new ImportError('invalid_pdf')
}
try {
return await extractReportJson(pdfDoc)
return await extractReportJson(pdfDoc, map)
} catch (err) {
if (err instanceof IncompatibleReportVersionError) {
throw new ImportError('incompatible_version', err.foundVersion)
+14 -4
View File
@@ -1,6 +1,6 @@
import { PageSizes, type PDFDocument } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { drawHeader, type HeaderAssets } from './header'
@@ -61,9 +61,19 @@ export async function addConclusionPage(
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'] },
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 =
+10 -3
View File
@@ -55,7 +55,10 @@ export function drawFooter(
}
const poweredLabel = `${dict['footer.powered_by']} `
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(poweredLabel, FONT_SIZE)
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(
poweredLabel,
FONT_SIZE,
)
const zqLogoW = 70
const zqLogoH = 16
const zqFallback = 'zenquality.fr'
@@ -106,12 +109,16 @@ export function drawFooter(
}
const partnerLabel = `${dict['footer.in_partnership']} `
const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(partnerLabel, FONT_SIZE)
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 pawsLogoW =
pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height)
const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW
page.drawText(partnerLabel, {
x: partnerX,
+1 -1
View File
@@ -1,6 +1,6 @@
import type { PDFPage, PDFImage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { formatDate } from '@/lib/dates'
+174 -198
View File
@@ -1,19 +1,25 @@
import { rgb, PageSizes, type PDFDocument, type PDFPage, type PDFImage } from 'pdf-lib'
import {
rgb,
PageSizes,
type PDFDocument,
type PDFPage,
type PDFImage,
} from 'pdf-lib'
import type {
Finding,
Observation,
Report,
ReportZone,
Severity,
} from '@faunosteo/domain'
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 { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { buildViewSvg } from '@/anatomy/drawing'
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,
@@ -39,10 +45,10 @@ 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 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
@@ -70,7 +76,7 @@ function countSegmentedLines(
let x = 0
for (let i = 0; i < items.length; i += 1) {
const itemW = fonts.bodyRegular.widthOfTextAtSize(
items[i],
items[i]!,
SECTION_TEXT_SIZE,
)
if (x + itemW > maxWidth && x > 0) {
@@ -92,8 +98,7 @@ function countSegmentedLines(
/**
* 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.
* bullet. Returns the cursor y *below* the last line drawn.
*/
function drawSegmentedText(
page: PDFPage,
@@ -105,15 +110,11 @@ function drawSegmentedText(
): 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 item = items[i]!
const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE)
if (x + itemW > startX + maxWidth && x > startX) {
x = startX
@@ -150,22 +151,17 @@ 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.
* Adds a Gaussian-blur "halo" filter so the highlighted markers stay
* visible on the whole-animal view once rasterised at print scale.
*/
function ensureHaloFilter(root: SVGSVGElement): void {
const doc = root.ownerDocument
if (!doc) return
if (doc.getElementById(HALO_FILTER_ID)) return
if (root.querySelector(`#${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%')
@@ -173,84 +169,63 @@ function ensureHaloFilter(root: SVGSVGElement): void {
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) {
for (const input of [
'haloWide',
'haloWide',
'haloWide',
'haloTight',
'haloTight',
'SourceGraphic',
]) {
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
n.setAttribute('in', 'haloWide')
n.setAttribute('in', input)
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,
/**
* The view rendered from the sheet with the observation's zones of that
* view highlighted (legacy picture: accent fill, halo on the main view,
* other markers hidden, no data attributes left).
*/
export function highlightedViewSvg(
sheet: SheetIndex,
viewId: string,
observation: Observation,
sourceDetailId: string | undefined,
): Promise<string> {
const root = await loadSvg(speciesSvgPath)
const bones = parseSvgBones(root)
const selectedIds = new Set(
): string {
const selected = new Set(
observation.zones
.filter((z) => z.detailSourceId === sourceDetailId)
.map((z) => z.boneId),
.filter((z) => z.viewId === viewId)
.map((z) => z.annotationId),
)
// 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
const root = buildViewSvg(sheet, viewId, new Map())
const applyHalo = sheet.view(viewId)?.kind === 'main'
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) => {
root.querySelectorAll<Element>('[data-anno-id]').forEach((el) => {
if (selected.has(el.getAttribute('data-anno-id') ?? '')) {
el.setAttribute('fill', '#b85a3f')
el.setAttribute('fill-opacity', '0.85')
if (applyHalo) el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
} else {
el.setAttribute('display', 'none')
}
Array.from(el.attributes)
.filter((a) => a.name.startsWith('data-anno-'))
.filter((a) => a.name.startsWith('data-'))
.forEach((a) => el.removeAttribute(a.name))
})
return new XMLSerializer().serializeToString(root)
}
@@ -261,49 +236,40 @@ export interface ObservationPageContext {
observation: Observation
obsIndex: number
fonts: EmbeddedFonts
zoneLabels: Map<string, ZoneLabelPair>
findingsTree: SpeciesFindings | null
sheet: SheetIndex
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'],
severity: Severity | undefined,
): 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'], {
page.drawText(dict['pdf.eyebrow.observation']!, {
x: MARGIN_X,
y: eyebrowY,
size: 9,
@@ -319,14 +285,11 @@ function drawObservationTitleBlock(
})
if (severity) {
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
const sev = severity
const sevLabel = dict[`severity.${sev}`] ?? sev
const sevText = sevLabel.toUpperCase()
const sevText = (dict[`severity.${severity}`] ?? severity).toUpperCase()
const sevSize = 9
const sevTextW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize)
const padX = 8
const padY = 4
const pillW = sevTextW + padX * 2
const pillW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) + padX * 2
const pillH = sevSize + padY * 2
const pillX = MARGIN_X + numW + 14
const pillY = titleY + 4
@@ -335,7 +298,7 @@ function drawObservationTitleBlock(
y: pillY,
width: pillW,
height: pillH,
color: SEVERITY_BG[sev] ?? COLOR_MUTED,
color: SEVERITY_BG[severity] ?? COLOR_MUTED,
})
page.drawText(sevText, {
x: pillX + padX,
@@ -354,100 +317,97 @@ function drawObservationTitleBlock(
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.
*/
/** Every view the observation touches, main first, each rasterised with its highlights. */
async function buildObservationImages(
pdfDoc: PDFDocument,
species: SpeciesManifest,
sheet: SheetIndex,
observation: Observation,
locale: Locale,
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,
})
}
const viewIds = [...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),
)
return Promise.all(
items.map(async (it) => {
const svgStr = await colorizedSvgString(it.src, observation, it.sourceId)
const png = await rasterizeSvg(svgStr)
viewIds.map(async (viewId) => {
const view = sheet.view(viewId)!
const label =
view.kind === 'main'
? dict['pdf.view.general']!
: `${dict['pdf.view.detail_prefix']}${pickLabel(view.name, locale).toUpperCase()}`
const png = await rasterizeSvg(
highlightedViewSvg(sheet, viewId, observation),
)
const img = await pdfDoc.embedPng(png)
const aspect = img.width > 0 ? img.height / img.width : 0.6
return { label: it.label, img, aspect }
return {
label,
img,
aspect: img.width > 0 ? img.height / img.width : 0.6,
}
}),
)
}
/** Renders the "Zones" section value: bilingual labels + vertebra/side suffixes. */
function zoneText(z: ReportZone, sheet: SheetIndex, locale: Locale): 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 describeObservationZones(
zones: Observation['zones'],
zoneLabels: Map<string, ZoneLabelPair>,
zones: ReportZone[],
sheet: SheetIndex,
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}`
return `${zoneText(z, sheet, locale)}${v}${side}`
})
.join(' · ')
}
/** Groups findings by zone+side, one label/value section entry per group. */
function findingZoneName(
zoneId: string,
sheet: SheetIndex,
locale: Locale,
): string {
const zone = sheet.findingZone(zoneId)
return zone ? pickLabel(zone.name, locale) : zoneId
}
/** Groups findings by zone+side, one section per group; snapshots give the text. */
function buildFindingsSections(
findings: Finding[],
findingsTree: SpeciesFindings | null,
sheet: SheetIndex,
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 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 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})`
}
let zoneName = findingZoneName(zoneId, sheet, locale)
if (side)
zoneName = `${zoneName} (${dict[side === 'left' ? 'lateral.left' : 'lateral.right']})`
const value = group
.map((f) => {
const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
@@ -462,37 +422,46 @@ function buildFindingsSections(
return sections
}
/** Assembles the ordered label/value sections drawn below the images. */
function buildObservationSections(
observation: Observation,
zoneLabels: Map<string, ZoneLabelPair>,
findingsTree: SpeciesFindings | null,
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): ObservationSection[] {
const zonesText = describeObservationZones(observation.zones, zoneLabels, locale, dict)
const zonesText = describeObservationZones(
observation.zones,
sheet,
locale,
dict,
)
const sections: ObservationSection[] = [
{ label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] },
{
label: dict['pdf.section.zones']!,
value: zonesText || dict['pdf.empty']!,
},
...buildFindingsSections(observation.findings, sheet, locale, dict),
]
sections.push(...buildFindingsSections(observation.findings, findingsTree, locale, dict))
if (observation.freeTextFindings.length) {
sections.push({
label: dict['pdf.section.free_findings'],
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 })
sections.push({
label: dict['pdf.section.severity']!,
value: dict[`severity.${observation.severity}`] ?? observation.severity,
})
}
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
}
/** Estimates the vertical space the given sections will occupy once drawn. */
function estimateSectionsHeight(
sections: ObservationSection[],
fonts: EmbeddedFonts,
@@ -503,16 +472,13 @@ function estimateSectionsHeight(
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
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.
*/
/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
function drawObservationImageGrid(
ctx: PageDrawContext,
rendered: RenderedImage[],
@@ -522,14 +488,10 @@ function drawObservationImageGrid(
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)
@@ -537,7 +499,6 @@ function drawObservationImageGrid(
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))
@@ -557,9 +518,9 @@ function drawObservationImageGrid(
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
page.drawImage(it.img, {
x,
y: cursorY - cellHs[c],
y: cursorY - cellHs[c]!,
width: cellW,
height: cellHs[c],
height: cellHs[c]!,
})
})
cursorY -= rowH
@@ -569,7 +530,6 @@ function drawObservationImageGrid(
return cursorY
}
/** Draws each label/value section, returns the cursor y below the last one. */
function drawObservationSections(
ctx: PageDrawContext,
sections: ObservationSection[],
@@ -597,8 +557,12 @@ function drawObservationSections(
fonts,
)
} else {
const lines = wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW)
for (const line of lines) {
for (const line of wrapLines(
value,
fonts.bodyRegular,
SECTION_TEXT_SIZE,
maxTextW,
)) {
page.drawText(line, {
x: MARGIN_X,
y: cursorY,
@@ -623,8 +587,7 @@ export async function addObservationPage(
observation,
obsIndex,
fonts,
zoneLabels,
findingsTree,
sheet,
locale,
headerAssets,
} = ctx
@@ -634,18 +597,31 @@ export async function addObservationPage(
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 titleY = drawObservationTitleBlock(
drawCtx,
dict,
obsIndex,
observation.severity,
)
const rendered = await buildObservationImages(
pdfDoc,
sheet,
observation,
locale,
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)
const sections = buildObservationSections(observation, sheet, 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)
}
+5 -2
View File
@@ -22,7 +22,8 @@ function ensureSvgAttributes(
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))
if (!root.getAttribute('height'))
root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
@@ -77,7 +78,9 @@ async function rasterizeWithImageElement(
return canvas
}
async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> {
async function canvasToPngBytes(
canvas: HTMLCanvasElement,
): Promise<Uint8Array> {
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/png')
})