From 1fc302f69524463e0a3963796fef69d39eabec60 Mon Sep 17 00:00:00 2001 From: Gert Pellin Date: Tue, 13 Oct 2026 16:26:32 +0200 Subject: [PATCH] EPUB: the navigation lists the headings, with a title in the book's language (#769, #770) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nav.xhtml had one entry per placed story, labelled with its first paragraph (body text too), and always the title "Contents". - Headings (h1-h6) get an id in the EPUB, and the navigation lists the h1-h3 headings of the stories in reading order, nested by level and linked to them. A document without headings keeps one entry per story (its first paragraph). - The navigation's title follows the language (Inhoud, Inhalt, Table des matières, Índice, Indice, 目次, 目录; Contents otherwise), and file.exportEpub takes tocTitle to set it. Fixes #769 Fixes #770 --- crates/engine/src/cmd/export.rs | 3 +- crates/epub/src/lib.rs | 183 ++++++++++++++++++++++--- crates/epub/tests/export_tag_styles.rs | 15 +- 3 files changed, 178 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs index 8e0f04d69..c466a9701 100644 --- a/crates/engine/src/cmd/export.rs +++ b/crates/engine/src/cmd/export.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec { "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), flatten?: high|medium|low|ppi (Transparency Flattener: spreads with transparency are rasterised), spreads?: bool, fullScreen?: bool, bookmarksPanel?: bool, pageLayout?: single|continuous|twoUp|twoUpCover|twoUpContinuous, view?: fitPage|fitWidth|actual, advanceSeconds?: number (interactive PDF), bleed?: bool (document bleed), marks?: bool | {crop?, bleed?, pageInfo?, weight?, offset?}, standard?: \"none\"|\"x4\"|\"a2b\", compressImages?: bool, tagged?: bool (structure tree: stories as paragraphs, figures with alt text), media?: bool (interactive: embed placed video and sound), title?, author?} → {path, bytes, pages, warnings} (no path: {base64, …})", has_doc, export_pdf), cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None, - "{path?, title?, author?, language?: \"en\", cover?: bool (the first page as the cover image), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes} (no path: {base64, bytes})", + "{path?, title?, author?, language?: \"en\", tocTitle?: str (the table of contents' title; from the language by default), cover?: bool (the first page as the cover image), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes} (no path: {base64, bytes})", has_doc, export_epub), cmd!(noundo "file.exportFixedEpub", "Export EPUB (Fixed Layout)…", ["File"], None, "{path?, title?, author?, language?} — pre-paginated EPUB → {path, bytes} (no path: {base64, bytes})", @@ -137,6 +137,7 @@ fn export_epub(s: &mut Session, p: &Value) -> Result { language: p.get("language").and_then(Value::as_str).unwrap_or("en").to_string(), identifier: None, cover, + toc_title: p.get("tocTitle").and_then(Value::as_str).map(str::to_string), }; if fixed { let d = &st.doc; diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs index 77b509d0b..57e7c9d88 100644 --- a/crates/epub/src/lib.rs +++ b/crates/epub/src/lib.rs @@ -22,6 +22,24 @@ pub struct EpubOptions { pub identifier: Option, /// Cover image (PNG), shown first and marked as the book's cover. pub cover: Option>, + /// Title of the navigation (table of contents); from `language` when absent. + pub toc_title: Option, +} + +/// The table of contents' title in `language` (a BCP 47 tag or a language name's code), English +/// for languages without one here. +pub fn contents_title(language: &str) -> &'static str { + let code = language.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase(); + match code.as_str() { + "nl" => "Inhoud", + "de" => "Inhalt", + "fr" => "Table des matières", + "es" | "pt" => "Índice", + "it" => "Indice", + "ja" => "目次", + "zh" => "目录", + _ => "Contents", + } } /// A page of a fixed-layout EPUB: its image (PNG), size in points and text (kept for search, @@ -100,7 +118,7 @@ pub fn export_fixed_epub(doc: &Document, pages: &[FixedPage], opts: &EpubOptions impl Default for EpubOptions { fn default() -> Self { - EpubOptions { title: None, author: None, language: "en".into(), identifier: None, cover: None } + EpubOptions { title: None, author: None, language: "en".into(), identifier: None, cover: None, toc_title: None } } } @@ -427,6 +445,12 @@ fn class_selector(tag: &str, class: &str) -> Option { /// One story as XHTML paragraphs. pub fn story_html(doc: &Document, sid: StoryId) -> String { + story_html_in(doc, sid, None) +} + +/// [`story_html`] with an `id` on every heading (`h1`–`h6`): `{prefix}-p{paragraph index}`, the +/// targets of the table of contents. +fn story_html_in(doc: &Document, sid: StoryId, ids: Option<&str>) -> String { let Some(st) = doc.story(sid) else { return String::new() }; let (pc, cc) = (para_classes(&doc.styles), char_classes(&doc.styles)); let mut out = String::new(); @@ -436,7 +460,11 @@ pub fn story_html(doc: &Document, sid: StoryId) -> String { let (tag, class) = export_mapping(&doc.styles, &pf.style, false, &pc); let text_empty = st.text[r.clone()].trim().is_empty(); let rtl = doc.styles.resolve_para(pf).0.direction == designcraft_doc::TextDirection::RightToLeft; - let _ = write!(out, "<{tag} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" }); + let id = match ids { + Some(prefix) if heading_level(tag).is_some() => format!(" id=\"{prefix}-p{pi}\""), + _ => String::new(), + }; + let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" }); if text_empty { out.push_str(" "); } @@ -482,6 +510,73 @@ pub fn story_html(doc: &Document, sid: StoryId) -> String { out } +/// The level of a heading element (`h1` → 1 … `h6` → 6). +fn heading_level(tag: &str) -> Option { + tag.strip_prefix('h').and_then(|n| n.parse::().ok()).filter(|n| (1..=6).contains(n)) +} + +/// Table of contents entries (target, label, level): the `h1`–`h3` paragraphs of the stories in +/// reading order, or, in a document without headings, each story's first paragraph (level 1). +fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, String, u8)> { + let pc = para_classes(&doc.styles); + let label = |t: &str| -> String { t.chars().filter(|c| !('\u{E000}'..='\u{E0FF}').contains(c)).take(80).collect::().trim().to_string() }; + let mut headings = Vec::new(); + let mut firsts = Vec::new(); + for (k, b) in order.iter().enumerate() { + let Block::Story(sid) = b else { continue }; + let Some(st) = doc.story(*sid) else { continue }; + let first = label(st.text.split('\n').next().unwrap_or("")); + if !first.is_empty() { + firsts.push((format!("s{k}"), first, 1)); + } + for (pi, r) in st.para_ranges().iter().enumerate() { + let Some(pf) = st.paras.get(pi) else { continue }; + let (tag, _) = export_mapping(&doc.styles, &pf.style, false, &pc); + let Some(level) = heading_level(tag).filter(|l| *l <= 3) else { continue }; + let text = label(st.text.get(r.clone()).unwrap_or("")); + if !text.is_empty() { + headings.push((format!("s{k}-p{pi}"), text, level)); + } + } + } + if headings.is_empty() { firsts } else { headings } +} + +/// The table of contents as nested `li`/`ol` items (the content of the navigation's outer +/// `ol`): a deeper level goes into the previous item, skipped levels count as one. +fn nav_list(entries: &[(String, String, u8)]) -> String { + let mut out = String::new(); + let mut open: Vec = Vec::new(); + for (target, label, level) in entries { + let item = format!("
  • {}", xml_text(label)); + match open.last().copied() { + None => open.push(*level), + Some(top) if *level > top => { + out.push_str("
      "); + open.push(*level); + } + Some(_) => { + while open.len() > 1 && open.last().is_some_and(|t| t > level) { + open.pop(); + out.push_str("
    "); + } + out.push_str("
  • "); + if let Some(t) = open.last_mut() { + *t = (*t).min(*level); + } + } + } + out.push_str(&item); + } + for i in (0..open.len()).rev() { + out.push_str(""); + if i > 0 { + out.push_str(""); + } + } + out +} + /// Reading order of document content: (page, y, x) of each story's first frame and of graphics. #[derive(Debug, Clone, PartialEq)] pub enum Block { @@ -570,24 +665,17 @@ fn ext(mime: &str) -> &'static str { fn body_html<'a>( doc: &'a Document, img_src: &dyn Fn(&str, &str, &[u8]) -> String, -) -> (String, BTreeMap, Vec<(String, String)>) { + heading_ids: bool, +) -> (String, BTreeMap, Vec<(String, String, u8)>) { let order = reading_order(doc); let mut body = String::new(); let mut images: BTreeMap = BTreeMap::new(); - let mut toc: Vec<(String, String)> = Vec::new(); + let toc = toc_entries(doc, &order); for (k, b) in order.iter().enumerate() { match b { Block::Story(sid) => { let anchor = format!("s{k}"); - // First paragraph text as the TOC label. - if let Some(st) = doc.story(*sid) { - let first: String = - st.text.split('\n').next().unwrap_or("").chars().filter(|c| !('\u{E000}'..='\u{E0FF}').contains(c)).take(60).collect(); - if !first.trim().is_empty() { - toc.push((anchor.clone(), first)); - } - } - let _ = write!(body, "
    \n{}
    \n", story_html(doc, *sid)); + let _ = write!(body, "
    \n{}
    \n", story_html_in(doc, *sid, heading_ids.then_some(anchor.as_str()))); } Block::Image(iid) => { let Some(Content::Graphic(g)) = doc.item(*iid).map(|i| &i.content) else { continue }; @@ -660,7 +748,7 @@ pub fn export_html(doc: &Document, opts: &HtmlOptions) -> String { let title = opts.title.clone().unwrap_or_else(|| doc.title.clone()); let language = opts.language.as_deref().unwrap_or("en"); let lang = language_tag(language); - let (body, _, _) = body_html(doc, &|_, mime, data| format!("data:{mime};base64,{}", base64(data))); + let (body, _, _) = body_html(doc, &|_, mime, data| format!("data:{mime};base64,{}", base64(data)), false); format!( "\n\n\n\n\n\n{}\n\n\n\n{body}\n\n", xml_text(&title), @@ -686,22 +774,20 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr let zerr = |e: zip::result::ZipError| EpubError(e.to_string()); let title = opts.title.clone().unwrap_or_else(|| doc.title.clone()); let id = opts.identifier.clone().unwrap_or_else(|| format!("urn:designcraft:{}", slug(&title))); - let (body, images, toc) = body_html(doc, &|name, _, _| name.to_string()); + let (body, images, toc) = body_html(doc, &|name, _, _| name.to_string(), true); let lang = language_tag(&opts.language); let chapter = format!( "\n\n\n{}\n\n{body}\n\n", xml_text(&title) ); - let mut nav_items = String::new(); - for (a, label) in &toc { - let _ = write!(nav_items, "
  • {}
  • ", xml_text(label)); - } + let mut nav_items = nav_list(&toc); if nav_items.is_empty() { nav_items = format!("
  • {}
  • ", xml_text(&title)); } let nav = format!( - "\n\n\n{}\n\n\n", - xml_text(&title) + "\n\n\n{}\n\n\n", + xml_text(&title), + xml_text(opts.toc_title.as_deref().filter(|t| !t.trim().is_empty()).unwrap_or(contents_title(&opts.language))) ); let mut manifest = String::from( "\n\n\n", @@ -788,6 +874,60 @@ mod tests { assert!(z.by_name("OEBPS/nav.xhtml").is_ok()); } + /// #769, #770: the navigation lists the h1–h3 headings (nested by level) and links to them, + /// with its title in the book's language; without headings, each story's first paragraph. + #[test] + fn navigation_follows_the_headings() { + let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() }); + let lid = d.default_layer(); + for (name, tag) in [("Chapter", "h1"), ("Section", "h2")] { + d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { + name: name.into(), + based_on: None, + next_style: None, + para: Default::default(), + chars: CharAttrs::default(), + shortcut: String::new(), + }); + d.styles_mut().export_tags.insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new() }); + } + let text = "One\nBody\nOne point one\nMore\nTwo\nText"; + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap(); + let st = d.story_mut(sid).unwrap(); + for (i, style) in [(0, "Chapter"), (2, "Section"), (4, "Chapter")] { + st.paras[i].style = style.into(); + } + // A story that starts with body text adds nothing to the table of contents. + d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 400.0, 300.0, 500.0), lid, "Text after the figure.", ParaFormat::default()).unwrap(); + let read = |d: &Document, opts: &EpubOptions, path: &str| { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap(); + let mut s = String::new(); + z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); + s + }; + let nl = EpubOptions { language: "nl".into(), ..Default::default() }; + let nav = read(&d, &nl, "OEBPS/nav.xhtml"); + let link = |t: &str, l: &str| format!("{l}"); + let want = format!( + "

    Inhoud

    1. {}
      1. {}
    2. {}
    ", + link("s0-p0", "One"), + link("s0-p2", "One point one"), + link("s0-p4", "Two") + ); + assert!(nav.contains(&want), "{nav}"); + assert!(!nav.contains("Text after the figure"), "{nav}"); + let content = read(&d, &nl, "OEBPS/content.xhtml"); + assert!(content.contains("

    One

    ") && content.contains("

    In dit boek

    ")); + // Without headings: one entry per story, its first paragraph. + let mut plain = Document::new(&NewDocument::default()); + let lid = plain.default_layer(); + plain.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Opening\nrest", ParaFormat::default()).unwrap(); + let nav = read(&plain, &EpubOptions::default(), "OEBPS/nav.xhtml"); + assert!(nav.contains(&format!("

    Contents

    1. {}
    ", link("s0", "Opening"))), "{nav}"); + } + #[test] fn styles_whose_names_slug_alike_keep_their_own_classes() { let mut d = Document::new(&NewDocument::default()); @@ -902,6 +1042,7 @@ mod tests { language: "English (US)".into(), identifier: Some("notes&edition".into()), cover: None, + toc_title: None, }, ) .unwrap(); diff --git a/crates/epub/tests/export_tag_styles.rs b/crates/epub/tests/export_tag_styles.rs index 47485b532..b25d31c36 100644 --- a/crates/epub/tests/export_tag_styles.rs +++ b/crates/epub/tests/export_tag_styles.rs @@ -55,7 +55,20 @@ fn package(doc: &Document) -> (String, String) { let opf = read("OEBPS/content.opf"); assert!(xhtml.contains("")); assert!(opf.contains("href=\"style.css\" media-type=\"text/css\"")); - (xhtml, css) + (without_heading_ids(&xhtml), css) +} + +/// The markup without the `id`s headings get as table-of-contents targets (` id="s0-p0"`). +fn without_heading_ids(html: &str) -> String { + let mut out = String::with_capacity(html.len()); + let mut rest = html; + while let Some(i) = rest.find(" id=\"s") { + out.push_str(&rest[..i]); + let after = &rest[i + 6..]; + rest = after.find('"').map_or("", |j| &after[j + 1..]); + } + out.push_str(rest); + out } fn rule<'a>(css: &'a str, selector: &str) -> &'a str {