From b42f2d7c2e726596d69b654cdc64fd182b7fcd09 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 23 Nov 2026 00:55:30 +0100 Subject: [PATCH] fix(pdf): long notes continue on the next page, nothing reaches the footer Observation text and image rows go through a cursor: a row or a line that would go under the text floor opens a continuation page repeating the header and the title block. Rows never go under 60 pt; they continue first, the text follows. Pages that fit draw the same calls bit for bit (O1, R4 digests). Wasm gzip: 596 729 B of 600 000 (margin 3 271 B). --- .claude/tasks/TODO.md | 1 + .../core/src/pdf/write/layout/observation.rs | 219 ++++--- crates/core/tests/pdf_proportions.rs | 616 ++++++++++++++++++ 3 files changed, 751 insertions(+), 85 deletions(-) diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 63fad367..894978f4 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -749,6 +749,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - [ ] Owner corrections before the trial (owner brief 2026-11-19 « Le bilan technique de U2 est encourageant », plan rev 4 Tasks 11-16, contract addendum criteria 25-31): [x] T11 « Reprendre le tracé » with board 04 C handles · [x] T12 Backspace and « + » on a vertex (Mac), group name pinned · [x] T13 focus after a touch commit · [x] T14 strip below the sticky top bar · [x] T15 why « Refaire » is unavailable · [x] T16 docs, gates, verifiers, security (final head 56a76a70; criterion 22 `up fresh`, the red environment suites and criterion 25 below 1 024 px left to the owner) · [ ] STOP for the db:trial run - [ ] Follow-up (owner approved 2026-11-19): the rights screen pages its grants (about 10 380 rows in the sandbox render at once; admin.spec axe Target crashed, lookup timeout; same on pre-U2 56c75b1). Production risk at those volumes. - [ ] Follow-up (owner approved 2026-11-19): the catalogue loads published versions progressively (`useCardDetails` loads 426 at once in the sandbox; catalogue-integrity times out; same on pre-U2 56c75b1). + - [ ] Follow-up (Task 27, owner A3 out of scope): the conclusion page does not paginate (`crates/core/src/pdf/write/layout/conclusion.rs`). Census on a long conclusion (`pdf_proportions`, throwaway probe): 3 000 characters clean, 6 000 characters 21 faults (text into the footer). Observation pages continue since Task 27; the conclusion needs the same cursor and continuation page. - [x] `shortcut:` the « − » bubble for a mouse is 28 × 22 px, read off board 05 (R-9 gives only the touch size), `apps/app/src/editor/annotations/handleSize.ts`. Upgrade: the owner's value at the trial (U2 Task 5). settled by the owner trial 2026-11-20 - [x] (criterion 25, 23865071: a `scroll-margin-top` of the bar height plus 0.5 rem on the editor page's focusables outside the drawing place, `styles/index.css`) No `scroll-padding-top` under the sticky top bar (pre-existing, WCAG 2.4.11): a keyboard focus on the header's « Défaire », « Refaire » or « Enregistrer » while scrolled can stay hidden under it; axe target-size flags them once a list click scrolled the page (U2 Task 5 review M-3). - [x] At the page's end, a side panel that shortens (the issue list leaving it) clamps the scroll and moves the canvas by its height (11 px in `editor-geometry.spec.ts`, which starts from the top for that reason). Gone with Task 6: the column keeps the overview, the issue is in the strip and the dialog. `editor-geometry.spec.ts` now runs the accepted repair (the issue leaving) from the page's end under `expectNoShift`, buttons pressed in place, scroll position unchanged (U2 Task 5 fix round 1, closed by Task 6 fix round 1). diff --git a/crates/core/src/pdf/write/layout/observation.rs b/crates/core/src/pdf/write/layout/observation.rs index 3ca3b976..4fcff73e 100644 --- a/crates/core/src/pdf/write/layout/observation.rs +++ b/crates/core/src/pdf/write/layout/observation.rs @@ -1,5 +1,5 @@ -//! `render/observationPage.ts`: one page per observation: header, title block with the -//! severity pill, the image grid of the observation's views, then the sections (zones, +//! `render/observationPage.ts`: one page per observation, continued on the next pages when its +//! text does not fit (A3): header, title block with the severity pill, the image grid of the observation's views, then the sections (zones, //! findings by zone and side, free findings, severity, comment). use std::collections::HashMap; @@ -142,42 +142,75 @@ fn draw_body_text(layout: &mut Layout<'_>, page: usize, text: &str, x: f64, y: f ); } -/// Items separated by a visibly larger accent bullet; returns the y below the last line. +/// Where the next text line goes: its page and its baseline. +struct Cursor { + page: usize, + y: f64, +} + +/// What a continuation page repeats (A3): the header and the observation's title block. No new +/// wording, so no new label key: the N-1 readers keep reading the archived labels. +struct PageHead<'h> { + header: &'h HeaderAssets<'h>, + position: usize, + severity: Option, +} + +/// Opens a continuation page when a line with `below` points of text under its baseline would +/// go under the floor: never into the footer, never off the page (R2). +fn ensure_room(layout: &mut Layout<'_>, cursor: &mut Cursor, head: &PageHead<'_>, below: f64) { + if cursor.y - below >= TEXT_FLOOR_Y { + return; + } + let page = layout.log.add_page(); + draw_header(layout, page, head.header); + let title_y = draw_title_block(layout, page, head.position, head.severity); + *cursor = Cursor { + page, + y: title_y - IMAGE_TOP_GAP, + }; +} + +fn next_line(layout: &mut Layout<'_>, cursor: &mut Cursor, head: &PageHead<'_>) { + cursor.y -= TEXT_LINE_HEIGHT; + ensure_room(layout, cursor, head, 0.0); +} + +/// Items separated by a visibly larger accent bullet, line after line, across pages. fn draw_segmented_text( layout: &mut Layout<'_>, - page: usize, + cursor: &mut Cursor, + head: &PageHead<'_>, items: &[&str], - start: (f64, f64), - max_width: f64, -) -> f64 { - let (start_x, start_y) = start; +) { if items.is_empty() { - return start_y - TEXT_LINE_HEIGHT; + cursor.y -= TEXT_LINE_HEIGHT; + return; } let sep_w = separator_width(); - let (mut x, mut y) = (start_x, start_y); + let right = MARGIN_X + BODY_W; + let mut x = MARGIN_X; for (i, item) in items.iter().enumerate() { let item_w = measure(BODY_REGULAR, item, SECTION_TEXT_SIZE); - if x + item_w > start_x + max_width && x > start_x { - x = start_x; - y -= TEXT_LINE_HEIGHT; + if x + item_w > right && x > MARGIN_X { + x = MARGIN_X; + next_line(layout, cursor, head); } - draw_body_text(layout, page, item, x, y); + draw_body_text(layout, cursor.page, item, x, cursor.y); x += item_w; if i == items.len() - 1 { continue; } - if x + sep_w > start_x + max_width { - x = start_x; - y -= TEXT_LINE_HEIGHT; + if x + sep_w > right { + x = MARGIN_X; + next_line(layout, cursor, head); } else { - draw_separator(layout, page, x, y); + draw_separator(layout, cursor.page, x, cursor.y); x += sep_w; } } - y - TEXT_LINE_HEIGHT + cursor.y -= TEXT_LINE_HEIGHT; } - // --------------------------------------------------------------------------- // Title block @@ -414,12 +447,23 @@ fn grid_rows<'a>(narrow: &[&'a Rendered]) -> Vec> { .collect() } -/// The height each row's images may take, as before 2026-11-22 (`grid_of`): the room the -/// text leaves, split between the rows, never under `IMAGE_MIN_CELL_H`. -fn row_budget(rows: usize, avail: f64) -> f64 { +/// A section label and the first line under it. +const FIRST_LINE: f64 = SECTION_LABEL_GAP + 9.0; + +/// The height each row's images may take (R2). As before 2026-11-22, the room the text leaves +/// split between the rows, as long as that is `IMAGE_MIN_CELL_H` or more. Under it, the text +/// cannot fit beside the images (A3): each row takes its share of what the page leaves above +/// the first section, never under `IMAGE_MIN_CELL_H` (owner: paginate before shrinking under +/// 60 pt). Rows that no longer fit then continue on the next page, and the text follows them. +fn row_budget(rows: usize, start_y: f64, avail: f64) -> f64 { let rows_f = rows as f64; - IMAGE_MIN_CELL_H - .max((avail - rows_f * IMAGE_LABEL_GAP - (rows_f - 1.0) * IMAGE_ROW_GAP) / rows_f) + let gaps = rows_f * IMAGE_LABEL_GAP + (rows_f - 1.0) * IMAGE_ROW_GAP; + let fit = (avail - gaps) / rows_f; + if fit >= IMAGE_MIN_CELL_H { + return fit; + } + let page = start_y - IMAGE_BOTTOM_GAP - TEXT_TOP_GAP - FIRST_LINE - TEXT_FLOOR_Y; + IMAGE_MIN_CELL_H.max((page - gaps) / rows_f) } /// The image's size in a cell `cell_w` wide and `budget` high, keeping its own proportions @@ -433,15 +477,17 @@ fn fitted(cell_w: f64, aspect: f64, budget: f64) -> (f64, f64) { } } -/// One row: the labels at their cells' left edge, as before, then each image fitted in its cell -/// and centred in it; returns the row height. An image under the budget is drawn as before -/// 2026-11-22, to the last bit. -fn draw_row(log: &mut DrawLog, page: usize, row: &Row<'_>, budget: f64, top_y: f64) -> f64 { - let sizes: Vec<(f64, f64)> = row - .items +/// The tallest image of `row` at `budget`: the row's height. +fn row_height(row: &Row<'_>, budget: f64) -> f64 { + row.items .iter() - .map(|it| fitted(row.cell_w, it.aspect, budget)) - .collect(); + .map(|it| fitted(row.cell_w, it.aspect, budget).1) + .fold(0.0, f64::max) +} + +/// One row: the labels at their cells' left edge, as before, then each image fitted in its cell +/// and centred in it. An image under the budget is drawn as before 2026-11-22, to the last bit. +fn draw_row(log: &mut DrawLog, page: usize, row: &Row<'_>, budget: f64, top_y: f64) { let x_of = |c: usize, width: f64| row.cell_x(c) + (row.cell_w - width) / 2.0; for (c, it) in row.items.iter().enumerate() { log.text( @@ -457,44 +503,47 @@ fn draw_row(log: &mut DrawLog, page: usize, row: &Row<'_>, budget: f64, top_y: f ); } let images_y = top_y - IMAGE_LABEL_GAP; - for (c, (it, (width, height))) in row.items.iter().zip(&sizes).enumerate() { + for (c, it) in row.items.iter().enumerate() { + let (width, height) = fitted(row.cell_w, it.aspect, budget); log.image( page, ImageOp { embed: it.image.embed, - x: x_of(c, *width), + x: x_of(c, width), y: images_y - height, - width: *width, - height: *height, + width, + height, }, ); } - sizes.iter().fold(0.0, |max, (_, h)| f64::max(max, *h)) } -/// The views' rows from `start_y` down; returns the cursor under them (`start_y` when none). +/// The views' rows from the cursor down, each on the page that has room for it (A3), then the +/// bottom gap; nothing when there is no image. On a page that fits, the same subtractions in the +/// same order as before 2026-11-22, so the same floats. fn draw_images( - log: &mut DrawLog, - page: usize, + layout: &mut Layout<'_>, + cursor: &mut Cursor, + head: &PageHead<'_>, rendered: &[Rendered], - start_y: f64, text_need: f64, -) -> f64 { +) { if rendered.is_empty() { - return start_y; + return; } let rows = rows_of(rendered); - let avail = IMAGE_MIN_CELL_H.max(start_y - (TEXT_BOTTOM + text_need + IMAGE_BOTTOM_GAP)); - let budget = row_budget(rows.len(), avail); - let mut cursor_y = start_y; + let avail = IMAGE_MIN_CELL_H.max(cursor.y - (TEXT_BOTTOM + text_need + IMAGE_BOTTOM_GAP)); + let budget = row_budget(rows.len(), cursor.y, avail); for (r, row) in rows.iter().enumerate() { - let row_h = draw_row(log, page, row, budget, cursor_y); - cursor_y -= IMAGE_LABEL_GAP + row_h; - if r < rows.len() - 1 { - cursor_y -= IMAGE_ROW_GAP; + let row_h = row_height(row, budget); + if r > 0 { + cursor.y -= IMAGE_ROW_GAP; } + ensure_room(layout, cursor, head, IMAGE_LABEL_GAP + row_h); + draw_row(&mut layout.log, cursor.page, row, budget, cursor.y); + cursor.y -= IMAGE_LABEL_GAP + row_h; } - cursor_y - IMAGE_BOTTOM_GAP + cursor.y -= IMAGE_BOTTOM_GAP; } // --------------------------------------------------------------------------- @@ -657,51 +706,48 @@ fn estimate_sections_height(sections: &[Section], max_text_w: f64) -> f64 { fn draw_section_value( layout: &mut Layout<'_>, - page: usize, + cursor: &mut Cursor, + head: &PageHead<'_>, value: &str, - start_y: f64, - max_text_w: f64, -) -> f64 { +) { if value.contains(ITEM_JOIN) { let items: Vec<&str> = value.split(ITEM_JOIN).collect(); - return draw_segmented_text(layout, page, &items, (MARGIN_X, start_y), max_text_w); + draw_segmented_text(layout, cursor, head, &items); + return; } - let mut cursor_y = start_y; - for line in wrap_lines(value, BODY_REGULAR, SECTION_TEXT_SIZE, max_text_w) { - draw_body_text(layout, page, &line, MARGIN_X, cursor_y); - cursor_y -= TEXT_LINE_HEIGHT; + for line in wrap_lines(value, BODY_REGULAR, SECTION_TEXT_SIZE, BODY_W) { + ensure_room(layout, cursor, head, 0.0); + draw_body_text(layout, cursor.page, &line, MARGIN_X, cursor.y); + cursor.y -= TEXT_LINE_HEIGHT; } - cursor_y } fn draw_sections( layout: &mut Layout<'_>, - page: usize, + cursor: &mut Cursor, + head: &PageHead<'_>, sections: &[Section], - start_y: f64, - max_text_w: f64, -) -> f64 { - let mut cursor_y = start_y; +) { for section in sections { + ensure_room(layout, cursor, head, FIRST_LINE); layout.log.text( - page, + cursor.page, TextOp { text: safe_text(§ion.label), x: MARGIN_X, - y: cursor_y, + y: cursor.y, size: 8.0, font: BODY_BOLD, color: COLOR_ACCENT, }, ); - cursor_y -= SECTION_LABEL_GAP + 9.0; - cursor_y = draw_section_value(layout, page, §ion.value, cursor_y, max_text_w); - cursor_y -= SECTION_BLOCK_GAP; + cursor.y -= FIRST_LINE; + draw_section_value(layout, cursor, head, §ion.value); + cursor.y -= SECTION_BLOCK_GAP; } - cursor_y } -/// `addObservationPage`. +/// `addObservationPage`, continued on the next pages when its text does not fit (A3). pub fn add_observation_page( layout: &mut Layout<'_>, header: &HeaderAssets<'_>, @@ -715,15 +761,18 @@ pub fn add_observation_page( let rendered = build_images(layout, images); let sections = sections(layout, observation); let text_need = estimate_sections_height(§ions, BODY_W); - let mut cursor_y = draw_images( - &mut layout.log, + let head = PageHead { + header, + position, + severity: observation.severity, + }; + let mut cursor = Cursor { page, - &rendered, - title_y - IMAGE_TOP_GAP, - text_need, - ); - cursor_y -= TEXT_TOP_GAP; - draw_sections(layout, page, §ions, cursor_y, BODY_W); + y: title_y - IMAGE_TOP_GAP, + }; + draw_images(layout, &mut cursor, &head, &rendered, text_need); + cursor.y -= TEXT_TOP_GAP; + draw_sections(layout, &mut cursor, &head, §ions); } #[cfg(test)] @@ -749,11 +798,11 @@ mod tests { let mut log = DrawLog::default(); let page = log.add_page(); let rows = rows_of(rendered); - let budget = row_budget(rows.len(), avail); + let budget = row_budget(rows.len(), 687.89, avail); let mut top_y = 687.89; for row in &rows { - top_y -= IMAGE_LABEL_GAP + draw_row(&mut log, page, row, budget, top_y); - top_y -= IMAGE_ROW_GAP; + draw_row(&mut log, page, row, budget, top_y); + top_y -= IMAGE_LABEL_GAP + row_height(row, budget) + IMAGE_ROW_GAP; } log.calls_in_order() .filter_map(|(_, op)| match op { diff --git a/crates/core/tests/pdf_proportions.rs b/crates/core/tests/pdf_proportions.rs index 27f22f00..d5bb0217 100644 --- a/crates/core/tests/pdf_proportions.rs +++ b/crates/core/tests/pdf_proportions.rs @@ -107,3 +107,619 @@ fn the_o4_inputs_where_views_differ_from_logos_are_listed() { .collect(); assert_eq!(differing, expected); } + +// --------------------------------------------------------------------------- +// The case builder (reused by the page-flow and the editor-preview tests) + +use common::r4::{PngKeeper, repo_root}; +use faunosteo_core::domain::archive::build_sheet_snapshot; +use faunosteo_core::domain::js::parse_json; +use faunosteo_core::domain::report::Report; +use faunosteo_core::domain::sheet::edit::{EditCommand, apply_edit}; +use faunosteo_core::domain::sheet::fingerprint::document_fingerprint; +use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet}; +use faunosteo_core::pdf::read::probe::{ProbeLimits, read_attached_document}; +use faunosteo_core::pdf::write::input::{CheckedInput, ExportInput, Rasters, check_input}; +use serde_json::{Value, json}; + +const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft"; +/// The drawing's own `viewBox` (main view) and the head's frame of the draft. +const MAIN_BOX: &str = "0 0 2073.4 1629.4"; +const HEAD_BOX: &str = "60 100 500 380"; + +/// Where a view of a case comes from: the draft's own main or head view, or a crop view of the +/// main view added by the case, with its frame `[min_x, min_y, width, height]`. +#[derive(Clone)] +pub enum Source { + Main, + Head, + Crop { name: String, frame: [f64; 4] }, +} + +#[derive(Clone)] +pub struct CaseView { + pub source: Source, + pub points: usize, +} + +/// One observation: its views in order (zones view by view) and its comment. +pub struct Case { + pub views: Vec, + pub comment: String, +} + +pub fn crop(name: &str, frame: [f64; 4], points: usize) -> CaseView { + let source = Source::Crop { + name: name.to_owned(), + frame, + }; + CaseView { source, points } +} + +pub fn main_view() -> CaseView { + CaseView { + source: Source::Main, + points: 1, + } +} + +pub fn head_view() -> CaseView { + CaseView { + source: Source::Head, + points: 1, + } +} + +/// `chars` characters of French words repeated. +pub fn french_comment(chars: usize) -> String { + let words = "mobilité articulaire restreinte à la palpation, tension des fascias. "; + let text: String = words.chars().cycle().take(chars).collect(); + text.trim_end().to_owned() +} + +fn read_seed(name: &str) -> String { + std::fs::read_to_string(repo_root().join(SEED).join(name)).unwrap() +} + +fn draft_payload() -> BundledSheetData { + let manifest: Value = serde_json::from_str(&read_seed("assets.json")).unwrap(); + let mut assets = serde_json::Map::new(); + let mut hashes = serde_json::Map::new(); + for asset in manifest.as_array().unwrap() { + let id = asset["svg_asset_id"].as_str().unwrap().to_owned(); + let file = format!("assets/{}", asset["file"].as_str().unwrap()); + assets.insert(id.clone(), Value::String(read_seed(&file))); + hashes.insert(id, asset["sha256"].clone()); + } + let payload = json!({ + "status": "draft", + "ref": parse_json(&read_seed("sheet-ref.json")).unwrap(), + "document": parse_json(&read_seed("document.json")).unwrap(), + "migrationMap": parse_json(&read_seed("report-migration-map.json")).unwrap(), + "assets": assets, + "assetHashes": hashes, + }); + serde_json::from_value(payload).unwrap() +} + +fn insert(kind: &str, value: Value) -> EditCommand { + serde_json::from_value(json!({ "op": "insert", "element": { "kind": kind, "value": value } })) + .unwrap() +} + +fn crop_id(index: usize) -> String { + format!("crop-{index}") +} + +fn point_id(index: usize, n: usize) -> String { + format!("crop-{index}-p{n}") +} + +/// The commands that add one crop view, its access on the main view and its points. +fn crop_commands(index: usize, name: &str, frame: [f64; 4], points: usize) -> Vec { + let [min_x, min_y, width, height] = frame; + let view_box = json!({ "min_x": min_x, "min_y": min_y, "width": width, "height": height }); + let polygon = [ + [min_x, min_y], + [min_x + width, min_y], + [min_x + width, min_y + height], + [min_x, min_y + height], + ]; + let mut commands = vec![ + insert( + "view", + json!({ "id": crop_id(index), "kind": "detail", "name": { "fr": name, "en": name }, + "parent_view_id": "main", "svg_asset_id": null, "view_box": view_box }), + ), + insert( + "annotation", + json!({ "id": format!("crop-{index}-access"), "kind": "detail_trigger", + "view_id": "main", "category_id": "cat-access", "laterality": "bilateral", + "geometry": { "type": "polygon", "points": polygon }, + "review_status": "to_confirm", "color": null, "name": null, + "opens_view_id": crop_id(index) }), + ), + ]; + for n in 0..points { + let label = format!("Articulation de test numéro {index}-{n:03}"); + commands.push(insert( + "annotation", + json!({ "id": point_id(index, n), "kind": "point", "view_id": crop_id(index), + "category_id": "articulations", "laterality": "bilateral", + "geometry": { "type": "circle", "cx": min_x + width / 2.0, + "cy": min_y + height / 2.0, "r": width.min(height) / 4.0 }, + "name": { "fr": label, "en": label }, "finding_zone_id": "hind-fetlock", + "vertebral_region_code": null, "review_status": "to_confirm" }), + )); + } + commands +} + +/// The draft with the case's crop views, loaded under the fingerprint the core computes for +/// the edited document (no historical alias). +fn case_sheet(case: &Case) -> LoadedSheet { + let mut data = draft_payload(); + let mut document = serde_json::from_value(data.document.clone()).unwrap(); + let crops = case.views.iter().filter_map(|v| match &v.source { + Source::Crop { name, frame } => Some((name, frame, v.points)), + _ => None, + }); + for (index, (name, frame, points)) in crops.enumerate() { + for command in crop_commands(index, name, *frame, points) { + document = apply_edit(&document, command).unwrap(); + } + } + data.document = serde_json::to_value(&document).unwrap(); + data.reference.document_sha256 = document_fingerprint(&document).unwrap(); + data.reference.fingerprint.as_mut().unwrap().aliases.clear(); + LoadedSheet::from_bundle(data).unwrap() +} + +const MAIN_ZONES: [&str; 4] = ["hind-fetlock", "hock", "stifle", "hip"]; +const HEAD_ZONES: [&str; 3] = ["parietal", "frontal", "sphenoid"]; + +/// The report's zones of a case, view by view: `(view id, annotation id)`. +fn case_zones(case: &Case) -> Vec<(String, String)> { + let mut zones = Vec::new(); + let mut crops = 0; + for view in &case.views { + match &view.source { + Source::Main => zones.extend( + MAIN_ZONES + .iter() + .take(view.points) + .map(|a| ("main".into(), (*a).into())), + ), + Source::Head => zones.extend( + HEAD_ZONES + .iter() + .take(view.points) + .map(|a| ("head".into(), (*a).into())), + ), + Source::Crop { .. } => { + zones.extend((0..view.points).map(|n| (crop_id(crops), point_id(crops, n)))); + crops += 1; + } + } + } + zones +} + +fn view_box_of(source: &Source) -> String { + match source { + Source::Main => MAIN_BOX.to_owned(), + Source::Head => HEAD_BOX.to_owned(), + Source::Crop { frame, .. } => { + format!("{} {} {} {}", frame[0], frame[1], frame[2], frame[3]) + } + } +} + +/// A PNG of `size` that holds a signature and its `IHDR` only: the layout reads nothing else. +pub fn header_only_png((width, height): (u32, u32)) -> Vec { + let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]; + png.extend_from_slice(b"IHDR"); + png.extend_from_slice(&width.to_be_bytes()); + png.extend_from_slice(&height.to_be_bytes()); + png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]); + png +} + +/// The envelope of the demo run: practitioner, animal, branding, labels, locale and date. +fn demo_envelope() -> Value { + let path = repo_root().join("apps/app/tests/fixtures/pdf/r3/demo.fr.nologos.pdf"); + let pdf = std::fs::read(path).unwrap(); + let located = read_attached_document(&pdf, ProbeLimits::UNBOUNDED).unwrap(); + parse_json(&located.text).unwrap() +} + +/// The export input and the header-only rasters of a case. +pub fn proportions_input(case: &Case) -> (CheckedInput, Rasters) { + let sheet = case_sheet(case); + let envelope = demo_envelope(); + let zones = case_zones(case); + let mut report = envelope["report"].clone(); + report["sheet"] = json!({ "sheetId": sheet.reference.sheet_id, "versionId": null, + "documentSha256": sheet.reference.document_sha256 }); + report["observations"] = json!([{ + "id": "obs-case", "findings": [], "freeTextFindings": [], "severity": "moderate", + "comment": case.comment, + "zones": zones.iter().map(|(view, annotation)| + json!({ "annotationId": annotation, "viewId": view })).collect::>(), + }]); + let report: Report = serde_json::from_value(report).unwrap(); + let snapshot = serde_json::to_value(build_sheet_snapshot(&sheet, &report)).unwrap(); + let mut rasters = Rasters { + header_logo: None, + footer_logo: None, + powered_by: None, + partner: None, + views: Default::default(), + }; + for (view, source) in case.views.iter().map(|v| &v.source).enumerate() { + let view_id = match source { + Source::Main => "main".to_owned(), + Source::Head => "head".to_owned(), + Source::Crop { .. } => crop_id( + case.views[..view] + .iter() + .filter(|v| matches!(v.source, Source::Crop { .. })) + .count(), + ), + }; + let png = header_only_png(view_raster_size(Some(&view_box_of(source)))); + rasters.views.insert(("obs-case".to_owned(), view_id), png); + } + let input = ExportInput { + report, + sheet_snapshot: snapshot, + branding: envelope["branding"].clone(), + labels: envelope["labels"].clone(), + locale: serde_json::from_value(envelope["locale"].clone()).unwrap(), + exported_at: envelope["exportedAt"].as_str().unwrap().to_owned(), + }; + (check_input(input).unwrap(), rasters) +} + +// --------------------------------------------------------------------------- +// Page flow (A3, R2) + +use common::page_boxes::census; +use faunosteo_core::pdf::write::draw_log::{DrawOp, ImageOp, PAGE_HEIGHT, PageLog, TextOp}; +use faunosteo_core::pdf::write::layout::{BODY_REGULAR, layout, png}; +use faunosteo_core::pdf::write::text::wrap_lines; + +const MARGIN_X: f64 = 36.0; +const BODY_W: f64 = 595.28 - 72.0; +const TITLE_Y: f64 = PAGE_HEIGHT - 122.0; +const IMAGE_TOP_GAP: f64 = 32.0; +const BODY_TOP: f64 = 700.0; + +struct Drawn { + pages: Vec, + sizes: Vec<(u32, u32)>, +} + +fn draw(case: &Case) -> Drawn { + let (checked, rasters) = proportions_input(case); + let mut keeper = PngKeeper::default(); + let drawn = layout(&checked, &rasters, &mut keeper).unwrap(); + assert!(drawn.warnings.is_empty(), "{:?}", drawn.warnings); + let sizes = keeper + .pngs + .iter() + .map(|p| png::dimensions(p).unwrap()) + .collect(); + Drawn { + pages: drawn.log.pages, + sizes, + } +} + +/// The observation's pages: every page but the conclusion's. +fn observation_pages(drawn: &Drawn) -> &[PageLog] { + &drawn.pages[..drawn.pages.len() - 1] +} + +fn content(page: &PageLog) -> &[DrawOp] { + &page.ops[..page.footer_start] +} + +fn images(page: &PageLog) -> Vec { + content(page) + .iter() + .filter_map(|op| match op { + DrawOp::Image(i) if i.y < BODY_TOP => Some(*i), + _ => None, + }) + .collect() +} + +fn texts(page: &PageLog) -> Vec<&TextOp> { + content(page) + .iter() + .filter_map(|op| match op { + DrawOp::Text(t) => Some(t), + _ => None, + }) + .collect() +} + +fn op_y(op: &DrawOp) -> f64 { + match op { + DrawOp::Text(t) => t.y, + DrawOp::Image(i) => i.y, + DrawOp::Line(l) => l.start.y, + DrawOp::Rectangle(r) => r.y, + } +} + +/// The calls before the first one under the title block: header, eyebrow, number, pill, rule. +fn head_calls(page: &PageLog) -> &[DrawOp] { + let ops = content(page); + let end = ops + .iter() + .position(|op| op_y(op) < BODY_TOP) + .unwrap_or(ops.len()); + &ops[..end] +} + +fn assert_clean(drawn: &Drawn) { + for (p, page) in drawn.pages.iter().enumerate() { + assert_eq!(census(page), Vec::::new(), "page {p}"); + } +} + +/// The body lines (10 pt regular, at the left margin) of every observation page, in order. +fn body_lines(drawn: &Drawn) -> Vec { + observation_pages(drawn) + .iter() + .flat_map(texts) + .filter(|t| t.size == 10.0 && t.font == BODY_REGULAR && t.x == MARGIN_X) + .map(|t| t.text.clone()) + .collect() +} + +fn all_images(drawn: &Drawn) -> Vec { + observation_pages(drawn).iter().flat_map(images).collect() +} + +/// Every image keeps its raster's ratio; none is under 60 pt; they come in view order. +fn assert_images_hold(drawn: &Drawn, views: usize) { + let drawn_images = all_images(drawn); + assert_eq!(drawn_images.len(), views); + for (n, image) in drawn_images.iter().enumerate() { + let (w, h) = drawn.sizes[image.embed]; + let ratio = (image.width / image.height) / (f64::from(w) / f64::from(h)); + assert!((ratio - 1.0).abs() < 1e-9, "image {n}: ratio {ratio}"); + assert!( + image.height >= 60.0 - 1e-9, + "image {n}: {} pt high", + image.height + ); + assert_eq!(image.embed, n, "views keep their order"); + } +} + +fn long_comment_case(views: Vec) -> (Case, Vec) { + let comment = french_comment(5000); + let wrapped = wrap_lines(&comment, BODY_REGULAR, 10.0, BODY_W); + (Case { views, comment }, wrapped) +} + +#[test] +fn a_long_note_with_no_view_continues_on_the_next_pages() { + let (case, wrapped) = long_comment_case(vec![]); + let drawn = draw(&case); + let pages = observation_pages(&drawn); + assert!(pages.len() >= 2, "{} observation pages", pages.len()); + for page in &pages[1..] { + assert_eq!(head_calls(page), head_calls(&pages[0])); + let first_body = content(page).iter().find(|op| op_y(op) < BODY_TOP).unwrap(); + assert!((op_y(first_body) - (TITLE_Y - IMAGE_TOP_GAP)).abs() < 1e-9); + } + let lines = body_lines(&drawn); + // The zones section (« empty ») and the severity come first, the comment is the rest. + assert_eq!(lines[lines.len() - wrapped.len()..], wrapped[..]); + assert_eq!(lines.len(), wrapped.len() + 2); + assert_clean(&drawn); +} + +#[test] +fn a_long_note_beside_main_and_head_keeps_the_images_whole_budget() { + let (case, wrapped) = long_comment_case(vec![main_view(), head_view()]); + let drawn = draw(&case); + assert!(observation_pages(&drawn).len() >= 2); + let first = images(&drawn.pages[0]); + assert_eq!(first.len(), 2, "both images on the first page"); + assert!((first[0].width - 253.64).abs() < 1e-9); + assert!(drawn.pages[1..].iter().all(|p| images(p).is_empty())); + let lines = body_lines(&drawn); + assert_eq!(lines[lines.len() - wrapped.len()..], wrapped[..]); + assert_clean(&drawn); +} + +#[test] +fn a_zones_section_of_120_points_crosses_the_page_in_order() { + let case = Case { + views: vec![crop("Membre antérieur", [625.0, 969.0, 220.0, 660.0], 120)], + comment: String::new(), + }; + let drawn = draw(&case); + assert!(observation_pages(&drawn).len() >= 2); + let (mut items, mut separators, mut order) = (Vec::new(), 0, String::new()); + for page in observation_pages(&drawn) { + for t in texts(page) { + if t.size == 14.0 && t.text == "•" { + separators += 1; + order.push('s'); + } else if t.size == 10.0 && t.text.starts_with("Articulation de test") { + items.push(t.text.clone()); + order.push('i'); + } + } + } + let expected: Vec = (0..120) + .map(|n| format!("Articulation de test numéro 0-{n:03}")) + .collect(); + assert_eq!(items, expected); + assert_eq!(separators, 119); + assert_eq!(order, "is".repeat(119) + "i"); + assert_clean(&drawn); +} + +#[test] +fn a_tall_view_is_capped_at_the_budget_beside_a_short_note() { + let case = Case { + views: vec![ + main_view(), + crop("Un sixième", [200.0, 300.0, 150.0, 900.0], 1), + crop("Un dixième", [500.0, 300.0, 100.0, 1000.0], 1), + crop("Un centième", [800.0, 100.0, 12.0, 1200.0], 1), + ], + comment: french_comment(100), + }; + let drawn = draw(&case); + let shown = images(&drawn.pages[0]); + assert_eq!(shown.len(), 4); + assert!((shown[0].width - 253.64).abs() < 1e-9); + assert!((shown[0].height - 253.64 * 943.0 / 1200.0).abs() < 1e-9); + let budget = shown[1].height; + assert!(budget < 253.64 * 6.0 && budget > 60.0); + assert!((shown[2].height - budget).abs() < 1e-9 && (shown[3].height - budget).abs() < 1e-9); + // Cells: (36, 305.64) and again; each image centred in its cell of 253.64. + for (image, cell_x) in shown[1..].iter().zip([305.64, 36.0, 305.64]) { + assert!((image.x - (cell_x + (253.64 - image.width) / 2.0)).abs() < 1e-9); + } + assert_images_hold(&drawn, 4); + assert_clean(&drawn); +} + +fn mixed_views(all: bool) -> Vec { + let mut views = vec![ + main_view(), + head_view(), + crop("Membre antérieur", [625.0, 969.0, 220.0, 660.0], 1), + crop("Ligne du dos", [770.0, 458.0, 980.0, 140.0], 1), + ]; + if all { + views.extend([ + crop("Épaule", [584.0, 757.0, 400.0, 300.0], 1), + crop("Un sixième", [200.0, 300.0, 150.0, 900.0], 1), + crop("Un dixième", [500.0, 300.0, 100.0, 1000.0], 1), + crop("Trois pour un", [100.0, 100.0, 600.0, 200.0], 1), + ]); + } + views +} + +#[test] +fn mixed_views_with_a_long_note_keep_order_ratios_and_the_sixty_points() { + for all in [false, true] { + let views = mixed_views(all); + let count = views.len(); + let (case, wrapped) = long_comment_case(views); + let drawn = draw(&case); + assert_images_hold(&drawn, count); + let lines = body_lines(&drawn); + assert_eq!( + lines[lines.len() - wrapped.len()..], + wrapped[..], + "{count} views" + ); + assert_clean(&drawn); + println!("{count} views: {} pages", drawn.pages.len()); + } +} + +#[test] +fn eight_seven_to_one_views_paginate_before_going_under_sixty_points() { + let views = (0..8) + .map(|n| { + crop( + &format!("Dos {n}"), + [770.0, 458.0 + f64::from(n), 980.0, 140.0], + 1, + ) + }) + .collect(); + let case = Case { + views, + comment: french_comment(200), + }; + let drawn = draw(&case); + assert!(observation_pages(&drawn).len() >= 2); + assert_images_hold(&drawn, 8); + let heights: Vec = all_images(&drawn).iter().map(|i| i.height).collect(); + let lowest = heights.iter().copied().fold(f64::INFINITY, f64::min); + println!( + "8 x 7:1: {} pages, lowest image {lowest:.3} pt", + drawn.pages.len() + ); + // Every row is before any text of the sections. + let calls: Vec<(usize, &DrawOp)> = observation_pages(&drawn) + .iter() + .enumerate() + .flat_map(|(p, page)| content(page).iter().map(move |op| (p, op))) + .collect(); + let last_image = calls + .iter() + .rposition(|(_, op)| matches!(op, DrawOp::Image(i) if i.y < BODY_TOP)); + let first_body = calls + .iter() + .position(|(_, op)| matches!(op, DrawOp::Text(t) if t.size == 10.0)) + .unwrap(); + assert!(last_image.unwrap() < first_body); + assert_clean(&drawn); +} + +#[test] +fn the_footers_count_the_continuation_pages_and_the_conclusion_comes_last() { + let (case, _) = long_comment_case(vec![]); + let drawn = draw(&case); + let total = drawn.pages.len(); + assert!(total >= 3); + for (p, page) in drawn.pages.iter().enumerate() { + let wanted = format!("{} / {total}", p + 1); + let found = page.ops[page.footer_start..] + .iter() + .any(|op| matches!(op, DrawOp::Text(t) if t.text == wanted)); + assert!(found, "page {p}: no `{wanted}`"); + } + let eyebrow_of = |page: &PageLog| { + texts(page) + .iter() + .find(|t| (t.y - (PAGE_HEIGHT - 95.0)).abs() < 1e-9) + .map(|t| t.text.clone()) + }; + let last = eyebrow_of(&drawn.pages[total - 1]); + assert!(last.is_some()); + assert!( + drawn.pages[..total - 1] + .iter() + .all(|p| eyebrow_of(p) != last) + ); +} + +#[test] +fn a_long_view_name_in_the_right_column_stays_inside_the_page() { + let case = Case { + views: vec![ + main_view(), + crop( + "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + [200.0, 300.0, 150.0, 900.0], + 1, + ), + ], + comment: french_comment(100), + }; + let drawn = draw(&case); + let page = &drawn.pages[0]; + let label = texts(page) + .into_iter() + .find(|t| t.text.contains("TÊTE") && t.size == 8.0) + .unwrap(); + assert!((label.x - 305.64).abs() < 1e-9); + assert_clean(&drawn); +}