diff --git a/README.md b/README.md index fc2208e..0bae21d 100644 --- a/README.md +++ b/README.md @@ -568,6 +568,6 @@ It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph` builder, and returns the v1-compatible preview shape plus per-page hashes and SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures, and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page. The v1 `/preview` and project APIs are unchanged and remain the default. -Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D +Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages and a one-paragraph edit returns the changed/recomputed page set. `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. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 9e8d6bc..6917eb1 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -303,10 +303,12 @@ deliberately open rather than approximated: - **M7**: `POST /api/route-d/preview`, `/api/route-d/pdf` and `/api/route-d/edit/{unit}` expose route-D pages, PDF export and edit diff. The project preview can opt in with `POST /api/projects/{id}/preview?engine=route-d`; - `route_d::latex_preview_json` strips the preamble/body wrapper and hands the - document body to the same route-D paragraph parser. The v1 semantic pipeline - remains the default fallback. LaTeX-to-route-D semantic mapping is still a - subset, the project preview recomputes rather than reusing edit checkpoints, - and there is no editor toggle or pixel comparison yet. + `route_d::project_preview_json` strips the preamble/body wrapper and keeps a + project-scoped `(paragraphs, Engine)` session. An unchanged source returns + `changedPages: []` and `recomputedPages: 0`; a single-paragraph edit goes + through `Engine::edit` and reports the changed/recomputed pages, while + structural edits fall back to a full layout. The v1 semantic pipeline remains + the default fallback. LaTeX-to-route-D semantic mapping is still a subset, and + there is no editor toggle UI or pixel comparison yet. - `\middle` does not scale with its enclosing delimiter; math delimiters are scaled glyphs rather than TeX delimiter variants. diff --git a/src/main.rs b/src/main.rs index 9bd0168..7ef6f7e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -500,7 +500,7 @@ fn handle_project_request( Err(error) => return respond_api_error(request, 422, &error), }; if query_param(url, "engine").as_deref() == Some("route-d") { - return match route_d::latex_preview_json(&source) { + return match route_d::project_preview_json(id, &source) { Ok(json) => respond_json(request, 200, &json), Err(error) => respond_api_error(request, 422, &error), }; diff --git a/src/route_d.rs b/src/route_d.rs index f864209..7370d00 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -5,7 +5,9 @@ //! core. The v1 preview remains the default and the fallback. use std::cell::RefCell; +use std::collections::HashMap; use std::fmt::Write as _; +use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; use texrra_tex_core::math::parse_math; @@ -20,17 +22,96 @@ thread_local! { static ROUTE_D_SESSION: RefCell> = const { RefCell::new(None) }; } +struct ProjectSession { + paragraphs: Vec, + engine: Engine, +} + +fn project_sessions() -> &'static Mutex> { + static SESSIONS: OnceLock>> = OnceLock::new(); + SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn latex_body(source: &str) -> &str { + let body = source + .split_once("\\begin{document}") + .map_or(source, |(_, body)| body); + body.split("\\end{document}").next().unwrap_or(body) +} + +/// Project-scoped route-D preview. Reuses the previous engine when the +/// paragraph list is unchanged and applies exactly one paragraph edit through +/// `Engine::edit`; multi-paragraph or structural edits fall back to a full +/// layout. The v1 project preview remains the default. +pub fn project_preview_json(project_id: &str, source: &str) -> Result { + let paragraphs = paragraphs(latex_body(source))?; + let texts: Vec = paragraphs.iter().map(|entry| entry.text.clone()).collect(); + let document = build_document(¶graphs); + let mut sessions = project_sessions() + .lock() + .map_err(|_| "route-D session lock".to_string())?; + let previous = sessions.remove(project_id); + let (mut engine, changed, recomputed) = match previous { + Some(session) + if session.paragraphs.len() == texts.len() + && session + .paragraphs + .iter() + .zip(&texts) + .filter(|(a, b)| a != b) + .count() + == 0 => + { + (session.engine, Vec::new(), 0) + } + Some(mut session) + if session.paragraphs.len() == texts.len() + && session + .paragraphs + .iter() + .zip(&texts) + .filter(|(a, b)| a != b) + .count() + == 1 => + { + let index = session + .paragraphs + .iter() + .zip(&texts) + .position(|(a, b)| a != b) + .expect("one changed paragraph"); + session + .engine + .edit(&document, index as u64, texts[index].clone()); + let changed = session.engine.changed_pages().to_vec(); + let recomputed = session.engine.recomputed_pages(); + (session.engine, changed, recomputed) + } + _ => { + let engine = Engine::layout(&document); + let changed: Vec = (0..engine.pages().len()).collect(); + let recomputed = changed.len(); + (engine, changed, recomputed) + } + }; + let json = render_json(&engine, Some((&changed, recomputed))); + sessions.insert( + project_id.to_string(), + ProjectSession { + paragraphs: texts, + engine, + }, + ); + Ok(json) +} + /// Build a JSON preview from the document body of a small LaTeX file. /// /// This is the opt-in M7 bridge for v1 projects: the preamble is discarded and /// the body is handed to the same route-D paragraph parser used by /// `/api/route-d/preview`. The v1 semantic pipeline remains the default. pub fn latex_preview_json(source: &str) -> Result { - let body = source - .split_once("\\begin{document}") - .map_or(source, |(_, body)| body); - let body = body.split("\\end{document}").next().unwrap_or(body); - preview_json(body) + preview_json(latex_body(source)) } /// Build a JSON preview from blank-line-separated plain-text paragraphs. diff --git a/tests/server.rs b/tests/server.rs index 172df1b..ee446de 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -280,6 +280,50 @@ fn project_preview_can_switch_to_route_d() { .is_some_and(|pages| !pages.is_empty()) ); assert_eq!(value["pageHeightPt"], 792); + let page_count = value["pageCount"].as_u64().unwrap(); + + let again = server.request( + "POST", + "/api/projects/hello/preview?engine=route-d", + &[], + "application/json", + ); + assert_eq!(again.status, 200, "{}", again.text()); + let again: Value = serde_json::from_slice(&again.body).expect("repeat preview JSON"); + assert_eq!(again["changedPages"], serde_json::json!([])); + assert_eq!(again["recomputedPages"], 0); + assert_eq!(again["pageCount"].as_u64().unwrap(), page_count); + + let raw = server.get("/api/projects/hello/raw?path=hello.tex"); + assert_eq!(raw.status, 200); + let edited = raw + .text() + .replacen("Compatibility examples", "Compatibility examples edited", 1); + let put = server.request( + "PUT", + "/api/projects/hello/file?path=hello.tex", + edited.as_bytes(), + "text/plain; charset=utf-8", + ); + assert_eq!(put.status, 200, "{}", put.text()); + let incremental = server.request( + "POST", + "/api/projects/hello/preview?engine=route-d", + &[], + "application/json", + ); + assert_eq!(incremental.status, 200, "{}", incremental.text()); + let incremental: Value = + serde_json::from_slice(&incremental.body).expect("incremental preview JSON"); + assert!( + incremental["changedPages"] + .as_array() + .is_some_and(|pages| !pages.is_empty()) + ); + assert!( + incremental["recomputedPages"].as_u64().unwrap() + <= incremental["pageCount"].as_u64().unwrap() + ); let v1 = server.request( "POST",