From 996a6b50427aa44f497746fc5656ee81f2408171 Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Mon, 16 Nov 2026 23:30:48 -0300 Subject: [PATCH] craft-html: container background does not leak into character shading (#1786) (#1803) --- crates/flow/src/from_doc.rs | 10 +- crates/flow/tests/round_trip.rs | 22 + crates/html/src/doc.rs | 2 +- crates/html/src/doc/builder.rs | 110 ++++- crates/html/src/doc/css.rs | 467 +++++++++++++++++- crates/html/src/doc/export.rs | 77 ++- crates/html/src/doc/tests.rs | 831 ++++++++++++++++++++++++++++++++ 7 files changed, 1497 insertions(+), 22 deletions(-) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index ee9158280..549602ec5 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -197,7 +197,7 @@ fn para_extra(doc: &Document, p: &craft_wordmodel::props::ParaProps) -> Option Vec { if c == PAGE_BREAK { if !hidden { out.push_text(&std::mem::take(&mut buf), &f); + let extra = out.extra.as_ref().and_then(|x| { + let mut x = (**x).clone(); + x.drop_cap = None; + x.drop_cap_distance = None; + (x != craft_wordmodel::props::ParaProps::default()).then(|| Box::new(x)) + }); let next = Para { kind, list: None, @@ -562,7 +568,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { mark_ins: None, mark_del: None, fmt_change: None, - extra: None, + extra, mark: None, kept: None, wrap: None, diff --git a/crates/flow/tests/round_trip.rs b/crates/flow/tests/round_trip.rs index 33a508485..9be4213d5 100644 --- a/crates/flow/tests/round_trip.rs +++ b/crates/flow/tests/round_trip.rs @@ -99,3 +99,25 @@ fn pictures_are_sniffed_and_sized_from_their_headers() { let wide = make_img(PNG.to_vec(), Some(1000.0), Some(500.0), "").unwrap(); assert_eq!((wide.w, wide.h), (468.0, 234.0)); } + +#[test] +fn drop_cap_not_repeated_after_page_break() { + let mut doc = craft_wordmodel::Document::default(); + let mut para = craft_wordmodel::Paragraph::with_text("Before\x0cAfter", craft_wordmodel::props::CharProps::default()); + para.props.drop_cap = Some(3); + para.props.drop_cap_distance = Some(72.0); + para.props.shading = Some(craft_wordmodel::Rgb(255, 0, 0)); + doc.body = vec![std::sync::Arc::new(craft_wordmodel::Block::Para(para))]; + + let flow = craft_flow::from_doc_with(&doc, craft_flow::FlowOpts { paras: true, ..Default::default() }); + let paras: Vec<_> = flow.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p) } else { None }).collect(); + assert_eq!(paras.len(), 2); + // First paragraph keeps drop cap and shading + assert_eq!(paras[0].extra.as_ref().and_then(|x| x.drop_cap), Some(3)); + assert_eq!(paras[0].extra.as_ref().and_then(|x| x.drop_cap_distance), Some(72.0)); + assert_eq!(paras[0].extra.as_ref().and_then(|x| x.shading), Some(craft_wordmodel::Rgb(255, 0, 0))); + // Continuation clears drop cap, but preserves shading + assert_eq!(paras[1].extra.as_ref().and_then(|x| x.drop_cap), None); + assert_eq!(paras[1].extra.as_ref().and_then(|x| x.drop_cap_distance), None); + assert_eq!(paras[1].extra.as_ref().and_then(|x| x.shading), Some(craft_wordmodel::Rgb(255, 0, 0))); +} diff --git a/crates/html/src/doc.rs b/crates/html/src/doc.rs index 56b8aabbc..c8598639e 100644 --- a/crates/html/src/doc.rs +++ b/crates/html/src/doc.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use craft_wordmodel::props::LineSpacing; use craft_wordmodel::props::VAlign; -use craft_wordmodel::{Align, Document}; +use craft_wordmodel::{Align, Document, Rgb}; use craft_flow::{ self as model, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, ListInfo, Meta, Para, Spacing, base64_encode, data_uri, make_img, mime_of, diff --git a/crates/html/src/doc/builder.rs b/crates/html/src/doc/builder.rs index 32ba2a7f3..68bb7d8db 100644 --- a/crates/html/src/doc/builder.rs +++ b/crates/html/src/doc/builder.rs @@ -1,7 +1,7 @@ use super::css::{apply_style, css_len_pt, strip_important}; use super::import::{PAGE_FONT, PAGE_HEADING_SIZES, collapse_ws}; use super::{ - Align, Arc, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, LineSpacing, ListInfo, Meta, Para, Spacing, VAlign, data_uri, make_img, model, + Align, Arc, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, LineSpacing, ListInfo, Meta, Para, Rgb, Spacing, VAlign, data_uri, make_img, model, parse_color, }; @@ -31,6 +31,11 @@ struct El { name: String, kind: ElKind, fmt: Fmt, + /// Block or container background declared on this element (e.g. div, p, pre, table, cell), + /// kept separate from character shading (`fmt.background`) so child elements can explicitly + /// inherit it (`background: inherit` / `background-color: inherit`) and table cells can + /// resolve shading through transparent row groups or rows (#1786). + block_background: Option, /// Margins, indents and line height its CSS states (blocks only; they don't inherit; on a /// page's spans, their margins). spacing: Spacing, @@ -54,6 +59,7 @@ struct TableB { struct ElementStyle { fmt: Fmt, + block_background: Option, align: Option, preserve: bool, page_break: bool, @@ -650,6 +656,16 @@ impl<'r> Builder<'r> { } let pb_before = self.stack.iter_mut().rev().take_while(|e| e.kind != ElKind::Cell).any(|e| std::mem::take(&mut e.page_break)); p.page_break = pb_before || std::mem::take(&mut self.pending_page_break); + let block_shading = self + .stack + .iter() + .rev() + .take_while(|e| e.kind != ElKind::Cell && e.kind != ElKind::Table) + .filter(|e| self.page || !matches!(e.name.as_str(), "body" | "html")) + .find_map(|e| e.block_background); + if let Some(bg) = block_shading { + p.extra.get_or_insert_with(Default::default).shading = Some(bg); + } self.para = Some(p); } self.para.get_or_insert_with(Para::default) @@ -700,6 +716,35 @@ impl<'r> Builder<'r> { && prev.list.is_some() && prev.list.map(|l| l.level) == level { + let prev_bg = prev.extra.as_ref().and_then(|x| x.shading); + let cont_bg = p.extra.as_ref().and_then(|x| x.shading); + if prev_bg != cont_bg { + if let Some(bg) = prev_bg { + for inline in &mut prev.inlines { + let fmt = match inline { + Inline::Text(_, fmt) | Inline::Ruby { fmt, .. } => fmt, + _ => continue, + }; + if fmt.background.is_none() { + fmt.background = Some(bg); + } + } + if let Some(extra) = &mut prev.extra { + extra.shading = None; + } + } + if let Some(bg) = cont_bg { + for inline in &mut p.inlines { + let fmt = match inline { + Inline::Text(_, fmt) | Inline::Ruby { fmt, .. } => fmt, + _ => continue, + }; + if fmt.background.is_none() { + fmt.background = Some(bg); + } + } + } + } prev.push_text("\n", &Fmt::default()); prev.inlines.extend(p.inlines); return; @@ -933,6 +978,11 @@ impl<'r> Builder<'r> { { self.pop_to(k); } + if matches!(name, "tbody" | "thead" | "tfoot") + && let Some(k) = self.find_open(|e| matches!(e.name.as_str(), "tbody" | "thead" | "tfoot"), |e| e.kind == ElKind::Table) + { + self.pop_to(k); + } if is_table_part && !self.tables.is_empty() { if matches!(name, "td" | "th") && let Some(k) = self.find_open(|e| e.kind == ElKind::Cell, |e| matches!(e.kind, ElKind::Table | ElKind::Tr)) @@ -1049,11 +1099,34 @@ impl<'r> Builder<'r> { fmt.color.get_or_insert(craft_wordmodel::Rgb(0, 0, 0)); fmt.size = PAGE_HEADING_SIZES.get(usize::from(n.clamp(1, 6)) - 1).copied(); } - apply_style(css, &mut fmt, &mut align, &mut preserve, &mut page_break, &mut page_break_after); + if kind != ElKind::Inline { + // CSS background does not inherit from inline ancestors to non-inline elements (#1786). + // HTML bgcolor presentational attribute supplies the initial background, which can be + // overridden or cleared by CSS declarations in apply_style. + fmt.background = attr(attrs, "bgcolor").and_then(parse_color); + } + let parent_bg = self + .stack + .last() + .and_then(|e| if !self.page && matches!(e.name.as_str(), "body" | "html") { None } else { e.fmt.background.or(e.block_background) }); + apply_style(css, &mut fmt, &mut align, &mut preserve, &mut page_break, &mut page_break_after, parent_bg); if kind == ElKind::Pre { preserve = true; } - ElementStyle { fmt, align, preserve, page_break, page_break_after } + // CSS background-color does not inherit to child text runs; container elements (div, p, + // pre, table, row groups, cells, etc.) do not set character shading (#1786). Container + // backgrounds are saved to `block_background` for paragraph shading on block containers, + // explicit child inheritance (`background: inherit`), and table cell shading, while + // character shading `fmt.background` is kept `None`. + let block_background = if kind != ElKind::Inline { fmt.background.take() } else { None }; + let has_root_bg = + block_background.is_some() || self.stack.iter().any(|e| matches!(e.name.as_str(), "body" | "html") && e.block_background.is_some()); + if !self.page && matches!(name, "body" | "html") && has_root_bg { + // A pasted fragment drops the root background; its foreground was chosen for that + // background, so drop it too rather than painting light text on the page default. + fmt.color = None; + } + ElementStyle { fmt, block_background, align, preserve, page_break, page_break_after } } pub(super) fn start(&mut self, name: &str, attrs: &[(String, String)], self_close: bool) { @@ -1089,7 +1162,7 @@ impl<'r> Builder<'r> { self.flush(); } let css = self.css_of(name, attrs); - let ElementStyle { mut fmt, align, preserve, page_break, page_break_after } = self.element_style(name, attrs, kind, &css); + let ElementStyle { mut fmt, block_background, align, preserve, page_break, page_break_after } = self.element_style(name, attrs, kind, &css); match kind { ElKind::Table => self.tables.push(TableB { rows: Vec::new(), row: None, bordered: declares_border(attrs, &css, true) }), ElKind::Tr => { @@ -1115,7 +1188,20 @@ impl<'r> Builder<'r> { } let num = |k: &str| attr(attrs, k).and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 63)); let colspan = num("colspan").unwrap_or(1); - let shading = attr(attrs, "bgcolor").and_then(parse_color).or(fmt.background); + let shading = block_background.or_else(|| { + for e in self.stack.iter().rev() { + if !self.page && matches!(e.name.as_str(), "body" | "html") { + continue; + } + if let Some(bg) = e.block_background { + return Some(bg); + } + if e.kind == ElKind::Cell { + break; + } + } + None + }); let mut valign = attr(attrs, "valign").and_then(|v| match v.trim().to_ascii_lowercase().as_str() { "top" => Some(VAlign::Top), "middle" | "center" => Some(VAlign::Center), @@ -1153,7 +1239,19 @@ impl<'r> Builder<'r> { let spacing = if (kind != ElKind::Inline || self.page) && !matches!(name, "body" | "html") { block_spacing(&css) } else { Spacing::default() }; let auto_margins = self.page && (name == "p" || matches!(kind, ElKind::Heading(_))); - self.stack.push(El { name: name.to_string(), kind, fmt, spacing, auto_margins, align, preserve, page_break, page_break_after, used: false }); + self.stack.push(El { + name: name.to_string(), + kind, + fmt, + block_background, + spacing, + auto_margins, + align, + preserve, + page_break, + page_break_after, + used: false, + }); } pub(super) fn end(&mut self, name: &str) { diff --git a/crates/html/src/doc/css.rs b/crates/html/src/doc/css.rs index 9dc6d7526..b5b230dc8 100644 --- a/crates/html/src/doc/css.rs +++ b/crates/html/src/doc/css.rs @@ -1,6 +1,6 @@ use super::builder::decls; use super::import::PAGE_FONT; -use super::{Align, Fmt, model, parse_color}; +use super::{Align, Fmt, Rgb, model, parse_color}; /// A CSS length (or font-size keyword) in points; `None` when it is not one. pub fn css_len_pt(v: &str) -> Option { @@ -88,7 +88,398 @@ pub(super) fn css_unescape(s: &str) -> String { o } -/// Apply a `style` attribute to formatting / block properties. +/// Maximum number of tokens parsed in a CSS background shorthand declaration to prevent DOS. +const MAX_CSS_SHORTHAND_TOKENS: usize = 64; + +/// Returns true if `c` is a CSS whitespace character according to CSS Syntax Level 3 § 4.2. +/// +/// Only U+0020 (space), U+0009 (tab), U+000A (LF), U+000C (FF), and U+000D (CR) are CSS whitespace. +/// Non-breaking space (U+00A0) and other Unicode whitespace characters are not CSS whitespace. +fn is_css_whitespace(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n' | '\x0C' | '\r') +} + +/// Trims leading and trailing CSS whitespace from a string slice according to CSS Syntax Level 3 § 4.2. +fn trim_css_whitespace(s: &str) -> &str { + s.trim_matches(is_css_whitespace) +} + +/// Check whether a token is a valid CSS length or percentage value. +/// +/// Returns `true` for `"0"` or numeric quantities ending in valid CSS length units +/// (`px`, `pt`, `em`, `rem`, `%`, `in`, `cm`, `mm`, `vw`, `vh`, `vmin`, `vmax`, `pc`, `ch`, `ex`). +fn is_length_or_percentage(s: &str) -> bool { + let s = trim_css_whitespace(s); + if s.parse::().is_ok_and(|x| x == 0.0) { + return true; + } + let units = ["px", "pt", "em", "rem", "%", "in", "cm", "mm", "vw", "vh", "vmin", "vmax", "pc", "ch", "ex"]; + for unit in units { + if let Some(num_str) = s.strip_suffix(unit) + && trim_css_whitespace(num_str).parse::().is_ok_and(|x| x.is_finite()) + { + return true; + } + } + false +} + +/// Represents a parsed CSS background layer containing its tokens and depth-zero slash count. +struct BgLayer<'a> { + /// Tokens belonging to this layer, trimmed of CSS whitespace. + tokens: Vec<&'a str>, + /// Number of slashes occurring at parenthesis depth 0 in this layer. + depth_zero_slashes: usize, +} + +/// Push a sliced and trimmed token to the layer's token list, enforcing the shorthand token limit. +fn push_shorthand_token<'a>(val: &'a str, start: &mut Option, end: usize, tokens: &mut Vec<&'a str>, total_tokens: &mut usize) -> Option<()> { + if let Some(s) = start.take() + && let Some(token) = val.get(s..end) + { + let trimmed = trim_css_whitespace(token); + if !trimmed.is_empty() { + if *total_tokens >= MAX_CSS_SHORTHAND_TOKENS { + return None; + } + tokens.push(trimmed); + *total_tokens = total_tokens.saturating_add(1); + } + } + Some(()) +} + +/// Parse CSS background shorthand value into comma-separated layers and tokens. +/// +/// Respects quotes and parenthesis depth. Rejects and returns `None` if the token +/// limit `MAX_CSS_SHORTHAND_TOKENS` is exceeded (indicating hostile or truncated input), +/// or if quotes or parentheses are unbalanced. +fn parse_bg_layers(val: &str) -> Option>> { + let mut layers = Vec::new(); + let mut current_tokens = Vec::new(); + let mut current_slashes = 0usize; + let mut total_tokens = 0usize; + + let mut start = None; + let mut paren_depth = 0usize; + let mut in_quote = None; + let mut escaped = false; + let mut in_raw_url = false; + + let mut byte_idx = 0; + while byte_idx < val.len() { + let Some(c) = val[byte_idx..].chars().next() else { break }; + let char_len = c.len_utf8(); + let i = byte_idx; + byte_idx += char_len; + + if escaped { + escaped = false; + continue; + } + if c == '\\' { + escaped = true; + if start.is_none() { + start = Some(i); + } + continue; + } + if let Some(q) = in_quote { + if c == q { + in_quote = None; + } + } else if c == '\'' || c == '"' { + in_quote = Some(c); + if start.is_none() { + start = Some(i); + } + } else if !in_raw_url && val[i..].starts_with("/*") { + // CSS comments outside strings and URLs are consumed before delimiter classification + if paren_depth == 0 { + push_shorthand_token(val, &mut start, i, &mut current_tokens, &mut total_tokens)?; + } + if let Some(end_offset) = val[i + 2..].find("*/") { + byte_idx = i + 2 + end_offset + 2; + } else { + byte_idx = val.len(); + } + continue; + } else if c == '(' { + if in_quote.is_none() + && let Some(s) = start + && val.get(s..i).is_some_and(|prefix| trim_css_whitespace(prefix).eq_ignore_ascii_case("url")) + { + in_raw_url = true; + } + paren_depth = paren_depth.saturating_add(1); + if start.is_none() { + start = Some(i); + } + } else if c == ')' { + if paren_depth == 0 { + return None; + } + paren_depth -= 1; + if paren_depth == 0 { + in_raw_url = false; + } + } else if paren_depth == 0 { + if c == '/' { + current_slashes = current_slashes.saturating_add(1); + push_shorthand_token(val, &mut start, i, &mut current_tokens, &mut total_tokens)?; + if total_tokens >= MAX_CSS_SHORTHAND_TOKENS { + return None; + } + if let Some(slash_token) = val.get(i..i + 1) { + current_tokens.push(slash_token); + total_tokens = total_tokens.saturating_add(1); + } + } else if c == ',' { + push_shorthand_token(val, &mut start, i, &mut current_tokens, &mut total_tokens)?; + if current_tokens.is_empty() { + return None; + } + layers.push(BgLayer { tokens: std::mem::take(&mut current_tokens), depth_zero_slashes: current_slashes }); + current_slashes = 0; + } else if is_css_whitespace(c) { + push_shorthand_token(val, &mut start, i, &mut current_tokens, &mut total_tokens)?; + } else if start.is_none() { + start = Some(i); + } + } else if start.is_none() { + start = Some(i); + } + } + + if escaped || paren_depth != 0 || in_quote.is_some() { + return None; + } + + push_shorthand_token(val, &mut start, val.len(), &mut current_tokens, &mut total_tokens)?; + + if current_tokens.is_empty() { + return None; + } + + layers.push(BgLayer { tokens: current_tokens, depth_zero_slashes: current_slashes }); + + Some(layers) +} + +fn is_valid_rgb_component(s: &str) -> bool { + let s = trim_css_whitespace(s); + if s.eq_ignore_ascii_case("none") { + return true; + } + if let Some(p) = s.strip_suffix('%') { + trim_css_whitespace(p).parse::().is_ok_and(|v| v.is_finite()) + } else { + s.parse::().is_ok_and(|v| v.is_finite()) + } +} + +fn is_valid_hue_component(s: &str) -> bool { + let s = trim_css_whitespace(s); + if s.eq_ignore_ascii_case("none") { + return true; + } + let num_str = if let Some(deg) = s.strip_suffix("deg") { + deg + } else if let Some(rad) = s.strip_suffix("rad") { + rad + } else if let Some(turn) = s.strip_suffix("turn") { + turn + } else { + s + }; + trim_css_whitespace(num_str).parse::().is_ok_and(|v| v.is_finite()) +} + +fn is_valid_zero_alpha(a: &str) -> bool { + let a = trim_css_whitespace(a); + if a.eq_ignore_ascii_case("none") || a == "0" || a == "0%" || a == "0.0" { + return true; + } + if let Some(p) = a.strip_suffix('%') { + trim_css_whitespace(p).parse::().is_ok_and(|v| v <= 0.0) + } else { + a.parse::().is_ok_and(|v| v <= 0.0) + } +} + +/// Returns true if a CSS color expression specifies a fully transparent color (alpha = 0). +fn is_zero_alpha_color(s: &str) -> bool { + let s = trim_css_whitespace(s).to_ascii_lowercase(); + if s == "transparent" { + return true; + } + if let Some(h) = s.strip_prefix('#') { + if h.len() == 4 && h.ends_with('0') && h.bytes().all(|b| b.is_ascii_hexdigit()) { + return true; + } + if h.len() == 8 && h.ends_with("00") && h.bytes().all(|b| b.is_ascii_hexdigit()) { + return true; + } + return false; + } + if let Some(inner) = s.strip_prefix("rgb(").or_else(|| s.strip_prefix("rgba(")) { + let Some(inner) = inner.strip_suffix(')') else { return false }; + let (rgb_part, alpha_part) = inner.split_once('/').map_or((inner, None), |(a, b)| (a, Some(b))); + let (parts, alpha_str) = match alpha_part { + Some(a) => { + let parts: Vec<&str> = if rgb_part.contains(',') { rgb_part.split(',').collect() } else { rgb_part.split_whitespace().collect() }; + (parts, a) + } + None => { + let parts: Vec<&str> = if inner.contains(',') { inner.split(',').collect() } else { inner.split_whitespace().collect() }; + if parts.len() == 4 { + (parts[..3].to_vec(), parts[3]) + } else { + return false; + } + } + }; + return parts.len() == 3 && parts.iter().all(|&p| is_valid_rgb_component(p)) && is_valid_zero_alpha(alpha_str); + } + if let Some(inner) = s.strip_prefix("hsl(").or_else(|| s.strip_prefix("hsla(")) { + let Some(inner) = inner.strip_suffix(')') else { return false }; + let (hsl_part, alpha_part) = inner.split_once('/').map_or((inner, None), |(a, b)| (a, Some(b))); + let (parts, alpha_str) = match alpha_part { + Some(a) => { + let parts: Vec<&str> = if hsl_part.contains(',') { hsl_part.split(',').collect() } else { hsl_part.split_whitespace().collect() }; + (parts, a) + } + None => { + let parts: Vec<&str> = if inner.contains(',') { inner.split(',').collect() } else { inner.split_whitespace().collect() }; + if parts.len() == 4 { + (parts[..3].to_vec(), parts[3]) + } else { + return false; + } + } + }; + return parts.len() == 3 + && is_valid_hue_component(parts[0]) + && is_valid_rgb_component(parts[1]) + && is_valid_rgb_component(parts[2]) + && is_valid_zero_alpha(alpha_str); + } + false +} + +/// Returns true if a lowercase token represents a recognized CSS image function. +fn is_valid_image_function(ltok: &str) -> bool { + if !ltok.ends_with(')') { + return false; + } + ltok.starts_with("url(") + || ltok.starts_with("image(") + || ltok.starts_with("image-set(") + || ltok.starts_with("-webkit-image-set(") + || ltok.starts_with("cross-fade(") + || ltok.starts_with("element(") + || ltok.starts_with("paint(") + || ltok.starts_with("linear-gradient(") + || ltok.starts_with("radial-gradient(") + || ltok.starts_with("conic-gradient(") + || ltok.starts_with("repeating-linear-gradient(") + || ltok.starts_with("repeating-radial-gradient(") + || ltok.starts_with("repeating-conic-gradient(") + || ltok.starts_with("-webkit-linear-gradient(") + || ltok.starts_with("-webkit-radial-gradient(") + || ltok.starts_with("-webkit-gradient(") + || ltok.starts_with("-moz-linear-gradient(") + || ltok.starts_with("-moz-radial-gradient(") +} + +/// Returns true if a lowercase token represents a recognized CSS math or environment function. +fn is_valid_math_or_value_function(ltok: &str) -> bool { + if !ltok.ends_with(')') { + return false; + } + ltok.starts_with("calc(") + || ltok.starts_with("min(") + || ltok.starts_with("max(") + || ltok.starts_with("clamp(") + || ltok.starts_with("var(") + || ltok.starts_with("env(") +} + +/// Check whether a token is a valid CSS background position component (`top`, `bottom`, `left`, `right`, `center`, length, percentage, or math function). +fn is_valid_pos_token(s: &str) -> bool { + let ls = s.to_ascii_lowercase(); + matches!(ls.as_str(), "top" | "bottom" | "left" | "right" | "center") || is_length_or_percentage(&ls) || is_valid_math_or_value_function(&ls) +} + +/// Check whether a token is a valid CSS background size component (`auto`, length, percentage, or math function). +fn is_valid_size_component(s: &str) -> bool { + let ls = s.to_ascii_lowercase(); + ls == "auto" || is_length_or_percentage(&ls) || is_valid_math_or_value_function(&ls) +} + +/// Check whether a token is a valid CSS background property token outside of position-and-size slash expressions. +/// +/// Recognizes color names/hex codes, images, repeat styles, attachments, and box keywords. +/// Standalone size keywords (`cover`, `contain`, `auto`) and slashes are rejected unless positioned in a valid slash layer. +fn is_valid_non_slash_bg_token(tok: &str) -> bool { + let ltok = tok.to_ascii_lowercase(); + if is_valid_image_function(<ok) || is_valid_math_or_value_function(<ok) { + return true; + } + if is_zero_alpha_color(tok) || parse_color(tok).is_some() || ltok == "transparent" { + return true; + } + match ltok.as_str() { + "none" | "repeat" | "no-repeat" | "repeat-x" | "repeat-y" | "space" | "round" | "scroll" | "fixed" | "local" | "border-box" + | "padding-box" | "content-box" | "top" | "bottom" | "left" | "right" | "center" => true, + _ => is_length_or_percentage(<ok), + } +} + +/// Validate that a single CSS background shorthand layer satisfies the position-and-size grammar. +/// +/// If depth-zero slashes are present, exactly one slash must separate a valid `` from a valid ``. +/// Background size keywords `cover` and `contain` are rejected unless preceded by a valid position and slash (#1786). +fn is_valid_bg_layer(layer: &BgLayer<'_>) -> bool { + if layer.depth_zero_slashes > 1 { + return false; + } + if layer.depth_zero_slashes == 0 { + return layer.tokens.iter().all(|t| is_valid_non_slash_bg_token(t)); + } + + let Some(slash_idx) = layer.tokens.iter().position(|&t| t == "/") else { + return false; + }; + let before_tokens = &layer.tokens[..slash_idx]; + let after_tokens = &layer.tokens[slash_idx + 1..]; + + let Some(&last_before) = before_tokens.last() else { + return false; + }; + if !is_valid_pos_token(last_before) { + return false; + } + if !before_tokens[..before_tokens.len().saturating_sub(1)].iter().all(|t| is_valid_non_slash_bg_token(t)) { + return false; + } + + if after_tokens.is_empty() { + return false; + } + let first_after = after_tokens[0]; + let remaining_after = if first_after.eq_ignore_ascii_case("cover") || first_after.eq_ignore_ascii_case("contain") { + &after_tokens[1..] + } else if is_valid_size_component(first_after) { + if after_tokens.len() > 1 && is_valid_size_component(after_tokens[1]) { &after_tokens[2..] } else { &after_tokens[1..] } + } else { + return false; + }; + + remaining_after.iter().all(|t| is_valid_non_slash_bg_token(t)) +} + +/// Apply CSS `style` declarations to formatting and block properties, updating character and block attributes. pub(super) fn apply_style( css: &str, f: &mut Fmt, @@ -96,6 +487,7 @@ pub(super) fn apply_style( preserve: &mut bool, page_break: &mut bool, page_break_after: &mut bool, + parent_bg: Option, ) { for (k, v) in decls(css) { let lv = v.to_ascii_lowercase(); @@ -119,11 +511,78 @@ pub(super) fn apply_style( f.color = Some(c); } } - "background-color" | "background" => { - if let Some(c) = v.split_whitespace().find_map(parse_color) { + "background-color" => { + let trimmed = trim_css_whitespace(v); + let lv = trimmed.to_ascii_lowercase(); + if lv == "transparent" || lv == "none" || lv == "initial" || lv == "unset" || is_zero_alpha_color(trimmed) { + f.background = None; + } else if lv == "inherit" { + f.background = parent_bg; + } else if let Some(c) = parse_color(trimmed) { f.background = Some(c); } } + "background" => { + let Some(layers) = parse_bg_layers(v) else { + continue; + }; + + // CSS-wide keywords (inherit, initial, unset) must be the sole value of the declaration. + if layers.len() == 1 && layers[0].tokens.len() == 1 { + let first = layers[0].tokens[0].to_ascii_lowercase(); + match first.as_str() { + "inherit" => { + f.background = parent_bg; + continue; + } + "initial" | "unset" | "none" | "transparent" => { + f.background = None; + continue; + } + _ => {} + } + } else if layers.iter().any(|l| l.tokens.iter().any(|t| matches!(t.to_ascii_lowercase().as_str(), "inherit" | "initial" | "unset"))) { + // Invalid CSS: CSS-wide keywords cannot be combined with other values. + continue; + } + + // In CSS background shorthand: + // 1. Each layer may have at most one slash separating position and size. + // 2. All layers must satisfy the grammar (e.g. `cover` requires position and slash). + // 3. Only the final layer may specify a background color. + if !layers.iter().all(is_valid_bg_layer) { + continue; + } + + // Only the final layer can specify background-color. If any earlier layer has a color, + // the entire declaration is invalid CSS. + let earlier_has_color = layers[..layers.len().saturating_sub(1)] + .iter() + .any(|l| l.tokens.iter().any(|t| is_zero_alpha_color(t) || parse_color(t).is_some())); + if earlier_has_color { + continue; + } + + // Extract background color from the final layer. + let final_layer = &layers[layers.len().saturating_sub(1)]; + let color_tokens: Vec<_> = + final_layer.tokens.iter().copied().filter(|t| is_zero_alpha_color(t) || parse_color(t).is_some()).collect(); + if color_tokens.len() > 1 { + // Invalid CSS: multiple background colors in a single layer. + continue; + } + if let Some(&tok) = color_tokens.first() { + if is_zero_alpha_color(tok) { + f.background = None; + } else if let Some(c) = parse_color(tok) { + f.background = Some(c); + } + } else { + // A valid background shorthand without a color (such as background: url(...) or none repeat) + // resets background-color to transparent. + f.background = None; + } + } "font-size" => { if let Some(p) = css_len_pt(v).filter(|p| *p >= 1.0 && *p <= 1638.0) { f.size = Some(p); diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs index 78f6d9ae8..9fb861d85 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -183,18 +183,70 @@ pub fn inlines_html(inlines: &[Inline]) -> String { o } +/// Formatted code inline spans inside `
`: preserves formatting tags while keeping
+/// raw whitespace semantics (spaces and tabs are preserved, not converted to ` ` or `
`). +fn code_inlines_html(inlines: &[Inline]) -> String { + let mut o = String::new(); + for i in inlines { + match i { + Inline::Text(t, f) => { + let (open, close) = fmt_tags(f); + o.push_str(&open); + o.push_str(&esc(t)); + for c in close.iter().rev() { + o.push_str(c); + } + } + Inline::Ruby { base, ruby, fmt } => { + let (open, close) = fmt_tags(fmt); + o.push_str(&open); + o.push_str(&format!("{}{}", esc(base), esc(ruby))); + for c in close.iter().rev() { + o.push_str(c); + } + } + Inline::Anchor(a) => o.push_str(&format!("", esc(a))), + Inline::Image(img) => { + o.push_str(&format!( + "\"{}\"", + mime_of(&img.ext), + base64_encode(&img.data), + esc(&img.alt), + (img.w / 0.75).round(), + (img.h / 0.75).round() + )); + } + Inline::Field { result, fmt, .. } | Inline::Control { text: result, fmt, .. } => { + let (open, close) = fmt_tags(fmt); + o.push_str(&open); + o.push_str(&esc(result)); + for c in close.iter().rev() { + o.push_str(c); + } + } + Inline::Figure(alt) | Inline::Chart(craft_flow::Chart { alt, .. }) => o.push_str(&format!("\"{}\"", esc(alt))), + Inline::Equation { linear, display } => o.push_str(&craft_math::mathml::linear_to_mathml(linear, *display)), + _ => {} + } + } + o +} + fn trim_num(v: f32) -> String { let s = format!("{:.2}", v); s.trim_end_matches('0').trim_end_matches('.').to_string() } fn para_attrs(p: &Para) -> String { - let mut css: Vec<&str> = Vec::new(); + let mut css: Vec = Vec::new(); if let Some(a) = align_css(p.align) { - css.push(a); + css.push(a.to_string()); } if p.page_break { - css.push("break-before:page;page-break-before:always"); + css.push("break-before:page;page-break-before:always".to_string()); + } + if let Some(bg) = p.extra.as_ref().and_then(|x| x.shading) { + css.push(format!("background-color:#{}", bg.hex())); } if css.is_empty() { String::new() } else { format!(" style=\"{}\"", css.join(";")) } } @@ -240,7 +292,11 @@ fn table_html(t: &FTable, out: &mut String, depth: usize) { css.push(format!("background-color:#{}", s.hex())); } let single = match c.blocks.as_slice() { - [FBlock::Para(p)] if p.kind == Kind::Normal && p.list.is_none() && !p.page_break => Some(p), + [FBlock::Para(p)] + if p.kind == Kind::Normal && p.list.is_none() && !p.page_break && p.extra.as_ref().and_then(|x| x.shading).is_none() => + { + Some(p) + } _ => None, }; if let Some(a) = single.and_then(|p| align_css(p.align)) { @@ -310,17 +366,20 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) { out.push('\n'); } FBlock::Para(p) if p.kind == Kind::Code => { - out.push_str("
");
+                // One `
` per run of code paragraphs whose attributes match: they share the
+                // `
`'s shading, so a different background starts a new block.
+                let attrs = para_attrs(p);
+                out.push_str(&format!(""));
                 let mut first = true;
                 while let Some(FBlock::Para(q)) = blocks.get(i) {
-                    if q.kind != Kind::Code || q.list.is_some() {
+                    if q.kind != Kind::Code || q.list.is_some() || para_attrs(q) != attrs {
                         break;
                     }
                     if !first {
                         out.push('\n');
                     }
                     first = false;
-                    out.push_str(&esc(&q.text()));
+                    out.push_str(&code_inlines_html(&q.inlines));
                     i += 1;
                 }
                 out.push_str("
\n"); @@ -357,14 +416,14 @@ fn close_list(stack: &mut Vec<(bool, bool)>, out: &mut String) { /// A complete HTML document. pub fn export(doc: &Document) -> String { - let flow = model::from_doc(doc); + let flow = model::from_doc_with(doc, model::FlowOpts { paras: true, ..Default::default() }); export_flow(&flow, doc.styles.default_chr.lang.as_deref().unwrap_or("en")) } /// `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). pub fn export_fragment(doc: &Document) -> String { - let flow = model::from_doc(doc); + let flow = model::from_doc_with(doc, model::FlowOpts { paras: true, ..Default::default() }); let mut out = String::from(""); blocks_html(&flow.blocks, &mut out, 0); out diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index 640ab07d0..c0b00084b 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -767,3 +767,834 @@ fn hostile_style_sheets_never_panic() { let _ = parse_in(&format!("

x

y"), &|_| None, true); } } + +/// Ensure container elements (such as `div` and `p`) with background colors do not leak +/// character shading onto their child text runs (#1786). +#[test] +fn container_background_color_does_not_leak_into_character_shading() { + let html = r#"
code
"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert!(!p.runs.is_empty(), "expected nonempty runs"); + assert_eq!(&p.text, "code"); + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x1e, 0x1e, 0x1e)), "container div background is preserved as paragraph shading"); + for r in &p.runs { + assert_eq!(r.props.shading, None, "character should have no shading from container div"); + } +} + +/// Verify that table background colors cascade down to cell shading through implicit or explicit +/// row groups (`tbody`, `thead`, `tfoot`), but do not leak into cell character shading. +#[test] +fn table_background_inherits_through_row_groups() { + let html = r#"
cell1
+
cell2
+
head
"#; + let doc = import(html); + let tables: Vec<_> = doc + .body + .iter() + .filter_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .collect(); + assert_eq!(tables.len(), 3); + for (t, want_hex) in tables.iter().zip(["e8f0fa", "d0e0f0", "c0d0e0"]) { + let cell = &t.rows[0].cells[0]; + assert_eq!( + cell.props.shading.map(|c| c.hex().to_ascii_lowercase()), + Some(want_hex.to_string()), + "cell should inherit shading from table or row group" + ); + let p = &cell.blocks[0]; + let craft_wordmodel::Block::Para(p) = &**p else { + panic!("expected table cell block to be a paragraph"); + }; + assert!(!p.runs.is_empty(), "expected nonempty runs"); + for r in &p.runs { + assert_eq!(r.props.shading, None, "cell text should have no character shading"); + } + } +} + +/// Verify that block-level container backgrounds (`p`, `pre`, `div`) are preserved as paragraph +/// shading on paragraphs rather than character shading on individual runs (#1786). +#[test] +fn block_element_backgrounds_preserve_paragraph_shading() { + let html = r#"

text

code

inner

"#; + let doc = import(html); + assert_eq!(doc.body.len(), 3); + let craft_wordmodel::Block::Para(p1) = &*doc.body[0] else { panic!("expected Para") }; + let craft_wordmodel::Block::Para(p2) = &*doc.body[1] else { panic!("expected Para") }; + let craft_wordmodel::Block::Para(p3) = &*doc.body[2] else { panic!("expected Para") }; + assert_eq!(p1.props.shading, Some(craft_wordmodel::Rgb(0x1e, 0x1e, 0x1e))); + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x2a, 0x2a, 0x2a))); + assert_eq!(p3.props.shading, Some(craft_wordmodel::Rgb(0x3a, 0x3a, 0x3a))); + assert_eq!(&p1.text, "text"); + assert_eq!(&p2.text, "code"); + assert_eq!(&p3.text, "inner"); + assert!(!p1.runs.is_empty()); + assert!(!p2.runs.is_empty()); + assert!(!p3.runs.is_empty()); + for r in &p1.runs { + assert_eq!(r.props.shading, None, "character should have no shading from paragraph background"); + } + for r in &p2.runs { + assert_eq!(r.props.shading, None, "character should have no shading from pre background"); + } + for r in &p3.runs { + assert_eq!(r.props.shading, None, "character should have no shading from container div background"); + } +} + +/// Verify that paragraph shading created by a container background survives an HTML round trip (#1786). +#[test] +fn paragraph_shading_survives_an_html_round_trip() { + let html = r#"

code

pre
"#; + let doc = import(html); + let out = export(&doc); + assert!(out.contains("background-color:#1E1E1E"), "paragraph shading is exported: {out}"); + assert!(out.contains("background-color:#2A2A2A"), "code block shading is exported: {out}"); + + let back = import(&out); + let craft_wordmodel::Block::Para(p1) = &*back.body[0] else { panic!("expected Para") }; + let craft_wordmodel::Block::Para(p2) = &*back.body[1] else { panic!("expected Para") }; + assert_eq!(p1.props.shading, Some(craft_wordmodel::Rgb(0x1e, 0x1e, 0x1e))); + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x2a, 0x2a, 0x2a))); +} + +/// Verify that paragraph shading inside a single-paragraph table cell survives an HTML round trip (#1786). +#[test] +fn table_cell_paragraph_shading_survives_an_html_round_trip() { + let html = r#"

text

"#; + let doc = import(html); + let out = export(&doc); + assert!(out.contains("background-color:#123456"), "paragraph shading is exported: {out}"); + + let back = import(&out); + let table = back + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .expect("expected table"); + let cell = &table.rows[0].cells[0]; + assert_eq!(cell.props.shading, None, "paragraph shading must not become cell shading"); + let craft_wordmodel::Block::Para(p) = &*cell.blocks[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that consecutive code paragraphs with different backgrounds export their own `
`.
+#[test]
+fn consecutive_code_blocks_keep_their_own_shading() {
+    let html = r#"
a
b
"#; + let out = export(&import(html)); + assert!(out.contains("
a
"), "{out}"); + assert!(out.contains("
b
"), "{out}"); +} + +/// Verify that paragraph shading inherited from a paragraph style is exported (#1786). +#[test] +fn paragraph_shading_from_a_style_survives_html_export() { + let mut doc = Document::new(); + std::sync::Arc::make_mut(&mut doc.styles).styles.push(craft_wordmodel::Style { + id: "Shaded".into(), + name: "Shaded".into(), + para: craft_wordmodel::props::ParaProps { shading: Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56)), ..Default::default() }, + ..Default::default() + }); + let mut p = craft_wordmodel::Paragraph::with_text("text", craft_wordmodel::CharProps::default()); + p.props.style = Some("Shaded".into()); + doc.body = vec![craft_wordmodel::para_block(p)]; + + let out = export(&doc); + assert!(out.contains("background-color:#123456"), "style shading is exported: {out}"); +} + +/// A closing parenthesis without an opening one invalidates the declaration (#1786). +#[test] +fn background_shorthand_unbalanced_closing_paren_is_ignored() { + let html = r#"text"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0xff, 0x00, 0x00)), "invalid shorthand must not clear inherited shading"); +} + +/// A shaded paragraph keeps its shading on both sides of an internal page break (#1786). +#[test] +fn paragraph_shading_survives_an_internal_page_break() { + let mut p = craft_wordmodel::Paragraph::with_text("before\u{000C}after", craft_wordmodel::CharProps::default()); + p.props.shading = Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56)); + let mut doc = Document::new(); + doc.body = vec![craft_wordmodel::para_block(p)]; + let out = export(&doc); + assert_eq!(out.matches("background-color:#123456").count(), 2, "{out}"); +} + +/// Verify that CSS-escaped quote characters in background shorthand URLs remain part of the URL +/// content and do not cause the shorthand declaration to be rejected. +#[test] +fn background_shorthand_escaped_quotes_in_url() { + let doc = import(r#"

text

"#); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(&p.text, "text"); + assert!(!p.runs.is_empty()); + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that valid multi-token CSS background shorthands without a color (such as `none repeat`) +/// reset character shading, while invalid declarations are ignored. +#[test] +fn background_shorthand_without_color_resets_background() { + let html = r#"plain"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None); + + let html_invalid = r#"shaded"#; + let doc_invalid = import(html_invalid); + let p_invalid = match &*doc_invalid.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_invalid.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that CSS `background: inherit` keeps inherited character shading instead of removing it (#1786). +#[test] +fn background_inherit_retains_inline_shading() { + let html = r#"shaded"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0)), "background: inherit should retain inherited character shading"); + + // Also verify background-color: inherit retains shading. + let html_color = r#"shaded"#; + let doc_color = import(html_color); + let p_color = match &*doc_color.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p_color.runs[0].props.shading, + Some(craft_wordmodel::Rgb(255, 0, 0)), + "background-color: inherit should retain inherited character shading" + ); + + // CSS-wide keyword inherit mixed with other values is invalid and ignored. + let html_mixed = r#"green"#; + let doc_mixed = import(html_mixed); + let p_mixed = match &*doc_mixed.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p_mixed.runs[0].props.shading, + Some(craft_wordmodel::Rgb(0, 255, 0)), + "invalid shorthand mixing inherit with values should be ignored" + ); +} + +/// Verify that hostile background declarations with deeply nested slashes do not cause stack overflow (#1786). +#[test] +fn hostile_background_slashes_never_stack_overflow() { + let slashes = "/".repeat(20_000); + let html = format!(r#"hostile"#); + let doc = import(&html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None); +} + +/// Verify that non-breaking space (U+00A0) is not treated as CSS whitespace when splitting tokens (#1786). +#[test] +fn background_whitespace_preserves_nbsp() { + let html = "shaded"; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p.runs[0].props.shading, + Some(craft_wordmodel::Rgb(255, 0, 0)), + "non-breaking space is not CSS whitespace and should not clear shading" + ); +} + +/// Verify that background shorthands exceeding the token limit are rejected and unapplied (#1786). +#[test] +fn background_shorthand_truncated_rejects_unapplied() { + let mut layers = String::new(); + for i in 0..64 { + layers.push_str(&format!("url(img{i}.png), ")); + } + layers.push_str("#00ff00"); + let html = format!(r#"retained"#); + let doc = import(&html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p.runs[0].props.shading, + Some(craft_wordmodel::Rgb(255, 0, 0)), + "truncated shorthand should be rejected and leave inherited background untouched" + ); +} + +/// Verify that shorthands with image-set or calc functions parse and preserve colors (#1786). +#[test] +fn background_shorthand_valid_functions_preserve_color() { + let html_image_set = r#"image-set"#; + let doc = import(html_image_set); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + let html_calc = r#"calc"#; + let doc_calc = import(html_calc); + let p_calc = match &*doc_calc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_calc.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that multi-layer background shorthands validate slashes per layer and preserve final-layer color (#1786). +#[test] +fn background_shorthand_multi_layer_slashes_apply_color() { + let html = r#"multi-layer"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + // Color in a non-final layer is invalid CSS and must be ignored. + let html_invalid_color = r#"invalid"#; + let doc_invalid_color = import(html_invalid_color); + let p_invalid_color = match &*doc_invalid_color.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_invalid_color.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + // Multiple slashes in a single layer makes the declaration invalid. + let html_multi_slash = + r#"invalid"#; + let doc_multi_slash = import(html_multi_slash); + let p_multi_slash = match &*doc_multi_slash.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_multi_slash.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that background shorthands with empty layers (leading, trailing, or double commas) are rejected (#1786). +#[test] +fn background_shorthand_rejects_empty_layers() { + // Leading comma + let html_leading = r#"leading"#; + let doc_leading = import(html_leading); + let p_leading = match &*doc_leading.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_leading.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + // Trailing comma + let html_trailing = r#"trailing"#; + let doc_trailing = import(html_trailing); + let p_trailing = match &*doc_trailing.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_trailing.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + // Double comma + let html_double = r#"double"#; + let doc_double = import(html_double); + let p_double = match &*doc_double.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_double.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that zero-alpha colors in background shorthands or declarations remain transparent (#1786). +#[test] +fn background_zero_alpha_colors_are_transparent() { + for decl in ["rgb(0 0 0 / 0)", "rgba(0, 0, 0, 0)", "#0000", "#00000000", "#ffffff00", "hsla(120, 100%, 50%, 0)", "hsl(120 100% 50% / 0)"] { + let html = format!(r#"transparent"#); + let doc = import(&html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None, "zero-alpha color `{decl}` must clear background rather than composite over white"); + } +} + +/// Verify that ancestor table shading is preserved beneath transparent table layers (#1786). +#[test] +fn transparent_table_layers_preserve_ancestor_table_shading() { + let html = r#" + + + + + + +
transparent_layersexplicit_cell
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!( + table.rows[0].cells[0].props.shading, + Some(craft_wordmodel::Rgb(0xe8, 0xf0, 0xfa)), + "table background must show through transparent tbody, tr, and td" + ); + assert_eq!( + table.rows[0].cells[1].props.shading, + Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56)), + "cell with explicit background must override table background" + ); +} + +/// Verify that block-level container background is available to immediate inline children using explicit `inherit` (#1786). +#[test] +fn block_background_explicit_inherit() { + // When the immediate parent

has no background, an inline span inheriting background gets transparent (None): + let html_indirect = r#"

text

"#; + let doc_indirect = import(html_indirect); + let p_indirect = match &*doc_indirect.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_indirect.runs[0].props.shading, None); + + // When the span is an immediate child of the styled div, it inherits the div's computed background: + let html_direct = r#"
text
"#; + let doc_direct = import(html_direct); + let p_direct = match &*doc_direct.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_direct.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html_shorthand = r#"
text
"#; + let doc_shorthand = import(html_shorthand); + let p_shorthand = match &*doc_shorthand.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_shorthand.runs[0].props.shading, Some(craft_wordmodel::Rgb(0, 255, 0))); +} + +/// Verify that CSS-escaped quotes inside background URLs do not close the quote or drop declaration colors (#1786). +#[test] +fn background_escaped_quote_url() { + let html = r#"text"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + let html_single = r#"text"#; + let doc_single = import(html_single); + let p_single = match &*doc_single.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_single.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x65, 0x43, 0x21))); +} + +/// Verify that invalid hex color declarations like `#ggg0` do not clear inherited shading (#1786). +#[test] +fn background_invalid_hex_retains_shading() { + let html = r#"text"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that background size keywords (`cover`, `contain`) without preceding position and slash are invalid and retain shading (#1786). +#[test] +fn background_cover_without_slash_invalid() { + let html_cover = r#"text"#; + let doc_cover = import(html_cover); + let p_cover = match &*doc_cover.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_cover.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html_contain = r#"text"#; + let doc_contain = import(html_contain); + let p_contain = match &*doc_contain.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_contain.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html_valid = r#"text"#; + let doc_valid = import(html_valid); + let p_valid = match &*doc_valid.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_valid.runs[0].props.shading, None); +} + +/// Verify that table backgrounds declared on thead or tbody are applied to cells (#1786). +#[test] +fn table_row_group_background_inheritance() { + let html = r#" + + + + + + +
head
body
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0, 255, 0))); + assert_eq!(table.rows[1].cells[0].props.shading, Some(craft_wordmodel::Rgb(0, 0, 255))); +} + +/// Verify that background shorthand with slashes inside URL functions correctly identifies the position/size slash (#1786). +#[test] +fn background_url_with_slashes_and_position_size() { + let html = r#"text"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that a table inside an inline element with background shading does not turn character shading into table/cell background (#1786). +#[test] +fn table_inside_inline_element_does_not_inherit_character_shading() { + let html = r#"
cell
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, None); +} + +/// Verify that a child with `background: inherit` inside an unstyled cell in a shaded table does not inherit the table fallback (#1786). +#[test] +fn cell_inherit_uses_cell_background_not_table_fallback() { + let html = r#"
text
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + let p = match &*table.rows[0].cells[0].blocks[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None); +} + +/// Verify that CSS `background: transparent` overrides HTML `bgcolor` presentational attribute (#1786). +#[test] +fn bgcolor_overridden_by_css_transparent() { + let html = r##"
cell
"##; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, None); +} + +/// Verify that nested container shading is preserved when merging list continuation paragraphs (#1786). +#[test] +fn list_continuation_preserves_nested_container_shading() { + let html = r#"
  • before
    inside
    after
