feat(anatomy): view.canvas op on the loaded sheet; drawings read once at load
This commit is contained in:
1 parent
1ec9316a73
commit
842797b440
5 files changed
+168
No files matched your search
@@ -8,6 +8,7 @@ use serde::Deserialize;
|
|||||||
|
|
||||||
use super::index::{IndexedDocument, NoMainView, SheetIndex};
|
use super::index::{IndexedDocument, NoMainView, SheetIndex};
|
||||||
use super::schema::AnatomicalSheetDocument;
|
use super::schema::AnatomicalSheetDocument;
|
||||||
|
use crate::anatomy::svg::{Element, read_svg};
|
||||||
use crate::domain::archive::SheetStatus;
|
use crate::domain::archive::SheetStatus;
|
||||||
use crate::domain::js::JsInt;
|
use crate::domain::js::JsInt;
|
||||||
use crate::domain::report::{ReportMigrationMap, SheetRef};
|
use crate::domain::report::{ReportMigrationMap, SheetRef};
|
||||||
@@ -49,6 +50,23 @@ pub struct LoadedSheet {
|
|||||||
pub asset_hashes: HashMap<String, String>,
|
pub asset_hashes: HashMap<String, String>,
|
||||||
pub migration_map: ReportMigrationMap,
|
pub migration_map: ReportMigrationMap,
|
||||||
index: SheetIndex,
|
index: SheetIndex,
|
||||||
|
/// Each asset read once at load (R3): the sanitised tree, or why it cannot be drawn. A
|
||||||
|
/// rejection only affects the views on that asset; `assets` keeps the raw texts (the
|
||||||
|
/// snapshot archives them).
|
||||||
|
drawings: HashMap<String, Drawing>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A sheet drawing ready to compose, or the closed reason it cannot be drawn: the reader's
|
||||||
|
/// rejection, or `removed …` when the allowlist would take something out of a product
|
||||||
|
/// drawing (refused, never repaired: LRN-055).
|
||||||
|
pub type Drawing = Result<Element, String>;
|
||||||
|
|
||||||
|
fn read_drawing(text: &str) -> Drawing {
|
||||||
|
match read_svg(text) {
|
||||||
|
Ok(read) if read.removed.is_empty() => Ok(read.root),
|
||||||
|
Ok(read) => Err(format!("removed {}", read.removed.join(", "))),
|
||||||
|
Err(rejection) => Err(rejection.reason().to_owned()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why a bundled sheet cannot be loaded.
|
/// Why a bundled sheet cannot be loaded.
|
||||||
@@ -78,6 +96,11 @@ impl LoadedSheet {
|
|||||||
let document = AnatomicalSheetDocument::deserialize(&data.document)?;
|
let document = AnatomicalSheetDocument::deserialize(&data.document)?;
|
||||||
let migration_map = ReportMigrationMap::deserialize(&data.migration_map)?;
|
let migration_map = ReportMigrationMap::deserialize(&data.migration_map)?;
|
||||||
let index = SheetIndex::build(&document)?;
|
let index = SheetIndex::build(&document)?;
|
||||||
|
let drawings = data
|
||||||
|
.assets
|
||||||
|
.iter()
|
||||||
|
.map(|(id, text)| (id.clone(), read_drawing(text)))
|
||||||
|
.collect();
|
||||||
let r = data.reference;
|
let r = data.reference;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
status: data.status,
|
status: data.status,
|
||||||
@@ -93,6 +116,7 @@ impl LoadedSheet {
|
|||||||
asset_hashes: data.asset_hashes,
|
asset_hashes: data.asset_hashes,
|
||||||
migration_map,
|
migration_map,
|
||||||
index,
|
index,
|
||||||
|
drawings,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,4 +127,9 @@ impl LoadedSheet {
|
|||||||
pub fn index(&self) -> &SheetIndex {
|
pub fn index(&self) -> &SheetIndex {
|
||||||
&self.index
|
&self.index
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The drawing of an asset; `None` when the bundle has no such asset.
|
||||||
|
pub fn drawing(&self, asset_id: &str) -> Option<&Drawing> {
|
||||||
|
self.drawings.get(asset_id)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,8 @@ use serde_json::Value;
|
|||||||
#[cfg(feature = "ts")]
|
#[cfg(feature = "ts")]
|
||||||
use ts_rs::TS;
|
use ts_rs::TS;
|
||||||
|
|
||||||
|
use crate::anatomy::compose::{ComposeError, asset_id_of_view, compose_canvas};
|
||||||
|
use crate::anatomy::svg::serialize::serialize;
|
||||||
use crate::domain::archive::build_sheet_snapshot;
|
use crate::domain::archive::build_sheet_snapshot;
|
||||||
use crate::domain::editor::{
|
use crate::domain::editor::{
|
||||||
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
|
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
|
||||||
@@ -215,6 +217,7 @@ pub fn on_sheet(sheet: &LoadedSheet, op: &str, input: &str) -> Option<Outcome> {
|
|||||||
"draft.restore" => draft_restore(sheet, input),
|
"draft.restore" => draft_restore(sheet, input),
|
||||||
"archive.import" => archive_import(sheet, input),
|
"archive.import" => archive_import(sheet, input),
|
||||||
"archive.snapshot" => archive_snapshot(sheet, input),
|
"archive.snapshot" => archive_snapshot(sheet, input),
|
||||||
|
"view.canvas" => view_canvas(sheet, input),
|
||||||
_ => return None,
|
_ => return None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -339,3 +342,47 @@ fn archive_snapshot(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|||||||
let input: SnapshotInput = parse_input(input)?;
|
let input: SnapshotInput = parse_input(input)?;
|
||||||
to_value(&build_sheet_snapshot(sheet, &input.report))
|
to_value(&build_sheet_snapshot(sheet, &input.report))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Anatomy (R3)
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct CanvasViewInput {
|
||||||
|
pub view_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The editor canvas of one view, as SVG text the browser parses.
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
||||||
|
pub struct CanvasView {
|
||||||
|
pub svg: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A composed view larger than this is refused (plan R3 C2: output bounded).
|
||||||
|
pub const MAX_COMPOSED_BYTES: usize = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
fn view_canvas(sheet: &LoadedSheet, input: &str) -> Outcome {
|
||||||
|
let input: CanvasViewInput = parse_input(input)?;
|
||||||
|
let document = &sheet.document;
|
||||||
|
if !document.views.iter().any(|v| v.id() == input.view_id) {
|
||||||
|
return Err(Failure::new("unknown_view", &input.view_id));
|
||||||
|
}
|
||||||
|
let asset_id = asset_id_of_view(document, &input.view_id)
|
||||||
|
.ok_or_else(|| Failure::new("no_asset", &input.view_id))?;
|
||||||
|
let drawing = match sheet.drawing(asset_id) {
|
||||||
|
None => return Err(Failure::new("no_asset", asset_id)),
|
||||||
|
Some(Err(reason)) => return Err(Failure::new("svg_rejected", reason)),
|
||||||
|
Some(Ok(drawing)) => drawing,
|
||||||
|
};
|
||||||
|
let canvas = compose_canvas(document, &input.view_id, drawing).map_err(|e| match e {
|
||||||
|
ComposeError::UnknownView => Failure::new("unknown_view", &input.view_id),
|
||||||
|
ComposeError::InvalidCharacter => Failure::new("invalid_character", &input.view_id),
|
||||||
|
})?;
|
||||||
|
let svg = serialize(&canvas);
|
||||||
|
if svg.len() > MAX_COMPOSED_BYTES {
|
||||||
|
return Err(Failure::new("svg_rejected", "too_large"));
|
||||||
|
}
|
||||||
|
to_value(&CanvasView { svg })
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
//! R3 facade: `view.canvas` on the loaded sheet. The drawing is read once at load; a view
|
||||||
|
//! answers its composed canvas, a rejected or unknown asset a closed kind for that view only.
|
||||||
|
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::svg_tree::tree_value;
|
||||||
|
use faunosteo_core::anatomy::svg::tree::parse_svg;
|
||||||
|
use faunosteo_core::domain::js::parse_json;
|
||||||
|
use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet};
|
||||||
|
use faunosteo_core::facade::call_with_sheet;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
|
||||||
|
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
|
||||||
|
|
||||||
|
fn sheet_with(horse: &str) -> LoadedSheet {
|
||||||
|
let payload = json!({
|
||||||
|
"status": "draft",
|
||||||
|
"ref": {
|
||||||
|
"sheet_id": "s", "version_id": null, "document_sha256": "0".repeat(64),
|
||||||
|
"schema_version": 2, "species_id": "equine"
|
||||||
|
},
|
||||||
|
"document": parse_json(&common::repo_file(&format!("{SEED}/document.json"))).unwrap(),
|
||||||
|
"migrationMap": parse_json(&common::repo_file(&format!("{SEED}/report-migration-map.json"))).unwrap(),
|
||||||
|
"assets": { HORSE_ID: horse }, "assetHashes": { HORSE_ID: "0".repeat(64) }
|
||||||
|
});
|
||||||
|
let data: BundledSheetData = serde_json::from_value(payload).unwrap();
|
||||||
|
LoadedSheet::from_bundle(data).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(sheet: &LoadedSheet, input: Value) -> Value {
|
||||||
|
serde_json::from_str(&call_with_sheet(sheet, "view.canvas", &input.to_string())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn golden(name: &str) -> Value {
|
||||||
|
serde_json::from_str(&common::repo_file(&format!(
|
||||||
|
"apps/app/tests/fixtures/goldens/r3/{name}"
|
||||||
|
)))
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_view_answers_the_frozen_canvas() {
|
||||||
|
let sheet = sheet_with(&common::repo_file(&format!("{SEED}/assets/horse.svg")));
|
||||||
|
for view in ["main", "head"] {
|
||||||
|
let out = call(&sheet, json!({ "viewId": view }));
|
||||||
|
assert_eq!(out["ok"], true, "{out}");
|
||||||
|
let svg = out["value"]["svg"].as_str().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
tree_value(&parse_svg(svg).unwrap()),
|
||||||
|
golden(&format!("canvas.{view}.json")),
|
||||||
|
"{view}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_kinds_for_an_unknown_view_a_rejected_or_altered_drawing_and_bad_input() {
|
||||||
|
let horse = common::repo_file(&format!("{SEED}/assets/horse.svg"));
|
||||||
|
let sheet = sheet_with(&horse);
|
||||||
|
assert_eq!(
|
||||||
|
call(&sheet, json!({ "viewId": "nope" }))["kind"],
|
||||||
|
"unknown_view"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
call(&sheet, json!({ "view": "main" }))["kind"],
|
||||||
|
"invalid_shape"
|
||||||
|
);
|
||||||
|
let deep = format!(
|
||||||
|
"<svg xmlns=\"http://www.w3.org/2000/svg\">{}</svg>",
|
||||||
|
"<g>".repeat(80) + &"</g>".repeat(80)
|
||||||
|
);
|
||||||
|
let rejected = call(&sheet_with(&deep), json!({ "viewId": "main" }));
|
||||||
|
assert_eq!(
|
||||||
|
(rejected["kind"].as_str(), rejected["detail"].as_str()),
|
||||||
|
(Some("svg_rejected"), Some("too_deep"))
|
||||||
|
);
|
||||||
|
let scripted = horse.replacen("<path", "<script>alert(1)</script><path onclick=\"x\"", 1);
|
||||||
|
let altered = call(&sheet_with(&scripted), json!({ "viewId": "head" }));
|
||||||
|
assert_eq!(altered["kind"], "svg_rejected");
|
||||||
|
assert_eq!(altered["detail"], "removed script, path@onclick");
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The editor canvas of one view, as SVG text the browser parses.
|
||||||
|
*/
|
||||||
|
export type CanvasView = { svg: string, };
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||||
|
|
||||||
|
export type CanvasViewInput = { viewId: string, };
|
||||||
Reference in new issue
Block a user