DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #791
Brandon Thomas9ee2eb2c7a44
diff --cc crates/epub/src/lib.rsindex 162686eb0,e9cb16cec..5cdf14184--- a/crates/epub/src/lib.rs+++ b/crates/epub/src/lib.rs@@@ -425,14 -443,14 +443,20 @@@ fn class_selector(tag: &str, class: &stSome(selector)}-/// One story as XHTML paragraphs.+/// 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())- story_html_in(doc, sid, None)++ story_html_with(doc, sid, None, &mut |_| String::new())}-/// [`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 {+/// 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 {++/// markup `object` returns for it. With `ids`, every heading (`h1`–`h6`) gets an `id`,++/// `{prefix}-p{paragraph index}`: the targets of the table of contents.++fn story_html_with(++ doc: &Document,++ sid: StoryId,++ ids: Option<&str>,++ 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();@@@ -446,31 -459,15 +470,38 @@@// Export Tagging: the style's element and class.let (tag, class) = export_mapping(&doc.styles, &pf.style, false, &pc);let text_empty = st.text[r.clone()].trim().is_empty();- let rtl = doc.styles.resolve_para(pf).0.direction == designcraft_doc::TextDirection::RightToLeft;- let id = match ids {- Some(prefix) if heading_level(tag).is_some() => format!(" id=\"{prefix}-p{pi}\""),- _ => String::new(),- };- if ids.is_some() && heading_level(tag) == Some(1) {- out.push_str(CHAPTER_MARK);+ 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));+ }+ 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 ids {++ Some(prefix) if heading_level(tag).is_some() => format!(" id=\"{prefix}-p{pi}\""),++ _ => String::new(),++ };++ if ids.is_some() && heading_level(tag) == Some(1) {++ out.push_str(CHAPTER_MARK);++ }++ let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });}- let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });if text_empty {out.push_str(" ");}@@@ -682,46 -746,50 +849,38 @@@ fn body_html<'a>match b {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", story_html_in(doc, *sid, heading_ids.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);+ // 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);}- }- 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))));+ });+ 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 _ = writeln!(- body,- "<figure><{kind} src=\"{}\"{attrs}>{}</{kind}></figure>",- xml_attr(&img_src(&name, mime, &a.data)),- xml_text(&a.name)- );+ };- 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", story_html_with(doc, *sid, heading_ids.then_some(anchor.as_str()), &mut object));+ }+ Block::Image(iid) => {+ let Some(it) = doc.item(*iid) else { continue };+ let Some((markup, media)) = graphic_html(doc, it, &mut images, img_src) 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));@@@ -878,117 -971,155 +1061,266 @@@ 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)),+ }),+ );+ 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],+ });+ 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);+ 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);+ 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");+ 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"));+ }++ 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 = |f: &str, t: &str, l: &str| format!("<a href=\"{f}#{t}\">{l}</a>");+ // Each h1 starts a chapter file (#768).+ let want = format!(+ "<h1>Inhoud</h1><ol><li>{}<ol><li>{}</li></ol></li><li>{}</li></ol>",+ link("content.xhtml", "s0-p0", "One"),+ link("content.xhtml", "s0-p2", "One point one"),+ link("content2.xhtml", "s0-p4", "Two")+ );+ assert!(nav.contains(&want), "{nav}");+ assert!(!nav.contains("Text after the figure"), "{nav}");+ 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("content.xhtml", "s0", "Opening"))), "{nav}");+ // A heading shallower than the one before it but deeper than its parent stays under the+ // parent: h1 A, h3 B, h2 C nest B and C under A.+ let e = |t: &str, l: u8| (t.to_string(), t.to_string(), l);+ let l = |t: &str| link("content.xhtml", t, t);+ assert_eq!(+ nav_list(&[e("A", 1), e("B", 3), e("C", 2), e("D", 1)], &BTreeMap::new()),+ format!("<li>{}<ol><li>{}</li><li>{}</li></ol></li><li>{}</li>", l("A"), l("B"), l("C"), l("D"))+ );+ assert_eq!(+ nav_list(&[e("A", 1), e("B", 2), e("C", 3), e("D", 1)], &BTreeMap::new()),+ format!("<li>{}<ol><li>{}<ol><li>{}</li></ol></li></ol></li><li>{}</li>", l("A"), l("B"), l("C"), l("D"))+ );+ }++ /// #768: the book is split into one file per chapter, before each h1, with well-formed+ /// sections; the spine and manifest list the files in order.+ #[test]+ fn chapters_are_split_at_h1() {+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ let lid = d.default_layer();+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {+ name: "Chapter".into(),+ based_on: None,+ next_style: None,+ para: Default::default(),+ chars: CharAttrs::default(),+ shortcut: String::new(),+ });+ d.styles_mut().export_tags.insert("p:Chapter".into(), designcraft_doc::ExportTag { tag: "h1".into(), class: String::new() });+ // A title page without a heading, then a story that opens with a chapter and has a+ // second one in the middle.+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Title page", ParaFormat::default()).unwrap();+ let (_, sid) = d+ .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 400.0), lid, "One\nFirst text\nTwo\nSecond text", ParaFormat::default())+ .unwrap();+ let st = d.story_mut(sid).unwrap();+ st.paras[0].style = "Chapter".into();+ st.paras[2].style = "Chapter".into();+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap();+ let mut read = |path: &str| {+ let mut s = String::new();+ z.by_name(path).unwrap().read_to_string(&mut s).unwrap();+ s+ };+ let (c1, c2, c3) = (read("OEBPS/content.xhtml"), read("OEBPS/content2.xhtml"), read("OEBPS/content3.xhtml"));+ assert!(c1.contains("Title page") && !c1.contains("One"), "{c1}");+ assert!(c2.contains("<section id=\"s1\">\n<h1 id=\"s1-p0\"") && c2.contains("First text") && !c2.contains("Two"), "{c2}");+ assert!(c3.contains("<section>\n<h1 id=\"s1-p2\""), "{c3}");+ for c in [&c1, &c2, &c3] {+ assert_eq!(c.matches("<section").count(), c.matches("</section>").count(), "{c}");+ assert!(!c.contains(CHAPTER_MARK));+ }+ let opf = read("OEBPS/content.opf");+ assert!(opf.contains("<itemref idref=\"content\"/>\n<itemref idref=\"content2\"/>\n<itemref idref=\"content3\"/>\n</spine>"), "{opf}");+ assert!(opf.contains("<item id=\"content3\" href=\"content3.xhtml\""), "{opf}");+ let nav = read("OEBPS/nav.xhtml");+ assert!(nav.contains("href=\"content2.xhtml#s1-p0\"") && nav.contains("href=\"content3.xhtml#s1-p2\""), "{nav}");+ assert!(z.by_name("OEBPS/content4.xhtml").is_err());+ // HTML stays one page, without the marks.+ let html = export_html(&d, &HtmlOptions::default());+ assert!(!html.contains(CHAPTER_MARK) && html.contains("Second text"));+ }++ /// Note links stay working across chapter files: a link whose target ended up in another+ /// file (endnotes end the book) names that file; one in its own file stays as it is.+ #[test]+ fn note_links_point_at_the_chapter_file_of_their_target() {+ let files: BTreeMap<String, String> =+ [("enref-1", "content.xhtml"), ("fn-1", "content.xhtml"), ("fnref-1", "content.xhtml"), ("en-1", "content2.xhtml")]+ .into_iter()+ .map(|(id, f)| (id.to_string(), f.to_string()))+ .collect();+ let first = "<p>First<a id=\"enref-1\" href=\"#en-1\">1</a><a id=\"fnref-1\" href=\"#fn-1\">*</a></p><aside id=\"fn-1\"><a href=\"#fnref-1\">*</a></aside><a href=\"#gone\">x</a>";+ assert_eq!(+ link_across_chapters(first, "content.xhtml", &files),+ "<p>First<a id=\"enref-1\" href=\"content2.xhtml#en-1\">1</a><a id=\"fnref-1\" href=\"#fn-1\">*</a></p><aside id=\"fn-1\"><a href=\"#fnref-1\">*</a></aside><a href=\"#gone\">x</a>"+ );+ let last = "<li id=\"en-1\"><a href=\"#enref-1\">1</a> End note</li>";+ assert_eq!(link_across_chapters(last, "content2.xhtml", &files), "<li id=\"en-1\"><a href=\"content.xhtml#enref-1\">1</a> End note</li>");+ }++ #[test]+ fn split_chapters_keeps_sections_well_formed() {+ let m = CHAPTER_MARK;+ assert_eq!(split_chapters("<section id=\"s0\">\n<p>a</p>\n</section>\n"), vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n"]);+ assert_eq!(+ split_chapters(&format!("<section id=\"s0\">\n{m}<h1>A</h1>\n</section>\n")),+ vec!["<section id=\"s0\">\n<h1>A</h1>\n</section>\n"]+ );+ assert_eq!(+ split_chapters(&format!("<section id=\"s0\">\n<p>a</p>\n{m}<h1>B</h1>\n</section>\n")),+ vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n", "<section>\n<h1>B</h1>\n</section>\n"]+ );+ assert_eq!(split_chapters(""), vec![String::new()]);+ }+#[test]fn styles_whose_names_slug_alike_keep_their_own_classes() {let mut d = Document::new(&NewDocument::default());