"#; + let flow = parse(html); + assert_eq!(flow.blocks.len(), 1); + let FBlock::Para(p) = &flow.blocks[0] else { panic!("expected Para") }; + assert!(p.list.is_some(), "expected list item"); + let dark = Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)); + let inside = p + .inlines + .iter() + .find_map(|i| match i { + Inline::Text(t, fmt) if t.contains("inside") => Some(fmt.background), + _ => None, + }) + .expect("inside text inline"); + assert_eq!(inside, dark, "nested container shading should be preserved on merged run"); + + let doc = import(html); + let craft_wordmodel::Block::Para(p_doc) = &*doc.body[0] else { panic!("expected Para") }; + let mut offset = 0usize; + let mut inside_shading = None; + for r in &p_doc.runs { + let text_slice = &p_doc.text[offset..offset + r.len]; + if text_slice.contains("inside") { + inside_shading = Some(r.props.shading); + } else if text_slice.contains("before") || text_slice.contains("after") { + assert_eq!(r.props.shading, None); + } + offset += r.len; + } + assert_eq!(inside_shading, Some(dark)); +} + +/// Verify that starting a new row group implicitly closes any preceding sibling row group so +/// cell shading is not inherited from an omitted-end-tag preceding group (#1786). +#[test] +fn consecutive_row_groups_with_omitted_end_tag_do_not_leak_shading() { + let html = r#"
a
b
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows.len(), 2); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + assert_eq!(table.rows[1].cells[0].props.shading, None, "second cell should not inherit shading from closed tbody"); +} + +/// Verify that a list item with a shaded container followed by unshaded text preserves separate +/// background regions so the trailing text does not inherit the container's background (#1786). +#[test] +fn shaded_container_first_in_list_item_preserves_unshaded_trailing_text() { + let html = r#"
  • inside
    after
