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

+4
View File
@@ -567,3 +567,7 @@ The first M7 service integration is available as `POST /api/route-d/preview`.
It accepts blank-line-separated plain text, lays it out with the route-D page
builder, and returns the v1-compatible preview shape plus per-page hashes and
SVG. The v1 `/preview` and project APIs are unchanged and remain the default.
`POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
document and returns the same page list plus `changedPages` and
`recomputedPages`, exposing the checkpoint/page-hash diff from the core.
+3 -2
View File
@@ -262,7 +262,7 @@ M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row hei
Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits.
The crate currently has 131 unit tests plus one route-D integration test. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 213 tests (131 route-D unit, 1 route-D integration, 71 v1 integration, 5 server, 4 v1 unit, 1 doctest). v1 remains the live server path.
The crate currently has 131 unit tests plus one route-D integration test. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 214 tests (131 route-D unit, 1 route-D integration, 71 v1 integration, 6 server, 4 v1 unit, 1 doctest). v1 remains the live server path.
### M0 incremental demo
@@ -292,7 +292,8 @@ deliberately open rather than approximated:
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. all five text faces embed Liberation Serif/Mono as Type0/Identity-H with `/W` widths; ff/fi/fl/ffi/ffl ligatures come from TFM, but full NFSS family switching and italic correction are not implemented.
- **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and
math limit policies are only partially modeled.
- **M7**: first service step is `POST /api/route-d/preview`, which lays out
- **M7**: `POST /api/route-d/preview` and `/api/route-d/edit/{unit}` expose
route-D pages and edit diff; the preview path lays out
blank-line-separated plain text and returns route-D pages with SVG and page
hashes. It is not yet the editor preview: LaTeX-to-route-D semantic mapping and
edit-diff reuse inside the project preview remain open.
+25
View File
@@ -135,6 +135,31 @@ fn handle_request(
None => respond(request, 404, "text/plain; charset=utf-8", "not found"),
}
}
(&Method::Post, path) if path.starts_with("/api/route-d/edit/") => {
let unit = path["/api/route-d/edit/".len()..].parse::<usize>();
let Ok(unit) = unit else {
return respond(request, 400, "text/plain; charset=utf-8", "invalid unit");
};
let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) {
Ok(bytes) => bytes,
Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error),
};
let source = match String::from_utf8(bytes) {
Ok(source) => source,
Err(_) => {
return respond(
request,
400,
"text/plain; charset=utf-8",
"source is not valid UTF-8",
);
}
};
match route_d::edit_json(&source, unit) {
Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json),
Err(error) => respond(request, 422, "application/json; charset=utf-8", &error),
}
}
(&Method::Post, "/api/route-d/preview") => {
let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) {
Ok(bytes) => bytes,
+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 {
+27
View File
@@ -307,3 +307,30 @@ Second paragraph",
assert!(svg.contains(">H</text>"));
assert!(value["pages"][0]["hash"].as_str().unwrap().len() == 16);
}
#[test]
fn edits_route_d_preview_pages() {
let server = TestServer::start("route-d-edit");
let body = b"First paragraph
Second paragraph
Third paragraph";
let first = server.request("POST", "/api/route-d/edit/1", body, "text/plain");
assert_eq!(first.status, 200, "{}", first.text());
assert!(first.text().contains("changedPages"));
let second = server.request(
"POST",
"/api/route-d/edit/1",
b"First paragraph
Second changed paragraph
Third paragraph",
"text/plain",
);
assert_eq!(second.status, 200, "{}", second.text());
let value: Value = serde_json::from_slice(&second.body).expect("edit JSON");
assert!(value["recomputedPages"].as_u64().is_some());
assert!(value["pages"].as_array().is_some());
}