Skip to content

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

Merge #791: EPUB: one content file per chapter, split before each h1

aiongge12fa9ba2dc0
diff --cc crates/epub/src/lib.rs
index a5719a1c3,3f6dd820d..1097fd0b5
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -604,168 -443,37 +604,173 @@@ fn class_selector(tag: &str, class: &st
Some(selector)
}
-/// One story as XHTML paragraphs.
-pub fn story_html(doc: &Document, sid: StoryId) -> String {
- story_html_in(doc, sid, None)
+/// Closes the open list, if any.
+fn close_list(list: &mut Option<&str>, out: &mut String) {
+ if let Some(l) = list.take() {
+ let _ = writeln!(out, "</{}>", l.split(' ').next().unwrap_or(l));
+ }
}
-/// [`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();
- for (pi, r) in st.para_ranges().iter().enumerate() {
- let pf = &st.paras[pi];
- // Export Tagging: the style's element and class.
- 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 id = match ids {
- 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);
+/// Closes the open preformatted block and list, if any.
+fn close_blocks(list: &mut Option<&str>, pre: &mut Option<(String, bool)>, out: &mut String) {
+ if pre.take().is_some() {
+ out.push_str("</pre>\n");
+ }
+ close_list(list, out);
+}
+
+/// Nesting limit for stories inside stories (table cells, footnotes, tables in cells), so a deeply
+/// nested or cyclic document can't recurse without bound.
+const MAX_DEPTH: usize = 8;
+
+/// Writes stories with their tables and notes, numbering notes across the stories of one export.
+struct StoryWriter<'a, 'f> {
+ doc: &'a Document,
+ pc: BTreeMap<&'a str, String>,
+ cc: BTreeMap<&'a str, String>,
+ /// EPUB structural semantics (`epub:type`); plain HTML doesn't declare the namespace.
+ epub: bool,
+ /// Notes written so far, for unique element ids.
+ footnote_ids: u32,
+ endnote_ids: u32,
+ /// Number shown on the next footnote and endnote of the current story.
+ next_footnote: u32,
+ next_endnote: u32,
+ /// Endnotes met so far: (number, list item markup).
+ endnotes: Vec<(u32, String)>,
+ /// Names each packaged file (a package path, or a data URI for single-file HTML). Without
+ /// it, anchored objects are left out.
+ img_src: Option<&'f dyn Fn(&str, &str, &[u8]) -> String>,
+ /// Images, video and sound met so far, by package name.
+ images: BTreeMap<String, (&'a str, &'a [u8])>,
+ /// Asset names of the images written without alt text (decorative).
+ no_alt: Vec<String>,
+ /// Prefix of the `id`s the current story's headings get (`{prefix}-p{paragraph index}`, the
+ /// targets of the table of contents); only top-level paragraphs get one.
+ heading_ids: Option<String>,
+}
+
+impl<'a, 'f> StoryWriter<'a, 'f> {
+ fn new(doc: &'a Document, epub: bool, img_src: Option<&'f dyn Fn(&str, &str, &[u8]) -> String>) -> Self {
+ StoryWriter {
+ doc,
+ pc: para_classes(&doc.styles),
+ cc: char_classes(&doc.styles),
+ epub,
+ footnote_ids: 0,
+ endnote_ids: 0,
+ next_footnote: 1,
+ next_endnote: 1,
+ endnotes: Vec::new(),
+ img_src,
+ images: BTreeMap::new(),
+ no_alt: Vec::new(),
+ heading_ids: None,
}
- let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });
- if text_empty {
- out.push_str("&#160;");
+ }
+
+ fn epub_type(&self, t: &str) -> String {
+ if self.epub { format!(" epub:type=\"{t}\"") } else { String::new() }
+ }
+
+ /// One document story: paragraphs, tables, and each footnote after the paragraph that refers
+ /// to it.
+ fn story(&mut self, sid: StoryId, heading_ids: Option<&str>) -> String {
+ let Some(st) = self.doc.story(sid) else { return String::new() };
+ self.heading_ids = heading_ids.map(str::to_string);
+ self.next_footnote = self.doc.footnote_start(sid);
+ self.next_endnote = self.doc.endnote_start(sid);
+ let mut out = String::new();
+ self.paragraphs(st, 0, "", &mut out);
+ out
+ }
+
+ /// `st`'s paragraphs. `lead` (a note's number) starts the first paragraph.
+ ///
+ /// Consecutive `li` paragraphs share one list (`ol` for a numbered style, `ul` for a bulleted
+ /// one, an unmarked `ul` when the style has no list type of its own, e.g. typed bullets), and
+ /// consecutive `pre` paragraphs of one style one block, their lines separated by newlines.
+ fn paragraphs(&mut self, st: &Story, depth: usize, lead: &str, out: &mut String) {
+ let doc = self.doc;
+ let mut lead = lead;
+ let mut list: Option<&str> = None;
+ let mut pre: Option<(String, bool)> = None;
+ for (pi, (r, pf)) in st.para_ranges().into_iter().zip(&st.paras).enumerate() {
+ let Some(text) = st.text.get(r.clone()) else { continue };
+ let table = pf.table.and_then(|id| st.tables.get(&id)).filter(|_| text.contains(story::TABLE_ANCHOR));
+ let only_table = table.is_some() && text.chars().all(|c| c == story::TABLE_ANCHOR || c.is_whitespace());
+ if !only_table || !lead.is_empty() {
+ // Export Tagging: the style's element and class.
+ let (tag, class) = export_mapping(&doc.styles, &pf.style, false, &self.pc);
+ let props = doc.styles.resolve_para(pf).0;
+ let rtl = props.direction == designcraft_doc::TextDirection::RightToLeft;
+ let continues_pre = tag == "pre" && pre.as_ref() == Some(&(class.clone(), rtl));
+ if !continues_pre && pre.take().is_some() {
+ out.push_str("</pre>\n");
+ }
+ let list_tag = (tag == "li").then_some(match props.list_type {
+ designcraft_doc::ListType::Numbers => "ol",
+ designcraft_doc::ListType::Bullets => "ul",
+ designcraft_doc::ListType::None => "ul style=\"list-style:none\"",
+ });
+ if list != list_tag {
+ close_list(&mut list, out);
+ if let Some(l) = list_tag {
+ let _ = writeln!(out, "<{l}>");
+ }
+ list = list_tag;
+ }
++ // An EPUB chapter file starts before each top-level h1, outside any open list or
++ // preformatted block.
++ if depth == 0 && self.heading_ids.is_some() && heading_level(tag) == Some(1) {
++ out.push_str(CHAPTER_MARK);
++ }
+ if continues_pre {
+ out.push('\n');
+ } else {
+ let id = match &self.heading_ids {
+ Some(prefix) if depth == 0 && 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 { "" });
+ }
+ out.push_str(lead);
+ if lead.is_empty() && text.trim().is_empty() {
+ out.push_str("&#160;");
+ }
+ lead = "";
+ let mut after = String::new();
+ if !only_table {
+ self.runs(st, r, depth, out, &mut after);
+ }
+ if tag == "pre" {
+ // Closed when the next paragraph isn't a line of the same block.
+ pre = Some((class, rtl));
+ } else {
+ let _ = writeln!(out, "</{tag}>");
+ }
+ // Footnotes follow the paragraph outside any list or preformatted block.
+ if !after.is_empty() {
+ close_blocks(&mut list, &mut pre, out);
+ out.push_str(&after);
+ }
+ }
+ if let Some(t) = table
+ && depth < MAX_DEPTH
+ {
+ close_blocks(&mut list, &mut pre, out);
+ self.table(t, depth + 1, out);
+ }
}
+ close_blocks(&mut list, &mut pre, out);
+ }
+
+ /// The runs of paragraph `para` of `st`; footnotes go to `after`.
+ fn runs(&mut self, st: &Story, para: std::ops::Range<usize>, depth: usize, out: &mut String, after: &mut String) {
+ let doc = self.doc;
for (rr, f) in st.runs() {
- let a = rr.start.max(r.start);
- let b = rr.end.min(r.end);
+ let a = rr.start.max(para.start);
+ let b = rr.end.min(para.end);
if a >= b {
continue;
}
@@@ -814,207 -508,55 +819,251 @@@
let _ = write!(out, "<{ctag}{cls}{style_attr}>{t}</{ctag}>");
}
}
- let _ = writeln!(out, "</{tag}>");
}
- out
+
+ /// An anchored object where it is anchored: its graphics in the text, an above-line object as
+ /// a block of its own. Anchored text frames are left out.
+ fn object(&mut self, o: &AnchoredObject) -> String {
+ let mut out = String::new();
+ o.item.walk(&mut |it| {
+ if let Some((markup, _)) = self.graphic(it) {
+ out.push_str(&markup);
+ }
+ });
+ match &o.position {
+ AnchorPosition::AboveLine { align, .. } if !out.is_empty() => {
+ let align = match align {
+ designcraft_doc::anchored::AnchorAlign::Left => "left",
+ designcraft_doc::anchored::AnchorAlign::Center => "center",
+ designcraft_doc::anchored::AnchorAlign::Right => "right",
+ };
+ format!("<span class=\"anchored\" style=\"display:block;text-align:{align}\">{out}</span>")
+ }
+ _ => out,
+ }
+ }
+
+ /// The markup for one graphic item: an `<img>`, or an HTML5 player for video and sound (with
+ /// `true`), its file registered in `images`. `None` for an item that isn't a graphic, whose
+ /// asset has no data, or when the writer names no files.
+ fn graphic(&mut self, it: &Item) -> Option<(String, bool)> {
+ let img_src = self.img_src?;
+ let doc = self.doc;
+ let Content::Graphic(g) = &it.content else { return None };
+ let a = doc.assets.get(&g.asset)?;
+ if a.data.is_empty() {
+ return None;
+ }
+ let mime = safe_mime(&a.mime);
+ // Video and sound: an HTML5 player (with the poster, when there is one).
+ if let Some(kind) = designcraft_doc::media_kind(mime) {
+ let name = asset_path("media", a, mime);
+ self.images.insert(name.clone(), (mime, a.data.as_slice()));
+ let m = it.media.clone().unwrap_or_default();
+ let mut attrs = String::new();
+ for (on, attr) in [(m.controls, " controls=\"controls\""), (m.play_on_page_load, " autoplay=\"autoplay\""), (m.looping, " loop=\"loop\"")] {
+ if on {
+ attrs.push_str(attr);
+ }
+ }
+ if let Some(pa) = m.poster.and_then(|p| doc.assets.get(&p)) {
+ let poster_mime = safe_mime(&pa.mime);
+ let pn = asset_path("images", pa, poster_mime);
+ self.images.insert(pn.clone(), (poster_mime, pa.data.as_slice()));
+ if kind == "video" {
+ attrs.push_str(&format!(" poster=\"{}\"", xml_attr(&img_src(&pn, poster_mime, &pa.data))));
+ }
+ }
+ let markup = format!("<{kind} src=\"{}\"{attrs}>{}</{kind}>", xml_attr(&img_src(&name, mime, &a.data)), xml_text(&a.name));
+ return Some((markup, true));
+ }
+ let name = asset_path("images", a, mime);
+ self.images.insert(name.clone(), (mime, a.data.as_slice()));
+ // Alt text from Object Export Options; without one the image counts as decorative
+ // (`alt=""`): a file name read aloud helps nobody.
+ if it.alt_text.trim().is_empty() {
+ self.no_alt.push(a.name.clone());
+ }
+ Some((format!("<img src=\"{}\" alt=\"{}\"/>", xml_attr(&img_src(&name, mime, &a.data)), xml_attr(&it.alt_text)), false))
+ }
+
+ /// The footnote whose reference is at byte `pos` of `st`: a note reference in `out`, the note
+ /// itself in `after`.
+ fn footnote(&mut self, st: &Story, pos: usize, depth: usize, out: &mut String, after: &mut String) {
+ let Some(note) = st.notes.get(st.notes_before(pos)) else { return };
+ let doc = self.doc;
+ let o = &doc.footnote_options;
+ let n = self.next_footnote;
+ self.next_footnote = n.saturating_add(1);
+ self.footnote_ids = self.footnote_ids.saturating_add(1);
+ let id = self.footnote_ids;
+ let _ = write!(
+ out,
+ "<sup><a{} role=\"doc-noteref\" id=\"fnref-{id}\" href=\"#fn-{id}\">{}</a></sup>",
+ self.epub_type("noteref"),
+ xml_text(&o.label(n, false))
+ );
+ let lead = format!("<a href=\"#fnref-{id}\">{}</a> ", xml_text(&o.label(n, true)));
+ let mut body = String::new();
+ self.paragraphs(&note.text, depth + 1, &lead, &mut body);
+ let _ = write!(after, "<aside{} role=\"doc-footnote\" id=\"fn-{id}\">\n{body}</aside>\n", self.epub_type("footnote"));
+ }
+
+ /// The endnote whose reference is at byte `pos` of `st`: a note reference in `out`; the note
+ /// joins the endnotes section.
+ fn endnote(&mut self, st: &Story, pos: usize, depth: usize, out: &mut String) {
+ let Some(note) = st.endnotes.get(st.endnotes_before(pos)) else { return };
+ let n = self.next_endnote;
+ self.next_endnote = n.saturating_add(1);
+ self.endnote_ids = self.endnote_ids.saturating_add(1);
+ let id = self.endnote_ids;
+ let label = xml_text(&self.doc.endnote_options.label(n));
+ let _ = write!(out, "<sup><a{} role=\"doc-noteref\" id=\"enref-{id}\" href=\"#en-{id}\">{label}</a></sup>", self.epub_type("noteref"));
+ let mut body = String::new();
+ self.paragraphs(&note.text, depth + 1, &format!("<a href=\"#enref-{id}\">{label}</a> "), &mut body);
+ let item = format!("<li{} id=\"en-{id}\">\n{body}</li>\n", self.epub_type("endnote"));
+ self.endnotes.push((n, item));
+ }
+
+ /// The endnotes met so far, in number order, as one section (empty when there are none).
+ fn endnotes_section(&mut self) -> String {
+ if self.endnotes.is_empty() {
+ return String::new();
+ }
+ self.endnotes.sort_by_key(|(n, _)| *n);
+ let doc = self.doc;
+ let o = &doc.endnote_options;
+ let mut out = format!("<section{} role=\"doc-endnotes\" id=\"endnotes\">\n", self.epub_type("endnotes"));
+ if !o.heading.trim().is_empty() {
+ let (tag, class) = export_mapping(&doc.styles, &o.heading_style, false, &self.pc);
+ let _ = writeln!(out, "<{tag} class=\"{}\">{}</{tag}>", xml_attr(&class), xml_text(&o.heading));
+ }
+ out.push_str("<ol style=\"list-style: none; padding-left: 0\">\n");
+ for (_, item) in &self.endnotes {
+ out.push_str(item);
+ }
+ out.push_str("</ol>\n</section>\n");
+ out
+ }
+
+ /// A table: header rows as `thead`, footer rows as `tfoot`, merged cells as row and column
+ /// spans (kept within their row group).
+ fn table(&mut self, t: &Table, depth: usize, out: &mut String) {
+ let (nr, nc) = (t.nrows(), t.ncols());
+ if nr.checked_mul(nc) != Some(t.cells.len()) {
+ return;
+ }
+ let (h, f) = (t.header_rows(), t.footer_rows());
+ let body_end = nr.saturating_sub(f).max(h);
+ let mut covered = vec![false; t.cells.len()];
+ out.push_str("<table>\n");
+ for (rows, group, cell_tag) in [(0..h, "thead", "th"), (h..body_end, "tbody", "td"), (body_end..nr, "tfoot", "td")] {
+ if rows.is_empty() {
+ continue;
+ }
+ let _ = writeln!(out, "<{group}>");
+ for r in rows.clone() {
+ out.push_str("<tr>");
+ for c in 0..nc {
+ let i = r * nc + c;
+ if covered.get(i).copied().unwrap_or(true) {
+ continue;
+ }
+ let Some(cell) = t.cells.get(i) else { continue };
+ let rs = (cell.row_span.max(1) as usize).min(rows.end - r);
+ let cs = (cell.col_span.max(1) as usize).min(nc - c);
+ for rr in r..r + rs {
+ for cc in c..c + cs {
+ if let Some(slot) = covered.get_mut(rr * nc + cc) {
+ *slot = true;
+ }
+ }
+ }
+ let _ = write!(out, "<{cell_tag}");
+ if rs > 1 {
+ let _ = write!(out, " rowspan=\"{rs}\"");
+ }
+ if cs > 1 {
+ let _ = write!(out, " colspan=\"{cs}\"");
+ }
+ out.push('>');
+ self.paragraphs(&cell.text, depth, "", out);
+ let _ = writeln!(out, "</{cell_tag}>");
+ }
+ out.push_str("</tr>\n");
+ }
+ let _ = writeln!(out, "</{group}>");
+ }
+ out.push_str("</table>\n");
+ }
+}
+
+/// Run text with variables replaced by their values.
+fn run_text(doc: &Document, raw: &str) -> String {
+ if raw.chars().any(|c| designcraft_doc::vars::var_index(c).is_some()) {
+ let sub: String = raw
+ .chars()
+ .map(|c| match designcraft_doc::vars::var_index(c) {
+ Some(i) => doc.variable_value(i, None).unwrap_or_default(),
+ None => c.to_string(),
+ })
+ .collect();
+ story_markup(&sub)
+ } else {
+ story_markup(raw)
+ }
+}
+
+/// One story as XHTML: paragraphs, tables, and each footnote after the paragraph that refers to
+/// it. Endnote references link to the endnotes section that the full export ends with.
+pub fn story_html(doc: &Document, sid: StoryId) -> String {
+ StoryWriter::new(doc, true, None).story(sid, None)
}
+ /// Where the EPUB body splits into chapter files: before each `h1`.
+ const CHAPTER_MARK: &str = "<!--dc:chapter-->";
+
+ /// 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<String> {
+ let mut out: Vec<String> = Vec::new();
+ let mut carry: Option<String> = 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("<section").filter(|i| !part[*i..].contains("</section>")) {
+ 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("</section>\n");
+ carry = Some("<section>\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("</section>\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<u8> {
tag.strip_prefix('h').and_then(|n| n.parse::<u8>().ok()).filter(|n| (1..=6).contains(n))
@@@ -1296,15 -821,29 +1346,30 @@@ pub fn export_epub(doc: &Document, opts
let io = |e: std::io::Error| EpubError(e.to_string());
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(), true);
+ let id = identifier(doc, opts, &title);
+ let modified = modified(doc, opts);
+ let Body { html: body, images, toc, .. } = body_html(doc, true, &|name, _, _| name.to_string());
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 = nav_list(&toc);
+ // One file per chapter (split before each h1), so e-readers needn't load the whole book.
+ let chapters: Vec<String> = split_chapters(&body)
+ .into_iter()
+ .map(|part| {
+ 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{part}</body>\n</html>\n",
+ xml_text(&title)
+ )
+ })
+ .collect();
+ // The file each navigation target (an element id) ended up in.
+ let mut files: BTreeMap<String, String> = 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!("<li><a href=\"content.xhtml\">{}</a></li>", xml_text(&title));
}
@@@ -1334,7 -871,7 +1405,7 @@@
let cover_spine = if opts.cover.is_some() { "<itemref idref=\"cover\"/>\n" } else { "" };
let author = opts.author.as_deref().map(|a| format!("<dc:creator>{}</dc:creator>", xml_text(a))).unwrap_or_default();
let opf = format!(
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"bookid\" xml:lang=\"{lang}\">\n<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<dc:identifier id=\"bookid\">{}</dc:identifier>\n<dc:title>{}</dc:title>\n<dc:language>{lang}</dc:language>{author}\n<meta property=\"dcterms:modified\">{modified}</meta>\n<meta name=\"generator\" content=\"DesignCraft\"/>\n</metadata>\n<manifest>\n{manifest}</manifest>\n<spine>\n{cover_spine}<itemref idref=\"content\"/>\n</spine>\n</package>\n",
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"bookid\" xml:lang=\"{lang}\">\n<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<dc:identifier id=\"bookid\">{}</dc:identifier>\n<dc:title>{}</dc:title>\n<dc:language>{lang}</dc:language>{author}\n<meta property=\"dcterms:modified\">2026-01-01T00:00:00Z</meta>\n<meta name=\"generator\" content=\"DesignCraft\"/>\n</metadata>\n<manifest>\n{manifest}</manifest>\n<spine>\n{cover_spine}{spine}</spine>\n</package>\n",
++ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"bookid\" xml:lang=\"{lang}\">\n<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<dc:identifier id=\"bookid\">{}</dc:identifier>\n<dc:title>{}</dc:title>\n<dc:language>{lang}</dc:language>{author}\n<meta property=\"dcterms:modified\">{modified}</meta>\n<meta name=\"generator\" content=\"DesignCraft\"/>\n</metadata>\n<manifest>\n{manifest}</manifest>\n<spine>\n{cover_spine}{spine}</spine>\n</package>\n",
xml_text(&id),
xml_text(&title)
);
@@@ -1350,8 -887,7 +1421,7 @@@
("META-INF/container.xml", container.as_bytes()),
("OEBPS/content.opf", opf.as_bytes()),
("OEBPS/nav.xhtml", nav.as_bytes()),
- ("OEBPS/style.css", stylesheet(doc).as_bytes()),
+ ("OEBPS/style.css", stylesheet_with(doc, &opts.generic_families, &opts.fonts).as_bytes()),
- ("OEBPS/content.xhtml", chapter.as_bytes()),
] {
z.start_file(name, deflate).map_err(zerr)?;
z.write_all(data).map_err(io)?;
@@@ -1627,18 -998,71 +1702,83 @@@ 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!("<h1>Contents</h1><ol><li>{}</li></ol>", link("s0", "Opening"))), "{nav}");
+ assert!(nav.contains(&format!("<h1>Contents</h1><ol><li>{}</li></ol>", link("content.xhtml", "s0", "Opening"))), "{nav}");
+ // A heading shallower than the one before it but deeper than its parent stays under the
+ // parent: h1 A, h3 B, h2 C nest B and C under A.
++ let files: BTreeMap<String, String> = "ABCD".chars().map(|c| (c.to_string(), c.to_string())).collect();
+ let e = |t: &str, l: u8| (t.to_string(), t.to_string(), l);
+ assert_eq!(
- nav_list(&[e("A", 1), e("B", 3), e("C", 2), e("D", 1)]),
- format!("<li>{}<ol><li>{}</li><li>{}</li></ol></li><li>{}</li>", link("A", "A"), link("B", "B"), link("C", "C"), link("D", "D"))
++ nav_list(&[e("A", 1), e("B", 3), e("C", 2), e("D", 1)], &files),
++ format!("<li>{}<ol><li>{}</li><li>{}</li></ol></li><li>{}</li>", link("A", "A", "A"), link("B", "B", "B"), link("C", "C", "C"), link("D", "D", "D"))
++ );
++ assert_eq!(
++ nav_list(&[e("A", 1), e("B", 2), e("C", 3), e("D", 1)], &files),
++ format!("<li>{}<ol><li>{}<ol><li>{}</li></ol></li></ol></li><li>{}</li>", link("A", "A", "A"), link("B", "B", "B"), link("C", "C", "C"), link("D", "D", "D"))
++ );
+ }
+
+ /// #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("<section id=\"s1\">\n<h1 id=\"s1-p0\"") && c2.contains("First text") && !c2.contains("Two"), "{c2}");
+ assert!(c3.contains("<section>\n<h1 id=\"s1-p2\""), "{c3}");
+ for c in [&c1, &c2, &c3] {
+ assert_eq!(c.matches("<section").count(), c.matches("</section>").count(), "{c}");
+ assert!(!c.contains(CHAPTER_MARK));
+ }
+ let opf = read("OEBPS/content.opf");
+ assert!(opf.contains("<itemref idref=\"content\"/>\n<itemref idref=\"content2\"/>\n<itemref idref=\"content3\"/>\n</spine>"), "{opf}");
+ assert!(opf.contains("<item id=\"content3\" href=\"content3.xhtml\""), "{opf}");
+ let nav = read("OEBPS/nav.xhtml");
+ assert!(nav.contains("href=\"content2.xhtml#s1-p0\"") && nav.contains("href=\"content3.xhtml#s1-p2\""), "{nav}");
+ assert!(z.by_name("OEBPS/content4.xhtml").is_err());
+ // HTML stays one page, without the marks.
+ let html = export_html(&d, &HtmlOptions::default());
+ assert!(!html.contains(CHAPTER_MARK) && html.contains("Second text"));
+ }
+
+ #[test]
+ fn split_chapters_keeps_sections_well_formed() {
+ let m = CHAPTER_MARK;
+ assert_eq!(split_chapters("<section id=\"s0\">\n<p>a</p>\n</section>\n"), vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n"]);
+ assert_eq!(
+ split_chapters(&format!("<section id=\"s0\">\n{m}<h1>A</h1>\n</section>\n")),
+ vec!["<section id=\"s0\">\n<h1>A</h1>\n</section>\n"]
);
assert_eq!(
- nav_list(&[e("A", 1), e("B", 2), e("C", 3), e("D", 1)]),
- format!("<li>{}<ol><li>{}<ol><li>{}</li></ol></li></ol></li><li>{}</li>", link("A", "A"), link("B", "B"), link("C", "C"), link("D", "D"))
+ split_chapters(&format!("<section id=\"s0\">\n<p>a</p>\n{m}<h1>B</h1>\n</section>\n")),
+ vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n", "<section>\n<h1>B</h1>\n</section>\n"]
);
+ assert_eq!(split_chapters(""), vec![String::new()]);
}
#[test]