"#; + let doc = import(html); + assert_eq!(doc.body.len(), 1); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, None, "list paragraph as a whole should have no background when regions differ"); + let dark = Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)); + let mut offset = 0usize; + let mut inside_shading = None; + let mut after_shading = None; + for r in &p.runs { + let text_slice = &p.text[offset..offset + r.len]; + if text_slice.contains("inside") { + inside_shading = Some(r.props.shading); + } else if text_slice.contains("after") { + after_shading = Some(r.props.shading); + } + offset += r.len; + } + assert_eq!(inside_shading, Some(dark)); + assert_eq!(after_shading, Some(None), "trailing text should have no shading"); +} + +/// Verify that container backgrounds behind tables are preserved on table cells (#1786). +#[test] +fn container_background_behind_table_preserved_on_cells() { + let html = r#"
text
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + + // Nested table inside an unshaded cell stops at the cell boundary: + let nested_html = r#"
nested
"#; + let nested_doc = import(nested_html); + let outer_table = nested_doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(outer_table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + let inner_table = match &*outer_table.rows[0].cells[0].blocks[0] { + craft_wordmodel::Block::Table(t) => t, + _ => panic!("expected nested Table"), + }; + assert_eq!(inner_table.rows[0].cells[0].props.shading, None, "nested table in unshaded cell must stop at cell boundary"); +} + +/// Verify that page imports preserve root (body/html) backgrounds while pasted fragments do not (#1786). +#[test] +fn root_background_preserved_on_page_import_only() { + let html = r#"

