Reuse route-D page checkpoints in project previews

This commit is contained in:
gloamxun committed 2026-10-20 23:13:49 +08:00
1 parent fe7fd68321
commit ea69301804
5 files changed
+139 -12

No files matched your search

+1 -1
View File
@@ -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.
+7 -5
View File
@@ -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.
+1 -1
View File
@@ -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),
};
+86 -5
View File
@@ -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<Option<(Document, Engine)>> = const { RefCell::new(None) };
}
struct ProjectSession {
paragraphs: Vec<String>,
engine: Engine,
}
fn project_sessions() -> &'static Mutex<HashMap<String, ProjectSession>> {
static SESSIONS: OnceLock<Mutex<HashMap<String, ProjectSession>>> = 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<String, String> {
let paragraphs = paragraphs(latex_body(source))?;
let texts: Vec<String> = paragraphs.iter().map(|entry| entry.text.clone()).collect();
let document = build_document(&paragraphs);
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<usize> = (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<String, String> {
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.
+44
View File
@@ -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",