Skip to content

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

Merge #782: EPUB: the navigation lists the headings, with a title in the book's language

aiongg1486f8221242
diff --cc crates/engine/src/cmd/export.rs
index 110c3aab3,c466a9701..716583034
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@@ -12,7 -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\", identifier?: str (dc:identifier; a stable urn:uuid by default), coverImage?: path (a PNG or JPEG as the cover), cover?: bool (the first page as the cover image), embedFonts?: bool (package the stylesheet's fonts whose licence allows it, whole files), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative, and fonts not embedded",
- "{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})",
++ "{path?, title?, author?, language?: \"en\", tocTitle?: str (the table of contents' title; from the language by default), identifier?: str (dc:identifier; a stable urn:uuid by default), coverImage?: path (a PNG or JPEG as the cover), cover?: bool (the first page as the cover image), embedFonts?: bool (package the stylesheet's fonts whose licence allows it, whole files), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative, and fonts not embedded",
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})",
@@@ -192,19 -135,9 +192,20 @@@ fn export_epub(s: &mut Session, p: &Val
title: p.get("title").and_then(Value::as_str).map(str::to_string),
author: p.get("author").and_then(Value::as_str).map(str::to_string),
language: p.get("language").and_then(Value::as_str).unwrap_or("en").to_string(),
- identifier: None,
+ identifier: p.get("identifier").and_then(Value::as_str).map(str::to_string),
cover,
+ generic_families: generic_families(&st.doc),
+ fonts: if p.get("embedFonts").and_then(Value::as_bool).unwrap_or(false) && !fixed {
+ embedded_fonts(&st.doc, &mut warnings)
+ } else {
+ Vec::new()
+ },
+ // The export time; on the web the document's own save time stands in.
+ #[cfg(not(target_arch = "wasm32"))]
+ modified: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().and_then(|d| i64::try_from(d.as_secs()).ok()),
+ #[cfg(target_arch = "wasm32")]
+ modified: None,
+ toc_title: p.get("tocTitle").and_then(Value::as_str).map(str::to_string),
};
if fixed {
let d = &st.doc;
diff --cc crates/epub/src/lib.rs
index aa1269b28,57e7c9d88..c151f530c
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -26,143 -20,28 +26,161 @@@ pub struct EpubOptions
pub language: String,
/// Stable identifier (urn:uuid:…); derived from the title when absent.
pub identifier: Option<String>,
- /// Cover image (PNG), shown first and marked as the book's cover.
+ /// Cover image (PNG or JPEG), shown first and marked as the book's cover.
pub cover: Option<Vec<u8>>,
+ /// Generic CSS family (`serif`, `sans-serif`, `monospace`, `cursive`, `fantasy`) per font
+ /// family, from the fonts' classification; families not in it are guessed from their name.
+ pub generic_families: BTreeMap<String, String>,
+ /// Font files packaged with the book and declared with `@font-face`.
+ pub fonts: Vec<EmbeddedFont>,
+ /// `dcterms:modified` (Unix seconds, UTC); the document's last save, else its creation, when
+ /// absent.
+ pub modified: Option<i64>,
+ /// Title of the navigation (table of contents); from `language` when absent.
+ pub toc_title: Option<String>,
}
+/// A font file packaged with an EPUB: the face of `family` in `style` (`Bold Italic`…).
+#[derive(Clone, Debug)]
+pub struct EmbeddedFont {
+ pub family: String,
+ pub style: String,
+ pub data: Vec<u8>,
+}
+
+/// The `(family, style)` pairs the stylesheet names, one each, in style order: the fonts an
+/// export can embed.
+pub fn stylesheet_fonts(doc: &Document) -> Vec<(String, String)> {
+ let st: &Styles = &doc.styles;
+ let mut out: Vec<(String, String)> = Vec::new();
+ for ps in &st.paragraph {
+ if ps.name == designcraft_doc::NO_PARA_STYLE {
+ continue;
+ }
+ let (_, cp) = st.resolve_para_style(&ps.name);
+ let f = (cp.font_family.clone(), cp.font_style.clone());
+ if !f.0.is_empty() && !out.contains(&f) {
+ out.push(f);
+ }
+ }
+ out
+}
+
+/// The CSS generic family for `family`: the known one, else a guess from the name
+/// (`… Mono`/`Courier`/`… Code` → monospace, `… Sans`/`Gothic`/`Grotesk`/`Helvetica`/`Arial`/
+/// `Verdana` → sans-serif), else serif.
+fn generic_family<'a>(family: &str, known: &'a BTreeMap<String, String>) -> &'a str {
+ const GENERIC: [&str; 6] = ["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui"];
+ if let Some(g) = known.get(family).and_then(|g| GENERIC.iter().find(|x| **x == g.as_str())) {
+ return g;
+ }
+ let f = family.to_lowercase();
+ let has = |words: &[&str]| words.iter().any(|w| f.contains(w));
+ if has(&["mono", "courier", " code", "consol"]) {
+ "monospace"
+ } else if has(&["sans", "gothic", "grotesk", "grotesque", "helvetica", "arial", "verdana"]) {
+ "sans-serif"
+ } else {
+ "serif"
+ }
+}
+
+/// CSS weight and style of a style name (`Semibold Italic` → 600, italic).
+fn css_weight_style(style: &str) -> (u16, &'static str) {
+ let s = style.to_lowercase().replace([' ', '-'], "");
+ let weight = [
+ ("thin", 100),
+ ("extralight", 200),
+ ("ultralight", 200),
+ ("light", 300),
+ ("medium", 500),
+ ("semibold", 600),
+ ("demibold", 600),
+ ("extrabold", 800),
+ ("ultrabold", 800),
+ ("bold", 700),
+ ("black", 900),
+ ("heavy", 900),
+ ]
+ .iter()
+ .find(|(n, _)| s.contains(n))
+ .map_or(400, |(_, w)| *w);
+ (weight, if s.contains("italic") || s.contains("oblique") { "italic" } else { "normal" })
+}
+
+/// Package path and media type of an embedded font (`fonts/{k}-{family}-{style}.{ext}`).
+fn font_file(k: usize, f: &EmbeddedFont) -> (String, &'static str) {
+ let (ext, mime) = match f.data.get(..4) {
+ Some(b"OTTO") => ("otf", "font/otf"),
+ Some(b"wOFF") => ("woff", "font/woff"),
+ Some(b"wOF2") => ("woff2", "font/woff2"),
+ _ => ("ttf", "font/ttf"),
+ };
+ let name: String =
+ format!("{}-{}", f.family, f.style).chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
+ let name = name.split('-').filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-");
+ (format!("fonts/{k}-{name}.{ext}"), mime)
+}
+
+/// An ISO 8601 UTC timestamp (`2026-10-13T09:30:00Z`) for Unix seconds `t`.
+fn iso8601(t: i64) -> String {
+ let (days, secs) = (t.div_euclid(86_400), t.rem_euclid(86_400));
+ // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z - era * 146_097;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let day = doy - (153 * mp + 2) / 5 + 1;
+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
+ let year = yoe + era * 400 + i64::from(month <= 2);
+ format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", secs / 3600, secs % 3600 / 60, secs % 60)
+}
+
+/// The package's `dcterms:modified`: the given time, else the document's last save or creation.
+fn modified(doc: &Document, opts: &EpubOptions) -> String {
+ let t = opts.modified.or((doc.modified > 0).then_some(doc.modified)).or((doc.created > 0).then_some(doc.created));
+ t.map_or_else(|| "2026-01-01T00:00:00Z".to_string(), iso8601)
+}
+
+/// The book's identifier: the given one, else a `urn:uuid` derived from the title and the
+/// document's creation time, so a book keeps its identifier from export to export and two books
+/// with the same title don't share one.
+fn identifier(doc: &Document, opts: &EpubOptions, title: &str) -> String {
+ if let Some(id) = opts.identifier.clone().filter(|i| !i.trim().is_empty()) {
+ return id;
+ }
+ // Two FNV-1a 64-bit hashes (different offsets) as 128 bits, shaped as a version-5-style UUID.
+ let seed = format!("{title}\n{}", doc.created);
+ let fnv = |offset: u64| seed.bytes().fold(offset, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3));
+ let (a, b) = (fnv(0xcbf2_9ce4_8422_2325), fnv(0x84222325_cbf29ce4));
+ let hi = (a & 0xffff_ffff_ffff_0fff) | 0x5000;
+ let lo = (b & 0x3fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000;
+ format!("urn:uuid:{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", hi >> 32, (hi >> 16) & 0xffff, hi & 0xffff, lo >> 48, lo & 0xffff_ffff_ffff)
+}
+
+/// Package name and media type of a cover image: JPEG by its signature, else PNG.
+fn cover_file(data: &[u8]) -> (&'static str, &'static str) {
+ if data.starts_with(&[0xFF, 0xD8, 0xFF]) { ("images/cover.jpg", "image/jpeg") } else { ("images/cover.png", "image/png") }
+}
+
+ /// 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,
/// read-aloud and accessibility).
#[derive(Clone, Debug)]
@@@ -240,16 -118,7 +258,17 @@@ pub fn export_fixed_epub(doc: &Document
impl Default for EpubOptions {
fn default() -> Self {
- EpubOptions { title: None, author: None, language: "en".into(), identifier: None, cover: None, toc_title: None }
+ EpubOptions {
+ title: None,
+ author: None,
+ language: "en".into(),
+ identifier: None,
+ cover: None,
+ generic_families: BTreeMap::new(),
+ fonts: Vec::new(),
+ modified: None,
++ toc_title: None,
+ }
}
}
@@@ -585,159 -443,34 +604,168 @@@ 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(),
- };
- let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });
- if text_empty {
- out.push_str("&#160;");
+/// 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,
+ }
+ }
+
+ 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) -> String {
++ 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 (r, pf) in st.para_ranges().into_iter().zip(&st.paras) {
++ 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;
+ }
+ if continues_pre {
+ out.push('\n');
+ } else {
- let _ = write!(out, "<{tag} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } 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;
}
@@@ -786,205 -505,76 +814,276 @@@
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)
++ StoryWriter::new(doc, true, None).story(sid, None)
+ }
+
+ /// 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 };
++ // The endnote story isn't written (the endnotes section stands in for it).
++ if doc.endnote_story == Some(*sid) {
++ 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.
@@@ -1091,50 -658,67 +1190,42 @@@ fn ext(mime: &str) -> &'static str
}
}
+/// The document content as HTML, with the files it names.
+struct Body<'a> {
+ html: String,
+ /// Images, video and sound by package name: (media type, bytes).
+ images: BTreeMap<String, (&'a str, &'a [u8])>,
- /// Table of contents: (element id, label).
- toc: Vec<(String, String)>,
++ /// Table of contents: (element id, label, level).
++ toc: Vec<(String, String, u8)>,
+ /// Asset names of the images written without alt text.
+ no_alt: Vec<String>,
+}
+
/// The content in reading order as HTML sections and figures; `img_src` names each image
-/// (a package path, or a data URI for single-file HTML). Returns (body, images by name, table of
-/// contents).
-#[allow(clippy::type_complexity)]
-fn body_html<'a>(
- doc: &'a Document,
- img_src: &dyn Fn(&str, &str, &[u8]) -> String,
- heading_ids: bool,
-) -> (String, BTreeMap<String, (&'a str, &'a [u8])>, Vec<(String, String, u8)>) {
+/// (a package path, or a data URI for single-file HTML).
+fn body_html<'a>(doc: &'a Document, epub: bool, img_src: &dyn Fn(&str, &str, &[u8]) -> String) -> Body<'a> {
let order = reading_order(doc);
+ let mut writer = StoryWriter::new(doc, epub, Some(img_src));
let mut body = String::new();
- let mut toc: Vec<(String, String)> = Vec::new();
- let mut images: BTreeMap<String, (&str, &[u8])> = BTreeMap::new();
- let toc = toc_entries(doc, &order);
++ let mut toc = toc_entries(doc, &order);
for (k, b) in order.iter().enumerate() {
match b {
+ // The endnote frame's text is generated from the endnotes, which end the body as a
+ // linked section instead.
+ Block::Story(sid) if doc.endnote_story == Some(*sid) => {}
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", writer.story(*sid));
- let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", story_html_in(doc, *sid, heading_ids.then_some(anchor.as_str())));
++ let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", writer.story(*sid, epub.then_some(anchor.as_str())));
}
Block::Image(iid) => {
- let Some(Content::Graphic(g)) = doc.item(*iid).map(|i| &i.content) else { continue };
- let Some(a) = doc.assets.get(&g.asset) else { continue };
- if a.data.is_empty() {
- continue;
- }
- 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 = format!("media/{}.{}", g.asset.0, ext(mime));
- images.insert(name.clone(), (mime, a.data.as_slice()));
- let m = doc.item(*iid).and_then(|i| i.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 = format!("images/{}.{}", pa.id.0, ext(poster_mime));
- 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 _ = writeln!(
- body,
- "<figure><{kind} src=\"{}\"{attrs}>{}</{kind}></figure>",
- xml_attr(&img_src(&name, mime, &a.data)),
- xml_text(&a.name)
- );
+ let Some(it) = doc.item(*iid) else { continue };
+ let Some((markup, media)) = writer.graphic(it) else { continue };
+ if media {
+ let _ = writeln!(body, "<figure>{markup}</figure>");
continue;
}
- let name = format!("images/{}.{}", g.asset.0, ext(mime));
- images.insert(name.clone(), (mime, a.data.as_slice()));
- // Alt text from Object Export Options, else the file name.
- let alt = doc.item(*iid).map(|i| i.alt_text.as_str()).filter(|t| !t.is_empty()).unwrap_or(&a.name);
// Object Export Options: alignment and a page break before.
- let eo = doc.item(*iid).map(|i| i.export_options.clone()).unwrap_or_default();
+ let eo = &it.export_options;
let mut css = String::new();
if matches!(eo.align.as_str(), "left" | "center" | "right") {
css.push_str(&format!("text-align:{};", eo.align));
@@@ -1147,21 -732,7 +1238,21 @@@
}
}
}
- (body, images, toc)
+ let endnotes = writer.endnotes_section();
+ if !endnotes.is_empty() {
+ let heading = &doc.endnote_options.heading;
+ if !heading.trim().is_empty() {
- toc.push(("endnotes".into(), heading.clone()));
++ toc.push(("endnotes".into(), heading.clone(), 1));
+ }
+ body.push_str(&endnotes);
+ }
+ Body { html: body, images: writer.images, toc, no_alt: writer.no_alt }
+}
+
+/// Placed and anchored images (not video or sound) without alt text, by asset name: they are exported as
+/// decorative (`alt=""`), which an export can report.
+pub fn images_without_alt(doc: &Document) -> Vec<String> {
+ body_html(doc, true, &|name, _, _| name.to_string()).no_alt
}
/// Options for [`export_html`].
@@@ -1321,171 -874,60 +1410,225 @@@ mod tests
assert!(z.by_name("OEBPS/nav.xhtml").is_ok());
}
+ /// #766: anchored graphics are exported where they are anchored (inline in the text, an
+ /// above-line object as a block of its own), and their images go into the package.
+ #[test]
+ fn anchored_objects_are_exported_in_place() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 200.0), lid, "AB\nCD", ParaFormat::default()).unwrap();
+ let aid = AssetId(d.alloc());
+ d.assets.insert(
+ aid,
+ Arc::new(Asset {
+ page: 0,
+ id: aid,
+ name: "dot.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(vec![7]),
+ pixels: Some((1, 1)),
+ ..Default::default()
+ }),
+ );
+ let graphic = |d: &mut Document, alt: &str| {
+ let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
+ item.alt_text = alt.into();
+ item.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (1.0, 1.0),
+ xf: Affine::IDENTITY,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ clip: None,
+ wrap: Default::default(),
+ });
+ item
+ };
+ let inline = designcraft_doc::AnchoredObject::new(graphic(&mut d, "inline"), designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 });
+ let above = designcraft_doc::AnchoredObject::new(
+ graphic(&mut d, "above"),
+ designcraft_doc::AnchorPosition::AboveLine { align: designcraft_doc::anchored::AnchorAlign::Center, space_before: 0.0, space_after: 0.0 },
+ );
+ let st = d.story_mut(sid).unwrap();
+ st.insert_object(1, inline);
+ // Byte offsets: "A" (1), the mark (3), "B\nC" (3): the second object goes between C and D.
+ st.insert_object(7, above);
+ // An anchored image without alt text is decorative and reported, like a placed one.
+ let bare = designcraft_doc::AnchoredObject::new(graphic(&mut d, ""), designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 });
+ let end = d.story(sid).unwrap().text.len();
+ d.story_mut(sid).unwrap().insert_object(end, bare);
+ assert_eq!(images_without_alt(&d), vec!["dot.png".to_string()]);
+ let bytes = export_epub(&d, &EpubOptions::default()).unwrap();
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
+ let mut html = String::new();
+ z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap();
+ let img = |alt: &str| format!("<img src=\"images/dot-{}.png\" alt=\"{alt}\"/>", aid.0);
+ assert!(html.contains(&format!("A{}B</p>", img("inline"))), "{html}");
+ assert!(html.contains(&format!("C<span class=\"anchored\" style=\"display:block;text-align:center\">{}</span>D", img("above"))), "{html}");
+ assert!(z.by_name(&format!("OEBPS/images/dot-{}.png", aid.0)).is_ok(), "the image is in the package");
+ let page = export_html(&d, &HtmlOptions::default());
+ assert!(page.contains("alt=\"inline\"") && page.contains("alt=\"above\""), "{page}");
+ // story_html on its own still leaves objects out.
+ assert!(!story_html(&d, sid).contains("<img"));
+ }
+
+ #[test]
+ fn iso8601_timestamps() {
+ for (t, want) in [
+ (0, "1970-01-01T00:00:00Z"),
+ (951_782_400, "2000-02-29T00:00:00Z"),
+ (1_791_891_000, "2026-10-13T11:30:00Z"),
+ (-86_400, "1969-12-31T00:00:00Z"),
+ ] {
+ assert_eq!(iso8601(t), want);
+ }
+ }
+
+ /// #771, #773: dcterms:modified is a real time, the default identifier is a stable urn:uuid
+ /// that differs between documents with the same title, and a JPEG cover keeps its type.
+ #[test]
+ fn package_metadata_and_cover_image() {
+ let opf = |d: &Document, opts: &EpubOptions| {
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap();
+ let mut s = String::new();
+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut s).unwrap();
+ let names: Vec<String> = z.file_names().map(str::to_string).collect();
+ (s, names)
+ };
+ let id_of = |opf: &str| opf.split("<dc:identifier id=\"bookid\">").nth(1).and_then(|r| r.split('<').next()).unwrap_or_default().to_string();
+ let mut a = Document::new(&NewDocument::default());
+ a.title = "Same".into();
+ a.created = 1_700_000_000;
+ let mut b = a.clone();
+ b.created = 1_700_000_001;
+ let (oa, _) = opf(&a, &EpubOptions::default());
+ let (oa2, _) = opf(&a, &EpubOptions::default());
+ let (ob, _) = opf(&b, &EpubOptions::default());
+ assert!(id_of(&oa).starts_with("urn:uuid:") && id_of(&oa).len() == 45, "{}", id_of(&oa));
+ assert_eq!(id_of(&oa), id_of(&oa2), "stable from export to export");
+ assert_ne!(id_of(&oa), id_of(&ob), "not shared by two books with the same title");
+ // Modified: the given time, else the document's save (or creation) time.
+ assert!(oa.contains("<meta property=\"dcterms:modified\">2023-11-14T22:13:20Z</meta>"), "{oa}");
+ let at = EpubOptions { modified: Some(1_791_891_000), ..Default::default() };
+ assert!(opf(&a, &at).0.contains("2026-10-13T11:30:00Z"));
+ // A JPEG cover is packaged as such.
+ let jpeg = EpubOptions { cover: Some(vec![0xFF, 0xD8, 0xFF, 0xE0, 1, 2]), ..Default::default() };
+ let (o, names) = opf(&a, &jpeg);
+ assert!(o.contains("href=\"images/cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\""), "{o}");
+ assert!(names.contains(&"OEBPS/images/cover.jpg".to_string()), "{names:?}");
+ }
+
+ fn st_typed(d: &mut Document, sid: StoryId) {
+ if let Some(st) = d.story_mut(sid) {
+ st.paras[8].style = "Typed".into();
+ }
+ }
+
+ /// #767: consecutive `li` paragraphs share one list (`ol` for a numbered style), and
+ /// consecutive `pre` paragraphs of one style one block with their lines on separate lines.
+ #[test]
+ fn lists_and_preformatted_blocks_are_grouped() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ for (name, tag, list) in [
+ ("Bullet", "li", Some(designcraft_doc::ListType::Bullets)),
+ ("Number", "li", Some(designcraft_doc::ListType::Numbers)),
+ ("Typed", "li", None),
+ ("Code", "pre", None),
+ ] {
+ let para = designcraft_doc::ParaAttrs { list_type: list, ..Default::default() };
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: name.into(),
+ based_on: None,
+ next_style: None,
+ para,
+ 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 = "Intro\nfirst\nsecond\none\ntwo\nx = 1\ny = 2\nEnd\n• typed";
+ 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 ["Bullet", "Bullet", "Number", "Number", "Code", "Code"].into_iter().enumerate() {
+ st.paras[i + 1].style = style.into();
+ }
+ let html = story_html(&d, sid);
+ let li = |c: &str, t: &str| format!("<li class=\"{c}\">{t}</li>");
+ assert!(
+ html.contains(&format!(
+ "<ul>\n{}\n{}\n</ul>\n<ol>\n{}\n{}\n</ol>\n",
+ li("bullet", "first"),
+ li("bullet", "second"),
+ li("number", "one"),
+ li("number", "two")
+ )),
+ "{html}"
+ );
+ assert!(html.contains("<pre class=\"code\">x = 1\ny = 2</pre>\n<p class=\"basic-paragraph\">End</p>"), "{html}");
+ assert_eq!(html.matches("<pre").count(), 1, "{html}");
+ // A style without a list type of its own (typed bullets) gets no second marker.
+ st_typed(&mut d, sid);
+ let html = story_html(&d, sid);
+ assert!(html.contains("<ul style=\"list-style:none\">\n<li class=\"typed\">• typed</li>\n</ul>\n"), "{html}");
+ }
+
+ /// #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());