text

"#; + let page_doc = import_page(html, &|_| None); + let craft_wordmodel::Block::Para(p_page) = &*page_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_page.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)), "page import must preserve body background on paragraphs"); + assert_eq!( + p_page.runs[0].props.color, + Some(craft_wordmodel::TextColor::Rgb(craft_wordmodel::Rgb(0xff, 0xff, 0xff))), + "page import keeps the root foreground with its background" + ); + + let frag_doc = import(html); + let craft_wordmodel::Block::Para(p_frag) = &*frag_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_frag.props.shading, None, "fragment paste must not turn body background into paragraph shading"); + assert_eq!(p_frag.runs[0].props.color, None, "fragment paste drops the root foreground with its background"); +} + +/// Verify that an inline child with `background: inherit` does not receive character shading from a pasted body background (#1786). +#[test] +fn pasted_body_background_not_inherited_by_inline_child() { + let html = r#"text"#; + let frag_doc = import(html); + let craft_wordmodel::Block::Para(p_frag) = &*frag_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_frag.runs[0].props.shading, None, "inline child in pasted fragment must not inherit character shading from body background"); + + let page_doc = import_page(html, &|_| None); + let craft_wordmodel::Block::Para(p_page) = &*page_doc.body[0] else { panic!("expected Para") }; + assert_eq!( + p_page.runs[0].props.shading, + Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)), + "inline child in page import inherits body background via inherit" + ); +} + +#[test] +fn root_background_on_html_and_foreground_on_body() { + let html = r#"

