feat(app): export and import through @faunosteo/pdf — snapshot, archived branding and labels, browser rasterizer, imported archive kept in session, explicit rebase with messages; legacy PDF modules removed

This commit is contained in:
bchanot committed 2026-10-11 13:32:14 +02:00
1 parent 20dafc0b00
commit 9bd5173a9c
43 files changed
+1492 -1989

No files matched your search

+1 -2
View File
@@ -57,8 +57,7 @@ export default function EditorRoute() {
// No report in memory: restore the per-tab draft once the sheet is known.
useEffect(() => {
if (report) return
if (sheet.status === 'ready')
store.restoreDraft(sheet.index.sheet.migrationMap)
if (sheet.status === 'ready') store.restoreDraft(sheet.index)
if (sheet.status !== 'loading' && !useReportStore.getState().report)
navigate('/')
}, [report, sheet, store, navigate])
+75 -35
View File
@@ -1,64 +1,104 @@
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import {
rebaseReportOnSheet,
type ArchiveReadOutcome,
type RebaseOutcome,
} from '@faunosteo/domain'
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
/**
* The lines of the one alert shown after a successful import (STEP6 §16):
* a lossy v2 migration, the archive kept, the snapshot dropped with its
* reason, the rebase onto the current sheet. Empty when nothing applies.
*/
function importMessages(
outcome: ArchiveReadOutcome,
rebase: RebaseOutcome,
t: Translate,
): string[] {
const lines: string[] = []
const lost = outcome.unresolvedFindings + outcome.unresolvedZones
if (outcome.migrated && lost > 0) {
lines.push(t('home.import.migrated').replace('{count}', String(lost)))
}
if (outcome.archive) lines.push(t('home.import.archive_ok'))
if (outcome.snapshotRejected) {
lines.push(
t('home.import.snapshot_rejected').replace(
'{reason}',
t(`home.import.snapshot_reason.${outcome.snapshotRejected}`),
),
)
}
if (rebase.rebased) {
const count = rebase.unresolvedZones + rebase.unresolvedFindings
lines.push(t('home.import.rebased').replace('{count}', String(count)))
}
return lines
}
/** The error line under the import button, by ImportError kind. */
function importErrorMessage(err: unknown, t: Translate): string {
if (!(err instanceof ImportError)) return t('home.import.error_generic')
switch (err.kind) {
case 'incompatible_version':
return t('home.import.error_incompatible_version').replace(
'{version}',
String(err.foundVersion ?? '?'),
)
case 'invalid_pdf':
return t('home.import.error_invalid_pdf')
case 'attachment_stripped':
return t('home.import.error_attachment_stripped')
case 'no_attachment':
return t('home.import.error_no_attachment')
}
}
export default function HomeRoute() {
const navigate = useNavigate()
const fileRef = useRef<HTMLInputElement | null>(null)
const hydrate = useReportStore((s) => s.hydrateReport)
const hydrateImport = useReportStore((s) => s.hydrateImport)
const sheet = useSheet(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const t = useT()
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File, index: SheetIndex) {
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
const rebase = rebaseReportOnSheet(
outcome.report,
index,
outcome.archive?.sheetSnapshot ?? null,
)
hydrateImport({ report: rebase.report, archive: outcome.archive })
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
navigate('/editor')
}
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file || sheet.status !== 'ready') return
setBusy(true)
setError(null)
try {
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(
bytes,
sheet.index.sheet.migrationMap,
)
if (
outcome.migrated &&
outcome.unresolvedFindings + outcome.unresolvedZones > 0
) {
window.alert(
t('home.import.migrated').replace(
'{count}',
String(outcome.unresolvedFindings + outcome.unresolvedZones),
),
)
}
hydrate(outcome.report)
navigate('/editor')
await importFile(file, sheet.index)
} catch (err) {
if (err instanceof ImportError) {
if (err.kind === 'incompatible_version') {
setError(
t('home.import.error_incompatible_version').replace(
'{version}',
String(err.foundVersion ?? '?'),
),
)
} else if (err.kind === 'invalid_pdf') {
setError(t('home.import.error_invalid_pdf'))
} else {
setError(t('home.import.error_no_attachment'))
}
} else {
setError(t('home.import.error_generic'))
}
setError(importErrorMessage(err, t))
} finally {
setBusy(false)
if (fileRef.current) fileRef.current.value = ''
+15 -19
View File
@@ -32,6 +32,21 @@ export const en: Dict = {
'This PDF uses format v{version}, which this version of the application cannot read (accepted formats: v2 and v3).',
'home.import.migrated':
'Report imported from an older format. Findings not found in the current sheet: {count} (kept with their labels).',
'home.import.archive_ok':
'Faunosteo archive imported: report and the original sheet snapshot kept.',
'home.import.snapshot_rejected':
'Report recovered, but the original sheet snapshot was rejected ({reason}): this archive cannot be reproduced as is.',
'home.import.snapshot_reason.unsupported_envelope':
'archive from a newer version',
'home.import.snapshot_reason.schema': 'invalid content',
'home.import.snapshot_reason.caps': 'size or complexity over the limits',
'home.import.snapshot_reason.integrity': 'inconsistent sheet',
'home.import.snapshot_reason.sheet_mismatch':
"sheet differs from the report's",
'home.import.rebased':
"Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels).",
'home.import.error_attachment_stripped':
'This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file.',
'home.no_sheet.title': 'No anatomical sheet',
'home.no_sheet.description':
'This build of the application carries no anatomical sheet: no report can be created or imported.',
@@ -150,25 +165,6 @@ export const en: Dict = {
'severity.moderate': 'moderate',
'severity.severe': 'severe',
'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHESIS',
'pdf.title.conclusion': 'Conclusion',
'pdf.section.zones': 'ZONES',
'pdf.section.findings_prefix': 'FINDINGS — ',
'pdf.section.free_findings': 'FREE FINDINGS',
'pdf.section.severity': 'SEVERITY',
'pdf.section.comment': 'COMMENT',
'pdf.section.conclusion': 'CONCLUSION',
'pdf.section.recommendations': 'RECOMMENDATIONS',
'pdf.section.next_appointment': 'NEXT APPOINTMENT',
'pdf.view.general': 'GENERAL VIEW',
'pdf.view.detail_prefix': 'DETAIL VIEW — ',
'pdf.empty': '—',
'pdf.owner_prefix': 'Owner: ',
'pdf.siret_prefix': 'SIRET ',
'pdf.title.suffix.bilan': 'Osteo report — ',
'pdf.subject': 'Animal osteopathic report',
'lang.group_label': 'Language',
'lang.switch_to_fr': 'Passer en français',
'lang.switch_to_en': 'Switch to English',
+15 -20
View File
@@ -34,6 +34,21 @@ export const fr: Dict = {
"Ce PDF est au format v{version}, que cette version de l'application ne sait pas lire (formats acceptés : v2 et v3).",
'home.import.migrated':
'Bilan importé depuis un ancien format. Constats non retrouvés dans la fiche actuelle : {count} (conservés avec leurs libellés).',
'home.import.archive_ok':
"Archive Faunosteo importée : bilan et instantané de la fiche d'origine conservés.",
'home.import.snapshot_rejected':
"Bilan récupéré, mais l'instantané de la fiche d'origine a été rejeté ({reason}) : cette archive ne pourra pas être reproduite telle quelle.",
'home.import.snapshot_reason.unsupported_envelope':
"archive d'une version plus récente",
'home.import.snapshot_reason.schema': 'contenu invalide',
'home.import.snapshot_reason.caps': 'taille ou complexité excessive',
'home.import.snapshot_reason.integrity': 'fiche incohérente',
'home.import.snapshot_reason.sheet_mismatch':
'fiche différente de celle du bilan',
'home.import.rebased':
"Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés).",
'home.import.error_attachment_stripped':
"Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine.",
'home.no_sheet.title': 'Aucune fiche anatomique',
'home.no_sheet.description':
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
@@ -165,26 +180,6 @@ export const fr: Dict = {
'severity.moderate': 'modérée',
'severity.severe': 'sévère',
// pdf
'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHÈSE',
'pdf.title.conclusion': 'Conclusion',
'pdf.section.zones': 'ZONES',
'pdf.section.findings_prefix': 'CONSTATS — ',
'pdf.section.free_findings': 'CONSTATS LIBRES',
'pdf.section.severity': 'SÉVÉRITÉ',
'pdf.section.comment': 'COMMENTAIRE',
'pdf.section.conclusion': 'CONCLUSION',
'pdf.section.recommendations': 'RECOMMANDATIONS',
'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS',
'pdf.view.general': 'VUE GÉNÉRALE',
'pdf.view.detail_prefix': 'VUE DÉTAIL — ',
'pdf.empty': '—',
'pdf.owner_prefix': 'Propriétaire : ',
'pdf.siret_prefix': 'SIRET ',
'pdf.title.suffix.bilan': 'Bilan ostéo — ',
'pdf.subject': "Bilan d'ostéopathie animalière",
// language switcher
'lang.group_label': 'Langue',
'lang.switch_to_fr': 'Passer en français',
-200
View File
@@ -1,200 +0,0 @@
import { AFRelationship, type PDFDocument } from 'pdf-lib'
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'
export class IncompatibleReportVersionError extends Error {
constructor(public readonly foundVersion: number | null) {
super(`incompatible_version:${foundVersion ?? 'unknown'}`)
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 v${REPORT_VERSION}`,
creationDate: new Date(),
modificationDate: new Date(),
afRelationship: AFRelationship.Data,
})
}
export interface ExtractedReport extends MigrationOutcome {
/** True when the attachment was an older version lifted to v3. */
migrated: boolean
}
/**
* The raw report document carried by the PDF, of whatever version, before
* any migration: what the archive check tool shows next to the v3 result.
* Throws when the PDF carries no Faunosteo attachment or an oversized one.
*/
export async function readAttachedDocument(
pdfDoc: PDFDocument,
): Promise<unknown> {
const bytes = await attachmentBytes(pdfDoc)
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
throw new Error('attachment too large')
}
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
if (versionOf(data) === null) {
throw new Error('attachment carries no report version')
}
return data
}
export async function extractReportJson(
pdfDoc: PDFDocument,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
const data = await readAttachedDocument(pdfDoc)
try {
return {
...readReportDocument(data, map),
migrated: versionOf(data) !== REPORT_VERSION,
}
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new IncompatibleReportVersionError(err.foundVersion)
}
throw err
}
}
async function attachmentBytes(pdfDoc: PDFDocument): Promise<Uint8Array> {
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 hit.data
}
}
const fallback = await traverseForJsonAttachment(pdfDoc)
if (!fallback) throw new Error('No osteo-report attachment found')
return fallback
}
/** Hard ceiling on an attachment (inflated or not): a report is a few hundred KB at most. */
const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
function versionOf(data: unknown): number | null {
if (data === null || typeof data !== 'object') return null
const v = (data as { version?: unknown }).version
return typeof v === 'number' ? v : null
}
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 = MAX_ATTACHMENT_BYTES
/** 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
}
+81
View File
@@ -0,0 +1,81 @@
import type { Branding, ImageAsset } from '@faunosteo/domain'
/**
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
* the four `public/` files fetched by their current URLs, each failure
* leaving its slot empty with a warning (the page then prints the credit's
* fallback text), plus the credit URLs. The result travels inside the
* archive, so a re-export never needs these files again.
*/
// shortcut: the site URL and the credit constants belong to the runtime
// config (ConfigProvider); they live here until AppConfig carries them.
const SITE_URL = 'https://faunosteo.com'
const POWERED_BY = {
url: 'https://zenquality.fr',
fallbackText: 'zenquality.fr',
}
const PARTNER = {
url: 'https://www.instagram.com/paws.iin.harmony',
fallbackText: '@paws.iin.harmony',
}
const HEADER_LOGO_URL = '/assets/faunosteo_logo_horizontal-512.png'
const FOOTER_LOGO_URL = '/assets/faunosteo-horizontal-com-512.png'
const POWERED_BY_LOGO_URL = '/brand/zenquality-logo-fr.png'
const PARTNER_LOGO_URL = '/Paws_in_harmony.svg'
/** btoa takes a binary string; chunking keeps the argument list small. */
function bytesToBase64(bytes: Uint8Array): string {
const CHUNK = 0x8000
let binary = ''
for (let i = 0; i < bytes.length; i += CHUNK) {
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
}
return btoa(binary)
}
async function fetchOk(url: string): Promise<Response> {
const resp = await fetch(url)
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
return resp
}
async function pngAsset(url: string): Promise<ImageAsset> {
const bytes = new Uint8Array(await (await fetchOk(url)).arrayBuffer())
return { kind: 'png', base64: bytesToBase64(bytes) }
}
async function svgAsset(url: string): Promise<ImageAsset> {
return { kind: 'svg', svg: await (await fetchOk(url)).text() }
}
/** A slot fails alone: the export goes on without that logo. */
async function slot(
load: Promise<ImageAsset>,
url: string,
): Promise<ImageAsset | null> {
try {
return await load
} catch (err) {
console.warn(`Branding asset ${url} skipped:`, err)
return null
}
}
export async function loadBranding(): Promise<Branding> {
const [headerLogo, footerLogo, poweredByLogo, partnerLogo] =
await Promise.all([
slot(pngAsset(HEADER_LOGO_URL), HEADER_LOGO_URL),
slot(pngAsset(FOOTER_LOGO_URL), FOOTER_LOGO_URL),
slot(pngAsset(POWERED_BY_LOGO_URL), POWERED_BY_LOGO_URL),
slot(svgAsset(PARTNER_LOGO_URL), PARTNER_LOGO_URL),
])
return {
siteUrl: SITE_URL,
headerLogo,
footerLogo,
poweredBy: { logo: poweredByLogo, ...POWERED_BY },
partner: { logo: partnerLogo, ...PARTNER },
}
}
+100
View File
@@ -0,0 +1,100 @@
import type { Rasterizer } from '@faunosteo/pdf'
/**
* The browser side of the engine's rasterizer adapter: the engine has fixed
* the pixel size, this module only stamps it on the SVG root and lets the
* browser draw the SVG through an Image / canvas pair, which renders exactly
* what the practitioner sees in the inline anatomy canvas.
*/
const SVG_NS = 'http://www.w3.org/2000/svg'
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
function startsWithPngSignature(bytes: Uint8Array): boolean {
if (bytes.length < PNG_SIGNATURE.length) return false
return PNG_SIGNATURE.every((byte, i) => bytes[i] === byte)
}
/** The root carries the namespace and the engine's size; nothing else changes. */
function sizedSvg(svg: string, widthPx: number, heightPx: number): string {
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
).documentElement
if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS)
root.setAttribute('width', String(widthPx))
root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
function loadImage(svg: string): Promise<HTMLImageElement> {
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
const url = URL.createObjectURL(blob)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
return new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => resolve(img)
img.onerror = () =>
reject(new Error('Browser failed to render the SVG into an Image'))
img.src = url
}).finally(() => URL.revokeObjectURL(url))
}
function drawOnWhiteCanvas(
img: HTMLImageElement,
widthPx: number,
heightPx: number,
): HTMLCanvasElement {
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
}
function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob | null> {
return new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
}
/** Fallback when toBlob yields nothing: decode the data URL by hand. */
function pngFromDataUrl(canvas: HTMLCanvasElement): Uint8Array {
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
}
async function canvasToPng(canvas: HTMLCanvasElement): Promise<Uint8Array> {
const blob = await canvasBlob(canvas)
if (blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
if (startsWithPngSignature(bytes)) return bytes
}
return pngFromDataUrl(canvas)
}
export const browserRasterizer: Rasterizer = async (
svg,
{ widthPx, heightPx },
) => {
const img = await loadImage(sizedSvg(svg, widthPx, heightPx))
return canvasToPng(drawOnWhiteCanvas(img, widthPx, heightPx))
}
+21 -82
View File
@@ -1,97 +1,36 @@
import { PDFDocument } from 'pdf-lib'
import type { Report } from '@faunosteo/domain'
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
import { defaultPdfLabels, exportReportArchive } from '@faunosteo/pdf'
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 { rasterizeSvg } from './render/svgToPng'
import { loadBranding } from './branding'
import { browserRasterizer } from './browserRasterizer'
export interface PdfExportOptions {
locale: Locale
}
/**
* 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.
* Exports the report as an archive PDF through the engine: the loaded sheet
* becomes the snapshot the pages are drawn from and the attachment carries,
* the branding is fetched once from `public/`, the browser rasterises the
* views. Non-fatal engine warnings (a logo or a view that failed) are logged.
*/
export async function exportReportToPdf(
report: Report,
sheet: SheetIndex,
index: SheetIndex,
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)
let headerLogoPdf = null
let footerLogoPdf = null
let zqLogoPdfImage = null
let pawsLogoPdf = null
try {
headerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoLogo())
} catch (err) {
console.warn('Faunosteo logo embed failed:', err)
}
try {
footerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoComLogo())
} catch (err) {
console.warn('Faunosteo -com logo embed failed:', err)
}
try {
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}`)
pawsLogoPdf = await pdfDoc.embedPng(await rasterizeSvg(await resp.text()))
} catch (err) {
console.warn('Paws in Harmony logo embed failed:', err)
}
const headerAssets = { logoPng: headerLogoPdf }
for (let i = 0; i < report.observations.length; i += 1) {
await addObservationPage({
pdfDoc,
report,
observation: report.observations[i]!,
obsIndex: i,
fonts,
sheet,
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)
const result = await exportReportArchive({
report,
sheet: buildSheetSnapshot(index.sheet, report),
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: opts.locale,
rasterizer: browserRasterizer,
exportedAt: new Date(),
})
await attachReportJson(pdfDoc, report)
return pdfDoc.save()
for (const warning of result.warnings) {
console.warn('PDF export warning', warning)
}
return result.pdf
}
-16
View File
@@ -1,16 +0,0 @@
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 }
}
+17 -28
View File
@@ -1,15 +1,13 @@
import { PDFDocument } from 'pdf-lib'
import type { ReportMigrationMap } from '@faunosteo/domain'
import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain'
import {
extractReportJson,
IncompatibleReportVersionError,
type ExtractedReport,
} from './attachment'
ArchiveReadError,
readReportArchive,
type ArchiveReadErrorKind,
} from '@faunosteo/pdf'
export type ImportErrorKind =
| 'invalid_pdf'
| 'incompatible_version'
| 'no_attachment'
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
export type ImportErrorKind = ArchiveReadErrorKind
/**
* Localization-agnostic import error. Carries a kind discriminant + an
@@ -26,31 +24,22 @@ export class ImportError extends Error {
}
}
/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */
export const MAX_PDF_BYTES = 50 * 1024 * 1024
/**
* 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.
* Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2
* migrated through the sheet's map) and, when the file is a Step 6 archive,
* the validated envelope or the reason its snapshot was dropped. Engine
* failures become ImportError kinds, one to one.
*/
export async function importReportFromPdf(
pdfBytes: Uint8Array,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
if (pdfBytes.byteLength > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
let pdfDoc: PDFDocument
): Promise<ArchiveReadOutcome> {
try {
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
} catch {
throw new ImportError('invalid_pdf')
}
try {
return await extractReportJson(pdfDoc, map)
return await readReportArchive(pdfBytes, map)
} catch (err) {
if (err instanceof IncompatibleReportVersionError) {
throw new ImportError('incompatible_version', err.foundVersion)
if (err instanceof ArchiveReadError) {
throw new ImportError(err.kind, err.foundVersion)
}
throw new ImportError('no_attachment')
throw err
}
}
-111
View File
@@ -1,111 +0,0 @@
import { PageSizes, type PDFDocument } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@faunosteo/domain'
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
}
}
-19
View File
@@ -1,19 +0,0 @@
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)
-180
View File
@@ -1,180 +0,0 @@
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,
})
}
-100
View File
@@ -1,100 +0,0 @@
import type { PDFPage, PDFImage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@faunosteo/domain'
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,
})
}
-35
View File
@@ -1,35 +0,0 @@
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)
}
}
-21
View File
@@ -1,21 +0,0 @@
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)
}
-627
View File
@@ -1,627 +0,0 @@
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 { Locale, Dict } from '@/i18n/types'
import { getDict } from '@/i18n'
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 {
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<Severity, ReturnType<typeof rgb>> = {
mild: rgb(0.55, 0.65, 0.45),
moderate: rgb(0.85, 0.55, 0.18),
severe: rgb(0.78, 0.2, 0.2),
}
const SECTION_TEXT_SIZE = 10
const SEPARATOR_GLYPH = '•'
const SEPARATOR_SIZE = 14
const SEPARATOR_SIDE_GAP = 5
/** 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.
*/
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)
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 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 (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%')
filter.setAttribute('y', '-100%')
filter.setAttribute('width', '300%')
filter.setAttribute('height', '300%')
filter.setAttribute('filterUnits', 'userSpaceOnUse')
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')
for (const input of [
'haloWide',
'haloWide',
'haloWide',
'haloTight',
'haloTight',
'SourceGraphic',
]) {
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
n.setAttribute('in', input)
merge.appendChild(n)
}
filter.appendChild(merge)
defs.appendChild(filter)
}
/**
* 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,
): string {
const selected = new Set(
observation.zones
.filter((z) => z.viewId === viewId)
.map((z) => z.annotationId),
)
const root = buildViewSvg(sheet, viewId, new Map())
const applyHalo = sheet.view(viewId)?.kind === 'main'
if (applyHalo) ensureHaloFilter(root)
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-'))
.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
sheet: SheetIndex
locale: Locale
headerAssets: HeaderAssets
}
interface PageDrawContext {
page: PDFPage
fonts: EmbeddedFonts
width: number
}
interface RenderedImage {
label: string
img: PDFImage
aspect: number
}
interface ObservationSection {
label: string
value: string
}
function drawObservationTitleBlock(
ctx: PageDrawContext,
dict: Dict,
obsIndex: number,
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']!, {
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 sevText = (dict[`severity.${severity}`] ?? severity).toUpperCase()
const sevSize = 9
const padX = 8
const padY = 4
const pillW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) + 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[severity] ?? 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
}
/** Every view the observation touches, main first, each rasterised with its highlights. */
async function buildObservationImages(
pdfDoc: PDFDocument,
sheet: SheetIndex,
observation: Observation,
locale: Locale,
dict: Dict,
): Promise<RenderedImage[]> {
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(
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)
return {
label,
img,
aspect: img.width > 0 ? img.height / img.width : 0.6,
}
}),
)
}
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: ReportZone[],
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): string {
return zones
.map((z) => {
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 `${zoneText(z, sheet, locale)}${v}${side}`
})
.join(' · ')
}
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[],
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): ObservationSection[] {
const byZoneSide = new Map<string, Finding[]>()
for (const f of findings) {
const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
}
const sections: ObservationSection[] = []
for (const [key, group] of byZoneSide) {
const zoneId = key.split(':')[0]!
const side = group[0]?.side
let zoneName = findingZoneName(zoneId, sheet, 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
return f.requiresVetReferral ? `(!) ${lbl}` : lbl
})
.join(' · ')
sections.push({
label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
value,
})
}
return sections
}
function buildObservationSections(
observation: Observation,
sheet: SheetIndex,
locale: Locale,
dict: Dict,
): ObservationSection[] {
const zonesText = describeObservationZones(
observation.zones,
sheet,
locale,
dict,
)
const sections: ObservationSection[] = [
{
label: dict['pdf.section.zones']!,
value: zonesText || dict['pdf.empty']!,
},
...buildFindingsSections(observation.findings, sheet, locale, dict),
]
if (observation.freeTextFindings.length) {
sections.push({
label: dict['pdf.section.free_findings']!,
value: observation.freeTextFindings.join(' · '),
})
}
if (observation.severity) {
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(),
})
}
return sections
}
function estimateSectionsHeight(
sections: ObservationSection[],
fonts: EmbeddedFonts,
maxTextW: number,
): number {
let h = TEXT_TOP_GAP
for (const { value } of sections) {
const lineCount = value.includes(' · ')
? 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 the (up to 2-column) image grid; returns the cursor y below it. */
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
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
}
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 {
for (const line of wrapLines(
value,
fonts.bodyRegular,
SECTION_TEXT_SIZE,
maxTextW,
)) {
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,
sheet,
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 rendered = await buildObservationImages(
pdfDoc,
sheet,
observation,
locale,
dict,
)
const maxTextW = width - MARGIN_X * 2
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)
}
-124
View File
@@ -1,124 +0,0 @@
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)
}
-27
View File
@@ -1,27 +0,0 @@
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
}
+46 -7
View File
@@ -1,13 +1,18 @@
import {
readReportDocument,
ReportArchiveEnvelopeSchema,
type Report,
type ReportArchiveEnvelope,
type ReportMigrationMap,
} from '@faunosteo/domain'
/**
* Where the report document lives between renders. One implementation today
* (the per-tab sessionStorage draft, migrated from v2 on read); the Supabase
* and outbox adapters of later steps implement the same interface.
* Where the session lives between renders. The report draft is mirrored on
* every change; the archive an import brought along (the envelope of a
* Step 6 PDF) is written only when the session starts or ends, so a stale
* draft can still be rebased with the labels of its original sheet. One
* implementation today (per-tab sessionStorage); the Supabase and outbox
* adapters of later steps implement the same interfaces.
*/
export interface ReportPersistence {
@@ -15,12 +20,33 @@ export interface ReportPersistence {
save(report: Report | null): void
}
export interface ArchivePersistence {
load(): ReportArchiveEnvelope | null
save(archive: ReportArchiveEnvelope | null): void
}
export const DRAFT_KEY = 'osteo:draft'
export const ARCHIVE_KEY = 'osteo:archive'
function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
function writeOrRemove(key: string, value: unknown): void {
const store = storage()
if (!store) return
if (value === null) {
store.removeItem(key)
return
}
try {
store.setItem(key, JSON.stringify(value))
} catch (err) {
// Quota exceeded: the session goes on, only the mirror is lost.
if (import.meta.env.DEV) console.warn(`${key} not saved`, err)
}
}
export const sessionStoragePersistence: ReportPersistence = {
load(map) {
const raw = storage()?.getItem(DRAFT_KEY)
@@ -33,9 +59,22 @@ export const sessionStoragePersistence: ReportPersistence = {
}
},
save(report) {
const store = storage()
if (!store) return
if (report) store.setItem(DRAFT_KEY, JSON.stringify(report))
else store.removeItem(DRAFT_KEY)
writeOrRemove(DRAFT_KEY, report)
},
}
export const sessionStorageArchivePersistence: ArchivePersistence = {
load() {
const raw = storage()?.getItem(ARCHIVE_KEY)
if (!raw) return null
try {
const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
},
save(archive) {
writeOrRemove(ARCHIVE_KEY, archive)
},
}
+86 -31
View File
@@ -1,19 +1,24 @@
import { create } from 'zustand'
import {
rebaseReportOnSheet,
REPORT_VERSION,
type Animal,
type NextAppointment,
type Observation,
type Owner,
type Practitioner,
type RebaseOutcome,
type Report,
type ReportMigrationMap,
type ReportArchiveEnvelope,
type SheetRef,
} from '@faunosteo/domain'
import { generateId } from '@/lib/id'
import { nowIso } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import {
sessionStorageArchivePersistence,
sessionStoragePersistence,
type ArchivePersistence,
type ReportPersistence,
} from './persistence'
@@ -21,7 +26,10 @@ import {
* In-memory report document (v3) and its editing actions. Observation-level
* zone rules live in services/zoneInteraction; the store only replaces
* documents. The per-tab draft is mirrored through the persistence adapter
* and restored once the sheet (and its migration map) is known.
* and restored once the sheet is known; a draft written on another revision
* of the sheet is rebased on restore. The archive an import brought along
* (STEP6 §14 "App session") is kept beside the report for later operations
* and written only when the session starts or ends.
*/
/** What a new report needs before the store stamps version, id and dates. */
@@ -30,13 +38,26 @@ export type NewReportDraft = Omit<
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
export interface ImportedSession {
report: Report
archive: ReportArchiveEnvelope | null
}
export interface ReportStore {
report: Report | null
/** The envelope of the imported archive, as exported; null otherwise. */
archive: ReportArchiveEnvelope | null
activeObservationIndex: number
initReport: (draft: NewReportDraft, sheet: SheetRef) => void
hydrateReport: (report: Report) => void
/** Restores the per-tab draft; a no-op when a report is already open. */
restoreDraft: (map: ReportMigrationMap) => void
/** Opens an imported report (already rebased) with its archive. */
hydrateImport: (session: ImportedSession) => void
/**
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
* written on another revision; a no-op when a report is already open.
* Returns the rebase outcome, null when nothing was restored.
*/
restoreDraft: (index: SheetIndex) => RebaseOutcome | null
addObservation: () => void
removeObservation: (index: number) => void
moveObservationUp: (index: number) => void
@@ -62,49 +83,79 @@ export function emptyObservation(): Observation {
}
}
/** A fresh v3 document: the store stamps version, id, dates and the sheet. */
function newReport(draft: NewReportDraft, sheet: SheetRef): Report {
return {
...draft,
version: REPORT_VERSION,
id: generateId(),
createdAt: nowIso(),
sheet,
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
localAnnotations: [],
}
}
function swapped(list: Observation[], i: number, j: number): Observation[] {
const next = [...list]
;[next[i], next[j]] = [next[j]!, next[i]!]
return next
}
type Patch = Partial<Pick<ReportStore, 'report' | 'activeObservationIndex'>>
type Patch = Partial<
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
>
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
}
export function createReportStore(persistence: ReportPersistence) {
const store = create<ReportStore>((set) => ({
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
) {
/** The archive mirror is explicit: these actions are the session's edges. */
const withArchive = (patch: Patch, archive: ReportArchiveEnvelope | null) => {
archives.save(archive)
return { ...patch, archive }
}
const store = create<ReportStore>((set, get) => ({
report: null,
archive: null,
activeObservationIndex: 0,
initReport: (draft, sheet) =>
set({
report: {
...draft,
version: REPORT_VERSION,
id: generateId(),
createdAt: nowIso(),
sheet,
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
localAnnotations: [],
},
activeObservationIndex: 0,
}),
set(
withArchive(
{ report: newReport(draft, sheet), activeObservationIndex: 0 },
null,
),
),
hydrateReport: (report) => set({ report, activeObservationIndex: 0 }),
hydrateReport: (report) =>
set(withArchive({ report, activeObservationIndex: 0 }, null)),
restoreDraft: (map) =>
set((s) => {
if (s.report) return s
const report = persistence.load(map)
return report ? { report, activeObservationIndex: 0 } : s
}),
hydrateImport: ({ report, archive }) =>
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
restoreDraft: (index) => {
if (get().report) return null
const draft = persistence.load(index.sheet.migrationMap)
if (!draft) return null
const archive = archives.load()
const rebase = rebaseReportOnSheet(
draft,
index,
archive?.sheetSnapshot ?? null,
)
set({ report: rebase.report, archive, activeObservationIndex: 0 })
return rebase
},
addObservation: () =>
onReport(set, (r) => {
@@ -177,10 +228,14 @@ export function createReportStore(persistence: ReportPersistence) {
delete rest.nextAppointment
return { report: next ? { ...rest, nextAppointment: next } : rest }
}),
reset: () => set({ report: null, activeObservationIndex: 0 }),
reset: () =>
set(withArchive({ report: null, activeObservationIndex: 0 }, null)),
}))
store.subscribe((state) => persistence.save(state.report))
return store
}
export const useReportStore = createReportStore(sessionStoragePersistence)
export const useReportStore = createReportStore(
sessionStoragePersistence,
sessionStorageArchivePersistence,
)