Expose route-D page-hash diffs for paragraph edits

This commit is contained in:
gloamxun committed 2026-10-20 21:18:57 +08:00
1 parent fab9a473fc
commit dbccedb579
5 files changed
+128 -29

No files matched your search

+69 -27
View File
@@ -1,22 +1,60 @@
//! Route-D preview endpoint: a small, independent TeX-style page pipeline.
//! Route-D preview endpoints: a small, independent TeX-style page pipeline.
//!
//! This is intentionally separate from the v1 `DocumentModel` preview. It
//! demonstrates checkpointed, page-hashed output from the route-D core. The
//! v1 preview remains the default and the fallback.
//! These endpoints are intentionally separate from the v1 `DocumentModel`
//! preview. They demonstrate checkpointed, page-hashed output from the route-D
//! core. The v1 preview remains the default and the fallback.
use std::cell::RefCell;
use std::fmt::Write as _;
use texrra_tex_core::{Document, Engine, ParagraphStyle, Unit};
const SCALE: i64 = 65_536;
const PAGE_HEIGHT_PT: i64 = 792;
const PAGE_WIDTH_PT: i64 = 612;
thread_local! {
static ROUTE_D_SESSION: RefCell<Option<(Document, Engine)>> = const { RefCell::new(None) };
}
/// Build a JSON preview from blank-line-separated plain-text paragraphs.
///
/// Each paragraph is a route-D unit, so `Engine` produces per-page checkpoints
/// and hashes. The response shape deliberately mirrors the useful parts of the
/// v1 preview without pretending to parse LaTeX yet.
pub fn preview_json(source: &str) -> Result<String, String> {
let paragraphs = paragraphs(source)?;
let document = build_document(&paragraphs);
let engine = Engine::layout(&document);
Ok(render_json(&engine, None))
}
/// Apply one paragraph edit to the last route-D document and report page
/// checkpoints that were reused versus rebuilt.
pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
let paragraphs = paragraphs(source)?;
if unit >= paragraphs.len() {
return Err(format!(
"unit {unit} is out of range for {} paragraphs",
paragraphs.len()
));
}
let next = build_document(&paragraphs);
ROUTE_D_SESSION.with(|slot| {
let mut slot = slot.borrow_mut();
let (_, mut engine) = match slot.take() {
Some(session) => session,
None => {
let engine = Engine::layout(&next);
(next.clone(), engine)
}
};
engine.edit(&next, unit as u64, paragraphs[unit].to_string());
let changed = engine.changed_pages().to_vec();
let recomputed = engine.recomputed_pages();
let json = render_json(&engine, Some((&changed, recomputed)));
*slot = Some((next, engine));
Ok(json)
})
}
fn paragraphs(source: &str) -> Result<Vec<&str>, String> {
let paragraphs: Vec<&str> = source
.split("\n\n")
.map(str::trim)
@@ -25,7 +63,10 @@ pub fn preview_json(source: &str) -> Result<String, String> {
if paragraphs.is_empty() {
return Err("route-D preview needs at least one paragraph".to_string());
}
Ok(paragraphs)
}
fn build_document(paragraphs: &[&str]) -> Document {
let style = ParagraphStyle {
line_width: 480 * SCALE,
left_skip: 0,
@@ -44,35 +85,36 @@ pub fn preview_json(source: &str) -> Result<String, String> {
Unit::paragraph_with_style(index as u64, (*paragraph).to_string(), style.clone())
})
.collect();
let document = Document::new(700 * SCALE, units);
let engine = Engine::layout(&document);
Document::new(700 * SCALE, units)
}
fn render_json(engine: &Engine, edit: Option<(&[usize], usize)>) -> String {
let mut json = String::new();
json.push_str("{\"status\":\"ok\",\"pageWidthMm\":215.90,\"pageHeightMm\":279.40,\"pages\":[");
let mut page_count = 0usize;
for page in engine.pages() {
for (index, page) in engine.pages().iter().enumerate() {
let mut list = page.display_list();
list.width = list.width.max(612 * SCALE);
list.width = list.width.max(PAGE_WIDTH_PT * SCALE);
list.height = list.height.max(PAGE_HEIGHT_PT * SCALE);
let svg = list.to_svg();
if page_count > 0 {
if index > 0 {
json.push(',');
}
write!(
let _ = write!(
json,
"{{\"index\":{page_count},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}",
"{{\"index\":{index},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}",
page.hash,
escape_json(&svg)
)
.map_err(|error| error.to_string())?;
page_count += 1;
escape_json(&list.to_svg())
);
}
write!(
json,
"],\"pageCount\":{page_count},\"pageHeightPt\":{PAGE_HEIGHT_PT}}}"
)
.map_err(|error| error.to_string())?;
Ok(json)
let _ = write!(json, "],\"pageCount\":{}", engine.pages().len());
if let Some((changed, recomputed)) = edit {
let _ = write!(
json,
",\"changedPages\":{:?},\"recomputedPages\":{recomputed}",
changed
);
}
json.push_str(",\"pageHeightPt\":792}");
json
}
fn escape_json(value: &str) -> String {