text

"#; + let frag_doc = import(html); + let craft_wordmodel::Block::Para(p_frag) = &*frag_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_frag.props.shading, None, "fragment paste drops html background"); + assert_eq!(p_frag.runs[0].props.color, None, "fragment paste drops body foreground when html supplied suppressed background"); + + let page_doc = import_page(html, &|_| None); + let craft_wordmodel::Block::Para(p_page) = &*page_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_page.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + assert_eq!(p_page.runs[0].props.color, Some(craft_wordmodel::TextColor::Rgb(craft_wordmodel::Rgb(0xff, 0xff, 0xff)))); +} + +#[test] +fn background_unitless_zero_lengths() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x65, 0x43, 0x21))); +} + +#[test] +fn background_comments_skipped_outside_strings() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x22, 0x22, 0x22))); +} + +#[test] +fn invalid_color_does_not_clear_preceding_background() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +#[test] +fn code_block_export_preserves_foreground_color() { + let html = r#"
const x = 1;
"#; + let doc = import_page(html, &|_| None); + let exported = export(&doc); + assert!(exported.contains("style=\"background-color:#000000\""), "exported pre must keep background: {}", exported); + assert!(exported.contains("color:#FFFFFF"), "exported code inlines must keep foreground: {}", exported); + assert!(exported.contains("const x = 1;"), "exported code text preserved: {}", exported); +} + +#[test] +fn background_comments_inside_functions() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + assert_eq!(p.runs[0].props.color, Some(craft_wordmodel::TextColor::Rgb(craft_wordmodel::Rgb(0xff, 0xff, 0xff)))); +} + +#[test] +fn zero_alpha_colors_with_none_channels() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, None); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, None); +}