mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 02:22:55 +00:00
craft-html: a fragment keeps its paragraphs' spacing and indents
export_fragment has no style sheet, so a copy pasted into a mail client lost each paragraph's space before and after and its indents. Top-level plain paragraphs and headings now write them as margins and text-indent in points. Only finite values are written, a value that rounds to zero prints as 0 (never -0), and a first-line indent of 0 is left out. List items, code, quotes and table cells are unchanged, and so is export. This moves the copy that WordCraft keeps for its clipboard (storytold/wordcraft#5600) into craft-html.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
use super::{Align, Document, FBlock, FTable, Flow, Fmt, Inline, Kind, Para, VAlign, base64_encode, mime_of, model};
|
||||
use super::{Align, Document, FBlock, FTable, Flow, Fmt, Inline, Kind, Para, Spacing, VAlign, base64_encode, mime_of, model};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Export
|
||||
@@ -237,11 +237,41 @@ fn trim_num(v: f32) -> String {
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
fn para_attrs(p: &Para) -> String {
|
||||
/// A paragraph's spacing and indents as CSS declarations in points: margins for the space before
|
||||
/// and after and the left and right indents, and `text-indent` for a first-line indent (negative:
|
||||
/// hanging). Values that aren't finite are left out, and so is a first-line indent that prints as 0.
|
||||
fn spacing_css(s: &Spacing) -> Vec<String> {
|
||||
// Rounded to the hundredths `trim_num` prints, so a value that prints as 0 compares as 0.
|
||||
// `+ 0.0` turns -0.0 into 0.0, which would otherwise print as "-0". A value too large to
|
||||
// scale stays as it is.
|
||||
let pt = |v: Option<f32>| {
|
||||
v.filter(|v| v.is_finite()).map(|v| {
|
||||
let r = (v * 100.0).round() / 100.0;
|
||||
if r.is_finite() { r + 0.0 } else { v }
|
||||
})
|
||||
};
|
||||
let mut css = Vec::new();
|
||||
for (name, v) in [("margin-top", s.before), ("margin-right", s.right), ("margin-bottom", s.after), ("margin-left", s.left)] {
|
||||
if let Some(v) = pt(v) {
|
||||
css.push(format!("{name}:{}pt", trim_num(v)));
|
||||
}
|
||||
}
|
||||
if let Some(v) = pt(s.first).filter(|v| *v != 0.0) {
|
||||
css.push(format!("text-indent:{}pt", trim_num(v)));
|
||||
}
|
||||
css
|
||||
}
|
||||
|
||||
/// A paragraph's ` style="…"` attribute (empty when it has nothing to say): its alignment, with
|
||||
/// `spaced` its spacing and indents, a page break before it and its shading.
|
||||
fn para_attrs(p: &Para, spaced: bool) -> String {
|
||||
let mut css: Vec<String> = Vec::new();
|
||||
if let Some(a) = align_css(p.align) {
|
||||
css.push(a.to_string());
|
||||
}
|
||||
if spaced {
|
||||
css.extend(spacing_css(&p.spacing));
|
||||
}
|
||||
if p.page_break {
|
||||
css.push("break-before:page;page-break-before:always".to_string());
|
||||
}
|
||||
@@ -251,9 +281,10 @@ fn para_attrs(p: &Para) -> String {
|
||||
if css.is_empty() { String::new() } else { format!(" style=\"{}\"", css.join(";")) }
|
||||
}
|
||||
|
||||
fn para_html(p: &Para) -> String {
|
||||
/// A paragraph, heading or rule as HTML, with `spaced` keeping its spacing and indents.
|
||||
fn para_html(p: &Para, spaced: bool) -> String {
|
||||
let body = inlines_html(&p.inlines);
|
||||
let attrs = para_attrs(p);
|
||||
let attrs = para_attrs(p, spaced);
|
||||
match p.kind {
|
||||
Kind::Heading(n) => format!("<h{n}{attrs}>{body}</h{n}>", n = n.clamp(1, 6)),
|
||||
Kind::Title => format!("<h1{attrs}>{body}</h1>"),
|
||||
@@ -307,7 +338,7 @@ fn table_html(t: &FTable, out: &mut String, depth: usize) {
|
||||
Some(p) => out.push_str(&inlines_html(&p.inlines)),
|
||||
None => {
|
||||
out.push('\n');
|
||||
blocks_html(&c.blocks, out, depth + 1);
|
||||
blocks_html(&c.blocks, out, depth + 1, false);
|
||||
}
|
||||
}
|
||||
out.push_str(&format!("</{tag}>"));
|
||||
@@ -317,7 +348,9 @@ fn table_html(t: &FTable, out: &mut String, depth: usize) {
|
||||
out.push_str("</table>\n");
|
||||
}
|
||||
|
||||
fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) {
|
||||
/// Append `blocks` as HTML. With `spaced`, plain paragraphs and headings write their own spacing
|
||||
/// and indents (for a fragment, which has no style sheet). List items, code and quotes don't.
|
||||
fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize, spaced: bool) {
|
||||
let mut i = 0;
|
||||
while let Some(b) = blocks.get(i) {
|
||||
match b {
|
||||
@@ -356,7 +389,7 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) {
|
||||
top.1 = true;
|
||||
}
|
||||
let body = inlines_html(&q.inlines);
|
||||
let attrs = para_attrs(q);
|
||||
let attrs = para_attrs(q, false);
|
||||
out.push_str(&format!("<li{attrs}>{body}"));
|
||||
i += 1;
|
||||
}
|
||||
@@ -368,11 +401,11 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) {
|
||||
FBlock::Para(p) if p.kind == Kind::Code => {
|
||||
// One `<pre>` per run of code paragraphs whose attributes match: they share the
|
||||
// `<pre>`'s shading, so a different background starts a new block.
|
||||
let attrs = para_attrs(p);
|
||||
let attrs = para_attrs(p, false);
|
||||
out.push_str(&format!("<pre{attrs}><code>"));
|
||||
let mut first = true;
|
||||
while let Some(FBlock::Para(q)) = blocks.get(i) {
|
||||
if q.kind != Kind::Code || q.list.is_some() || para_attrs(q) != attrs {
|
||||
if q.kind != Kind::Code || q.list.is_some() || para_attrs(q, false) != attrs {
|
||||
break;
|
||||
}
|
||||
if !first {
|
||||
@@ -390,14 +423,14 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) {
|
||||
if q.kind != Kind::Quote || q.list.is_some() {
|
||||
break;
|
||||
}
|
||||
out.push_str(¶_html(&Para { kind: Kind::Normal, ..q.clone() }));
|
||||
out.push_str(¶_html(&Para { kind: Kind::Normal, ..q.clone() }, false));
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
}
|
||||
out.push_str("</blockquote>\n");
|
||||
}
|
||||
FBlock::Para(p) => {
|
||||
out.push_str(¶_html(p));
|
||||
out.push_str(¶_html(p, spaced));
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
}
|
||||
@@ -421,11 +454,12 @@ pub fn export(doc: &Document) -> String {
|
||||
}
|
||||
|
||||
/// `doc`'s content as an HTML fragment (no head or style sheet): what a copy puts on the system
|
||||
/// clipboard beside its text, equations as MathML (#816).
|
||||
/// clipboard beside its text, equations as MathML (#816). With no style sheet to give them, its
|
||||
/// plain paragraphs and headings carry their own spacing and indents.
|
||||
pub fn export_fragment(doc: &Document) -> String {
|
||||
let flow = model::from_doc_with(doc, model::FlowOpts { paras: true, ..Default::default() });
|
||||
let mut out = String::from("<meta charset=\"utf-8\">");
|
||||
blocks_html(&flow.blocks, &mut out, 0);
|
||||
blocks_html(&flow.blocks, &mut out, 0, true);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -446,7 +480,7 @@ pub fn export_flow(flow: &Flow, lang: &str) -> String {
|
||||
table{border-collapse:collapse;margin:0.5em 0}\nblockquote{margin:0.5em 2em;font-style:italic;color:#404040}\n\
|
||||
pre{background:#f5f5f5;padding:0.5em;font-family:'Courier New',monospace;font-size:10pt}\n</style>\n</head>\n<body>\n",
|
||||
);
|
||||
blocks_html(&flow.blocks, &mut out, 0);
|
||||
blocks_html(&flow.blocks, &mut out, 0, false);
|
||||
out.push_str("</body>\n</html>\n");
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1598,3 +1598,73 @@ fn zero_alpha_colors_with_none_channels() {
|
||||
let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") };
|
||||
assert_eq!(p2.props.shading, None);
|
||||
}
|
||||
|
||||
/// A copy's HTML has no style sheet, so its top-level paragraphs and headings carry their own
|
||||
/// spacing and indents (as margins and `text-indent`, in points), and a mail client lays the text
|
||||
/// out as the app does. A page saved as HTML doesn't write them.
|
||||
#[test]
|
||||
fn the_fragment_writes_a_paragraphs_spacing_and_indents() {
|
||||
let chr = craft_wordmodel::CharProps::default();
|
||||
let mut spaced = craft_wordmodel::Paragraph::with_text("Spaced", chr.clone());
|
||||
spaced.props.space_before = Some(6.0);
|
||||
spaced.props.space_after = Some(12.0);
|
||||
spaced.props.indent_left = Some(36.0);
|
||||
spaced.props.indent_first = Some(-18.0);
|
||||
let mut plain = craft_wordmodel::Paragraph::with_text("Plain", chr.clone());
|
||||
plain.props.indent_right = Some(-0.0);
|
||||
plain.props.indent_first = Some(0.0);
|
||||
plain.props.space_after = Some(f32::NAN);
|
||||
// Values that round to zero print as 0 (never "-0"), and a first-line indent that does is left out.
|
||||
let mut tiny = craft_wordmodel::Paragraph::with_text("Tiny", chr.clone());
|
||||
tiny.props.indent_left = Some(-0.004);
|
||||
tiny.props.indent_first = Some(0.001);
|
||||
let mut heading = craft_wordmodel::Paragraph::with_text("Heading", chr).styled("Heading1");
|
||||
heading.props.space_before = Some(24.0);
|
||||
let mut d = Document::new();
|
||||
d.body = vec![
|
||||
craft_wordmodel::para_block(spaced),
|
||||
craft_wordmodel::para_block(plain),
|
||||
craft_wordmodel::para_block(tiny),
|
||||
craft_wordmodel::para_block(heading),
|
||||
];
|
||||
let fragment = export_fragment(&d);
|
||||
assert!(fragment.contains("<p style=\"margin-top:6pt;margin-bottom:12pt;margin-left:36pt;text-indent:-18pt\">Spaced</p>"), "{fragment}");
|
||||
assert!(fragment.contains("<p style=\"margin-right:0pt\">Plain</p>"), "{fragment}");
|
||||
assert!(fragment.contains("<p style=\"margin-left:0pt\">Tiny</p>"), "{fragment}");
|
||||
assert!(fragment.contains("<h1 style=\"margin-top:24pt\">Heading</h1>"), "{fragment}");
|
||||
let page = export(&d);
|
||||
assert!(!page.contains("margin-") && !page.contains("text-indent"), "{page}");
|
||||
}
|
||||
|
||||
/// Quotes, list items and code keep the fragment's plain markup, while a paragraph between them
|
||||
/// still writes its spacing.
|
||||
#[test]
|
||||
fn the_fragment_spaces_only_top_level_paragraphs_and_headings() {
|
||||
let chr = craft_wordmodel::CharProps::default();
|
||||
let mut quote = craft_wordmodel::Paragraph::with_text("Quoted", chr.clone()).styled("Quote");
|
||||
quote.props.space_after = Some(10.0);
|
||||
let mut body = craft_wordmodel::Paragraph::with_text("Body", chr.clone());
|
||||
body.props.space_after = Some(8.0);
|
||||
let mut d = Document::new();
|
||||
let num = std::sync::Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::ListKind::Bullet);
|
||||
let mut item = craft_wordmodel::Paragraph::with_text("Item", chr).styled("ListParagraph");
|
||||
item.props.numbering = Some(craft_wordmodel::props::NumRef { num, level: 0 });
|
||||
item.props.space_after = Some(6.0);
|
||||
d.body = vec![craft_wordmodel::para_block(quote), craft_wordmodel::para_block(body), craft_wordmodel::para_block(item)];
|
||||
let fragment = export_fragment(&d);
|
||||
assert!(fragment.contains("<blockquote>\n<p>Quoted</p>\n</blockquote>"), "{fragment}");
|
||||
assert!(fragment.contains("<p style=\"margin-bottom:8pt\">Body</p>"), "{fragment}");
|
||||
assert!(fragment.contains("<ul><li>Item</li></ul>"), "{fragment}");
|
||||
}
|
||||
|
||||
/// Code blocks and the paragraphs of a table cell keep the fragment's plain markup, whatever their
|
||||
/// spacing.
|
||||
#[test]
|
||||
fn the_fragment_leaves_code_and_table_cells_unspaced() {
|
||||
let d = import(
|
||||
"<table><tr><td><p style='margin-left:20pt'>One</p><p style='margin-left:20pt'>Two</p></td></tr></table> <pre style='margin-left:30pt'>code</pre>",
|
||||
);
|
||||
let fragment = export_fragment(&d);
|
||||
assert!(fragment.contains("One") && fragment.contains("code"), "{fragment}");
|
||||
assert!(!fragment.contains("margin-"), "{fragment}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user