feat(anatomy): R5.4 review files in Rust (CHANGELOG, REVIEW-REPORT, review overlays, app drawings) and the whole-draft --check

This commit is contained in:
bchanot committed 2026-10-23 11:21:49 +02:00
1 parent 43ce28a79b
commit fef21d67ef
17 files changed
+2103 -52

No files matched your search

+94 -32
View File
@@ -1,10 +1,12 @@
//! `import-equine` (R5.2, R5.3): the anatomical pipeline on the core. Reads the historical
//! `import-equine` (R5.2 to R5.4): the anatomical pipeline on the core. Reads the historical
//! equine files, the authored curation files and the frozen cleaned drawing of the repository,
//! and produces the two generated folders the TypeScript `pnpm import:equine` writes:
//! `legacy-import/` (complete) and `draft/` (its R5.3 files; the review drawings and the two
//! Markdown reports join at R5.4).
//! and produces the two generated folders the TypeScript `pnpm import:equine` writes, whole:
//! `legacy-import/` (6 files) and `draft/` (12 files).
//!
//! import-equine --check compare with the committed folders, write nothing
//! import-equine --check compare with the committed folders, write nothing: every file
//! byte for byte, except the application's drawings, which may
//! fall back on parsed trees under the declared R3 rule; a file
//! missing, not produced or different fails the check
//! import-equine --out <dir> write <dir>/legacy-import and <dir>/draft (<dir> absent or empty)
//!
//! The repository is found from this crate's manifest folder; a relative `--out` is typed from
@@ -19,6 +21,7 @@ use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::{env, fs, process};
use faunosteo_core::curation::draft::svg_compare::{TriggerNames, compare_drawing};
use faunosteo_core::curation::draft::{
DraftInput, build_equine_draft, parse_changeset, parse_references, parse_view_box,
render_draft_artifacts,
@@ -27,6 +30,7 @@ use faunosteo_core::curation::legacy::{
EquineLegacyInput, HEAD_VIEW_ID, ImportResult, SvgSource, import_equine_legacy,
render_artifacts,
};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
const SEED: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
@@ -37,16 +41,9 @@ const LEGACY_FOLDER: &str = "legacy-import";
const DRAFT_FOLDER: &str = "draft";
const CLEANED_ASSET: &str = "assets/horse.svg";
// shortcut: the draft files R5.4 will produce (review drawings, CHANGELOG, REVIEW-REPORT) are
// listed as pending by `--check` and not counted; R5.4 removes this list and compares them.
const PENDING_R5_4: [&str; 6] = [
"review/annotations-main.svg",
"review/annotations-head.svg",
"review/app-main.svg",
"review/app-head.svg",
"CHANGELOG.md",
"REVIEW-REPORT.md",
];
/// The files of the draft whose comparison may fall back on parsed trees under the declared
/// R3 trigger-name rule (`svg_compare`): the application's drawings of each view.
const APP_DRAWING_PREFIX: &str = "review/app-";
/// A file of a generated folder: its path relative to the folder and its bytes.
type FolderFile = (String, Vec<u8>);
@@ -55,6 +52,8 @@ type FolderFile = (String, Vec<u8>);
struct Folder {
name: &'static str,
files: Vec<FolderFile>,
/// The declared tree rule of the application's drawings (the draft only).
trigger_names: Option<TriggerNames>,
}
/// A bound no source or generated file approaches (the largest, the draft CHANGELOG, is about
@@ -122,6 +121,7 @@ fn legacy_folder(input: &EquineLegacyInput, result: &ImportResult) -> Result<Fol
Ok(Folder {
name: LEGACY_FOLDER,
files,
trigger_names: None,
})
}
@@ -143,11 +143,16 @@ fn draft_folder(result: &ImportResult) -> Result<Folder, String> {
changes: &changeset.changes,
})
.map_err(|error| error.to_string())?;
let mut files = texts(render_draft_artifacts(&draft).map_err(|error| error.to_string())?);
let rendered =
render_draft_artifacts(&draft, &result.anomalies).map_err(|error| error.to_string())?;
let typed: AnatomicalSheetDocument =
serde_json::from_value(draft.document.clone()).map_err(|error| error.to_string())?;
let mut files = texts(rendered);
files.push((CLEANED_ASSET.to_owned(), cleaned_svg));
Ok(Folder {
name: DRAFT_FOLDER,
files,
trigger_names: Some(TriggerNames::of(&typed)),
})
}
@@ -177,8 +182,41 @@ fn listed(dir: &Path, prefix: &str, out: &mut Vec<String>) -> Result<(), String>
Ok(())
}
/// The differences between a produced folder and the committed one; pending R5.4 files of the
/// draft are reported, not counted.
/// How one produced file compares with the committed one: byte identity, or, for the
/// application's drawings only, parsed trees under the declared R3 rule (printed as declared).
fn compare_file(
folder: &Folder,
name: &str,
produced: &[u8],
committed: &[u8],
) -> Result<(), String> {
if produced == committed {
return Ok(());
}
let rule = folder
.trigger_names
.as_ref()
.filter(|_| name.starts_with(APP_DRAWING_PREFIX));
let (Ok(produced), Ok(committed)) = (
std::str::from_utf8(produced),
std::str::from_utf8(committed),
) else {
return Err(format!("{}: differs: {name}", folder.name));
};
match compare_drawing(produced, committed, rule) {
Ok(_) => {
println!(
"{}: declared: {name} (trees equal under the R3 trigger-name rule)",
folder.name
);
Ok(())
}
Err(why) => Err(format!("{}: differs: {name} ({why})", folder.name)),
}
}
/// The differences between a produced folder and the committed one: every committed file must
/// be produced and every produced file committed and equal (`compare_file`).
fn check(folder: &Folder) -> Result<Vec<String>, String> {
let target = Path::new(SEED).join(folder.name);
// The generated folder itself must lie in the seed: a link there is never listed through.
@@ -190,8 +228,11 @@ fn check(folder: &Folder) -> Result<Vec<String>, String> {
let mut problems = Vec::new();
for (name, bytes) in &folder.files {
match read(&target.join(name)) {
Ok(committed) if committed == *bytes => {}
Ok(_) => problems.push(format!("{}: differs: {name}", folder.name)),
Ok(committed) => {
if let Err(problem) = compare_file(folder, name, bytes, &committed) {
problems.push(problem);
}
}
Err(_) => problems.push(format!("{}: missing: {name}", folder.name)),
}
}
@@ -201,10 +242,6 @@ fn check(folder: &Folder) -> Result<Vec<String>, String> {
if folder.files.iter().any(|(produced, _)| *produced == name) {
continue;
}
if folder.name == DRAFT_FOLDER && PENDING_R5_4.contains(&name.as_str()) {
println!("{}: pending R5.4 (not compared): {name}", folder.name);
continue;
}
problems.push(format!("{}: not produced: {name}", folder.name));
}
Ok(problems)
@@ -233,7 +270,7 @@ fn claim_destination(typed: &Path, seed: &Path) -> Result<PathBuf, String> {
}
None => return Err(refuse("not a destination folder")),
};
if inside(&parent, seed) || inside_by_identity(&parent, seed) {
if inside(&parent, seed) || inside_by_identity(&parent, seed)? {
return Err(refuse("inside the seed folder"));
}
let name = out
@@ -245,6 +282,10 @@ fn claim_destination(typed: &Path, seed: &Path) -> Result<PathBuf, String> {
Ok(metadata) if metadata.file_type().is_symlink() => return Err(refuse("a symbolic link")),
Ok(metadata) if !metadata.is_dir() => return Err(refuse("not a folder")),
Ok(_) => {
// An existing folder may itself be a second path to a folder of the seed.
if inside_by_identity(&root, seed)? {
return Err(refuse("inside the seed folder"));
}
let mut entries =
fs::read_dir(&root).map_err(|error| format!("{}: {error}", root.display()))?;
if entries.next().is_some() {
@@ -281,15 +322,18 @@ fn seed_identities(seed: &Path) -> Option<Vec<(u64, u64)>> {
/// Whether `folder` or one of its ancestors is the seed folder or a folder under it, by file
/// identity: a second path to any of them (a bind mount, a share mounted twice on the same
/// device) is caught too. A walk that fails counts as inside.
fn inside_by_identity(folder: &Path, seed: &Path) -> bool {
/// device) is caught too. A seed walk that fails is an error (the claim then refuses).
fn inside_by_identity(folder: &Path, seed: &Path) -> Result<bool, String> {
use std::os::unix::fs::MetadataExt;
let Some(identities) = seed_identities(seed) else {
return true;
};
folder.ancestors().any(|ancestor| {
let identities = seed_identities(seed).ok_or_else(|| {
format!(
"{}: the seed folder cannot be read, nothing written",
seed.display()
)
})?;
Ok(folder.ancestors().any(|ancestor| {
fs::metadata(ancestor).is_ok_and(|m| identities.contains(&(m.dev(), m.ino())))
})
}))
}
/// Where a relative destination is typed from: `INIT_CWD` when pnpm set it to an absolute
@@ -437,6 +481,24 @@ mod tests {
assert!(refused.contains("not empty"), "{refused}");
}
#[test]
fn a_difference_fails_the_check_unless_a_declared_rule_covers_it() {
let draft = Folder {
name: DRAFT_FOLDER,
files: Vec::new(),
trigger_names: None,
};
assert!(compare_file(&draft, "CHANGELOG.md", b"a\n", b"a\n").is_ok());
let differs = compare_file(&draft, "CHANGELOG.md", b"a\n", b"b\n")
.err()
.unwrap_or_default();
assert!(differs.contains("differs: CHANGELOG.md"), "{differs}");
// No rule for the folder: even an application drawing must be byte-identical.
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>";
let other = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><g/></svg>";
assert!(compare_file(&draft, "review/app-main.svg", svg, other).is_err());
}
#[test]
fn a_folder_under_the_seed_or_the_seed_itself_is_inside_it() {
let seed = Path::new("/repo/supabase/seed/anatomical-sheets/equine");
@@ -0,0 +1,37 @@
//! The drawing of one view exactly as the application renders it
//! (`packages/anatomy/src/curation/app-review.ts`): the cleaned asset framed on the view's box
//! plus the annotation layer generated from the document, by the R3 layer the editor canvas
//! uses. Written under `draft/review/app-<view>.svg` so the markers and the framing can be
//! compared outside the browser.
//!
//! Declared difference: the R3 owner decision (2026-10-15) gives a trigger without a name of
//! its own the opened view's name in each language; the TypeScript renderer wrote the French
//! name twice (`svg_compare::TriggerNames`).
use std::collections::HashSet;
use super::drawing::{CleanedDrawing, drawing_text};
use super::targets::fail;
use crate::anatomy::layer::{find_view, render_layer, view_box_of};
use crate::anatomy::svg::Node;
use crate::curation::PipelineError;
use crate::domain::sheet::AnatomicalSheetDocument;
pub fn render_app_review_drawing(
drawing: &CleanedDrawing,
document: &AnatomicalSheetDocument,
view_id: &str,
) -> Result<String, PipelineError> {
let view =
find_view(document, view_id).ok_or_else(|| fail(format!("unknown view \"{view_id}\"")))?;
let mut root = drawing.root.clone();
if let Some(view_box) = view_box_of(view) {
root.set_attr("viewBox", view_box);
}
root.remove_attr("width");
root.remove_attr("height");
let layer = render_layer(document, view_id, &HashSet::new())
.map_err(|_| fail(format!("unknown view \"{view_id}\"")))?;
root.children.push(Node::Element(layer));
Ok(drawing_text(&drawing.prolog, &root))
}
+187
View File
@@ -0,0 +1,187 @@
//! French CHANGELOG of the working revision (`packages/anatomy/src/curation/changelog.ts`):
//! volumes before / after, then one table per change level with every elementary edit. Pure
//! formatting of the records, deterministic (no dates). The text returned here is the raw
//! report; `markdown::format_markdown` aligns its tables as Prettier did.
use serde_json::Value;
use super::labels::{LEVELS, kind_label, level_label};
use super::migration_map::MigrationMapStats;
use super::records::ChangeRecord;
use super::schema::ChangeLevel;
use super::stats::{DocumentStats, stat_rows};
use super::targets::fail;
use crate::curation::PipelineError;
use crate::curation::markdown::{Cell, code, table};
use crate::json::to_js_compact;
/// The longest value text a table cell shows, in UTF-16 units (`text.length`).
const MAX_VALUE_LENGTH: usize = 120;
/// `isLabel`: a non-empty object whose keys are `fr` / `en` with string values.
fn is_label(value: &Value) -> bool {
value.as_object().is_some_and(|map| {
!map.is_empty()
&& map
.iter()
.all(|(key, value)| (key == "fr" || key == "en") && value.is_string())
})
}
/// `compactValue`: labels as text, other non-strings as JSON, cut to 120 UTF-16 units with an
/// ellipsis. A cut inside a surrogate pair leaves a lone surrogate, which the file write turned
/// into U+FFFD: `from_utf16_lossy` gives the same text.
pub fn compact_value(value: &Value) -> Result<String, PipelineError> {
let text = match value {
Value::String(text) => text.clone(),
Value::Object(map) if is_label(value) => map
.values()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join(" / "),
other => to_js_compact(other).map_err(|error| fail(format!("value: {error}")))?,
};
let units: Vec<u16> = text.encode_utf16().collect();
if units.len() <= MAX_VALUE_LENGTH {
return Ok(text);
}
Ok(format!(
"{}…",
String::from_utf16_lossy(&units[..MAX_VALUE_LENGTH - 1])
))
}
/// `recordSubject`: the target, with its field when there is one.
pub fn record_subject(record: &ChangeRecord) -> String {
match &record.field {
None => record.target.clone(),
Some(field) => format!("{}.{field}", record.target),
}
}
fn record_row(record: &ChangeRecord) -> Result<Vec<Cell>, PipelineError> {
let change = &record.change;
let references: Vec<String> = change
.reference_ids
.iter()
.map(|id| code(Some(id)))
.collect();
let references = if references.is_empty() {
"-".to_owned()
} else {
references.join(", ")
};
let confirm = if change.level.needs_confirmation() {
"oui"
} else {
"non"
};
Ok(vec![
Cell::from(format!("{} {}", code(Some(&change.id)), change.title.fr)),
Cell::from(code(Some(&record_subject(record)))),
Cell::from(compact_value(&record.before)?),
Cell::from(compact_value(&record.after)?),
Cell::from(kind_label(change.kind)),
Cell::from(change.rationale.as_str()),
Cell::from(references),
Cell::from(confirm),
])
}
fn level_section(level: ChangeLevel, records: &[ChangeRecord]) -> Result<String, PipelineError> {
let rows = records
.iter()
.filter(|record| record.change.level == level)
.map(record_row)
.collect::<Result<Vec<_>, _>>()?;
let head = [
"Changement",
"Objet",
"Avant",
"Après",
"Nature",
"Justification",
"Références",
"Confirmation requise",
];
let body = if rows.is_empty() {
"Aucun changement de ce niveau.".to_owned()
} else {
table(&head, &rows)
};
Ok(format!("## {}\n\n{body}", level_label(level)))
}
fn comparison(before: &DocumentStats, after: &DocumentStats) -> String {
let after_rows = stat_rows(after);
let rows: Vec<Vec<Cell>> = stat_rows(before)
.into_iter()
.map(|(label, value)| {
let later = after_rows
.iter()
.find(|(other, _)| *other == label)
.map_or(0, |(_, value)| *value);
vec![Cell::from(label), Cell::from(value), Cell::from(later)]
})
.collect();
format!(
"## Comparaison quantitative\n\n{}",
table(&["Indicateur", "Avant", "Après"], &rows)
)
}
fn intro() -> String {
[
"# Journal des changements : révision de travail",
"",
"Généré par `pnpm import:equine` : import historique (`legacy-import/`) puis changements \
rédigés (`curation/changes.json`). Ne pas modifier à la main : relancer la commande.",
"",
"Niveaux : A = erreur démontrée, B = amélioration étayée, C = point incertain. Les \
niveaux B et C demandent une confirmation professionnelle.",
]
.join("\n")
}
/// Fate of the legacy finding nodes a Report v2 may cite (`report-migration-map.json`).
fn migration(stats: &MigrationMapStats) -> String {
let row = |label: &str, value: usize| vec![Cell::from(label), Cell::from(value.to_string())];
let rows = vec![
row("Nœuds du catalogue historique", stats.nodes),
row("Chemin identique", stats.identical),
row(
"Chemin renommé ou déplacé (suivi des renommages)",
stats.remapped,
),
row(
"Relogé sous une autre catégorie (correspondance unique)",
stats.rehomed,
),
row(
"Retiré : le bilan garde le constat avec ses libellés figés",
stats.removed,
),
];
format!(
"## Migration des bilans v2\n\n{}",
table(&["Nœuds", "Nombre"], &rows)
)
}
/// `renderChangelog`: the raw text, before the table alignment.
pub fn render_changelog(
records: &[ChangeRecord],
before: &DocumentStats,
after: &DocumentStats,
migration_stats: &MigrationMapStats,
) -> Result<String, PipelineError> {
let mut sections = vec![
intro(),
comparison(before, after),
migration(migration_stats),
];
for level in LEVELS {
sections.push(level_section(level, records)?);
}
Ok(format!("{}\n", sections.join("\n\n")))
}
+41
View File
@@ -0,0 +1,41 @@
//! The frozen cleaned drawing as the review files read it: the text of
//! `draft/assets/horse.svg` through the core's one SVG reader (refused if the reader removes
//! anything: the product's drawings come out untouched), and its prolog (the bytes before the
//! root element: the XML declaration and its line break), kept verbatim in front of every
//! drawing the pipeline writes, as xmldom's serialiser kept it.
use crate::anatomy::svg::serialize::serialize;
use crate::anatomy::svg::{Element, read_svg};
use crate::curation::PipelineError;
pub struct CleanedDrawing {
pub prolog: String,
pub root: Element,
}
fn refuse(why: impl std::fmt::Display) -> PipelineError {
PipelineError::Source(format!("horse.svg: {why}"))
}
/// Reads the cleaned drawing (UTF-8, refused otherwise, as `TextDecoder` fatal was).
pub fn read_cleaned_drawing(bytes: &[u8]) -> Result<CleanedDrawing, PipelineError> {
let text = std::str::from_utf8(bytes).map_err(|_| refuse("invalid UTF-8"))?;
let sanitized = read_svg(text).map_err(|error| refuse(error.reason()))?;
if !sanitized.removed.is_empty() {
return Err(refuse(format!(
"the reader removed {:?}",
sanitized.removed
)));
}
let document = roxmltree::Document::parse(text).map_err(refuse)?;
let start = document.root_element().range().start;
Ok(CleanedDrawing {
prolog: text[..start].to_owned(),
root: sanitized.root,
})
}
/// The file text of a drawing built on the cleaned root.
pub fn drawing_text(prolog: &str, root: &Element) -> String {
format!("{prolog}{}", serialize(root))
}
+45
View File
@@ -0,0 +1,45 @@
//! French labels shared by the CHANGELOG and the review report
//! (`packages/anatomy/src/curation/labels.ts`).
use super::schema::{ChangeKind, ChangeLevel, ChangePriority};
pub fn kind_label(kind: ChangeKind) -> &'static str {
match kind {
ChangeKind::Correction => "Correction",
ChangeKind::Terminology => "Terminologie",
ChangeKind::Translation => "Traduction",
ChangeKind::Restructure => "Réorganisation",
ChangeKind::Enrichment => "Ajout",
ChangeKind::Reference => "Référence",
ChangeKind::Geometry => "Géométrie",
ChangeKind::Removal => "Suppression",
ChangeKind::Technical => "Technique",
}
}
pub fn level_label(level: ChangeLevel) -> &'static str {
match level {
ChangeLevel::A => "Niveau A : erreurs démontrées",
ChangeLevel::B => "Niveau B : améliorations étayées (confirmation requise)",
ChangeLevel::C => "Niveau C : points incertains (question au professionnel)",
}
}
pub fn priority_label(priority: ChangePriority) -> &'static str {
match priority {
ChangePriority::High => "haute",
ChangePriority::Medium => "moyenne",
ChangePriority::Low => "basse",
}
}
pub const LEVELS: [ChangeLevel; 3] = [ChangeLevel::A, ChangeLevel::B, ChangeLevel::C];
/// The letter of a level, as the reports print it.
pub fn level_letter(level: ChangeLevel) -> &'static str {
match level {
ChangeLevel::A => "A",
ChangeLevel::B => "B",
ChangeLevel::C => "C",
}
}
+7
View File
@@ -4,17 +4,24 @@
//! R5.4). Parity with the TypeScript is proven by `tests/curation_draft.rs` against the
//! committed `draft/` folder, `oracles/r5/pipeline.json` and `oracles/r5/curation-synthetic.json`.
pub mod app_review;
pub mod apply;
pub mod changelog;
pub mod drawing;
pub mod fields;
pub mod labels;
pub mod migration_map;
pub mod ops;
pub mod overlay;
pub mod pipeline;
pub mod records;
pub mod rename;
pub mod review_report;
pub mod schema;
pub mod seed;
pub mod shape;
pub mod stats;
pub mod svg_compare;
pub mod targets;
pub use apply::{apply_changeset, curated_issues};
+3 -1
View File
@@ -398,9 +398,11 @@ fn apply_cite(
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
// `before.includes(id)`: only an equal string matches; hashed once per item.
let existing: HashSet<&str> = before.iter().filter_map(Value::as_str).collect();
let added: Vec<Value> = distinct(&op.reference_ids)
.into_iter()
.filter(|id| !before.contains(&Value::from(id.as_str())))
.filter(|id| !existing.contains(id.as_str()))
.map(|id| Value::from(id.clone()))
.collect();
if added.is_empty() {
+365
View File
@@ -0,0 +1,365 @@
//! Before / after drawing of one view for the professional review
//! (`packages/anatomy/src/curation/overlay.ts`): the cleaned anatomy, the curated annotations
//! as an SVG layer, and the baseline position of every moved or removed annotation beside it
//! (dashed). Pure data, deterministic, opens in any browser.
use serde_json::Value;
use super::drawing::{CleanedDrawing, drawing_text};
use super::records::{js_deep_equal, js_string};
use super::targets::fail;
use crate::anatomy::svg::number::{is_js_space, js_number_of};
use crate::anatomy::svg::{Element, Node};
use crate::curation::PipelineError;
use crate::curation::text::js_round;
use crate::json::js_number;
pub const REVIEW_OVERLAY_DIR: &str = "review";
const LAYER_ID: &str = "review-annotations";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
Unchanged,
Moved,
Added,
Removed,
}
impl Status {
fn name(self) -> &'static str {
match self {
Self::Unchanged => "unchanged",
Self::Moved => "moved",
Self::Added => "added",
Self::Removed => "removed",
}
}
/// The marker style, attribute by attribute in the TypeScript order.
fn style(self) -> &'static [(&'static str, &'static str)] {
match self {
Self::Unchanged => &[
("stroke", "#1d4ed8"),
("fill", "#1d4ed8"),
("fill-opacity", "0.12"),
],
Self::Moved | Self::Added => &[
("stroke", "#15803d"),
("fill", "#15803d"),
("fill-opacity", "0.2"),
],
// fill-opacity rather than fill="none": some rasterizers drop unfilled shapes.
Self::Removed => &[
("stroke", "#b91c1c"),
("fill", "#b91c1c"),
("fill-opacity", "0.04"),
("stroke-dasharray", "8 6"),
],
}
}
fn stroke(self) -> &'static str {
self.style()[0].1
}
}
struct Marker<'a> {
id: String,
geometry: &'a Value,
status: Status,
}
fn annotations(doc: &Value) -> &[Value] {
doc.get("annotations")
.and_then(Value::as_array)
.map_or(&[], Vec::as_slice)
}
/// Annotations of the view that carry a geometry (`withGeometry`).
fn with_geometry<'a>(doc: &'a Value, view_id: &str) -> impl Iterator<Item = &'a Value> {
annotations(doc).iter().filter(move |a| {
a.get("view_id").and_then(Value::as_str) == Some(view_id)
&& a.get("geometry").is_some_and(|g| !g.is_null())
})
}
/// `new Map(entries)`: the first position of an id, its last value.
fn previous_geometries<'a>(before: &'a Value, view_id: &str) -> Vec<(String, &'a Value)> {
let mut map: Vec<(String, &Value)> = Vec::new();
for annotation in with_geometry(before, view_id) {
let id = js_string(annotation.get("id"));
let geometry = &annotation["geometry"];
match map.iter_mut().find(|(known, _)| *known == id) {
Some(entry) => entry.1 = geometry,
None => map.push((id, geometry)),
}
}
map
}
/// `overlayMarkers`: curated annotations with their status, then the baseline shapes they left.
fn overlay_markers<'a>(before: &'a Value, after: &'a Value, view_id: &str) -> Vec<Marker<'a>> {
let previous = previous_geometries(before, view_id);
let mut markers = Vec::new();
for annotation in with_geometry(after, view_id) {
let id = js_string(annotation.get("id"));
let geometry = &annotation["geometry"];
let old = previous
.iter()
.find(|(known, _)| *known == id)
.map(|(_, g)| *g);
let status = match old {
None => Status::Added,
Some(old) if js_deep_equal(old, geometry) => Status::Unchanged,
Some(_) => Status::Moved,
};
markers.push(Marker {
id: id.clone(),
geometry,
status,
});
if let (Status::Moved, Some(old)) = (status, old) {
markers.push(Marker {
id,
geometry: old,
status: Status::Removed,
});
}
}
let kept: Vec<String> = annotations(after)
.iter()
.map(|a| js_string(a.get("id")))
.collect();
for (id, geometry) in previous {
if !kept.contains(&id) {
markers.push(Marker {
id,
geometry,
status: Status::Removed,
});
}
}
markers
}
fn number(geometry: &Value, key: &str) -> f64 {
geometry
.get(key)
.and_then(Value::as_f64)
.unwrap_or(f64::NAN)
}
/// `String(number)`, NaN included.
fn text_of(value: f64) -> String {
if value.is_nan() {
"NaN".to_owned()
} else {
js_number(value)
}
}
fn points(geometry: &Value) -> Vec<(f64, f64)> {
let list = geometry.get("points").and_then(Value::as_array);
list.into_iter()
.flatten()
.map(|point| {
let at = |i: usize| point.get(i).and_then(Value::as_f64).unwrap_or(f64::NAN);
(at(0), at(1))
})
.collect()
}
fn shape_element(geometry: &Value) -> Result<Element, PipelineError> {
match geometry.get("type").and_then(Value::as_str) {
Some("circle") => Ok(Element::svg(
"circle",
vec![
("cx", text_of(number(geometry, "cx"))),
("cy", text_of(number(geometry, "cy"))),
("r", text_of(number(geometry, "r"))),
],
Vec::new(),
)),
Some("polygon") => {
let list: Vec<String> = points(geometry)
.into_iter()
.map(|(x, y)| format!("{},{}", text_of(x), text_of(y)))
.collect();
Ok(Element::svg(
"polygon",
vec![("points", list.join(" "))],
Vec::new(),
))
}
Some("path") => Ok(Element::svg(
"path",
vec![("d", js_string(geometry.get("d")))],
Vec::new(),
)),
_ => Err(fail("a geometry of an unknown type")),
}
}
fn label_anchor(geometry: &Value) -> Option<(f64, f64)> {
match geometry.get("type").and_then(Value::as_str) {
Some("circle") => Some((
number(geometry, "cx"),
number(geometry, "cy") - number(geometry, "r") - 4.0,
)),
Some("polygon") => {
let list = points(geometry);
let (sx, sy) = list
.iter()
.fold((0.0, 0.0), |(ax, ay), (x, y)| (ax + x, ay + y));
let n = list.len() as f64;
Some((sx / n, sy / n))
}
_ => None,
}
}
fn text_element(attrs: Vec<(&str, String)>, text: String) -> Element {
Element::svg("text", attrs, vec![Node::Text(text)])
}
fn marker_group(marker: &Marker<'_>, font_size: f64) -> Result<Element, PipelineError> {
let mut shape = shape_element(marker.geometry)?;
for (key, value) in marker.status.style() {
shape.set_attr(key, (*value).to_owned());
}
shape.set_attr("stroke-width", text_of(font_size / 8.0));
let title = Element::svg(
"title",
Vec::new(),
vec![Node::Text(format!(
"{} ({})",
marker.id,
marker.status.name()
))],
);
let mut children = vec![Node::Element(title), Node::Element(shape)];
if let Some((x, y)) = label_anchor(marker.geometry).filter(|_| marker.status != Status::Removed)
{
children.push(Node::Element(text_element(
vec![
("x", text_of(x)),
("y", text_of(y)),
("text-anchor", "middle".to_owned()),
("font-family", "sans-serif".to_owned()),
("font-size", text_of(font_size)),
("fill", marker.status.stroke().to_owned()),
],
marker.id.clone(),
)));
}
Ok(Element::svg(
"g",
vec![
("data-review-id", marker.id.clone()),
("data-review-status", marker.status.name().to_owned()),
],
children,
))
}
fn legend(layer: &mut Element, (x, y): (f64, f64), font_size: f64) {
let lines = [
(Status::Unchanged, "bleu : inchangé"),
(
Status::Moved,
"vert : déplacé ou ajouté (pointillé rouge = position précédente)",
),
(Status::Removed, "rouge pointillé : retiré"),
];
for (index, (status, label)) in lines.into_iter().enumerate() {
let line = (index + 1) as f64;
layer.children.push(Node::Element(text_element(
vec![
("x", text_of(x)),
("y", text_of(y + line * font_size * 1.3)),
("font-family", "sans-serif".to_owned()),
("font-size", text_of(font_size)),
("fill", status.stroke().to_owned()),
],
label.to_owned(),
)));
}
}
/// `raw.split(/[\s,]+/).map(Number)`, without the trim the TypeScript did not do: a run of
/// separators splits once, a leading or trailing run leaves an empty part (`Number("")` is 0).
fn split_numbers(raw: &str) -> Vec<f64> {
let mut parts = Vec::new();
let mut current = String::new();
let mut in_separator = false;
for c in raw.chars() {
if is_js_space(c) || c == ',' {
if !in_separator {
parts.push(std::mem::take(&mut current));
in_separator = true;
}
} else {
in_separator = false;
current.push(c);
}
}
parts.push(current);
parts.iter().map(|part| js_number_of(part)).collect()
}
/// `Math.max(Math.round(width / 90), 10)` with `Math.max`'s NaN.
fn font_size_of(width: f64) -> f64 {
let rounded = js_round(width / 90.0);
if rounded.is_nan() {
f64::NAN
} else {
rounded.max(10.0)
}
}
pub struct OverlayInput<'a> {
pub drawing: &'a CleanedDrawing,
pub before: &'a Value,
pub after: &'a Value,
pub view_id: &'a str,
}
/// The review drawing of one view, framed on that view's box (`renderReviewOverlay`).
pub fn render_review_overlay(input: &OverlayInput<'_>) -> Result<String, PipelineError> {
let view = input
.after
.get("views")
.and_then(Value::as_array)
.and_then(|views| {
views
.iter()
.find(|v| v.get("id").and_then(Value::as_str) == Some(input.view_id))
})
.ok_or_else(|| fail(format!("unknown view \"{}\"", input.view_id)))?;
let mut root = input.drawing.root.clone();
if let Some(view_box) = view.get("view_box").filter(|b| b.is_object()) {
let part = |key: &str| text_of(number(view_box, key));
let text = format!(
"{} {} {} {}",
part("min_x"),
part("min_y"),
part("width"),
part("height")
);
root.set_attr("viewBox", text);
}
root.remove_attr("width");
root.remove_attr("height");
let frame = split_numbers(root.attr("viewBox").unwrap_or("0 0 1000 1000"));
let at = |i: usize| frame.get(i).copied().unwrap_or(f64::NAN);
let font_size = font_size_of(at(2));
let mut layer = Element::svg("g", vec![("id", LAYER_ID.to_owned())], Vec::new());
for marker in overlay_markers(input.before, input.after, input.view_id) {
layer
.children
.push(Node::Element(marker_group(&marker, font_size)?));
}
legend(&mut layer, (at(0) + font_size, at(1)), font_size);
root.children.push(Node::Element(layer));
Ok(drawing_text(&input.drawing.prolog, &root))
}
+76 -9
View File
@@ -10,9 +10,14 @@
use serde_json::{Map, Value, json};
use super::app_review::render_app_review_drawing;
use super::apply::{apply_changeset, curated_issues};
use super::changelog::render_changelog;
use super::drawing::read_cleaned_drawing;
use super::migration_map::{MigrationMapInput, SheetRef, build_report_migration_map};
use super::overlay::{OverlayInput, REVIEW_OVERLAY_DIR, render_review_overlay};
use super::records::ChangeRecord;
use super::review_report::{ReviewReportInput, render_review_report};
use super::schema::{
ASSET_CHANGE_ID, Change, ChangeKind, ChangeLevel, ChangePriority, ChangeSummary, ChangeTitle,
Op, SetOp,
@@ -23,10 +28,11 @@ use super::targets::fail;
use crate::anatomy::svg::number::{js_number_of, js_split_list};
use crate::curation::PipelineError;
use crate::curation::ids::{asset_id_from_sha256, sha256_hex};
use crate::curation::legacy::types::{AssetRecord, ImportResult};
use crate::curation::legacy::types::{Anomaly, AssetRecord, ImportResult};
use crate::curation::legacy::{HEAD_VIEW_ID, MAIN_VIEW_ID};
use crate::curation::markdown::format_markdown;
use crate::curation::prettier_json::format_json;
use crate::domain::sheet::{Reference, SheetIssue, ViewBox};
use crate::domain::sheet::{AnatomicalSheetDocument, Reference, SheetIssue, ViewBox};
pub const DRAFT_SEED_SQL_FILE: &str = "equine_draft.sql";
pub const SHEET_REF_FILE: &str = "sheet-ref.json";
@@ -55,6 +61,8 @@ pub struct DraftResult {
/// Integrity warnings of the curated document (errors refuse).
pub issues: Vec<SheetIssue>,
pub sheet_id: String,
/// The frozen cleaned drawing, `draft/assets/horse.svg`, the review drawings' base.
pub cleaned_svg: Vec<u8>,
}
/// Manifest entry of the cleaned drawing; id derived from its sha256 (`cleanedAsset`).
@@ -151,6 +159,7 @@ pub fn build_equine_draft(input: &DraftInput<'_>) -> Result<DraftResult, Pipelin
changes: changes.iter().map(Change::summary).collect(),
assets: vec![asset],
sheet_id: input.import_result.sheet_id.clone(),
cleaned_svg: input.cleaned_svg.to_vec(),
})
}
@@ -179,12 +188,53 @@ pub fn draft_migration_map(
})
}
/// The R5.3 text artifacts of the draft folder, in the TypeScript order; the R5.4 files
/// (review drawings, CHANGELOG, REVIEW-REPORT) are not produced yet.
pub fn render_draft_artifacts(draft: &DraftResult) -> Result<Vec<(String, String)>, PipelineError> {
/// The views of the curated document, in document order.
fn view_ids(document: &Value) -> Vec<String> {
document
.get("views")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|view| view.get("id").and_then(Value::as_str).map(str::to_owned))
.collect()
}
/// One review overlay per view (`review/annotations-<view>.svg`), then the application's
/// drawing of each view (`review/app-<view>.svg`).
fn review_drawings(draft: &DraftResult) -> Result<Vec<(String, String)>, PipelineError> {
let drawing = read_cleaned_drawing(&draft.cleaned_svg)?;
let typed: AnatomicalSheetDocument = serde_json::from_value(draft.document.clone())
.map_err(|error| fail(format!("curated document: {error}")))?;
let views = view_ids(&draft.document);
let mut files = Vec::new();
for view_id in &views {
let overlay = render_review_overlay(&OverlayInput {
drawing: &drawing,
before: &draft.baseline,
after: &draft.document,
view_id,
})?;
files.push((
format!("{REVIEW_OVERLAY_DIR}/annotations-{view_id}.svg"),
overlay,
));
}
for view_id in &views {
let app = render_app_review_drawing(&drawing, &typed, view_id)?;
files.push((format!("{REVIEW_OVERLAY_DIR}/app-{view_id}.svg"), app));
}
Ok(files)
}
/// The text artifacts of the draft folder, keyed by file name, in the TypeScript order
/// (`renderDraftArtifacts`); the frozen `assets/horse.svg` is the caller's byte copy.
pub fn render_draft_artifacts(
draft: &DraftResult,
legacy_anomalies: &[Anomaly],
) -> Result<Vec<(String, String)>, PipelineError> {
let document_json = format_json(&draft.document)?;
let reference = sheet_ref(draft, &document_json);
let (map, _stats) = draft_migration_map(draft, &reference)?;
let (map, migration_stats) = draft_migration_map(draft, &reference)?;
let assets = serde_json::to_value(&draft.assets)
.map_err(|error| fail(format!("assets.json: {error}")))?;
let sheet_ref_json = json!({
@@ -194,17 +244,34 @@ pub fn render_draft_artifacts(draft: &DraftResult) -> Result<Vec<(String, String
"schema_version": draft.document.get("schema_version"),
"species_id": draft.document.get("species_id"),
});
let changelog = render_changelog(
&draft.records,
&draft.stats_before,
&draft.stats_after,
&migration_stats,
)?;
let review = render_review_report(&ReviewReportInput {
changes: &draft.changes,
records: &draft.records,
document: &draft.document,
stats_before: &draft.stats_before,
legacy_anomalies,
})?;
let seed = render_draft_seed_sql(&DraftSeedParams {
sheet_id: &draft.sheet_id,
assets: &draft.assets,
document_json: &document_json,
change_note: DRAFT_CHANGE_NOTE,
})?;
Ok(vec![
let mut files = vec![
("document.json".to_owned(), document_json),
("assets.json".to_owned(), format_json(&assets)?),
(SHEET_REF_FILE.to_owned(), format_json(&sheet_ref_json)?),
(MIGRATION_MAP_FILE.to_owned(), format_json(&map)?),
(DRAFT_SEED_SQL_FILE.to_owned(), seed),
])
];
files.extend(review_drawings(draft)?);
files.push(("CHANGELOG.md".to_owned(), format_markdown(&changelog)?));
files.push(("REVIEW-REPORT.md".to_owned(), format_markdown(&review)?));
files.push((DRAFT_SEED_SQL_FILE.to_owned(), seed));
Ok(files)
}
@@ -0,0 +1,379 @@
//! French review report for the osteopath, ten fixed sections
//! (`packages/anatomy/src/curation/review-report.ts`). It only formats data (changes,
//! records, stats, references): no medical content is written here, every statement comes
//! from the authored changeset. The text returned is the raw report, before the table
//! alignment.
use std::cmp::Ordering;
use std::collections::HashSet;
use serde_json::Value;
use super::changelog::{compact_value, record_subject};
use super::labels::{kind_label, level_letter, priority_label};
use super::records::{ChangeRecord, js_string};
use super::schema::{ChangeKind, ChangeLevel, ChangePriority, ChangeSummary};
use super::stats::{DocumentStats, stat_rows};
use super::targets::{Step, TargetKind, all_findings, at, top_collection_path, zone_findings};
use crate::curation::PipelineError;
use crate::curation::legacy::types::Anomaly;
use crate::curation::markdown::{Cell, code, table};
use crate::curation::text::utf16_cmp;
pub struct ReviewReportInput<'a> {
pub changes: &'a [ChangeSummary],
pub records: &'a [ChangeRecord],
pub document: &'a Value,
pub stats_before: &'a DocumentStats,
pub legacy_anomalies: &'a [Anomaly],
}
const NONE: &str = "Aucun élément dans cette révision.";
/// `[...new Set(items)]`: first occurrences, in order.
fn distinct(items: impl Iterator<Item = String>) -> Vec<String> {
let mut seen = HashSet::new();
items.filter(|item| seen.insert(item.clone())).collect()
}
fn codes(items: &[String]) -> String {
items
.iter()
.map(|item| code(Some(item)))
.collect::<Vec<_>>()
.join(", ")
}
fn subjects(input: &ReviewReportInput<'_>, change: &ChangeSummary) -> String {
let own = input
.records
.iter()
.filter(|record| record.change.id == change.id)
.map(record_subject);
codes(&distinct(own))
}
fn references(ids: &[String]) -> String {
if ids.is_empty() {
"aucune".to_owned()
} else {
codes(ids)
}
}
fn change_line(input: &ReviewReportInput<'_>, change: &ChangeSummary) -> String {
let confirm = if change.level.needs_confirmation() {
"oui"
} else {
"non"
};
let question = change
.question
.as_ref()
.map_or_else(String::new, |question| format!(" Question : {question}"));
format!(
"- {} {} (niveau {}, {}, confirmation requise : {confirm}). {} Objets : {}. \
Références : {}.{question}",
code(Some(&change.id)),
change.title.fr,
level_letter(change.level),
kind_label(change.kind),
change.rationale,
subjects(input, change),
references(&change.reference_ids),
)
}
fn change_list(input: &ReviewReportInput<'_>, keep: impl Fn(&ChangeSummary) -> bool) -> String {
let lines: Vec<String> = input
.changes
.iter()
.filter(|change| keep(change))
.map(|change| change_line(input, change))
.collect();
if lines.is_empty() {
NONE.to_owned()
} else {
lines.join("\n")
}
}
fn stat_table(head: &str, stats: &DocumentStats) -> String {
let rows: Vec<Vec<Cell>> = stat_rows(stats)
.into_iter()
.map(|(label, value)| vec![Cell::from(label), Cell::from(value)])
.collect();
table(&[head, "Valeur"], &rows)
}
fn initial_quality(input: &ReviewReportInput<'_>) -> String {
let to_validate = input
.legacy_anomalies
.iter()
.filter(|anomaly| anomaly.level == "a_valider")
.count();
[
format!(
"L'import historique signale {} anomalies, dont {to_validate} à valider (détail dans \
`legacy-import/IMPORT-REPORT.md`).",
input.legacy_anomalies.len()
),
String::new(),
stat_table("Indicateur (import historique)", input.stats_before),
]
.join("\n")
}
fn translations(input: &ReviewReportInput<'_>) -> String {
let changes: Vec<&ChangeSummary> = input
.changes
.iter()
.filter(|change| change.kind == ChangeKind::Translation)
.collect();
let ids: HashSet<&str> = changes.iter().map(|change| change.id.as_str()).collect();
let targets = distinct(
input
.records
.iter()
.filter(|record| ids.contains(record.change.id.as_str()))
.map(record_subject),
);
let head = format!(
"{} changement(s) de traduction, {} objet(s) traduit(s).",
changes.len(),
targets.len()
);
if targets.is_empty() {
return head;
}
let lines: Vec<String> = targets
.iter()
.map(|target| format!("- {}", code(Some(target))))
.collect();
format!("{head}\n\n{}", lines.join("\n"))
}
fn vet_flag_changes(input: &ReviewReportInput<'_>) -> Result<String, PipelineError> {
let mut lines = Vec::new();
for record in input
.records
.iter()
.filter(|record| record.field.as_deref() == Some("requires_vet_referral"))
{
lines.push(format!(
"- {} : {} → {} ({})",
code(Some(&record.target)),
compact_value(&record.before)?,
compact_value(&record.after)?,
code(Some(&record.change.id))
));
}
Ok(if lines.is_empty() {
"Aucun renvoi vétérinaire modifié dans cette révision.".to_owned()
} else {
lines.join("\n")
})
}
fn vet_flags_per_zone(document: &Value) -> Result<String, PipelineError> {
let zones_path = top_collection_path(TargetKind::Zone);
let count = document
.get("finding_zones")
.and_then(Value::as_array)
.map_or(0, Vec::len);
let mut rows = Vec::new();
for index in 0..count {
let mut zone_path = zones_path.clone();
zone_path.push(Step::Index(index));
let zone = at(document, &zone_path)?;
let flags = zone_findings(document, &zone_path)?
.iter()
.filter(|entry| {
at(document, &entry.path)
.is_ok_and(|item| item.get("requires_vet_referral") == Some(&Value::Bool(true)))
})
.count();
if flags > 0 {
rows.push(vec![
Cell::from(code(Some(&js_string(zone.get("id"))))),
Cell::from(flags),
]);
}
}
Ok(if rows.is_empty() {
"Aucun renvoi vétérinaire.".to_owned()
} else {
table(&["Zone", "Renvois vétérinaires"], &rows)
})
}
fn clinical_vigilance(input: &ReviewReportInput<'_>) -> Result<String, PipelineError> {
Ok([
"Renvois vétérinaires modifiés :".to_owned(),
String::new(),
vet_flag_changes(input)?,
String::new(),
"Renvois vétérinaires de la fiche, par zone :".to_owned(),
String::new(),
vet_flags_per_zone(input.document)?,
]
.join("\n"))
}
fn citation_count(document: &Value, id: &str) -> Result<usize, PipelineError> {
let wanted = Value::from(id);
let mut count = 0;
for entry in all_findings(document)? {
let cited = at(document, &entry.path)?
.get("reference_ids")
.and_then(Value::as_array)
.is_some_and(|ids| ids.contains(&wanted));
count += usize::from(cited);
}
Ok(count)
}
/// `Boolean(value)` of a reference field.
fn truthy_text(value: Option<&Value>) -> Option<String> {
match value {
None | Some(Value::Null | Value::Bool(false)) => None,
Some(Value::String(text)) if text.is_empty() => None,
other => Some(js_string(other)),
}
}
fn bibliography(document: &Value) -> Result<String, PipelineError> {
let references = document
.get("references")
.and_then(Value::as_array)
.map_or(&[][..], Vec::as_slice);
let mut lines = Vec::new();
for (index, reference) in references.iter().enumerate() {
let links: Vec<String> = [
truthy_text(reference.get("url")).map(|url| format!("URL : {url}")),
truthy_text(reference.get("doi")).map(|doi| format!("DOI : {doi}")),
]
.into_iter()
.flatten()
.collect();
let place = if links.is_empty() {
String::new()
} else {
format!(" ({})", links.join(", "))
};
let id = js_string(reference.get("id"));
lines.push(format!(
"{}. {} {}{place}, cité par {} nœud(s).",
index + 1,
code(Some(&id)),
js_string(reference.get("citation")),
citation_count(document, &id)?
));
}
Ok(if lines.is_empty() {
"Aucune référence déclarée.".to_owned()
} else {
lines.join("\n")
})
}
fn priority_rank(priority: ChangePriority) -> u8 {
match priority {
ChangePriority::High => 0,
ChangePriority::Medium => 1,
ChangePriority::Low => 2,
}
}
/// `byPriorityThenId`: priority order, then ids by UTF-16 code units (a stable sort).
fn by_priority_then_id(a: &&ChangeSummary, b: &&ChangeSummary) -> Ordering {
priority_rank(a.priority)
.cmp(&priority_rank(b.priority))
.then_with(|| utf16_cmp(&a.id, &b.id))
}
fn professional_decisions(input: &ReviewReportInput<'_>) -> String {
let mut questions: Vec<&ChangeSummary> = input
.changes
.iter()
.filter(|change| change.question.is_some())
.collect();
questions.sort_by(by_priority_then_id);
if questions.is_empty() {
return "Aucune question ouverte.".to_owned();
}
questions
.iter()
.enumerate()
.map(|(index, change)| {
format!(
"{}. {} (priorité {}) : {} Références : {}.",
index + 1,
code(Some(&change.id)),
priority_label(change.priority),
change.question.as_deref().unwrap_or_default(),
references(&change.reference_ids)
)
})
.collect::<Vec<_>>()
.join("\n")
}
fn intro() -> String {
[
"# Rapport de revue : révision de travail",
"",
"Généré par `pnpm import:equine` à partir des changements rédigés \
(`curation/changes.json`). Ne pas modifier à la main. Rien n’est publié : la révision \
reste un brouillon jusqu’à la décision du professionnel.",
]
.join("\n")
}
/// `renderReviewReport`: the raw text, before the table alignment.
pub fn render_review_report(input: &ReviewReportInput<'_>) -> Result<String, PipelineError> {
let is = |level: ChangeLevel| move |c: &ChangeSummary| c.level == level;
let sections: Vec<(&str, String)> = vec![
("1. Qualité des données initiales", initial_quality(input)),
(
"2. Principales erreurs anatomiques et ostéopathiques",
change_list(input, |c| {
c.level == ChangeLevel::A
&& matches!(c.kind, ChangeKind::Correction | ChangeKind::Removal)
}),
),
(
"3. Corrections effectuées",
change_list(input, is(ChangeLevel::A)),
),
(
"4. Ajouts",
change_list(input, |c| c.kind == ChangeKind::Enrichment),
),
(
"5. Réorganisations du catalogue",
change_list(input, |c| c.kind == ChangeKind::Restructure),
),
(
"6. Éléments incertains",
change_list(input, is(ChangeLevel::C)),
),
("7. Traductions", translations(input)),
(
"8. Points de vigilance clinique",
clinical_vigilance(input)?,
),
("9. Bibliographie", bibliography(input.document)?),
(
"10. Décisions réservées au professionnel",
professional_decisions(input),
),
];
let mut parts = vec![intro()];
parts.extend(
sections
.into_iter()
.map(|(title, body)| format!("## {title}\n\n{body}")),
);
Ok(format!("{}\n", parts.join("\n\n")))
}
+43
View File
@@ -172,3 +172,46 @@ pub fn document_stats(doc: &Value) -> Result<DocumentStats, PipelineError> {
.count(),
})
}
fn count_rows(label: &str, counts: &Counts) -> Vec<(String, usize)> {
counts
.iter()
.map(|(key, value)| {
let count = value
.as_u64()
.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX));
(format!("{label} ({key})"), count)
})
.collect()
}
/// `statRows`: labelled rows, fixed order, French labels.
pub fn stat_rows(stats: &DocumentStats) -> Vec<(String, usize)> {
let row = |label: &str, value: usize| vec![(label.to_owned(), value)];
[
row("Vues", stats.views),
row("Dessins SVG distincts", stats.assets),
row("Annotations", stats.annotations),
count_rows("Annotations", &stats.annotations_by_kind),
count_rows("Annotations, revue", &stats.annotations_by_review_status),
row("Catégories d'annotation", stats.annotation_categories),
row("Zones de constats", stats.finding_zones),
row("Catégories de constats", stats.finding_categories),
row("Nœuds (catégories incluses)", stats.nodes),
row("Feuilles", stats.leaves),
row("Renvois vétérinaires", stats.vet_referrals),
count_rows("Nœuds, revue", &stats.nodes_by_review_status),
row("Descriptions", stats.descriptions),
row(
"Descriptions en français seulement",
stats.descriptions_fr_only,
),
row("Références bibliographiques", stats.references),
row("Nœuds cités", stats.cited_nodes),
row(
"Régions vertébrales avec plage documentée",
stats.regions_with_count_range,
),
]
.concat()
}
@@ -0,0 +1,123 @@
//! How a produced review drawing is compared with the committed xmldom file: byte for byte,
//! else as parsed trees after a declared rule. One rule exists: the R3 owner decision
//! (2026-10-15) that a trigger without a name of its own carries the opened view's name in
//! each language, where the TypeScript renderer wrote the French name twice. It is applied to
//! the committed tree (the frozen file stays as it is): on an element that opens a view, a
//! `data-anno-name-en` equal to the view's French name takes its English name, and a title
//! `FR / FR` under it reads `FR / EN`. Any other difference is reported.
use crate::anatomy::svg::tree::parse_svg;
use crate::anatomy::svg::{Element, Node};
use crate::domain::sheet::AnatomicalSheetDocument;
/// (view id, French name, English name) of every view of the produced document.
pub struct TriggerNames {
views: Vec<(String, String, String)>,
}
impl TriggerNames {
pub fn of(document: &AnatomicalSheetDocument) -> Self {
let views = document
.views
.iter()
.map(|view| {
(
view.id().to_owned(),
view.name().fr.clone(),
view.name().en.clone(),
)
})
.collect();
Self { views }
}
fn apply(&self, element: &mut Element) {
let opened = element.attr("data-anno-opens-view").map(str::to_owned);
let view = opened.and_then(|id| self.views.iter().find(|(v, _, _)| *v == id));
if let Some((_, fr, en)) = view {
if element.attr("data-anno-name-en") == Some(fr.as_str()) {
element.set_attr("data-anno-name-en", en.clone());
}
rename_titles(element, &format!("{fr} / {fr}"), &format!("{fr} / {en}"));
}
for child in &mut element.children {
if let Node::Element(child) = child {
self.apply(child);
}
}
}
}
fn rename_titles(element: &mut Element, from: &str, to: &str) {
for child in &mut element.children {
let Node::Element(child) = child else {
continue;
};
if child.local_name() == "title" {
for text in &mut child.children {
if let Node::Text(value) = text
&& value == from
{
*value = to.to_owned();
}
}
}
}
}
/// How two drawings were found equal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Match {
Bytes,
TreeAfterRule,
}
/// The first place two trees differ, as a path of element names.
fn first_difference(a: &Element, b: &Element, path: &str) -> Option<String> {
let here = format!("{path}/{}", a.qname);
if a.qname != b.qname || a.namespace != b.namespace {
return Some(format!("{here}: element {} vs {}", a.qname, b.qname));
}
if a.attrs != b.attrs {
return Some(format!("{here}: attributes differ"));
}
if a.children.len() != b.children.len() {
return Some(format!(
"{here}: {} vs {} children",
a.children.len(),
b.children.len()
));
}
a.children
.iter()
.zip(&b.children)
.enumerate()
.find_map(|(index, pair)| match pair {
(Node::Element(x), Node::Element(y)) => {
first_difference(x, y, &format!("{here}[{index}]"))
}
(Node::Text(x), Node::Text(y)) if x == y => None,
_ => Some(format!("{here}[{index}]: text or node kind differs")),
})
}
/// Compares a produced drawing with the committed one: bytes, else trees after `rule`.
pub fn compare_drawing(
produced: &str,
committed: &str,
rule: Option<&TriggerNames>,
) -> Result<Match, String> {
if produced == committed {
return Ok(Match::Bytes);
}
let Some(rule) = rule else {
return Err("bytes differ and no tree rule is declared".to_owned());
};
let produced = parse_svg(produced).map_err(|e| format!("produced: {}", e.reason()))?;
let mut committed = parse_svg(committed).map_err(|e| format!("committed: {}", e.reason()))?;
rule.apply(&mut committed);
match first_difference(&produced, &committed, "") {
None => Ok(Match::TreeAfterRule),
Some(difference) => Err(difference),
}
}