Something went wrong. Try again.
Exploring the idea of generated web rendering engine.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377//! [`crate::absolute_runner`]'s counterpart for the stacking-order seam//! (`crates/layout/src/stacking.rs`, `specs/stacking-order.md`): the first seam whose//! output is an ordering rather than a rectangle set, so it neither builds a//! `harness::dump::Dump` nor reuses `harness::compare::vote`. Ground truth is//! [`StackingCachedCase`]: per probe point, the class names `document.elementsFromPoint`//! returned front to back, kept only where all three engines agreed exactly//! (`harness::trace::vote_stacking`). A candidate passes a point when the boxes the//! engine's own layout places under that point, listed front to back in the candidate's//! paint order, name exactly the same classes in the same order; a case passes when every//! agreed point does. Admission is regression-free against the permanent regression set,//! the same gate as every geometry seam.
use std::collections::BTreeMap;use std::fs;use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};use dom::Document;use layout::boxtree::BoxTree;use layout::fragment;use layout::stacking::{StackingInputs, StackingResolver};use serde::{Deserialize, Serialize};
use crate::runner::{CandidateReport, CategoryTally, Report};
/// The harness's fixed viewport (`docs/dump-format.md`), matching every other consumer/// of a corpus.const VIEWPORT_WIDTH: f64 = 800.0;const VIEWPORT_HEIGHT: f64 = 600.0;
/// One probe point every engine agreed on: `ids` front to back, exactly as/// `docs/dump-format.md` -> "Stacking probe" describes them (each is a box's `class`).#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct AgreedPoint { pub x: f64, pub y: f64, pub ids: Vec<String>,}
/// One case of the stacking ground-truth cache (`corpus/stacking-ground-truth/`),/// [`crate::groundtruth::CachedCase`]'s counterpart for an ordering oracle.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct StackingCachedCase { pub case_id: String, pub seed: u64, pub categories: Vec<String>, pub html: String, /// The points all engines agreed on, in request order. pub points: Vec<AgreedPoint>, /// Points dropped for engine disagreement, kept as a count so the corpus's own /// agreement rate is recoverable from the cache alone. pub dropped_points: usize, pub engine_versions: BTreeMap<String, String>,}
impl StackingCachedCase { pub fn write(&self, dir: &Path) -> Result<()> { fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; let path = dir.join(format!("{}.json", self.case_id)); let json = serde_json::to_string_pretty(self)?; fs::write(&path, json).with_context(|| format!("writing {}", path.display())) }}
/// Every cached case under `dir`, sorted by id.pub fn load_all(dir: &Path) -> Result<Vec<StackingCachedCase>> { let mut cases = Vec::new(); let Ok(entries) = fs::read_dir(dir) else { return Ok(cases) }; for entry in entries { let path = entry?.path(); if path.extension().and_then(|e| e.to_str()) != Some("json") { continue; } let json = fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?; let case: StackingCachedCase = serde_json::from_str(&json).with_context(|| format!("parsing {}", path.display()))?; cases.push(case); } cases.sort_by(|a, b| a.case_id.cmp(&b.case_id)); Ok(cases)}
/// One laid-out box as the candidate ordered it: its `class` (empty for the `html`/`body`/// wrappers, which the oracle drops too) and its absolute border-box rect.#[derive(Debug, Clone, PartialEq)]pub struct OrderedBox { pub class: String, pub x: f64, pub y: f64, pub width: f64, pub height: f64,}
/// Renders `html` through the real layout path (every geometry seam at its shipped/// default -- this seam does not touch layout) and returns every box in the paint order/// `resolver` assigns, back to front.pub fn candidate_paint_order(html: &str, resolver: StackingResolver) -> Vec<OrderedBox> { let document = Document::parse(html); let tree = BoxTree::build(&document); let root = fragment::layout(&document, &tree, (VIEWPORT_WIDTH, VIEWPORT_HEIGHT)); let (inputs, nodes) = StackingInputs::from_layout(&document, &root); let outputs = resolver(&inputs); outputs .order .iter() .filter_map(|&id| { let b = inputs.boxes.get(id)?; Some(OrderedBox { class: document.nodes()[nodes[id].index()] .as_element() .and_then(|e| e.attr("class")) .unwrap_or_default() .to_string(), x: b.x, y: b.y, width: b.width, height: b.height, }) }) .collect()}
/// The classes the candidate's paint order puts under `(x, y)`, front to back --/// what `document.elementsFromPoint(x, y)` would return if the engine painted this order./// Hit-testing is by border box, the same edge rule browsers apply: the left/top edges/// are inside, the right/bottom edges are not. Boxes without a class are skipped, matching/// the oracle's own filtering.pub fn hits_front_to_back(order: &[OrderedBox], x: f64, y: f64) -> Vec<String> { order .iter() .rev() .filter(|b| !b.class.is_empty()) .filter(|b| x >= b.x && x < b.x + b.width && y >= b.y && y < b.y + b.height) .map(|b| b.class.clone()) .collect()}
/// One case's outcome for one candidate.#[derive(Debug, Clone, Copy, PartialEq)]enum Outcome { Passed, Failed, /// No point survived the engine vote -- excluded from both the numerator and the /// denominator, matching `crate::runner`'s own `Untrustworthy`. Untrustworthy,}
fn score_case(case: &StackingCachedCase, resolver: StackingResolver) -> Outcome { if case.points.is_empty() { return Outcome::Untrustworthy; } let order = candidate_paint_order(&case.html, resolver); // A candidate that drops or duplicates a box is wrong regardless of what lands under // any point. let mut seen: Vec<&str> = order.iter().map(|b| b.class.as_str()).filter(|c| !c.is_empty()).collect(); seen.sort_unstable(); if seen.windows(2).any(|w| w[0] == w[1]) { return Outcome::Failed; } let all_match = case.points.iter().all(|p| hits_front_to_back(&order, p.x, p.y) == p.ids); if all_match { Outcome::Passed } else { Outcome::Failed }}
/// The case ids `resolver` passes over `cases`, to seed and extend the permanent/// regression set.pub fn passing_case_ids(resolver: StackingResolver, cases: &[StackingCachedCase]) -> Vec<String> { cases .iter() .filter(|case| score_case(case, resolver) == Outcome::Passed) .map(|case| case.case_id.clone()) .collect()}
/// Runs every `(name, resolver)` pair over `cases`, tallying pass/fail per case and per/// category, and checking each against `regression_set` -- `crate::runner::evaluate`'s/// shape exactly, over an ordering score instead of a geometry one.pub fn evaluate( registry: &[(&str, StackingResolver)], cases: &[StackingCachedCase], regression_set: Option<&[String]>,) -> Report { let candidates = registry .iter() .map(|(name, resolver)| { let mut cases_run = 0u64; let mut cases_passed = 0u64; let mut passed_ids: Vec<String> = Vec::new(); let mut per_category: BTreeMap<String, CategoryTally> = BTreeMap::new();
for case in cases { let outcome = score_case(case, *resolver); if outcome == Outcome::Untrustworthy { continue; } cases_run += 1; let passed = outcome == Outcome::Passed; if passed { cases_passed += 1; passed_ids.push(case.case_id.clone()); } for category in &case.categories { let tally = per_category.entry(category.clone()).or_default(); tally.total += 1; if passed { tally.passed += 1; } } }
let regressed_cases: Vec<String> = regression_set .unwrap_or(&[]) .iter() .filter(|id| !passed_ids.contains(id)) .cloned() .collect();
CandidateReport { name: name.to_string(), cases_run, cases_passed, admitted: regressed_cases.is_empty(), regressed_cases, per_category, passed_case_ids: passed_ids, // See `margin_runner.rs`: only the absolute-positioning seam builds a // geometry-diff prompt from this field. failing_case_diffs: Vec::new(), } }) .collect();
Report { candidates }}
/// Entry point a generated stacking-order candidate crate's `main.rs` calls/// (`crate::candidate_crate::write_for` with `Seam::StackingOrder`), the same/// environment-variable contract `crate::runner::main` and every other seam runner use.pub fn main(registry: &[(&str, StackingResolver)]) -> Result<()> { let cache_dir = PathBuf::from( std::env::var("GENERATION_CACHE_DIR") .context("GENERATION_CACHE_DIR must name the ground-truth cache directory")?, ); let cases = load_all(&cache_dir)?; if cases.is_empty() { bail!( "no cached cases under {}; run the stacking_ground_truth_cache binary first", cache_dir.display() ); } let regression_set: Option<Vec<String>> = match std::env::var("GENERATION_REGRESSION_SET") { Ok(path) => { let json = fs::read_to_string(&path).with_context(|| format!("reading {path}"))?; Some(serde_json::from_str(&json).with_context(|| format!("parsing {path}"))?) } Err(_) => None, }; let report = evaluate(registry, &cases, regression_set.as_deref()); let json = serde_json::to_string_pretty(&report)?; if let Ok(out) = std::env::var("GENERATION_REPORT_OUT") { fs::write(&out, &json).with_context(|| format!("writing {out}"))?; } println!("{json}"); Ok(())}
#[cfg(test)]mod tests { use super::*; use layout::stacking::resolve_baseline;
const RESET: &str = "* { margin: 0; padding: 0; border: 0; box-sizing: content-box; }\nhtml, body { display: block; }\n";
fn doc(css: &str, body: &str) -> String { format!("<!doctype html><html><head><style>{RESET}{css}</style></head><body>{body}</body></html>") }
fn case(id: &str, category: &str, html: String, points: Vec<AgreedPoint>) -> StackingCachedCase { StackingCachedCase { case_id: id.to_string(), seed: 0, categories: vec![category.to_string()], html, points, dropped_points: 0, engine_versions: BTreeMap::new(), } }
fn point(x: f64, y: f64, ids: &[&str]) -> AgreedPoint { AgreedPoint { x, y, ids: ids.iter().map(|s| s.to_string()).collect() } }
/// Two absolutely positioned siblings, no z-index: tree order is paint order. fn tree_order_case() -> StackingCachedCase { let html = doc( ".b0 { width: 700px; }\ .b1 { position: absolute; left: 20px; top: 20px; width: 100px; height: 100px; }\ .b2 { position: absolute; left: 60px; top: 60px; width: 100px; height: 100px; }", "<div class=\"b0\"><div class=\"b1\"></div><div class=\"b2\"></div></div>", ); case("tree-order", "OverlappingSiblingsTreeOrder", html, vec![point(100.0, 100.0, &["b2", "b1"])]) }
/// A positioned box first in tree order, then a static sibling it must still paint above. fn positioned_over_static_case() -> StackingCachedCase { let html = doc( ".b0 { width: 700px; }\ .b1 { position: absolute; left: 40px; top: 40px; width: 100px; height: 60px; }\ .b2 { width: 200px; height: 80px; }", "<div class=\"b0\"><div class=\"b1\"></div><div class=\"b2\"></div></div>", ); case( "positioned-over-static", "PositionedOverStatic", html, vec![point(60.0, 50.0, &["b1", "b2", "b0"])], ) }
#[test] fn hit_test_lists_only_boxes_under_the_point_front_to_back() { let order = candidate_paint_order(&tree_order_case().html, resolve_baseline); let classes: Vec<&str> = order.iter().map(|b| b.class.as_str()).collect(); assert_eq!(classes, ["", "", "b0", "b1", "b2"], "html and body carry no class"); assert_eq!(hits_front_to_back(&order, 100.0, 100.0), ["b2", "b1"]); assert_eq!(hits_front_to_back(&order, 30.0, 30.0), ["b1"]); assert!(hits_front_to_back(&order, 400.0, 400.0).is_empty()); }
#[test] fn baseline_passes_tree_order_and_fails_positioned_over_static() { let cases = [tree_order_case(), positioned_over_static_case()]; let report = evaluate(&[("baseline", resolve_baseline)], &cases, None); let c = &report.candidates[0]; assert_eq!((c.cases_run, c.cases_passed), (2, 1)); assert_eq!(c.passed_case_ids, ["tree-order"]); assert_eq!(c.per_category["PositionedOverStatic"].passed, 0); assert!(c.admitted, "nothing to regress against when no regression set is given"); }
#[test] fn a_case_with_no_agreed_points_is_untrustworthy() { let mut empty = tree_order_case(); empty.points.clear(); empty.dropped_points = 1; let report = evaluate(&[("baseline", resolve_baseline)], &[empty], None); assert_eq!(report.candidates[0].cases_run, 0); }
#[test] fn regression_set_gates_admission() { let cases = [tree_order_case(), positioned_over_static_case()]; let regression = vec!["positioned-over-static".to_string()]; let report = evaluate(&[("baseline", resolve_baseline)], &cases, Some(®ression)); let c = &report.candidates[0]; assert!(!c.admitted); assert_eq!(c.regressed_cases, ["positioned-over-static"]); }
#[test] fn cache_round_trips_through_disk() { let dir = std::env::temp_dir().join(format!("stacking-cache-test-{}", std::process::id())); let case = tree_order_case(); case.write(&dir).unwrap(); let loaded = load_all(&dir).unwrap(); fs::remove_dir_all(&dir).unwrap(); assert_eq!(loaded.len(), 1); assert_eq!(loaded[0].case_id, case.case_id); assert_eq!(loaded[0].points, case.points); }}