test(pdf): step 6 phase 0 freeze — demo report, bare v3 PDF, 39 goldens (text, images, links, views) and route characterisation tests
This commit is contained in:
1 parent
694092610d
commit
8b86b926c8
46 files changed
+18502
-5
No files matched your search
@@ -0,0 +1,296 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { expect, vi } from 'vitest'
|
||||
import {
|
||||
PDFArray,
|
||||
PDFDict,
|
||||
PDFDocument,
|
||||
PDFHexString,
|
||||
PDFName,
|
||||
PDFNumber,
|
||||
PDFPage,
|
||||
PDFString,
|
||||
} from 'pdf-lib'
|
||||
import type { Observation, Report } from '@faunosteo/domain'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { highlightedViewSvg } from '@/pdf/render/observationPage'
|
||||
|
||||
/**
|
||||
* Step 6 Phase 0 freeze: what the current PDF pipeline draws, recorded as
|
||||
* JSON goldens (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md §17). The
|
||||
* recorder spies on pdf-lib, the link reader parses the saved bytes, the
|
||||
* view snapshot parses the highlighted SVG. Numbers are rounded to 2
|
||||
* decimals; nothing ordered by drawing order is sorted.
|
||||
*/
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
export const FIXTURES_DIR = resolve(HERE, '../fixtures')
|
||||
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
||||
const PUBLIC_DIR = resolve(HERE, '../../public')
|
||||
|
||||
/** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */
|
||||
export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1'
|
||||
|
||||
export type LogoMode = 'nologos' | 'logos'
|
||||
|
||||
export interface TextEntry {
|
||||
page: number
|
||||
text: string
|
||||
x: number | null
|
||||
y: number | null
|
||||
size: number | null
|
||||
font: string | null
|
||||
}
|
||||
|
||||
export interface ImageEntry {
|
||||
page: number
|
||||
x: number | null
|
||||
y: number | null
|
||||
width: number | null
|
||||
height: number | null
|
||||
}
|
||||
|
||||
export interface LinkEntry {
|
||||
page: number
|
||||
rect: number[]
|
||||
uri: string
|
||||
}
|
||||
|
||||
export interface HighlightedElement {
|
||||
tag: string
|
||||
cx: string | null
|
||||
cy: string | null
|
||||
r: string | null
|
||||
points: string | null
|
||||
d: string | null
|
||||
fill: string | null
|
||||
fillOpacity: string | null
|
||||
filter: string | null
|
||||
}
|
||||
|
||||
export interface ViewSnapshot {
|
||||
observationId: string
|
||||
viewId: string
|
||||
viewBox: string | null
|
||||
halo: boolean
|
||||
highlighted: HighlightedElement[]
|
||||
nonHighlightedVisible: number
|
||||
dataAttributes: number
|
||||
titles: number
|
||||
}
|
||||
|
||||
export function round2(value: unknown): number | null {
|
||||
return typeof value === 'number' ? Math.round(value * 100) / 100 : null
|
||||
}
|
||||
|
||||
/** Pages are appended in order and never moved: the index at draw time is final. */
|
||||
function pageIndex(page: PDFPage): number {
|
||||
return page.doc.getPages().indexOf(page)
|
||||
}
|
||||
|
||||
export interface DrawRecording {
|
||||
texts: TextEntry[]
|
||||
images: ImageEntry[]
|
||||
stop(): void
|
||||
}
|
||||
|
||||
/** Records every drawText / drawImage while letting pdf-lib draw for real. */
|
||||
export function recordDrawing(): DrawRecording {
|
||||
const texts: TextEntry[] = []
|
||||
const images: ImageEntry[] = []
|
||||
const drawText = PDFPage.prototype.drawText
|
||||
const drawImage = PDFPage.prototype.drawImage
|
||||
const textSpy = vi
|
||||
.spyOn(PDFPage.prototype, 'drawText')
|
||||
.mockImplementation(function (this: PDFPage, text, options) {
|
||||
texts.push({
|
||||
page: pageIndex(this),
|
||||
text,
|
||||
x: round2(options?.x),
|
||||
y: round2(options?.y),
|
||||
size: round2(options?.size),
|
||||
font: options?.font?.name ?? null,
|
||||
})
|
||||
return drawText.call(this, text, options)
|
||||
})
|
||||
const imageSpy = vi
|
||||
.spyOn(PDFPage.prototype, 'drawImage')
|
||||
.mockImplementation(function (this: PDFPage, image, options) {
|
||||
images.push({
|
||||
page: pageIndex(this),
|
||||
x: round2(options?.x),
|
||||
y: round2(options?.y),
|
||||
width: round2(options?.width),
|
||||
height: round2(options?.height),
|
||||
})
|
||||
return drawImage.call(this, image, options)
|
||||
})
|
||||
return {
|
||||
texts,
|
||||
images,
|
||||
stop: () => {
|
||||
textSpy.mockRestore()
|
||||
imageSpy.mockRestore()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function linkOf(dict: PDFDict, page: number): LinkEntry | null {
|
||||
if (dict.get(PDFName.of('Subtype')) !== PDFName.of('Link')) return null
|
||||
const rect = dict
|
||||
.lookup(PDFName.of('Rect'), PDFArray)
|
||||
.asArray()
|
||||
.map((n) => round2((n as PDFNumber).asNumber()) ?? 0)
|
||||
const uri = dict.lookup(PDFName.of('A'), PDFDict).lookup(PDFName.of('URI'))
|
||||
const text =
|
||||
uri instanceof PDFString || uri instanceof PDFHexString
|
||||
? uri.decodeText()
|
||||
: String(uri)
|
||||
return { page, rect, uri: text }
|
||||
}
|
||||
|
||||
/** Every `/Annot /Link` of the saved PDF, page by page, in annotation order. */
|
||||
export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> {
|
||||
const doc = await PDFDocument.load(bytes)
|
||||
const out: LinkEntry[] = []
|
||||
doc.getPages().forEach((page, index) => {
|
||||
const annots = page.node.Annots()
|
||||
if (!annots) return
|
||||
for (let i = 0; i < annots.size(); i += 1) {
|
||||
const link = linkOf(annots.lookup(i, PDFDict), index)
|
||||
if (link) out.push(link)
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
const LOGO_FILES: Readonly<Record<string, string>> = {
|
||||
'/assets/faunosteo_logo_horizontal-512.png':
|
||||
'assets/faunosteo_logo_horizontal-512.png',
|
||||
'/assets/faunosteo-horizontal-com-512.png':
|
||||
'assets/faunosteo-horizontal-com-512.png',
|
||||
'/brand/zenquality-logo-fr.png': 'brand/zenquality-logo-fr.png',
|
||||
'/Paws_in_harmony.svg': 'Paws_in_harmony.svg',
|
||||
}
|
||||
|
||||
function serveLogo(input: RequestInfo | URL): Response {
|
||||
const path = new URL(String(input), 'http://localhost').pathname
|
||||
const relative = LOGO_FILES[path]
|
||||
const file = relative ? resolve(PUBLIC_DIR, relative) : null
|
||||
if (!file || !existsSync(file))
|
||||
return new Response('not found', { status: 404 })
|
||||
return new Response(new Uint8Array(readFileSync(file)), { status: 200 })
|
||||
}
|
||||
|
||||
/** Stubs fetch for one logo mode; returns the restore function. */
|
||||
export function installLogoFetch(mode: LogoMode): () => void {
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) =>
|
||||
mode === 'logos'
|
||||
? serveLogo(input)
|
||||
: new Response('not found', { status: 404 })) as typeof fetch
|
||||
return () => {
|
||||
globalThis.fetch = real
|
||||
}
|
||||
}
|
||||
|
||||
const HIGHLIGHT_FILL = '#b85a3f'
|
||||
|
||||
function highlightedOf(el: Element): HighlightedElement {
|
||||
const attr = (name: string) => el.getAttribute(name)
|
||||
return {
|
||||
tag: el.tagName,
|
||||
cx: attr('cx'),
|
||||
cy: attr('cy'),
|
||||
r: attr('r'),
|
||||
points: attr('points'),
|
||||
d: attr('d'),
|
||||
fill: attr('fill'),
|
||||
fillOpacity: attr('fill-opacity'),
|
||||
filter: attr('filter'),
|
||||
}
|
||||
}
|
||||
|
||||
/** Children of the annotation layer (last `<g>` of the root) still visible and not highlighted. */
|
||||
function countVisibleNonHighlighted(root: Element): number {
|
||||
const layer = Array.from(root.children)
|
||||
.filter((c) => c.tagName === 'g')
|
||||
.at(-1)
|
||||
if (!layer) return 0
|
||||
return Array.from(layer.children).filter(
|
||||
(el) =>
|
||||
el.getAttribute('fill') !== HIGHLIGHT_FILL &&
|
||||
el.getAttribute('display') !== 'none',
|
||||
).length
|
||||
}
|
||||
|
||||
function countDataAttributes(root: Element): number {
|
||||
return [root, ...Array.from(root.querySelectorAll('*'))].reduce(
|
||||
(count, el) =>
|
||||
count +
|
||||
Array.from(el.attributes).filter((a) => a.name.startsWith('data-'))
|
||||
.length,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
export function snapshotView(
|
||||
sheet: SheetIndex,
|
||||
observation: Observation,
|
||||
viewId: string,
|
||||
): ViewSnapshot {
|
||||
const svg = highlightedViewSvg(sheet, viewId, observation)
|
||||
const root = new DOMParser().parseFromString(
|
||||
svg,
|
||||
'image/svg+xml',
|
||||
).documentElement
|
||||
return {
|
||||
observationId: observation.id,
|
||||
viewId,
|
||||
viewBox: root.getAttribute('viewBox'),
|
||||
halo: root.querySelector('filter#osteo-halo') !== null,
|
||||
highlighted: Array.from(
|
||||
root.querySelectorAll(`[fill="${HIGHLIGHT_FILL}"]`),
|
||||
).map(highlightedOf),
|
||||
nonHighlightedVisible: countVisibleNonHighlighted(root),
|
||||
dataAttributes: countDataAttributes(root),
|
||||
titles: root.getElementsByTagName('title').length,
|
||||
}
|
||||
}
|
||||
|
||||
/** The views an observation draws, in the pipeline's order: main first, then first appearance. */
|
||||
export function viewIdsOf(
|
||||
sheet: SheetIndex,
|
||||
observation: Observation,
|
||||
): string[] {
|
||||
return [...new Set(observation.zones.map((z) => z.viewId))]
|
||||
.filter((id) => sheet.view(id))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
|
||||
)
|
||||
}
|
||||
|
||||
export function snapshotViews(
|
||||
sheet: SheetIndex,
|
||||
report: Report,
|
||||
): ViewSnapshot[] {
|
||||
return report.observations.flatMap((observation) =>
|
||||
viewIdsOf(sheet, observation).map((viewId) =>
|
||||
snapshotView(sheet, observation, viewId),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Writes the golden under MAKE_GOLDEN, asserts deep equality otherwise. */
|
||||
export function checkGolden(name: string, actual: unknown): void {
|
||||
const path = resolve(GOLDEN_DIR, name)
|
||||
if (MAKE_GOLDEN) {
|
||||
mkdirSync(GOLDEN_DIR, { recursive: true })
|
||||
writeFileSync(path, `${JSON.stringify(actual, null, 2)}\n`)
|
||||
return
|
||||
}
|
||||
const golden: unknown = JSON.parse(readFileSync(path, 'utf8'))
|
||||
expect(actual, name).toEqual(golden)
|
||||
}
|
||||
Reference in new issue
Block a user