Skip to content

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

Merge #779: EPUB/HTML: anchored objects are exported where they are anchored

aionggd6ecd3d2b45d
diff --cc crates/epub/src/lib.rs
index 8f2467417,ebb9d3de5..ce51eb8ab
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -13,11 -11,7 +13,11 @@@ use std::collections::BTreeMap
use std::fmt::Write as _;
use std::io::Write;
-use designcraft_doc::{Align, CharAttrs, CharProps, Content, Document, Item, ItemId, ParaProps, SpreadRef, StoryId, Styles, story};
+use designcraft_doc::geom::{Affine, Rect};
+use designcraft_doc::{
- Align, CharAttrs, CharProps, Content, Document, ENDNOTE_REF, FOOTNOTE_REF, Item, ItemId, ParaProps, SpreadRef, Story, StoryId, Styles, Table,
++ Align, AnchorPosition, AnchoredObject, CharAttrs, CharProps, Content, Document, ENDNOTE_REF, FOOTNOTE_REF, Item, ItemId, OBJECT_MARK, ParaProps, SpreadRef, Story, StoryId, Styles, Table,
+ story,
+};
#[derive(Clone, Debug)]
pub struct EpubOptions {
@@@ -585,96 -425,30 +585,106 @@@ fn class_selector(tag: &str, class: &st
Some(selector)
}
-/// One story as XHTML paragraphs (anchored objects left out; see [`story_html_with`]).
-pub fn story_html(doc: &Document, sid: StoryId) -> String {
- story_html_with(doc, sid, &mut |_| String::new())
-}
-
-/// One story as XHTML paragraphs, each anchored object written where it is anchored as the
-/// markup `object` returns for it.
-fn story_html_with(doc: &Document, sid: StoryId, object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String) -> 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 _ = write!(out, "<{tag} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });
- if text_empty {
- out.push_str("&#160;");
+/// 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> {
++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>,
+}
+
- impl<'a> StoryWriter<'a> {
- fn new(doc: &'a Document, epub: bool) -> Self {
++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(),
+ }
+ }
+
+ 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 {
+ let Some(st) = self.doc.story(sid) else { return String::new() };
+ 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.
+ fn paragraphs(&mut self, st: &Story, depth: usize, lead: &str, out: &mut String) {
+ let doc = self.doc;
+ let mut lead = lead;
+ for (r, pf) in st.para_ranges().into_iter().zip(&st.paras) {
+ 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 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 { "" });
+ 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);
+ }
+ let _ = writeln!(out, "</{tag}>");
+ out.push_str(&after);
+ }
+ if let Some(t) = table
+ && depth < MAX_DEPTH
+ {
+ self.table(t, depth + 1, 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;
}
@@@ -682,26 -456,35 +692,35 @@@
if f.over.conditions.as_deref().is_some_and(|c| doc.conditions_hide(c)) || f.over.change == Some(designcraft_doc::ChangeMark::Deleted) {
continue;
}
- let raw = &st.text[a..b];
- // Text with variables substituted; each anchored object's markup in place of its mark.
- let text = |seg: &str| {
- if seg.chars().any(|c| designcraft_doc::vars::var_index(c).is_some()) {
- let sub: String = seg
- .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(seg)
- }
- };
- let mut mark = st.text.get(..a).map_or(0, |t| t.matches(designcraft_doc::OBJECT_MARK).count());
+ let Some(raw) = st.text.get(a..b) else { continue };
let mut t = String::new();
- for (i, seg) in raw.split(designcraft_doc::OBJECT_MARK).enumerate() {
- if i > 0 {
- if let Some(o) = st.objects.get(mark) {
- t.push_str(&object(o));
+ let mut seg_start = 0;
++ // Index of the next anchored object: marks count from the story start, as
++ // `Story::object_at` counts them (counted once, at the run's first mark).
++ let mut mark: Option<usize> = None;
+ for (i, c) in raw.char_indices() {
- if c != FOOTNOTE_REF && c != ENDNOTE_REF {
++ if c != FOOTNOTE_REF && c != ENDNOTE_REF && c != OBJECT_MARK {
+ continue;
+ }
+ t.push_str(&run_text(doc, raw.get(seg_start..i).unwrap_or_default()));
+ seg_start = i + c.len_utf8();
- if depth < MAX_DEPTH {
++ if c == OBJECT_MARK {
++ let k = mark.unwrap_or_else(|| st.text.get(..a).map_or(0, |t| t.matches(OBJECT_MARK).count()));
++ mark = Some(k.saturating_add(1));
++ if let Some(o) = st.objects.get(k) {
++ t.push_str(&self.object(o));
++ }
++ } else if depth < MAX_DEPTH {
+ if c == FOOTNOTE_REF {
+ self.footnote(st, a + i, depth, &mut t, after);
+ } else {
+ self.endnote(st, a + i, depth, &mut t);
}
- mark += 1;
}
- t.push_str(&text(seg));
}
+ t.push_str(&run_text(doc, raw.get(seg_start..).unwrap_or_default()));
let (ctag, cls) = if f.style != story::NO_CHAR_STYLE {
- let (tag, class) = export_mapping(&doc.styles, &f.style, true, &cc);
+ let (tag, class) = export_mapping(&doc.styles, &f.style, true, &self.cc);
(tag, format!(" class=\"{}\"", xml_attr(&class)))
} else {
("span", String::new())
@@@ -714,139 -497,9 +733,205 @@@
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).story(sid)
++ StoryWriter::new(doc, true, None).story(sid)
}
/// Reading order of document content: (page, y, x) of each story's first frame and of graphics.
@@@ -953,19 -583,61 +1038,23 @@@ fn ext(mime: &str) -> &'static str
}
}
-/// The markup for one graphic item: an `<img>`, or an HTML5 player for video and sound (with
-/// `true`), its file registered in `images` under the name `img_src` is given. `None` for an
-/// item that isn't a graphic or whose asset has no data.
-fn graphic_html<'a>(
- doc: &'a Document,
- it: &Item,
- images: &mut BTreeMap<String, (&'a str, &'a [u8])>,
- img_src: &dyn Fn(&str, &str, &[u8]) -> String,
-) -> Option<(String, bool)> {
- 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 = format!("media/{}.{}", g.asset.0, ext(mime));
- 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 = 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 markup = format!("<{kind} src=\"{}\"{attrs}>{}</{kind}>", xml_attr(&img_src(&name, mime, &a.data)), xml_text(&a.name));
- return Some((markup, true));
- }
- 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 = if it.alt_text.is_empty() { a.name.as_str() } else { it.alt_text.as_str() };
- Some((format!("<img src=\"{}\" alt=\"{}\"/>", xml_attr(&img_src(&name, mime, &a.data)), xml_attr(alt)), false))
++/// 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)>,
++ /// 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,
- epub: bool,
-- img_src: &dyn Fn(&str, &str, &[u8]) -> String,
--) -> (String, BTreeMap<String, (&'a str, &'a [u8])>, Vec<(String, String)>) {
++/// (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);
++ let mut writer = StoryWriter::new(doc, epub, Some(img_src));
let mut body = String::new();
-- let mut images: BTreeMap<String, (&str, &[u8])> = BTreeMap::new();
let mut toc: Vec<(String, String)> = Vec::new();
for (k, b) in order.iter().enumerate() {
match b {
@@@ -982,51 -651,38 +1071,17 @@@
toc.push((anchor.clone(), first));
}
}
- // Anchored objects go where they are anchored: their graphics in the text, an
- // above-line object as a block of its own.
- let mut object = |o: &designcraft_doc::AnchoredObject| {
- let mut out = String::new();
- o.item.walk(&mut |it| {
- if let Some((markup, _)) = graphic_html(doc, it, &mut images, img_src) {
- out.push_str(&markup);
- }
- });
- match &o.position {
- designcraft_doc::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,
- }
- };
- let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", story_html_with(doc, *sid, &mut object));
+ let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", writer.story(*sid));
}
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() {
+ let Some(it) = doc.item(*iid) else { continue };
- let Some((markup, media)) = graphic_html(doc, it, &mut images, img_src) else { continue };
++ let Some((markup, media)) = writer.graphic(it) else { continue };
+ if media {
+ let _ = writeln!(body, "<figure>{markup}</figure>");
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 = asset_path("media", a, 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 = asset_path("images", pa, 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)
- );
- continue;
- }
- let name = asset_path("images", a, mime);
- 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.
- let alt = doc.item(*iid).map_or("", |i| i.alt_text.as_str());
// 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));
@@@ -1040,31 -695,7 +1094,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()));
+ }
+ body.push_str(&endnotes);
+ }
- (body, images, toc)
++ Body { html: body, images: writer.images, toc, no_alt: writer.no_alt }
+}
+
- /// Placed images (not video or sound) without alt text, by asset name: they are exported as
++/// 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> {
- let mut out = Vec::new();
- for b in reading_order(doc) {
- let Block::Image(iid) = b else { continue };
- let Some(it) = doc.item(iid) else { continue };
- let Content::Graphic(g) = &it.content else { continue };
- let Some(a) = doc.assets.get(&g.asset) else { continue };
- if !a.data.is_empty() && designcraft_doc::media_kind(safe_mime(&a.mime)).is_none() && it.alt_text.trim().is_empty() {
- out.push(a.name.clone());
- }
- }
- out
++ body_html(doc, true, &|name, _, _| name.to_string()).no_alt
}
/// Options for [`export_html`].
@@@ -1082,7 -711,7 +1126,7 @@@ pub fn export_html(doc: &Document, opts
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, false, &|_, mime, data| format!("data:{mime};base64,{}", base64(data)));
- let (body, _, _) = body_html(doc, &|_, mime, data| format!("data:{mime};base64,{}", base64(data)));
++ let body = body_html(doc, false, &|_, mime, data| format!("data:{mime};base64,{}", base64(data))).html;
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),
@@@ -1107,9 -736,8 +1151,9 @@@ 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());
+ let id = identifier(doc, opts, &title);
+ let modified = modified(doc, opts);
- let (body, images, toc) = body_html(doc, true, &|name, _, _| name.to_string());
++ 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",
@@@ -1224,52 -839,62 +1268,116 @@@ 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/{}.png\" alt=\"{alt}\"/>", aid.0);
++ 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/{}.png", aid.0)).is_ok(), "the image is in the package");
++ 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:?}");
+ }
+
#[test]
fn styles_whose_names_slug_alike_keep_their_own_classes() {
let mut d = Document::new(&NewDocument::default());