DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
TOC-2: generate and refresh nested PDF bookmarks
moppeeer924d9c1b7348
diff --git a/ROADMAP.md b/ROADMAP.mdindex 9bd0274ef..71aa1b62b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -346,6 +346,8 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m## Progress log+- **2026-10-18** · Table of Contents gains Create PDF Bookmarks: included headings become nested page destinations, regenerated on update without replacing manual bookmarks. The setting survives native and IDML files. No readiness percentage change.+Newest first.- **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change.diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 1bf834ae0..00c679ef9 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -793,6 +793,9 @@ pub struct Toc {/// Paragraph style of the title; `None` is the generated "TOC Title" style.#[serde(default, skip_serializing_if = "Option::is_none")]pub title_style: Option<String>,+ /// Generate a nested PDF outline from the included paragraphs when the TOC is updated.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub create_bookmarks: bool,}#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]@@ -803,6 +806,9 @@ pub struct Bookmark {pub page: usize,#[serde(default, skip_serializing_if = "Vec::is_empty")]pub children: Vec<Bookmark>,+ /// Owned by the document's generated TOC, so updating it preserves manual bookmarks.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub generated_by_toc: bool,}impl Document {diff --git a/crates/engine/src/cmd/interactive.rs b/crates/engine/src/cmd/interactive.rsindex 32562737c..2d918a01f 100644--- a/crates/engine/src/cmd/interactive.rs+++ b/crates/engine/src/cmd/interactive.rs@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {let name = str_param(p, "name").map(str::to_string);s.edit(|d, _| {let name = name.clone().unwrap_or_else(|| format!("Bookmark {}", d.bookmarks.len() + 1));- d.bookmarks.push(Bookmark { name, page, children: vec![] });+ d.bookmarks.push(Bookmark { name, page, children: vec![], generated_by_toc: false });Ok(json!({"index": d.bookmarks.len() - 1}))})}),diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rsindex d1bd06ad0..642992e76 100644--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@ -2987,6 +2987,7 @@ mod delete_tests {entries: vec![TocEntry { entry_style: Some("Table Body".into()), ..TocEntry::new("Table Body", 1) }],page_numbers: false,title_style: Some("Table Body".into()),+ create_bookmarks: false,});Ok(())})diff --git a/crates/engine/src/cmd/toc.rs b/crates/engine/src/cmd/toc.rsindex 23f5847a4..0515df478 100644--- a/crates/engine/src/cmd/toc.rs+++ b/crates/engine/src/cmd/toc.rs@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {"Table of Contents…",["Layout"],None,- "{entries: [{style, level?: 1 (1-9), entryStyle?: paragraph style of its entries (default \"TOC Level n\"), pageNumber?: \"after\"|\"before\"|\"none\", separator?: text between entry and number (default a tab), pageNumberStyle?: character style of the page number, separatorStyle?: character style of the separator, sort?: bool (Sort Entries in Alphabetical Order: among their siblings, each with the entries under it)}] | styles: [names] (levels 1, 2, …), title?: \"Contents\", titleStyle?: paragraph style of the title (default \"TOC Title\"), pageNumbers?: true, replace?: true (regenerate the existing table of contents in place; false makes a new frame), page?: 1-based page for a new frame (its margins), rect?: [x0,y0,x1,y1] (spread coords)} → {story, entries}",+ "{entries: [{style, level?: 1 (1-9), entryStyle?: paragraph style of its entries (default \"TOC Level n\"), pageNumber?: \"after\"|\"before\"|\"none\", separator?: text between entry and number (default a tab), pageNumberStyle?: character style of the page number, separatorStyle?: character style of the separator, sort?: bool (Sort Entries in Alphabetical Order: among their siblings, each with the entries under it)}] | styles: [names] (levels 1, 2, …), title?: \"Contents\", titleStyle?: paragraph style of the title (default \"TOC Title\"), pageNumbers?: true, createBookmarks?: bool (generate PDF bookmarks; keeps the existing setting when omitted), replace?: true (regenerate the existing table of contents in place; false makes a new frame), page?: 1-based page for a new frame (its margins), rect?: [x0,y0,x1,y1] (spread coords)} → {story, entries}",has_doc,generate),@@ -302,9 +302,27 @@ fn fill(d: &mut Document, toc: &Toc, width: Option<f64>) -> Result<usize> {st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() });}}+ d.bookmarks.retain(|b| !b.generated_by_toc);+ if toc.create_bookmarks {+ d.bookmarks.extend(bookmarks(&found));+ }Ok(found.len())}+/// Levels are validated to 1–9. Recursion follows strictly increasing levels, including when+/// a document skips a level; each destination is the physical page, not its section label.+fn bookmarks(found: &[Found]) -> Vec<designcraft_doc::Bookmark> {+ fn children(iter: &mut std::iter::Peekable<std::slice::Iter<'_, Found>>, parent: u8) -> Vec<designcraft_doc::Bookmark> {+ let mut out = Vec::new();+ while iter.peek().is_some_and(|f| f.level > parent) {+ let Some(f) = iter.next() else { break };+ out.push(designcraft_doc::Bookmark { name: f.text.clone(), page: f.key.0, children: children(iter, f.level), generated_by_toc: true });+ }+ out+ }+ children(&mut found.iter().peekable(), 0)+}+fn generate(s: &mut Session, p: &Value) -> Result<Value> {let entries = entries_param(p)?;if entries.is_empty() {@@ -320,6 +338,10 @@ fn generate(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad("toc.generate", format!("style names are at most {MAX_NAME} characters")));}let page_numbers = p.get("pageNumbers").and_then(Value::as_bool).unwrap_or(true);+ let create_bookmarks = match p.get("createBookmarks") {+ Some(v) => v.as_bool().ok_or_else(|| bad("toc.generate", "createBookmarks must be a boolean"))?,+ None => s.doc()?.doc.toc.as_ref().is_some_and(|t| t.create_bookmarks),+ };let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(true);let rect = super::rect_param(p, "rect");if rect.is_some_and(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) {@@ -345,7 +367,7 @@ fn generate(s: &mut Session, p: &Value) -> Result<Value> {(sid, w)}};- let toc = Toc { story, title: title.clone(), entries: entries.clone(), page_numbers, title_style: title_style.clone() };+ let toc = Toc { story, title: title.clone(), entries: entries.clone(), page_numbers, title_style: title_style.clone(), create_bookmarks };let n = fill(d, &toc, width)?;d.toc = Some(toc);Ok(json!({"story": story.0, "entries": n}))@@ -623,6 +645,45 @@ mod tests {assert!(toc_runs(&s).iter().any(|(t, st)| t == "1" && st == "Folio"), "{:?}", toc_runs(&s));}+ #[test]+ fn toc_bookmarks_refresh_nested_page_destinations_and_preserve_manual_bookmarks() {+ let (mut s, page) = doc_with(&[("First", "Head"), ("Child", "Sub"), ("Last", "Head")]);+ s.execute("layout.section", &json!({"page": 1, "style": "lowerRoman", "startNumber": 4})).unwrap();+ s.execute("bookmark.add", &json!({"name": "Manual", "page": page})).unwrap();+ let p = json!({"page": page, "createBookmarks": true, "entries": [+ {"style": "Head", "level": 1}, {"style": "Sub", "level": 3}+ ]});+ s.execute("toc.generate", &p).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.bookmarks.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Manual", "First", "Last"]);+ assert_eq!(d.bookmarks[1].page, 0, "physical page, although its label is iv");+ assert_eq!(d.bookmarks[1].children[0].name, "Child");+ assert!(d.bookmarks[1].children[0].generated_by_toc);+ let sid = d.stories.iter().find(|(_, st)| st.text.starts_with("First")).map(|(sid, _)| *sid).unwrap();+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap();+ s.execute("text.insert", &json!({"text": "Changed"})).unwrap();+ assert_eq!(s.doc().unwrap().doc.bookmarks[1].name, "First", "refresh is explicit");+ s.execute("toc.update", &json!({})).unwrap();+ let refreshed = s.doc().unwrap().doc.bookmarks.clone();+ assert_eq!(refreshed[1].name, "Changed");+ s.execute("toc.update", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.bookmarks, refreshed, "updates do not duplicate bookmarks");+ // Native storage retains both the option and ownership; old bookmarks default to manual.+ let stored = serde_json::to_value(&s.doc().unwrap().doc).unwrap();+ let back: Document = serde_json::from_value(stored).unwrap();+ assert!(back.toc.as_ref().unwrap().create_bookmarks);+ assert_eq!(back.bookmarks, refreshed);+ let old: designcraft_doc::Bookmark = serde_json::from_value(json!({"name": "Old", "page": 0})).unwrap();+ assert!(!old.generated_by_toc);+ let mut disabled = p;+ disabled["createBookmarks"] = json!(false);+ s.execute("toc.generate", &disabled).unwrap();+ assert_eq!(s.doc().unwrap().doc.bookmarks.len(), 1);+ assert_eq!(s.doc().unwrap().doc.bookmarks[0].name, "Manual");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.bookmarks, refreshed);+ }+#[test]fn toc_entry_options_round_trip_through_the_native_format() {let mut e = TocEntry::new("Head", 2);diff --git a/crates/engine/src/tests_idml.rs b/crates/engine/src/tests_idml.rsindex 0701052d0..7afb2acd5 100644--- a/crates/engine/src/tests_idml.rs+++ b/crates/engine/src/tests_idml.rs@@ -509,7 +509,7 @@ fn table_of_contents_definition_round_trips_through_idml_and_updates() {let basic = designcraft_doc::story::BASIC_PARAGRAPH;s.execute("toc.generate",- &json!({"page": page, "title": "Inside", "titleStyle": basic, "entries": [+ &json!({"page": page, "title": "Inside", "titleStyle": basic, "createBookmarks": true, "entries": [{"style": "Cover Title", "level": 1, "pageNumber": "before", "separator": " ^ "},{"style": "Headline", "level": 2, "entryStyle": basic, "pageNumber": "none"},]}),@@ -524,6 +524,7 @@ fn table_of_contents_definition_round_trips_through_idml_and_updates() {let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();s.execute("file.openIdml", &json!({"base64": b64, "name": "toc.idml"})).unwrap();let after = s.doc().unwrap().doc.toc.clone().expect("the TOC definition is imported");+ assert!(after.create_bookmarks);assert_eq!((&after.title, &after.title_style, &after.entries), (&before.title, &before.title_style, &before.entries));assert_eq!(toc_text(&s), text);s.execute("toc.update", &json!({})).unwrap();diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex a773ec9e5..180f25305 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -1111,7 +1111,7 @@ impl<'a> Ex<'a> {.attr("RunIn", "false").attr("IncludeHidden", "false").attr("IncludeBookDocuments", "false")- .attr("CreatePdfBookmarks", "false");+ .attr("CreateBookmarks", if toc.create_bookmarks { "true" } else { "false" });for e in &toc.entries {let format = e.entry_style.clone().unwrap_or_else(|| format!("TOC Level {}", e.level));let position = match e.page_number {diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 9a8985348..92e6b250b 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -1519,7 +1519,8 @@ impl<'r> Importer<'r> {}let title: String = ts.get("Title").unwrap_or("").chars().filter(|c| !matches!(c, '\n' | '\r' | '\u{2029}')).take(1024).collect();let title_style = known(ts.get("TitleStyle")).filter(|n| n != "TOC Title");- Some(designcraft_doc::Toc { story, title, entries, page_numbers: true, title_style })+ let create_bookmarks = ts.get("CreateBookmarks").or_else(|| ts.get("CreatePdfBookmarks")) == Some("true");+ Some(designcraft_doc::Toc { story, title, entries, page_numbers: true, title_style, create_bookmarks })}fn para_style_ref(&self, r: &str) -> String {diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 358416a4b..2a5cd7b24 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -6261,6 +6261,7 @@ pub fn open_toc(app: &mut DesignApp) {"charStyles": char_styles,"hasToc": toc.is_some(),"replace": toc.is_some(),+ "createBookmarks": toc.is_none_or(|t| t.create_bookmarks),});app.ui.dialog = Some(Dialog::new(TOC, fields));}@@ -6289,7 +6290,7 @@ fn toc_params(app: &DesignApp, d: &Dialog) -> Value {e}).collect();- let mut p = json!({"title": d.s("title"), "entries": entries, "replace": d.b("replace")});+ let mut p = json!({"title": d.s("title"), "entries": entries, "replace": d.b("replace"), "createBookmarks": d.b("createBookmarks")});let title_style = d.s("titleStyle");if !title_style.is_empty() {p["titleStyle"] = json!(title_style);@@ -6427,6 +6428,7 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {}ui.add_space(8.0);crate::rtl::label(ui, egui::RichText::new(tr("Options")).font(semibold(12.0)));+ check(ui, d, "createBookmarks", &tr("Create PDF Bookmarks"));let has_toc = d.b("hasToc");ui.add_enabled_ui(has_toc, |ui| check(ui, d, "replace", &tr("Replace Existing Table of Contents")));if let Some(st) = d.fields.get("status").and_then(Value::as_str) {@@ -7957,6 +7959,35 @@ mod tests {assert_eq!(opts(&app), before);}+ #[test]+ fn toc_bookmarks_checkbox_sets_and_reopens_the_persisted_option() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ open_toc(&mut app);+ assert!(app.ui.dialog.as_ref().unwrap().b("createBookmarks"));+ app.ui.dialog.as_mut().unwrap().fields.insert("included".into(), json!([{"style": "Headline", "level": 1}]));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Create PDF Bookmarks");+ confirm(&mut app).unwrap();+ assert!(app.session.doc().unwrap().doc.toc.as_ref().unwrap().create_bookmarks);+ assert!(!app.session.doc().unwrap().doc.bookmarks.is_empty());+ open_toc(&mut app);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Create PDF Bookmarks").center());+ confirm(&mut app).unwrap();+ assert!(app.session.doc().unwrap().doc.bookmarks.is_empty());+ open_toc(&mut app);+ assert!(!app.ui.dialog.as_ref().unwrap().b("createBookmarks"));+ }+#[test]fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() {let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --git a/docs/agents.md b/docs/agents.mdindex ed0d3bbd8..2358235ec 100644--- a/docs/agents.md+++ b/docs/agents.md@@ -54,6 +54,14 @@ same references, and MCP's `batch` tool takes `commands` or `script` text with t`.epub`, `.html`, and `.rtf` or `.txt` (the story being edited or of the selected frame). A name with no extensionis a PNG of the page; another extension is an error, and nothing runs.+## Table of contents bookmarks++`toc.generate` accepts `createBookmarks: true` to generate page-level PDF bookmarks from the+included paragraph styles and their levels. `toc.update` refreshes their titles, hierarchy and+destinations. Manual bookmarks stay intact; disabling the option removes only the generated+bookmarks. Omitting the parameter keeps the existing TOC setting (false for a new command-created+TOC). The Table of Contents dialog exposes Create PDF Bookmarks and defaults it on for a new TOC.+## Color themes`color.extractTheme {id?}` previews up to five RGB colours from a placed raster image (or the selected image).