Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

EPUB: the navigation lists the headings, with a title in the book's language (#769, #770)

Gert Pellin1fc302f69524
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<CommandSpec> {
"{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<Value> {
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<String>,
/// Cover image (PNG), shown first and marked as the book's cover.
pub cover: Option<Vec<u8>>,
+ /// Title of the navigation (table of contents); from `language` when absent.
+ pub toc_title: Option<String>,
+}
+
+/// 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<String> {
/// 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("&#160;");
}
@@ -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<u8> {
+ tag.strip_prefix('h').and_then(|n| n.parse::<u8>().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::<String>().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<u8> = Vec::new();
+ for (target, label, level) in entries {
+ let item = format!("<li><a href=\"content.xhtml#{target}\">{}</a>", xml_text(label));
+ match open.last().copied() {
+ None => open.push(*level),
+ Some(top) if *level > top => {
+ out.push_str("<ol>");
+ open.push(*level);
+ }
+ Some(_) => {
+ while open.len() > 1 && open.last().is_some_and(|t| t > level) {
+ open.pop();
+ out.push_str("</li></ol>");
+ }
+ out.push_str("</li>");
+ 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("</li>");
+ if i > 0 {
+ out.push_str("</ol>");
+ }
+ }
+ 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<String, (&'a str, &'a [u8])>, Vec<(String, String)>) {
+ heading_ids: bool,
+) -> (String, BTreeMap<String, (&'a str, &'a [u8])>, Vec<(String, String, u8)>) {
let order = reading_order(doc);
let mut body = String::new();
let mut images: BTreeMap<String, (&str, &[u8])> = 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, "<section id=\"{anchor}\">\n{}</section>\n", story_html(doc, *sid));
+ let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\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!(
"<!DOCTYPE html>\n<html lang=\"{lang}\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta name=\"generator\" content=\"DesignCraft\">\n<title>{}</title>\n<style>\nbody {{ max-width: 40em; margin: 2em auto; padding: 0 1em; }}\nfigure {{ margin: 1em 0; }} figure img {{ max-width: 100%; height: auto; }}\n{}</style>\n</head>\n<body>\n{body}</body>\n</html>\n",
xml_text(&title),
@@ -686,22 +774,20 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result<Vec<u8>, 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!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\" lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/></head>\n<body>\n{body}</body>\n</html>\n",
xml_text(&title)
);
- let mut nav_items = String::new();
- for (a, label) in &toc {
- let _ = write!(nav_items, "<li><a href=\"content.xhtml#{a}\">{}</a></li>", xml_text(label));
- }
+ let mut nav_items = nav_list(&toc);
if nav_items.is_empty() {
nav_items = format!("<li><a href=\"content.xhtml\">{}</a></li>", xml_text(&title));
}
let nav = format!(
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title></head>\n<body><nav epub:type=\"toc\" id=\"toc\"><h1>Contents</h1><ol>{nav_items}</ol></nav></body>\n</html>\n",
- xml_text(&title)
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title></head>\n<body><nav epub:type=\"toc\" id=\"toc\"><h1>{}</h1><ol>{nav_items}</ol></nav></body>\n</html>\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(
"<item id=\"nav\" href=\"nav.xhtml\" media-type=\"application/xhtml+xml\" properties=\"nav\"/>\n<item id=\"css\" href=\"style.css\" media-type=\"text/css\"/>\n<item id=\"content\" href=\"content.xhtml\" media-type=\"application/xhtml+xml\"/>\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!("<a href=\"content.xhtml#{t}\">{l}</a>");
+ let want = format!(
+ "<h1>Inhoud</h1><ol><li>{}<ol><li>{}</li></ol></li><li>{}</li></ol>",
+ 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("<h1 id=\"s0-p0\" class=\"chapter\">One</h1>") && content.contains("<h2 id=\"s0-p2\""), "{content}");
+ let custom = EpubOptions { toc_title: Some("In dit boek".into()), ..Default::default() };
+ assert!(read(&d, &custom, "OEBPS/nav.xhtml").contains("<h1>In dit boek</h1>"));
+ // 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!("<h1>Contents</h1><ol><li>{}</li></ol>", 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("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/>"));
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 {