DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #785
Brandon Thomasaa979dab79aa
diff --cc crates/engine/src/cmd/export.rsindex 4effa8bef,7fa6ea3aa..986df19c2--- 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\", 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\", cover?: bool (the first page as the cover image), 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",++ "{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, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative",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})",@@@ -161,10 -164,10 +165,10 @@@ fn export_epub(s: &mut Session, p: &Valmatch p.get("path").and_then(Value::as_str) {Some(path) => {#[cfg(not(target_arch = "wasm32"))]- crate::atomic::write_file(path, &bytes)?;+ crate::io::write_file(path, &bytes).map_err(crate::EngineError::Other)?;- Ok(serde_json::json!({"path": path, "bytes": bytes.len()}))+ Ok(serde_json::json!({"path": path, "bytes": bytes.len(), "warnings": warnings}))}- None => Ok(serde_json::json!({"base64": super::file::base64_encode(&bytes), "bytes": bytes.len()})),+ None => Ok(serde_json::json!({"base64": super::file::base64_encode(&bytes), "bytes": bytes.len(), "warnings": warnings})),}}diff --cc crates/epub/src/lib.rsindex cd14ac5ba,41959af51..d87d39c22--- a/crates/epub/src/lib.rs+++ b/crates/epub/src/lib.rs@@@ -1024,50 -574,6 +1035,51 @@@ 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));++ let name = asset_path("media", a, 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));++ 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 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));++ let name = asset_path("images", a, 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() };++ // Alt text from Object Export Options; without one the image counts as decorative++ // (`alt=""`): a file name read aloud helps nobody.++ let alt = it.alt_text.as_str();+ Some((format!("<img src=\"{}\" alt=\"{}\"/>", xml_attr(&img_src(&name, mime, &a.data)), xml_attr(alt)), false))+}+/// 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).@@@ -1309,266 -816,6 +1337,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);++ 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"));+ }++ 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());