feat(pdf): R4.6 app export on the core's session: export.ts drives ExportSession (rasters one by one, warnings in the engine's order, abort on unmount), labels moved to the app, EditorRoute downloads the Blob of the parts; suites read the file's content streams (pdfRead helper), app-path bytes = R4 digests, hex strings upper-case as pdf-lib
This commit is contained in:
1 parent
9e688b6801
commit
d492bf7112
29 files changed
+507
-131
No files matched your search
@@ -34,8 +34,10 @@ import { pickLabel } from '@/i18n/pickLocaleLabel'
|
|||||||
import type { ViewStates } from '@/anatomy/drawing'
|
import type { ViewStates } from '@/anatomy/drawing'
|
||||||
import { exportReportToPdf } from '@/pdf/export'
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
import { downloadBlob } from '@/lib/download'
|
import { downloadBlob } from '@/lib/download'
|
||||||
import type { ExportWarning } from '@faunosteo/pdf'
|
import type {
|
||||||
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
|
ExportWarning,
|
||||||
|
RebaseOutcome,
|
||||||
|
} from '@faunosteo/core-wasm/types'
|
||||||
import { useT } from '@/i18n/useT'
|
import { useT } from '@/i18n/useT'
|
||||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||||
import { coreFailureMessage } from '@/core/failure'
|
import { coreFailureMessage } from '@/core/failure'
|
||||||
@@ -95,6 +97,8 @@ export default function EditorRoute() {
|
|||||||
const heldAttempt = useRef<number | null>(null)
|
const heldAttempt = useRef<number | null>(null)
|
||||||
const [disclaimer, setDisclaimer] = useState<string | null>(null)
|
const [disclaimer, setDisclaimer] = useState<string | null>(null)
|
||||||
const [exporting, setExporting] = useState(false)
|
const [exporting, setExporting] = useState(false)
|
||||||
|
// Leaving the editor mid-export cancels it: the core's session is freed, no file results.
|
||||||
|
const exportAbort = useRef<AbortController | null>(null)
|
||||||
const [editDraft, setEditDraft] = useState<Identity | null>(null)
|
const [editDraft, setEditDraft] = useState<Identity | null>(null)
|
||||||
// One alert per restore, even if the effect runs again before the re-render.
|
// One alert per restore, even if the effect runs again before the re-render.
|
||||||
const rebaseAlerted = useRef(false)
|
const rebaseAlerted = useRef(false)
|
||||||
@@ -103,6 +107,10 @@ export default function EditorRoute() {
|
|||||||
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
|
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => exportAbort.current?.abort()
|
||||||
|
}, [])
|
||||||
|
|
||||||
// No report in memory: restore the per-tab draft once the sheet is known.
|
// No report in memory: restore the per-tab draft once the sheet is known.
|
||||||
// A draft rebased on another sheet is announced with its unresolved count,
|
// A draft rebased on another sheet is announced with its unresolved count,
|
||||||
// an unreadable one is set aside. While the core cannot run, nothing is
|
// an unreadable one is set aside. While the core cannot run, nothing is
|
||||||
@@ -233,14 +241,14 @@ export default function EditorRoute() {
|
|||||||
async function onExport(index: SheetIndex) {
|
async function onExport(index: SheetIndex) {
|
||||||
if (!report) return
|
if (!report) return
|
||||||
setExporting(true)
|
setExporting(true)
|
||||||
|
const abort = new AbortController()
|
||||||
|
exportAbort.current = abort
|
||||||
try {
|
try {
|
||||||
const { pdf, warnings } = await exportReportToPdf(report, index, {
|
const { pdf, warnings } = await exportReportToPdf(report, index, {
|
||||||
locale,
|
locale,
|
||||||
|
signal: abort.signal,
|
||||||
})
|
})
|
||||||
downloadBlob(
|
downloadBlob(pdf, `bilan-${report.animal.name}-${report.date}.pdf`)
|
||||||
new Blob([pdf as BlobPart], { type: 'application/pdf' }),
|
|
||||||
`bilan-${report.animal.name}-${report.date}.pdf`,
|
|
||||||
)
|
|
||||||
const missing = missingItemsOf(warnings)
|
const missing = missingItemsOf(warnings)
|
||||||
if (missing.length) {
|
if (missing.length) {
|
||||||
window.alert(
|
window.alert(
|
||||||
@@ -248,9 +256,12 @@ export default function EditorRoute() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// A cancelled export (the editor left) ends silently.
|
||||||
|
if (abort.signal.aborted) return
|
||||||
console.error('PDF export failed', err)
|
console.error('PDF export failed', err)
|
||||||
window.alert(coreFailureMessage(t, 'editor.export_failed'))
|
window.alert(coreFailureMessage(t, 'editor.export_failed'))
|
||||||
} finally {
|
} finally {
|
||||||
|
if (exportAbort.current === abort) exportAbort.current = null
|
||||||
setExporting(false)
|
setExporting(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
import type { Rasterizer } from '@faunosteo/pdf'
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The browser side of the engine's rasterizer adapter: the engine has fixed
|
* The browser side of the core's raster requests (R4.6; the engine's adapter
|
||||||
* the pixel size, this module only stamps it on the SVG root and lets the
|
* before): the core has fixed the pixel size, this module only stamps it on
|
||||||
* browser draw the SVG through an Image / canvas pair, which renders exactly
|
* the SVG root and lets the browser draw the SVG through an Image / canvas
|
||||||
* what the practitioner sees in the inline anatomy canvas.
|
* pair, which renders exactly what the practitioner sees in the inline
|
||||||
|
* anatomy canvas.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
export interface RasterSize {
|
||||||
|
widthPx: number
|
||||||
|
heightPx: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draws `svg` at `size` as a PNG. */
|
||||||
|
export type Rasterizer = (svg: string, size: RasterSize) => Promise<Uint8Array>
|
||||||
|
|
||||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||||
|
|
||||||
|
|||||||
+105
-25
@@ -1,33 +1,97 @@
|
|||||||
import type { Report } from '@faunosteo/core-wasm/types'
|
|
||||||
import {
|
import {
|
||||||
defaultPdfLabels,
|
openExportSession,
|
||||||
exportReportArchive,
|
type CoreExportSession,
|
||||||
type ExportInput,
|
type CoreOutcome,
|
||||||
type ExportWarning,
|
} from '@faunosteo/core-wasm'
|
||||||
} from '@faunosteo/pdf'
|
import type {
|
||||||
|
ExportInput,
|
||||||
|
ExportWarning,
|
||||||
|
RasterRequest,
|
||||||
|
Report,
|
||||||
|
} from '@faunosteo/core-wasm/types'
|
||||||
|
import { coreRuntime } from '@/core/runtime'
|
||||||
import type { Locale } from '@/i18n/types'
|
import type { Locale } from '@/i18n/types'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import { loadBranding } from './branding'
|
import { loadBranding } from './branding'
|
||||||
import { browserRasterizer } from './browserRasterizer'
|
import { browserRasterizer } from './browserRasterizer'
|
||||||
|
import { defaultPdfLabels } from './labels'
|
||||||
|
|
||||||
export interface PdfExportOptions {
|
export interface PdfExportOptions {
|
||||||
locale: Locale
|
locale: Locale
|
||||||
|
/** Aborting frees the session (the editor leaving mid-export); no file results. */
|
||||||
|
signal?: AbortSignal
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PdfExportResult {
|
export interface PdfExportResult {
|
||||||
pdf: Uint8Array
|
/** The file, from the parts the core handed out (never concatenated in memory). */
|
||||||
/** Non-fatal engine warnings: a logo or a view that failed to embed. */
|
pdf: Blob
|
||||||
|
/** Non-fatal warnings: a logo or a view that failed to embed. */
|
||||||
warnings: ExportWarning[]
|
warnings: ExportWarning[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A core call the export could not go past: its closed kind, for the DEV console. */
|
||||||
|
export class ExportFailure extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly kind: string,
|
||||||
|
detail?: string,
|
||||||
|
) {
|
||||||
|
super(detail ? `${kind}: ${detail}` : kind)
|
||||||
|
this.name = 'ExportFailure'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function unwrap<T>(outcome: CoreOutcome<T>): T {
|
||||||
|
if (!outcome.ok) throw new ExportFailure(outcome.kind, outcome.detail)
|
||||||
|
return outcome.value
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertNotAborted(signal: AbortSignal | undefined): void {
|
||||||
|
if (signal?.aborted) throw new DOMException('export aborted', 'AbortError')
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exports the report as an archive PDF through the engine: the core builds
|
* One batch of the session's requests rasterised under `Promise.all`, as the engine did:
|
||||||
* the snapshot of the loaded sheet the pages are drawn from and the
|
* a raster that fails is reported as it rejects (the warning order the engine recorded),
|
||||||
* attachment carries (R2), the branding comes from the bundled logos, the
|
* the others are given in request order once the batch has settled (the embedding order,
|
||||||
* browser rasterises the views, the TypeScript engine writes the file (the
|
* so the file's bytes do not depend on which raster finished first). The PNG bytes are
|
||||||
* writer moves to the core at R4). The core's report and snapshot are the
|
* copied into the core and dropped as each `addRaster` returns.
|
||||||
* same JSON contracts the engine's Zod types describe. Warnings are logged
|
*/
|
||||||
* and returned for the caller to surface.
|
async function answerBatch(
|
||||||
|
session: CoreExportSession,
|
||||||
|
requests: RasterRequest[],
|
||||||
|
signal: AbortSignal | undefined,
|
||||||
|
): Promise<void> {
|
||||||
|
const settled = await Promise.all(
|
||||||
|
requests.map(async (request) => {
|
||||||
|
try {
|
||||||
|
const png = await browserRasterizer(request.svg, {
|
||||||
|
widthPx: request.widthPx,
|
||||||
|
heightPx: request.heightPx,
|
||||||
|
})
|
||||||
|
return { key: request.key, png }
|
||||||
|
} catch {
|
||||||
|
assertNotAborted(signal)
|
||||||
|
unwrap(session.rasterFailed(request.key))
|
||||||
|
return { key: request.key, png: null }
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
for (const { key, png } of settled) {
|
||||||
|
if (!png) continue
|
||||||
|
assertNotAborted(signal)
|
||||||
|
unwrap(session.addRaster(key, png))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exports the report as an archive PDF through the core's session (R4.6, plan §B.1.6):
|
||||||
|
* the core builds the snapshot of the loaded sheet the pages are drawn from and the
|
||||||
|
* attachment carries, the branding comes from the bundled logos, the labels from
|
||||||
|
* `labels.ts`, the export time from the clock; the core then asks for each raster it
|
||||||
|
* needs (the SVG logos, then the views of each observation), the browser draws it, and
|
||||||
|
* the core writes the file as the rasters arrive. The session is freed whatever happens.
|
||||||
|
* A refused input or a core failure throws (`ExportFailure`, or the `AbortError` of a
|
||||||
|
* cancelled export); warnings are returned for the caller to surface.
|
||||||
*/
|
*/
|
||||||
export async function exportReportToPdf(
|
export async function exportReportToPdf(
|
||||||
report: Report,
|
report: Report,
|
||||||
@@ -35,18 +99,34 @@ export async function exportReportToPdf(
|
|||||||
opts: PdfExportOptions,
|
opts: PdfExportOptions,
|
||||||
): Promise<PdfExportResult> {
|
): Promise<PdfExportResult> {
|
||||||
const snapshot = index.ops.snapshot(report)
|
const snapshot = index.ops.snapshot(report)
|
||||||
if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`)
|
if (!snapshot.ok) throw new ExportFailure(snapshot.kind, snapshot.detail)
|
||||||
const result = await exportReportArchive({
|
const input: ExportInput = {
|
||||||
report: report as ExportInput['report'],
|
report,
|
||||||
sheet: snapshot.value as ExportInput['sheet'],
|
sheetSnapshot: snapshot.value,
|
||||||
branding: await loadBranding(),
|
branding: await loadBranding(),
|
||||||
labels: defaultPdfLabels,
|
labels: defaultPdfLabels,
|
||||||
locale: opts.locale,
|
locale: opts.locale,
|
||||||
rasterizer: browserRasterizer,
|
exportedAt: new Date().toISOString(),
|
||||||
exportedAt: new Date(),
|
}
|
||||||
})
|
assertNotAborted(opts.signal)
|
||||||
for (const warning of result.warnings) {
|
const session = unwrap(openExportSession(coreRuntime(), JSON.stringify(input)))
|
||||||
console.warn('PDF export warning', warning)
|
try {
|
||||||
|
for (;;) {
|
||||||
|
assertNotAborted(opts.signal)
|
||||||
|
const step = unwrap(session.next())
|
||||||
|
if (step.step === 'done') break
|
||||||
|
await answerBatch(session, step.requests, opts.signal)
|
||||||
|
}
|
||||||
|
const parts = unwrap(session.finish())
|
||||||
|
const warnings = unwrap(session.warnings())
|
||||||
|
for (const warning of warnings) {
|
||||||
|
console.warn('PDF export warning', warning)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
pdf: new Blob(parts as BlobPart[], { type: 'application/pdf' }),
|
||||||
|
warnings,
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
session.free()
|
||||||
}
|
}
|
||||||
return { pdf: result.pdf, warnings: result.warnings }
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { PdfLabelSet, PdfLabels } from '@faunosteo/core-wasm/types'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The static wording of the PDF (section headings, metadata), frozen into every archive
|
||||||
|
* the export writes (R4.6: moved verbatim from `packages/pdf/src/i18n`, same key order,
|
||||||
|
* which is the order every shipped attachment carries; the app dictionaries hold no
|
||||||
|
* `pdf.*` key). A wording change here changes new exports only: an old archive keeps the
|
||||||
|
* labels it was written with.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fr: PdfLabels = {
|
||||||
|
'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",
|
||||||
|
'severity.mild': 'légère',
|
||||||
|
'severity.moderate': 'modérée',
|
||||||
|
'severity.severe': 'sévère',
|
||||||
|
'lateral.left': 'Gauche',
|
||||||
|
'lateral.right': 'Droite',
|
||||||
|
'footer.powered_by': 'Propulsé par',
|
||||||
|
'footer.in_partnership': 'En partenariat avec',
|
||||||
|
}
|
||||||
|
|
||||||
|
const en: PdfLabels = {
|
||||||
|
'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',
|
||||||
|
'severity.mild': 'mild',
|
||||||
|
'severity.moderate': 'moderate',
|
||||||
|
'severity.severe': 'severe',
|
||||||
|
'lateral.left': 'Left',
|
||||||
|
'lateral.right': 'Right',
|
||||||
|
'footer.powered_by': 'Powered by',
|
||||||
|
'footer.in_partnership': 'In partnership with',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const defaultPdfLabels: PdfLabelSet = { fr, en }
|
||||||
@@ -1 +1 @@
|
|||||||
2b9a359c078f5fa1b623ee4db45407209b662909044a6a9f6d02eef4d103d72e
|
2bf8290a85caa5c7e51fee3804de647858633b9cb1d29c950d50e9ce91ae0f18
|
||||||
@@ -1 +1 @@
|
|||||||
3d76027dc76f799c3a9cb3e9ac5d082a27e58b2ef1e631e2003ba9fee6903b6b
|
6a405c4579dffaa06625ee363f406def86f70783e74551441b394b35ffb6b4d0
|
||||||
@@ -1 +1 @@
|
|||||||
52999af79a82a426ed76e6268388dd641e7eb233f826dab6f87d47c5ecc267ca
|
03b7e41957e39a68e9349231186710a05e4e0b92b1e791879401e78b5c073993
|
||||||
@@ -1 +1 @@
|
|||||||
e8ee3238a5c4df10c8564c67148abcdb7b2d282b5f7de3ee5dffbc72ff662247
|
3f89ff74fcec00b79d143a6e435bdb3fd70a81371daf5c73918997c703aabd9e
|
||||||
@@ -1 +1 @@
|
|||||||
287f608e77d0d41b15494e72db8415292058f8e65e0e61c4201c76b106763ba3
|
87f7a6095e38164ee7b06d452fb5eb00a266ffd6da4d77fa84999052ee8396c3
|
||||||
@@ -1 +1 @@
|
|||||||
54a0472c39791c1b5426bf17dbf824ba3079acde66f3062b43643163cc869841
|
400652e30e0d85d6bf1fbec68630bed743b147745d55d7c3b25000d821b7b447
|
||||||
@@ -1 +1 @@
|
|||||||
8ff84417d542cd200b5364844f382a21f19392284f0f7a61040e7e7269fc32dc
|
73580fb43b3505356547e6a1ed18c5412eca7427aacc9daf356b9bcf7f1f9f78
|
||||||
@@ -1 +1 @@
|
|||||||
6fe8ee50a6c6bda2eab48412f607181b23098cff7132747f623637cb9975c0a0
|
d4b6bc2af9286ebe870198e14ab60e82e54f48ee6027ee16dfee8b442caa2821
|
||||||
@@ -1 +1 @@
|
|||||||
58adc70d9de66848bd84a932edce590e1e151444ec063122a5b4eb67343b16f8
|
08a962fb15dbdf9a1064fa176a7c674b882d14d9321344fe4ded7480ce963f99
|
||||||
@@ -1 +1 @@
|
|||||||
b65b6289ee4c5252a32172b97241af253be73d8030dd92d090e18f9ca88b1d80
|
284d4a3b579da2c0cad3f90ca96909ca4901856387669d35d8949c16e81305e1
|
||||||
@@ -1 +1 @@
|
|||||||
138c6ca5c9513b5e03b2db76e6b085a0b1fe35a3afedb21f4fd5762049d2b82a
|
503ec265cab6d5c8a776fae458cf782c3bb51db3a9c0edf06e93b2365c41350e
|
||||||
@@ -1 +1 @@
|
|||||||
b842ceafdefacea26b376ab443b3c6b69a9466e853e640b3138f7f788ff781a5
|
cdac37b198552778e9afbc62a3b74a7868c61cd9c43800d41a689a389f2b6077
|
||||||
@@ -1 +1 @@
|
|||||||
0cf6d48786c388b1c1d2d48b2e78f854f92af378f22dcd2dcbafdb2650b676a3
|
0da6e80c849c040ca3584c208320412ddf6d2131fd9836e14c0584b44e2c49fd
|
||||||
@@ -1 +1 @@
|
|||||||
59569ab96f4a022bd70a2a1d260bda13daedb810f80744afc6b719b9f5a3f6d3
|
828c8250593af1133738843489205242e80804c9ebee76cdeda22bea75406188
|
||||||
@@ -56,6 +56,7 @@ export async function trappingCoreRuntime(marker: string) {
|
|||||||
call: glue.call,
|
call: glue.call,
|
||||||
SheetHandle: Trapping,
|
SheetHandle: Trapping,
|
||||||
FileBytes: glue.FileBytes,
|
FileBytes: glue.FileBytes,
|
||||||
|
ExportSession: glue.ExportSession,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import {
|
||||||
|
decodePDFRawStream,
|
||||||
|
PDFArray,
|
||||||
|
PDFDict,
|
||||||
|
PDFDocument,
|
||||||
|
PDFName,
|
||||||
|
PDFRawStream,
|
||||||
|
type PDFPage,
|
||||||
|
} from 'pdf-lib'
|
||||||
|
import { round2, type ImageEntry, type TextEntry } from './goldens'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The drawing facts of a saved PDF, read back from its content streams (R4.6: the core
|
||||||
|
* writes the file, so nothing is recorded at draw time any more; pdf-lib still reads the
|
||||||
|
* file in the tests until R4.8). The streams are the operator sequences pdf-lib emitted
|
||||||
|
* and the core reproduces: one operator per line, `q BT rg Tf TL Tm (Tj T*)+ ET Q` per
|
||||||
|
* text call, `q cm cm cm cm Do Q` per image. Positions are rounded like the recorder did.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** WinAnsi is Windows-1252 for every glyph the engine prints. */
|
||||||
|
const winAnsi = new TextDecoder('windows-1252')
|
||||||
|
|
||||||
|
function hexBytes(token: string): Uint8Array {
|
||||||
|
const hex = token.slice(1, -1)
|
||||||
|
const out = new Uint8Array(hex.length / 2)
|
||||||
|
for (let i = 0; i < out.length; i += 1) {
|
||||||
|
out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
function contentOf(page: PDFPage): string {
|
||||||
|
const contents = page.node.Contents()
|
||||||
|
const streams: PDFRawStream[] = []
|
||||||
|
if (contents instanceof PDFRawStream) streams.push(contents)
|
||||||
|
else if (contents instanceof PDFArray) {
|
||||||
|
for (let i = 0; i < contents.size(); i += 1) {
|
||||||
|
streams.push(contents.lookup(i, PDFRawStream))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return streams
|
||||||
|
.map((stream) =>
|
||||||
|
new TextDecoder('latin1').decode(decodePDFRawStream(stream).decode()),
|
||||||
|
)
|
||||||
|
.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `/F1` → `Helvetica`, through the page's font resources. */
|
||||||
|
function fontNames(page: PDFPage): Map<string, string> {
|
||||||
|
const names = new Map<string, string>()
|
||||||
|
const resources = page.node.lookup(PDFName.of('Resources'), PDFDict)
|
||||||
|
const fonts = resources.lookupMaybe(PDFName.of('Font'), PDFDict)
|
||||||
|
if (!fonts) return names
|
||||||
|
for (const [key, ref] of fonts.entries()) {
|
||||||
|
const font = fonts.context.lookup(ref, PDFDict)
|
||||||
|
const base = font.lookup(PDFName.of('BaseFont'))
|
||||||
|
names.set(key.decodeText(), String(base).replace(/^\//, ''))
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PageFacts {
|
||||||
|
texts: TextEntry[]
|
||||||
|
images: ImageEntry[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPage(page: PDFPage, index: number): PageFacts {
|
||||||
|
const fonts = fontNames(page)
|
||||||
|
const texts: TextEntry[] = []
|
||||||
|
const images: ImageEntry[] = []
|
||||||
|
let font: string | null = null
|
||||||
|
let size: number | null = null
|
||||||
|
let x: number | null = null
|
||||||
|
let y: number | null = null
|
||||||
|
let lines: string[] = []
|
||||||
|
let matrices: number[][] = []
|
||||||
|
for (const line of contentOf(page).split('\n')) {
|
||||||
|
const tokens = line.trim().split(' ')
|
||||||
|
const op = tokens[tokens.length - 1]
|
||||||
|
const operands = tokens.slice(0, -1)
|
||||||
|
switch (op) {
|
||||||
|
case 'q':
|
||||||
|
matrices = []
|
||||||
|
break
|
||||||
|
case 'BT':
|
||||||
|
lines = []
|
||||||
|
break
|
||||||
|
case 'Tf':
|
||||||
|
font = fonts.get(operands[0]!.slice(1)) ?? operands[0]!
|
||||||
|
size = round2(Number(operands[1]))
|
||||||
|
break
|
||||||
|
case 'Tm':
|
||||||
|
x = round2(Number(operands[4]))
|
||||||
|
y = round2(Number(operands[5]))
|
||||||
|
break
|
||||||
|
case 'Tj':
|
||||||
|
lines.push(winAnsi.decode(hexBytes(operands[0]!)))
|
||||||
|
break
|
||||||
|
case 'ET':
|
||||||
|
texts.push({ page: index, text: lines.join('\n'), x, y, size, font })
|
||||||
|
break
|
||||||
|
case 'cm':
|
||||||
|
matrices.push(operands.map(Number))
|
||||||
|
break
|
||||||
|
case 'Do': {
|
||||||
|
const translate = matrices[0] ?? []
|
||||||
|
const scale = matrices[2] ?? []
|
||||||
|
images.push({
|
||||||
|
page: index,
|
||||||
|
x: round2(translate[4]),
|
||||||
|
y: round2(translate[5]),
|
||||||
|
width: round2(scale[0]),
|
||||||
|
height: round2(scale[3]),
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { texts, images }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every text and image call of the file, page by page, in stream order. */
|
||||||
|
export async function readDrawing(bytes: Uint8Array): Promise<PageFacts> {
|
||||||
|
const doc = await PDFDocument.load(bytes)
|
||||||
|
const texts: TextEntry[] = []
|
||||||
|
const images: ImageEntry[] = []
|
||||||
|
doc.getPages().forEach((page, index) => {
|
||||||
|
const facts = readPage(page, index)
|
||||||
|
texts.push(...facts.texts)
|
||||||
|
images.push(...facts.images)
|
||||||
|
})
|
||||||
|
return { texts, images }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bytes of a Blob the export produced. */
|
||||||
|
export async function bytesOf(blob: Blob): Promise<Uint8Array> {
|
||||||
|
return new Uint8Array(await blob.arrayBuffer())
|
||||||
|
}
|
||||||
@@ -62,7 +62,8 @@ async function exportedAttachment(
|
|||||||
const { pdf } = await exportReportToPdf(golden.reports[name], sheet, {
|
const { pdf } = await exportReportToPdf(golden.reports[name], sheet, {
|
||||||
locale: 'fr',
|
locale: 'fr',
|
||||||
})
|
})
|
||||||
return new TextDecoder().decode(await readAttachmentBytes(pdf))
|
const bytes = new Uint8Array(await pdf.arrayBuffer())
|
||||||
|
return new TextDecoder().decode(await readAttachmentBytes(bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => {
|
describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => {
|
||||||
|
|||||||
@@ -55,9 +55,8 @@ describe('the 612 legacy leaves in the application', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
|
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
|
||||||
const { pdf: bytes } = await exportReportToPdf(report, sheet, {
|
const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
|
||||||
locale: 'fr',
|
const bytes = new Uint8Array(await pdf.arrayBuffer())
|
||||||
})
|
|
||||||
const { read: back } = await importReportFromPdf(bytes, sheet)
|
const { read: back } = await importReportFromPdf(bytes, sheet)
|
||||||
expect(back.migrated).toBe(false)
|
expect(back.migrated).toBe(false)
|
||||||
expect(back.origin).toBe('envelope_v1')
|
expect(back.origin).toBe('envelope_v1')
|
||||||
|
|||||||
@@ -179,8 +179,9 @@ describe('archives exported from core-built reports', () => {
|
|||||||
async (name) => {
|
async (name) => {
|
||||||
const { report } = importAttachment(fixture(name), sheet).read
|
const { report } = importAttachment(fixture(name), sheet).read
|
||||||
const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
|
const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
|
||||||
|
const bytes = new Uint8Array(await pdf.arrayBuffer())
|
||||||
const data: unknown = JSON.parse(
|
const data: unknown = JSON.parse(
|
||||||
new TextDecoder().decode(await readAttachmentBytes(pdf)),
|
new TextDecoder().decode(await readAttachmentBytes(bytes)),
|
||||||
)
|
)
|
||||||
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
|
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
|
||||||
const outcome = readArchiveDocument(data, await bundledMigrationMap())
|
const outcome = readArchiveDocument(data, await bundledMigrationMap())
|
||||||
|
|||||||
@@ -37,12 +37,12 @@ import {
|
|||||||
FIXTURES_DIR,
|
FIXTURES_DIR,
|
||||||
ONE_PX_PNG,
|
ONE_PX_PNG,
|
||||||
readLinks,
|
readLinks,
|
||||||
recordDrawing,
|
|
||||||
snapshotViews,
|
snapshotViews,
|
||||||
type ImageEntry,
|
type ImageEntry,
|
||||||
type LinkEntry,
|
type LinkEntry,
|
||||||
type TextEntry,
|
type TextEntry,
|
||||||
} from '../helpers/goldens'
|
} from '../helpers/goldens'
|
||||||
|
import { bytesOf, readDrawing } from '../helpers/pdfRead'
|
||||||
|
|
||||||
// Same fixed raster for every view and logo: images then depend on the
|
// Same fixed raster for every view and logo: images then depend on the
|
||||||
// branding and the layout only.
|
// branding and the layout only.
|
||||||
@@ -84,18 +84,18 @@ interface Facts {
|
|||||||
links: LinkEntry[]
|
links: LinkEntry[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Runs an export under the drawing recorder and reads the links back. */
|
/**
|
||||||
async function recorded<T extends { pdf: Uint8Array }>(
|
* Runs an export and reads its facts back from the file (R4.6: the app export is the
|
||||||
|
* core's, the re-export the engine's; both files are read the same way).
|
||||||
|
*/
|
||||||
|
async function recorded<T extends { pdf: Uint8Array | Blob }>(
|
||||||
run: () => Promise<T>,
|
run: () => Promise<T>,
|
||||||
): Promise<T & Facts> {
|
): Promise<Omit<T, 'pdf'> & { pdf: Uint8Array } & Facts> {
|
||||||
const recording = recordDrawing()
|
const result = await run()
|
||||||
try {
|
const pdf =
|
||||||
const result = await run()
|
result.pdf instanceof Uint8Array ? result.pdf : await bytesOf(result.pdf)
|
||||||
const { texts, images } = recording
|
const { texts, images } = await readDrawing(pdf)
|
||||||
return { ...result, texts, images, links: await readLinks(result.pdf) }
|
return { ...result, pdf, texts, images, links: await readLinks(pdf) }
|
||||||
} finally {
|
|
||||||
recording.stop()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const facts = ({ texts, images, links }: Facts): Facts => ({
|
const facts = ({ texts, images, links }: Facts): Facts => ({
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
/**
|
/**
|
||||||
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the
|
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the
|
||||||
* application export path: `exportReportToPdf` now runs the engine with the
|
* application export path: `exportReportToPdf` runs the core's session (R4.6)
|
||||||
* bundled sheet snapshotted, the bundled branding (mocked to every slot empty
|
* with the bundled sheet snapshotted, the bundled branding (mocked to every
|
||||||
* for the `nologos` mode, the real module for `logos`) and the browser
|
* slot empty for the `nologos` mode, the real module for `logos`) and the
|
||||||
* rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text,
|
* browser rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text,
|
||||||
* images and links goldens are asserted as frozen; `MAKE_GOLDEN=1` rewrites
|
* images and links goldens are read back from the file's content streams and
|
||||||
* them, never without a user decision. Never regenerate `report-v3.bare.pdf`:
|
* asserted as frozen; `MAKE_GOLDEN=1` rewrites them, never without a user
|
||||||
* it is the Step 5 bare export, an import fixture only.
|
* decision. At the fixed export time the file's bytes are the R4 digests the
|
||||||
|
* cargo suite froze (`goldens/r4/pdf.*.sha256`): the app path writes what the
|
||||||
|
* native core writes. Never regenerate `report-v3.bare.pdf`: it is the Step 5
|
||||||
|
* bare export, an import fixture only.
|
||||||
*/
|
*/
|
||||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
||||||
import { PDFDocument } from 'pdf-lib'
|
import { PDFDocument } from 'pdf-lib'
|
||||||
@@ -29,7 +32,6 @@ import {
|
|||||||
ONE_PX_PNG,
|
ONE_PX_PNG,
|
||||||
readGolden,
|
readGolden,
|
||||||
readLinks,
|
readLinks,
|
||||||
recordDrawing,
|
|
||||||
snapshotViews,
|
snapshotViews,
|
||||||
TWO_BY_ONE_PNG,
|
TWO_BY_ONE_PNG,
|
||||||
type ImageEntry,
|
type ImageEntry,
|
||||||
@@ -38,6 +40,8 @@ import {
|
|||||||
type TextEntry,
|
type TextEntry,
|
||||||
type ViewSnapshot,
|
type ViewSnapshot,
|
||||||
} from '../helpers/goldens'
|
} from '../helpers/goldens'
|
||||||
|
import { bytesOf, readDrawing } from '../helpers/pdfRead'
|
||||||
|
import { FIXED_EXPORTED_AT, R4_GOLDEN_DIR, sha256 } from '../helpers/r4-draw'
|
||||||
|
|
||||||
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
|
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
|
||||||
vi.mock('@/pdf/browserRasterizer', () => ({
|
vi.mock('@/pdf/browserRasterizer', () => ({
|
||||||
@@ -61,8 +65,13 @@ beforeAll(async () => {
|
|||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
|
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
|
||||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
|
vi.useFakeTimers({ toFake: ['Date'] })
|
||||||
|
vi.setSystemTime(FIXED_EXPORTED_AT)
|
||||||
|
})
|
||||||
|
afterAll(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
vi.restoreAllMocks()
|
||||||
})
|
})
|
||||||
afterAll(() => vi.restoreAllMocks())
|
|
||||||
|
|
||||||
interface Exported {
|
interface Exported {
|
||||||
bytes: Uint8Array
|
bytes: Uint8Array
|
||||||
@@ -78,14 +87,29 @@ async function exportWith(
|
|||||||
): Promise<Exported> {
|
): Promise<Exported> {
|
||||||
raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
||||||
logoMode.current = mode
|
logoMode.current = mode
|
||||||
const recording = recordDrawing()
|
const { pdf, warnings } = await exportReportToPdf(report, sheet, { locale })
|
||||||
try {
|
expect(warnings).toEqual([])
|
||||||
const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale })
|
const bytes = await bytesOf(pdf)
|
||||||
const { texts, images } = recording
|
const { texts, images } = await readDrawing(bytes)
|
||||||
return { bytes, texts, images, links: await readLinks(bytes) }
|
return { bytes, texts, images, links: await readLinks(bytes) }
|
||||||
} finally {
|
}
|
||||||
recording.stop()
|
|
||||||
}
|
/**
|
||||||
|
* The goldens were recorded in call order: every page's content, then the footers of
|
||||||
|
* every page (the engine drew them last). Read back from the file, the facts come page
|
||||||
|
* by page, each page's footer after its content: the golden in page order, stably, is
|
||||||
|
* the same sequence.
|
||||||
|
*/
|
||||||
|
function inPageOrder<T extends { page: number }>(name: string): T[] {
|
||||||
|
return [...readGolden<T[]>(name)].sort((a, b) => a.page - b.page)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The R4 digest of this run, frozen by the cargo suite from the native writer. */
|
||||||
|
function r4Digest(name: string, locale: Locale, mode: LogoMode): string {
|
||||||
|
return readFileSync(
|
||||||
|
resolve(R4_GOLDEN_DIR, `pdf.${name}.${locale}.${mode}.sha256`),
|
||||||
|
'utf8',
|
||||||
|
).trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
const pagesOf = (entries: readonly { page: number }[]) =>
|
const pagesOf = (entries: readonly { page: number }[]) =>
|
||||||
@@ -133,16 +157,22 @@ describe.each(REPORTS)('goldens of %s', (name) => {
|
|||||||
// Images and links are recorded per locale too: the footer centres the
|
// Images and links are recorded per locale too: the footer centres the
|
||||||
// "powered by" block on the label width, so the ZenQuality link (and its
|
// "powered by" block on the label width, so the ZenQuality link (and its
|
||||||
// logo) shift between FR and EN. Only the pagination is locale-free.
|
// logo) shift between FR and EN. Only the pagination is locale-free.
|
||||||
it('text, images and links per locale; same pagination across locales', async () => {
|
it('text, images and links per locale; same pagination across locales; app-path bytes = native digest', async () => {
|
||||||
const fr = await exportWith(reports[name], mode, 'fr')
|
const fr = await exportWith(reports[name], mode, 'fr')
|
||||||
const en = await exportWith(reports[name], mode, 'en')
|
const en = await exportWith(reports[name], mode, 'en')
|
||||||
for (const [locale, out] of [
|
for (const [locale, out] of [
|
||||||
['fr', fr],
|
['fr', fr],
|
||||||
['en', en],
|
['en', en],
|
||||||
] as const) {
|
] as const) {
|
||||||
checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts)
|
const id = `${name}.${locale}.${mode}`
|
||||||
checkGolden(`images.${name}.${locale}.${mode}.json`, out.images)
|
expect(out.texts, `text.${id}`).toEqual(inPageOrder(`text.${id}.json`))
|
||||||
checkGolden(`links.${name}.${locale}.${mode}.json`, out.links)
|
expect(out.images, `images.${id}`).toEqual(
|
||||||
|
inPageOrder(`images.${id}.json`),
|
||||||
|
)
|
||||||
|
checkGolden(`links.${id}.json`, out.links)
|
||||||
|
expect(sha256(out.bytes), id).toBe(
|
||||||
|
r4Digest(name, locale, mode),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
expect(pagesOf(en.images)).toEqual(pagesOf(fr.images))
|
expect(pagesOf(en.images)).toEqual(pagesOf(fr.images))
|
||||||
expect(pagesOf(en.links)).toEqual(pagesOf(fr.links))
|
expect(pagesOf(en.links)).toEqual(pagesOf(fr.links))
|
||||||
|
|||||||
@@ -1,30 +1,25 @@
|
|||||||
/**
|
/**
|
||||||
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the application
|
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the application
|
||||||
* export path on the engine with the bundled sheet (drawn strings from the
|
* export path on the core's session with the bundled sheet (drawn strings
|
||||||
* document, envelope attachment, roundtrip FR/EN) and the import of the
|
* from the document, read back from the file's content streams since R4.6,
|
||||||
* frozen v2 archive PDFs, migrated without silent loss.
|
* envelope attachment, roundtrip FR/EN) and the import of the frozen v2
|
||||||
|
* archive PDFs, migrated without silent loss.
|
||||||
*/
|
*/
|
||||||
import {
|
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
||||||
describe,
|
import { AFRelationship, PDFDocument } from 'pdf-lib'
|
||||||
it,
|
|
||||||
expect,
|
|
||||||
vi,
|
|
||||||
beforeAll,
|
|
||||||
beforeEach,
|
|
||||||
afterAll,
|
|
||||||
} from 'vitest'
|
|
||||||
import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
|
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
import { dirname, resolve } from 'node:path'
|
import { dirname, resolve } from 'node:path'
|
||||||
import type { Observation, Report } from '@faunosteo/core-wasm/types'
|
import type { Observation, Report } from '@faunosteo/core-wasm/types'
|
||||||
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
|
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
|
||||||
import { exportReportToPdf } from '@/pdf/export'
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
|
import { defaultPdfLabels } from '@/pdf/labels'
|
||||||
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
||||||
import { formatDate } from '@/lib/dates'
|
import { formatDate } from '@/lib/dates'
|
||||||
import type { Locale } from '@/i18n/types'
|
import type { Locale } from '@/i18n/types'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
|
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
|
||||||
|
import { bytesOf, readDrawing } from '../helpers/pdfRead'
|
||||||
|
|
||||||
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
|
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
|
||||||
vi.mock('@/pdf/browserRasterizer', async () => {
|
vi.mock('@/pdf/browserRasterizer', async () => {
|
||||||
@@ -40,12 +35,19 @@ async function readBack(bytes: Uint8Array) {
|
|||||||
return (await importReportFromPdf(bytes, sheet)).read
|
return (await importReportFromPdf(bytes, sheet)).read
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The static PDF strings now belong to the engine's label set. */
|
/** The static PDF strings belong to the app's label set. */
|
||||||
const { fr, en } = defaultPdfLabels
|
const { fr, en } = defaultPdfLabels
|
||||||
|
|
||||||
/** The bytes of an app export (its warnings are not under test here). */
|
/**
|
||||||
|
* The bytes of an app export (its warnings are not under test here); `drawn` holds the
|
||||||
|
* texts of its content streams, in draw order.
|
||||||
|
*/
|
||||||
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
|
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
|
||||||
return (await exportReportToPdf(report, sheet, { locale })).pdf
|
const bytes = await bytesOf(
|
||||||
|
(await exportReportToPdf(report, sheet, { locale })).pdf,
|
||||||
|
)
|
||||||
|
drawn = (await readDrawing(bytes)).texts.map((t) => t.text)
|
||||||
|
return bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
@@ -60,15 +62,6 @@ beforeAll(async () => {
|
|||||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
})
|
})
|
||||||
afterAll(() => vi.restoreAllMocks())
|
afterAll(() => vi.restoreAllMocks())
|
||||||
beforeEach(() => {
|
|
||||||
drawn = []
|
|
||||||
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
|
|
||||||
this: PDFPage,
|
|
||||||
text: string,
|
|
||||||
) {
|
|
||||||
drawn.push(text)
|
|
||||||
} as never)
|
|
||||||
})
|
|
||||||
|
|
||||||
/** A full v3 observation: plain zone, bilateral both sides, spine with vertebrae, head zone, findings. */
|
/** A full v3 observation: plain zone, bilateral both sides, spine with vertebrae, head zone, findings. */
|
||||||
function fullObservation(): Observation {
|
function fullObservation(): Observation {
|
||||||
@@ -208,7 +201,7 @@ function fullReport() {
|
|||||||
|
|
||||||
describe('PDF content on a two-observation report', () => {
|
describe('PDF content on a two-observation report', () => {
|
||||||
it('prints the empty marker for a zoneless observation and keeps its findings', async () => {
|
it('prints the empty marker for a zoneless observation and keeps its findings', async () => {
|
||||||
await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
|
await exportPdf(fullReport(), 'fr')
|
||||||
expect(drawn).toContain(fr['pdf.empty'])
|
expect(drawn).toContain(fr['pdf.empty'])
|
||||||
const prefix = fr['pdf.section.findings_prefix']!
|
const prefix = fr['pdf.section.findings_prefix']!
|
||||||
const occurrences = drawn.filter(
|
const occurrences = drawn.filter(
|
||||||
@@ -231,14 +224,14 @@ describe('PDF content on a two-observation report', () => {
|
|||||||
],
|
],
|
||||||
}
|
}
|
||||||
const report = minimalReport(sheet, { observations: [stale] })
|
const report = minimalReport(sheet, { observations: [stale] })
|
||||||
await exportReportToPdf(report, sheet, { locale: 'fr' })
|
await exportPdf(report, 'fr')
|
||||||
expect(drawn).toContain('point-gone')
|
expect(drawn).toContain('point-gone')
|
||||||
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
|
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
|
||||||
expect(drawn).toContain('Snapshot FR')
|
expect(drawn).toContain('Snapshot FR')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('draws the EN dictionary, annotation names and finding snapshots', async () => {
|
it('draws the EN dictionary, annotation names and finding snapshots', async () => {
|
||||||
await exportReportToPdf(fullReport(), sheet, { locale: 'en' })
|
await exportPdf(fullReport(), 'en')
|
||||||
expect(drawn).toContain(en['pdf.section.zones'])
|
expect(drawn).toContain(en['pdf.section.zones'])
|
||||||
expect(drawn.some((l) => l.includes('Hip joint'))).toBe(true)
|
expect(drawn.some((l) => l.includes('Hip joint'))).toBe(true)
|
||||||
expect(drawn).toContain('Junction fixation')
|
expect(drawn).toContain('Junction fixation')
|
||||||
@@ -282,7 +275,7 @@ describe('PDF content on a two-observation report', () => {
|
|||||||
})
|
})
|
||||||
expect(fetchSpy).not.toHaveBeenCalled()
|
expect(fetchSpy).not.toHaveBeenCalled()
|
||||||
expect(warnings).toEqual([])
|
expect(warnings).toEqual([])
|
||||||
const out = await readBack(pdf)
|
const out = await readBack(await bytesOf(pdf))
|
||||||
const branding = out.archive!.branding
|
const branding = out.archive!.branding
|
||||||
expect(branding.headerLogo?.kind).toBe('png')
|
expect(branding.headerLogo?.kind).toBe('png')
|
||||||
expect(branding.footerLogo?.kind).toBe('png')
|
expect(branding.footerLogo?.kind).toBe('png')
|
||||||
|
|||||||
@@ -16,11 +16,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
|||||||
import { AFRelationship, PageSizes, PDFDocument, StandardFonts } from 'pdf-lib'
|
import { AFRelationship, PageSizes, PDFDocument, StandardFonts } from 'pdf-lib'
|
||||||
import type { Branding, Practitioner, Report } from '@faunosteo/core-wasm/types'
|
import type { Branding, Practitioner, Report } from '@faunosteo/core-wasm/types'
|
||||||
import {
|
import {
|
||||||
|
exportReportArchive,
|
||||||
readAttachedDocument,
|
readAttachedDocument,
|
||||||
readAttachmentBytes,
|
readAttachmentBytes,
|
||||||
|
type ExportInput,
|
||||||
type Rasterizer,
|
type Rasterizer,
|
||||||
} from '@faunosteo/pdf'
|
} from '@faunosteo/pdf'
|
||||||
import { exportReportToPdf } from '@/pdf/export'
|
import { loadBranding } from '@/pdf/branding'
|
||||||
|
import { defaultPdfLabels } from '@/pdf/labels'
|
||||||
import { importAttachment } from '@/pdf/import'
|
import { importAttachment } from '@/pdf/import'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import type { Locale } from '@/i18n/types'
|
import type { Locale } from '@/i18n/types'
|
||||||
@@ -113,14 +116,26 @@ const fixedRaster =
|
|||||||
async () =>
|
async () =>
|
||||||
mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
||||||
|
|
||||||
/** One export through `@/pdf/export`, drawn under the full recorder. */
|
/**
|
||||||
|
* One export through the TypeScript engine with the application's inputs (the snapshot
|
||||||
|
* the core builds, the bundled branding of the mode, the app's labels, the fixed export
|
||||||
|
* time), drawn under the full recorder. R4.6 moved `@/pdf/export` onto the core's
|
||||||
|
* session: the oracles stay those of the R3 build, so the engine is called directly, as
|
||||||
|
* the app export called it until then (same inputs, same order).
|
||||||
|
*/
|
||||||
async function exportRun(run: Run): Promise<Exported> {
|
async function exportRun(run: Run): Promise<Exported> {
|
||||||
raster.rasterize = run.rasterize
|
raster.rasterize = run.rasterize
|
||||||
logoMode.current = run.mode
|
logoMode.current = run.mode
|
||||||
const recorder = recordFullDrawing()
|
const recorder = recordFullDrawing()
|
||||||
try {
|
try {
|
||||||
const { pdf, warnings } = await exportReportToPdf(run.report, sheet, {
|
const { pdf, warnings } = await exportReportArchive({
|
||||||
|
report: run.report as ExportInput['report'],
|
||||||
|
sheet: sheetSnapshot(sheet, run.report) as ExportInput['sheet'],
|
||||||
|
branding: await loadBranding(),
|
||||||
|
labels: defaultPdfLabels,
|
||||||
locale: run.locale,
|
locale: run.locale,
|
||||||
|
rasterizer: run.rasterize,
|
||||||
|
exportedAt: new Date(),
|
||||||
})
|
})
|
||||||
expect(warnings).toEqual([])
|
expect(warnings).toEqual([])
|
||||||
expect(recorder.unexpectedCalls()).toEqual([])
|
expect(recorder.unexpectedCalls()).toEqual([])
|
||||||
|
|||||||
@@ -27,7 +27,9 @@ import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
|||||||
|
|
||||||
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
|
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
|
||||||
const exportMock = vi.mocked(exportReportToPdf)
|
const exportMock = vi.mocked(exportReportToPdf)
|
||||||
const PDF_BYTES = new Uint8Array([37, 80, 68, 70])
|
const PDF_BYTES = new Blob([new Uint8Array([37, 80, 68, 70])], {
|
||||||
|
type: 'application/pdf',
|
||||||
|
})
|
||||||
|
|
||||||
let sheet: SheetIndex
|
let sheet: SheetIndex
|
||||||
const downloads: string[] = []
|
const downloads: string[] = []
|
||||||
@@ -69,25 +71,32 @@ afterEach(() => {
|
|||||||
URL.revokeObjectURL = realRevokeObjectURL
|
URL.revokeObjectURL = realRevokeObjectURL
|
||||||
})
|
})
|
||||||
|
|
||||||
async function mountAndExport(label: string): Promise<void> {
|
async function mountAndExport(label: string): Promise<() => void> {
|
||||||
render(
|
const { unmount } = render(
|
||||||
<MemoryRouter initialEntries={['/editor']}>
|
<MemoryRouter initialEntries={['/editor']}>
|
||||||
<EditorRoute />
|
<EditorRoute />
|
||||||
</MemoryRouter>,
|
</MemoryRouter>,
|
||||||
)
|
)
|
||||||
const button = await screen.findByRole('button', { name: label })
|
const button = await screen.findByRole('button', { name: label })
|
||||||
await userEvent.setup().click(button)
|
await userEvent.setup().click(button)
|
||||||
|
return unmount
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The options the route passes: the locale and the signal it aborts on unmount. */
|
||||||
|
const options = (locale: 'fr' | 'en') => ({
|
||||||
|
locale,
|
||||||
|
signal: expect.any(AbortSignal) as AbortSignal,
|
||||||
|
})
|
||||||
|
|
||||||
describe('EditorRoute export', () => {
|
describe('EditorRoute export', () => {
|
||||||
it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => {
|
it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => {
|
||||||
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
||||||
await mountAndExport(fr['editor.export']!)
|
await mountAndExport(fr['editor.export']!)
|
||||||
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
||||||
const [report, index, options] = exportMock.mock.calls[0]!
|
const [report, index, passed] = exportMock.mock.calls[0]!
|
||||||
expect(report).toBe(useReportStore.getState().report)
|
expect(report).toBe(useReportStore.getState().report)
|
||||||
expect(index).toBe(sheet)
|
expect(index).toBe(sheet)
|
||||||
expect(options).toEqual({ locale: 'fr' })
|
expect(passed).toEqual(options('fr'))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('passes the active locale (EN)', async () => {
|
it('passes the active locale (EN)', async () => {
|
||||||
@@ -95,7 +104,7 @@ describe('EditorRoute export', () => {
|
|||||||
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
||||||
await mountAndExport(en['editor.export']!)
|
await mountAndExport(en['editor.export']!)
|
||||||
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
||||||
expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' })
|
expect(exportMock.mock.calls[0]![2]).toEqual(options('en'))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('downloads bilan-<animal>-<date>.pdf through a blob URL it revokes after a delay', async () => {
|
it('downloads bilan-<animal>-<date>.pdf through a blob URL it revokes after a delay', async () => {
|
||||||
@@ -131,6 +140,28 @@ describe('EditorRoute export', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('aborts the export when the editor unmounts mid-way: no download, no alert', async () => {
|
||||||
|
let settle: (() => void) | null = null
|
||||||
|
exportMock.mockImplementation(
|
||||||
|
(_report, _index, opts) =>
|
||||||
|
new Promise((_, reject) => {
|
||||||
|
settle = () =>
|
||||||
|
reject(new DOMException('export aborted', 'AbortError'))
|
||||||
|
opts.signal?.addEventListener('abort', () => settle?.())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const unmount = await mountAndExport(fr['editor.export']!)
|
||||||
|
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
||||||
|
const signal = exportMock.mock.calls[0]![2].signal!
|
||||||
|
expect(signal.aborted).toBe(false)
|
||||||
|
unmount()
|
||||||
|
expect(signal.aborted).toBe(true)
|
||||||
|
await Promise.resolve()
|
||||||
|
await Promise.resolve()
|
||||||
|
expect(downloads).toHaveLength(0)
|
||||||
|
expect(window.alert).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
it('alerts editor.export_failed when the export rejects', async () => {
|
it('alerts editor.export_failed when the export rejects', async () => {
|
||||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||||
exportMock.mockRejectedValue(new Error('render exploded'))
|
exportMock.mockRejectedValue(new Error('render exploded'))
|
||||||
|
|||||||
@@ -230,11 +230,11 @@ pub fn name(text: &str) -> String {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `PDFHexString.fromText`: UTF-16BE with a BOM, lowercase hex.
|
/// `PDFHexString.fromText`: UTF-16BE with a BOM, upper-case hex as pdf-lib printed it.
|
||||||
pub fn hex_text(text: &str) -> String {
|
pub fn hex_text(text: &str) -> String {
|
||||||
let mut out = String::from("<feff");
|
let mut out = String::from("<FEFF");
|
||||||
for unit in text.encode_utf16() {
|
for unit in text.encode_utf16() {
|
||||||
out.push_str(&format!("{unit:04x}"));
|
out.push_str(&format!("{unit:04X}"));
|
||||||
}
|
}
|
||||||
out.push('>');
|
out.push('>');
|
||||||
out
|
out
|
||||||
|
|||||||
Reference in new issue
Block a user