From b0c364ee6001cba6e36e7bce572d7d861a402131 Mon Sep 17 00:00:00 2001 From: Gert Pellin Date: Tue, 13 Oct 2026 16:56:17 +0200 Subject: [PATCH] EPUB: one content file per chapter, split before each h1 (#768) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The whole book was one content.xhtml, which is slow on e-readers and loses chapter starts. The body is now split before each h1 into content.xhtml, content2.xhtml, …: a section a split goes through is closed and reopened, and a story that opens with its h1 starts in the new file with its id. The manifest and spine list the files in order, and the navigation links each heading to the file it is in. HTML export stays one page. Fixes #768 --- crates/epub/src/lib.rs | 167 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 152 insertions(+), 15 deletions(-) diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs index 57e7c9d88..3f6dd820d 100644 --- a/crates/epub/src/lib.rs +++ b/crates/epub/src/lib.rs @@ -464,6 +464,9 @@ fn story_html_in(doc: &Document, sid: StoryId, ids: Option<&str>) -> String { Some(prefix) if heading_level(tag).is_some() => format!(" id=\"{prefix}-p{pi}\""), _ => String::new(), }; + if ids.is_some() && heading_level(tag) == Some(1) { + out.push_str(CHAPTER_MARK); + } let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" }); if text_empty { out.push_str(" "); @@ -510,6 +513,50 @@ fn story_html_in(doc: &Document, sid: StoryId, ids: Option<&str>) -> String { out } +/// Where the EPUB body splits into chapter files: before each `h1`. +const CHAPTER_MARK: &str = ""; + +/// The body split at its [`CHAPTER_MARK`]s into chapter bodies, each with its sections closed +/// and the one a split goes through reopened in the next; a part with nothing but the start of a +/// section (a story that opens with its `h1`) moves that start into the next part. +fn split_chapters(body: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut carry: Option = None; + for piece in body.split(CHAPTER_MARK) { + let mut part = carry.take().unwrap_or_default(); + part.push_str(piece); + if let Some(open) = part.rfind("")) { + let tag_end = part[open..].find('>').map_or(part.len(), |e| open + e + 1); + if part[tag_end..].trim().is_empty() { + carry = Some(part[open..].to_string()); + part.truncate(open); + } else { + part.push_str("\n"); + carry = Some("
\n".to_string()); + } + } + if !part.trim().is_empty() { + out.push(part); + } + } + if let Some(rest) = carry.filter(|c| !c.trim().is_empty()) + && let Some(last) = out.last_mut() + { + // Only an opening tag can be left over; close it where it stands. + last.push_str(&rest); + last.push_str("
\n"); + } + if out.is_empty() { + out.push(String::new()); + } + out +} + +/// The package file of chapter `k` (0-based): `content.xhtml`, then `content2.xhtml`, …. +fn chapter_file(k: usize) -> String { + if k == 0 { "content.xhtml".to_string() } else { format!("content{}.xhtml", k + 1) } +} + /// 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)) @@ -544,11 +591,12 @@ fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, String, u8)> { /// 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 { +fn nav_list(entries: &[(String, String, u8)], files: &BTreeMap) -> String { let mut out = String::new(); let mut open: Vec = Vec::new(); for (target, label, level) in entries { - let item = format!("
  • {}", xml_text(label)); + let file = files.get(target).map_or("content.xhtml", String::as_str); + let item = format!("
  • {}", xml_text(label)); match open.last().copied() { None => open.push(*level), Some(top) if *level > top => { @@ -776,11 +824,26 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr let id = opts.identifier.clone().unwrap_or_else(|| format!("urn:designcraft:{}", slug(&title))); 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 = nav_list(&toc); + // One file per chapter (split before each h1), so e-readers needn't load the whole book. + let chapters: Vec = split_chapters(&body) + .into_iter() + .map(|part| { + format!( + "\n\n\n{}\n\n{part}\n\n", + xml_text(&title) + ) + }) + .collect(); + // The file each navigation target (an element id) ended up in. + let mut files: BTreeMap = BTreeMap::new(); + for (k, c) in chapters.iter().enumerate() { + for rest in c.split(" id=\"").skip(1) { + if let Some(id) = rest.split('"').next() { + files.entry(id.to_string()).or_insert_with(|| chapter_file(k)); + } + } + } + let mut nav_items = nav_list(&toc, &files); if nav_items.is_empty() { nav_items = format!("
  • {}
  • ", xml_text(&title)); } @@ -790,8 +853,14 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr 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", + "\n\n", ); + let mut spine = String::new(); + for k in 0..chapters.len() { + let item = if k == 0 { "content".to_string() } else { format!("content{}", k + 1) }; + let _ = writeln!(manifest, "", chapter_file(k)); + let _ = writeln!(spine, ""); + } for (k, (name, (mime, _))) in images.iter().enumerate() { let _ = writeln!(manifest, "", xml_attr(name), xml_attr(mime)); } @@ -802,7 +871,7 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr let cover_spine = if opts.cover.is_some() { "\n" } else { "" }; let author = opts.author.as_deref().map(|a| format!("{}", xml_text(a))).unwrap_or_default(); let opf = format!( - "\n\n\n{}\n{}\n{lang}{author}\n2026-01-01T00:00:00Z\n\n\n\n{manifest}\n\n{cover_spine}\n\n\n", + "\n\n\n{}\n{}\n{lang}{author}\n2026-01-01T00:00:00Z\n\n\n\n{manifest}\n\n{cover_spine}{spine}\n\n", xml_text(&id), xml_text(&title) ); @@ -819,11 +888,14 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr ("OEBPS/content.opf", opf.as_bytes()), ("OEBPS/nav.xhtml", nav.as_bytes()), ("OEBPS/style.css", stylesheet(doc).as_bytes()), - ("OEBPS/content.xhtml", chapter.as_bytes()), ] { z.start_file(name, deflate).map_err(zerr)?; z.write_all(data).map_err(io)?; } + for (k, c) in chapters.iter().enumerate() { + z.start_file(format!("OEBPS/{}", chapter_file(k)), deflate).map_err(zerr)?; + z.write_all(c.as_bytes()).map_err(io)?; + } for (name, (_, data)) in &images { z.start_file(format!("OEBPS/{name}"), stored).map_err(zerr)?; z.write_all(data).map_err(io)?; @@ -907,12 +979,13 @@ mod tests { }; 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 link = |f: &str, t: &str, l: &str| format!("{l}"); + // Each h1 starts a chapter file (#768). let want = format!( "

    Inhoud

    1. {}
      1. {}
    2. {}
    ", - link("s0-p0", "One"), - link("s0-p2", "One point one"), - link("s0-p4", "Two") + link("content.xhtml", "s0-p0", "One"), + link("content.xhtml", "s0-p2", "One point one"), + link("content2.xhtml", "s0-p4", "Two") ); assert!(nav.contains(&want), "{nav}"); assert!(!nav.contains("Text after the figure"), "{nav}"); @@ -925,7 +998,71 @@ mod tests { 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}"); + assert!(nav.contains(&format!("

    Contents

    1. {}
    ", link("content.xhtml", "s0", "Opening"))), "{nav}"); + } + + /// #768: the book is split into one file per chapter, before each h1, with well-formed + /// sections; the spine and manifest list the files in order. + #[test] + fn chapters_are_split_at_h1() { + let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() }); + let lid = d.default_layer(); + d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { + name: "Chapter".into(), + based_on: None, + next_style: None, + para: Default::default(), + chars: CharAttrs::default(), + shortcut: String::new(), + }); + d.styles_mut().export_tags.insert("p:Chapter".into(), designcraft_doc::ExportTag { tag: "h1".into(), class: String::new() }); + // A title page without a heading, then a story that opens with a chapter and has a + // second one in the middle. + d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Title page", ParaFormat::default()).unwrap(); + let (_, sid) = d + .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 400.0), lid, "One\nFirst text\nTwo\nSecond text", ParaFormat::default()) + .unwrap(); + let st = d.story_mut(sid).unwrap(); + st.paras[0].style = "Chapter".into(); + st.paras[2].style = "Chapter".into(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap(); + let mut read = |path: &str| { + let mut s = String::new(); + z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); + s + }; + let (c1, c2, c3) = (read("OEBPS/content.xhtml"), read("OEBPS/content2.xhtml"), read("OEBPS/content3.xhtml")); + assert!(c1.contains("Title page") && !c1.contains("One"), "{c1}"); + assert!(c2.contains("
    \n

    \n

    ").count(), "{c}"); + assert!(!c.contains(CHAPTER_MARK)); + } + let opf = read("OEBPS/content.opf"); + assert!(opf.contains("\n\n\n"), "{opf}"); + assert!(opf.contains("\n

    a

    \n

    \n"), vec!["
    \n

    a

    \n
    \n"]); + assert_eq!( + split_chapters(&format!("
    \n{m}

    A

    \n
    \n")), + vec!["
    \n

    A

    \n
    \n"] + ); + assert_eq!( + split_chapters(&format!("
    \n

    a

    \n{m}

    B

    \n
    \n")), + vec!["
    \n

    a

    \n
    \n", "
    \n

    B

    \n
    \n"] + ); + assert_eq!(split_chapters(""), vec![String::new()]); } #[test]