DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #780: EPUB/HTML: list paragraphs share one ul/ol, and pre lines one block
aionggefbd516ee721
diff --cc crates/epub/src/lib.rsindex ce51eb8ab,06745d16c..948f35a9f--- a/crates/epub/src/lib.rs+++ b/crates/epub/src/lib.rs@@@ -585,106 -425,52 +585,154 @@@ fn class_selector(tag: &str, class: &stSome(selector)}-/// One story as XHTML paragraphs.-pub fn story_html(doc: &Document, sid: StoryId) -> 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();- // 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.- let mut list: Option<&str> = None;- let mut pre: Option<(String, bool)> = None;- 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 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 {- if let Some(l) = list {- let _ = writeln!(out, "</{}>", l.split(' ').next().unwrap_or(l));++/// 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));++ }++}++++/// 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>,+}++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.++ ///++ /// 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) {+ 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 { "" });++ 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 { "" });++ }+ out.push_str(lead);+ if lead.is_empty() && text.trim().is_empty() {+ out.push_str(" ");+ }+ lead = "";+ let mut after = String::new();+ if !only_table {+ self.runs(st, r, depth, out, &mut after);+ }- let _ = writeln!(out, "</{tag}>");++ 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}>");++ }+ out.push_str(&after);}- if let Some(l) = list_tag {- let _ = writeln!(out, "<{l}>");+ if let Some(t) = table+ && depth < MAX_DEPTH+ {+ self.table(t, depth + 1, out);}- list = list_tag;- }- if continues_pre {- out.push('\n');- } else {- let _ = write!(out, "<{tag} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });- }- if text_empty {- out.push_str(" ");}++ 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;}@@@ -1268,116 -827,61 +1316,171 @@@ mod testsassert!(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}");+ }+#[test]fn styles_whose_names_slug_alike_keep_their_own_classes() {let mut d = Document::new(&NewDocument::default());