Skip to main content

sheetkit_core/
render.rs

1//! SVG renderer for worksheet visual output.
2//!
3//! Generates an SVG string from worksheet data including cell values,
4//! column widths, row heights, cell styles (fonts, fills, borders),
5//! optional gridlines, and optional row/column headers.
6
7use std::collections::HashMap;
8
9use crate::error::{Error, Result};
10use crate::resource::{
11    ResourceCategory, ResourceDimension, ResourceLimitError, ResourceOperation, ResourceStage,
12};
13use crate::row::get_row_height;
14use crate::sst::SharedStringTable;
15use crate::style::{
16    get_style, AlignmentStyle, BorderLineStyle, FontStyle, HorizontalAlign, PatternType, Style,
17    StyleColor, VerticalAlign,
18};
19use crate::theme::{default_theme_colors, resolve_theme_color};
20use crate::traversal::{CheckedRect, TraversalLimits};
21use crate::utils::cell_ref::{cell_name_to_coordinates, column_number_to_name};
22use sheetkit_xml::styles::StyleSheet;
23use sheetkit_xml::theme::ThemeColors;
24use sheetkit_xml::worksheet::{Cell, CellTypeTag, InlineString, WorksheetXml};
25
26/// Default column width in pixels (approximately 8.43 characters at 7px each).
27const DEFAULT_COL_WIDTH_PX: f64 = 64.0;
28
29/// Default row height in pixels (15 points).
30const DEFAULT_ROW_HEIGHT_PX: f64 = 20.0;
31
32/// Pixel width of the row/column header gutter area.
33const HEADER_WIDTH: f64 = 40.0;
34const HEADER_HEIGHT: f64 = 20.0;
35
36const HEADER_BG_COLOR: &str = "#F0F0F0";
37const HEADER_TEXT_COLOR: &str = "#666666";
38const GRIDLINE_COLOR: &str = "#D0D0D0";
39
40/// Maximum size of one non-streaming SVG result.
41pub const MAX_SVG_OUTPUT_BYTES: u64 = 64 * 1024 * 1024;
42
43struct SvgOutput {
44    value: String,
45    limit: u64,
46    base_offset: u64,
47}
48
49impl SvgOutput {
50    const fn new(limit: u64) -> Self {
51        Self {
52            value: String::new(),
53            limit,
54            base_offset: 0,
55        }
56    }
57
58    fn stage(&self) -> Self {
59        Self {
60            value: String::new(),
61            limit: self.limit,
62            base_offset: self.observed_len(),
63        }
64    }
65
66    /// Like [`Self::stage`], reusing `buffer`'s allocation.
67    fn stage_with(&self, mut buffer: String) -> Self {
68        buffer.clear();
69        Self {
70            value: buffer,
71            limit: self.limit,
72            base_offset: self.observed_len(),
73        }
74    }
75
76    /// Return `true` when `additional` more bytes stay within the limit.
77    fn fits(&self, additional: usize) -> bool {
78        self.observed_len()
79            .saturating_add(u64::try_from(additional).unwrap_or(u64::MAX))
80            <= self.limit
81    }
82
83    /// Push formatted text as one piece, formatting into a reusable buffer
84    /// instead of allocating a new `String` per call.
85    fn push_fmt(&mut self, scratch: &mut String, args: std::fmt::Arguments<'_>) -> Result<()> {
86        use std::fmt::Write as _;
87        scratch.clear();
88        scratch
89            .write_fmt(args)
90            .map_err(|_| Error::Internal("SVG formatting failed".to_string()))?;
91        self.push_str(scratch)
92    }
93
94    fn push_str(&mut self, value: &str) -> Result<()> {
95        let additional = u64::try_from(value.len()).unwrap_or(u64::MAX);
96        self.ensure_additional(additional)?;
97
98        self.value
99            .try_reserve(value.len())
100            .map_err(|_| Error::Internal("SVG output allocation failed".to_string()))?;
101        self.value.push_str(value);
102        Ok(())
103    }
104
105    /// Push a run of unescaped characters with the same limit outcome as
106    /// pushing them one character at a time: a run that fits is pushed
107    /// whole; otherwise characters are pushed individually so the error
108    /// reports the same observed length.
109    fn push_chars(&mut self, run: &str) -> Result<()> {
110        let observed = self
111            .observed_len()
112            .saturating_add(u64::try_from(run.len()).unwrap_or(u64::MAX));
113        if observed <= self.limit {
114            return self.push_str(run);
115        }
116        for c in run.chars() {
117            let mut encoded = [0; 4];
118            self.push_str(c.encode_utf8(&mut encoded))?;
119        }
120        Ok(())
121    }
122
123    /// Push `value`, replacing each character for which `escape` returns a
124    /// replacement. Equivalent to pushing every character or replacement
125    /// individually, including the limit error.
126    fn push_escaped(
127        &mut self,
128        value: &str,
129        escape: impl Fn(char) -> Option<&'static str>,
130    ) -> Result<()> {
131        let mut start = 0;
132        for (index, c) in value.char_indices() {
133            if let Some(replacement) = escape(c) {
134                if start < index {
135                    self.push_chars(&value[start..index])?;
136                }
137                self.push_str(replacement)?;
138                start = index + c.len_utf8();
139            }
140        }
141        if start < value.len() {
142            self.push_chars(&value[start..])?;
143        }
144        Ok(())
145    }
146
147    fn ensure_additional(&self, additional: u64) -> Result<()> {
148        let observed = self.observed_len().saturating_add(additional);
149        if observed > self.limit {
150            return Err(svg_output_limit_error(self.limit, observed));
151        }
152        Ok(())
153    }
154
155    fn observed_len(&self) -> u64 {
156        self.base_offset
157            .saturating_add(u64::try_from(self.value.len()).unwrap_or(u64::MAX))
158    }
159
160    fn finish(self) -> String {
161        self.value
162    }
163}
164
165fn svg_output_limit_error(limit: u64, observed: u64) -> Error {
166    let observed = observed.max(limit.saturating_add(1));
167    match ResourceLimitError::exceeded(
168        ResourceOperation::Render,
169        ResourceCategory::Output,
170        ResourceDimension::OutputBytes,
171        limit,
172        observed,
173        Some(ResourceStage::Render),
174    ) {
175        Some(metadata) => metadata.into(),
176        None => Error::Internal("invalid SVG output limit".to_string()),
177    }
178}
179
180/// Conversion factor from Excel column width units to pixels.
181/// Excel column width is in "number of characters" based on the default font.
182/// The approximate conversion is: pixels = width * 7 + 5 (for padding).
183fn col_width_to_px(width: f64) -> f64 {
184    width * 7.0 + 5.0
185}
186
187/// Conversion factor from Excel row height (points) to pixels.
188/// 1 point = 4/3 pixels at 96 DPI.
189fn row_height_to_px(height: f64) -> f64 {
190    height * 4.0 / 3.0
191}
192
193/// Options for rendering a worksheet to SVG.
194pub struct RenderOptions {
195    /// Name of the sheet to render. Required.
196    pub sheet_name: String,
197    /// Optional cell range to render (e.g. "A1:F20"). None renders the used range.
198    pub range: Option<String>,
199    /// Whether to draw gridlines between cells.
200    pub show_gridlines: bool,
201    /// Whether to draw row and column headers (A, B, C... and 1, 2, 3...).
202    pub show_headers: bool,
203    /// Scale factor for the output (1.0 = 100%).
204    pub scale: f64,
205    /// Default font family for cell text.
206    pub default_font_family: String,
207    /// Default font size in points for cell text.
208    pub default_font_size: f64,
209}
210
211impl Default for RenderOptions {
212    fn default() -> Self {
213        Self {
214            sheet_name: String::new(),
215            range: None,
216            show_gridlines: true,
217            show_headers: true,
218            scale: 1.0,
219            default_font_family: "Arial".to_string(),
220            default_font_size: 11.0,
221        }
222    }
223}
224
225/// Computed layout for a single cell during rendering.
226struct CellLayout {
227    x: f64,
228    y: f64,
229    width: f64,
230    height: f64,
231    col: u32,
232    row: u32,
233    column_style: u32,
234}
235
236struct ColumnMetadataIndex {
237    widths: Vec<f64>,
238    styles: Vec<u32>,
239}
240
241impl ColumnMetadataIndex {
242    fn build(ws: &WorksheetXml, min_col: u32, max_col: u32) -> Result<(Self, usize)> {
243        let count = usize::try_from(u64::from(max_col - min_col) + 1)
244            .map_err(|_| Error::Internal("render column count is not addressable".to_string()))?;
245
246        let mut widths = Vec::new();
247        widths
248            .try_reserve_exact(count)
249            .map_err(|_| Error::Internal("render column layout allocation failed".to_string()))?;
250        widths.resize(count, DEFAULT_COL_WIDTH_PX);
251
252        let mut styles = Vec::new();
253        styles
254            .try_reserve_exact(count)
255            .map_err(|_| Error::Internal("render column layout allocation failed".to_string()))?;
256        styles.resize(count, 0);
257
258        let parent_count = count.checked_add(1).ok_or_else(|| {
259            Error::Internal("render column metadata index is too large".to_string())
260        })?;
261        let mut next_unresolved = Vec::new();
262        next_unresolved
263            .try_reserve_exact(parent_count)
264            .map_err(|_| {
265                Error::Internal("render column metadata index allocation failed".to_string())
266            })?;
267        next_unresolved.extend(0..parent_count);
268
269        let mut resolution_work = 0usize;
270        if let Some(columns) = ws.cols.as_ref() {
271            // Resolve in source order to preserve the renderer's first-match semantics.
272            for column in &columns.cols {
273                resolution_work = resolution_work.saturating_add(1);
274                if column.min > column.max || column.max < min_col || column.min > max_col {
275                    continue;
276                }
277
278                let start = usize::try_from(column.min.max(min_col) - min_col).map_err(|_| {
279                    Error::Internal("render column start is not addressable".to_string())
280                })?;
281                let end = usize::try_from(column.max.min(max_col) - min_col).map_err(|_| {
282                    Error::Internal("render column end is not addressable".to_string())
283                })?;
284                let mut offset = find_next_unresolved(&mut next_unresolved, start);
285                while offset <= end {
286                    widths[offset] = column
287                        .width
288                        .map(col_width_to_px)
289                        .unwrap_or(DEFAULT_COL_WIDTH_PX);
290                    styles[offset] = column.style.unwrap_or(0);
291                    resolution_work = resolution_work.saturating_add(1);
292
293                    let next = find_next_unresolved(&mut next_unresolved, offset + 1);
294                    next_unresolved[offset] = next;
295                    offset = next;
296                }
297            }
298        }
299
300        Ok((Self { widths, styles }, resolution_work))
301    }
302}
303
304fn find_next_unresolved(parent: &mut [usize], index: usize) -> usize {
305    let mut root = index;
306    while parent[root] != root {
307        root = parent[root];
308    }
309
310    let mut current = index;
311    while parent[current] != current {
312        let next = parent[current];
313        parent[current] = root;
314        current = next;
315    }
316    root
317}
318
319/// Per-render memo of [`get_style`] results. Styles are pure functions of
320/// the stylesheet, so each referenced style id is resolved once.
321struct StyleCache<'s> {
322    stylesheet: &'s StyleSheet,
323    entries: HashMap<u32, Option<Style>>,
324}
325
326impl<'s> StyleCache<'s> {
327    fn new(stylesheet: &'s StyleSheet) -> Self {
328        Self {
329            stylesheet,
330            entries: HashMap::new(),
331        }
332    }
333
334    fn get(&mut self, style_id: u32) -> Option<&Style> {
335        let stylesheet = self.stylesheet;
336        self.entries
337            .entry(style_id)
338            .or_insert_with(|| get_style(stylesheet, style_id))
339            .as_ref()
340    }
341}
342
343struct LayoutGrid<'a> {
344    col_widths: &'a [f64],
345    col_styles: &'a [u32],
346    row_heights: &'a [f64],
347    min_col: u32,
348    min_row: u32,
349    x_offset: f64,
350    y_offset: f64,
351}
352
353impl LayoutGrid<'_> {
354    fn for_each(&self, mut visitor: impl FnMut(&CellLayout) -> Result<()>) -> Result<()> {
355        let mut y = self.y_offset;
356        for (row_index, height) in self.row_heights.iter().copied().enumerate() {
357            let row = self.min_row + row_index as u32;
358            let mut x = self.x_offset;
359            for (column_index, width) in self.col_widths.iter().copied().enumerate() {
360                let col = self.min_col + column_index as u32;
361                visitor(&CellLayout {
362                    x,
363                    y,
364                    width,
365                    height,
366                    col,
367                    row,
368                    column_style: self.col_styles[column_index],
369                })?;
370                x += width;
371            }
372            y += height;
373        }
374        Ok(())
375    }
376}
377
378/// Render a worksheet to an SVG string.
379///
380/// Uses the worksheet XML, shared string table, and stylesheet to produce
381/// a visual representation of the sheet as SVG. The `options` parameter
382/// controls which sheet, range, and visual features to include.
383pub fn render_to_svg(
384    ws: &WorksheetXml,
385    sst: &SharedStringTable,
386    stylesheet: &StyleSheet,
387    options: &RenderOptions,
388) -> Result<String> {
389    render_to_svg_with_limits(ws, sst, stylesheet, options, TraversalLimits::default())
390}
391
392/// Renders a worksheet using explicit finite dense traversal limits.
393pub fn render_to_svg_with_limits(
394    ws: &WorksheetXml,
395    sst: &SharedStringTable,
396    stylesheet: &StyleSheet,
397    options: &RenderOptions,
398    limits: TraversalLimits,
399) -> Result<String> {
400    render_to_svg_with_theme_and_limits(
401        ws,
402        sst,
403        stylesheet,
404        &default_theme_colors(),
405        options,
406        limits,
407    )
408}
409
410/// Render a worksheet to SVG using the supplied theme colors.
411pub(crate) fn render_to_svg_with_theme(
412    ws: &WorksheetXml,
413    sst: &SharedStringTable,
414    stylesheet: &StyleSheet,
415    theme: &ThemeColors,
416    options: &RenderOptions,
417) -> Result<String> {
418    render_to_svg_with_theme_and_limits(
419        ws,
420        sst,
421        stylesheet,
422        theme,
423        options,
424        TraversalLimits::default(),
425    )
426}
427
428pub(crate) fn render_to_svg_with_theme_and_limits(
429    ws: &WorksheetXml,
430    sst: &SharedStringTable,
431    stylesheet: &StyleSheet,
432    theme: &ThemeColors,
433    options: &RenderOptions,
434    limits: TraversalLimits,
435) -> Result<String> {
436    validate_positive_finite(options.scale, "render scale must be positive and finite")?;
437    validate_positive_finite(
438        options.default_font_size,
439        "default font size must be positive and finite",
440    )?;
441    let output_limit = MAX_SVG_OUTPUT_BYTES.min(limits.max_output_bytes());
442    let mut svg = SvgOutput::new(output_limit);
443    let default_font_family = css_font_family_attribute(&options.default_font_family, &svg)?;
444
445    let (min_col, min_row, max_col, max_row) = compute_range(ws, sst, options, limits)?;
446    let _rect = render_checked_rect(min_col, min_row, max_col, max_row, limits)?;
447
448    let (column_metadata, _metadata_work) = ColumnMetadataIndex::build(ws, min_col, max_col)?;
449    let col_widths = column_metadata.widths.as_slice();
450    let row_heights = compute_row_heights(ws, min_row, max_row)?;
451
452    let total_width: f64 = col_widths.iter().sum();
453    let total_height: f64 = row_heights.iter().sum();
454    validate_finite_nonnegative(total_width, "render width must be finite and non-negative")?;
455    validate_finite_nonnegative(
456        total_height,
457        "render height must be finite and non-negative",
458    )?;
459
460    let header_x_offset = if options.show_headers {
461        HEADER_WIDTH
462    } else {
463        0.0
464    };
465    let header_y_offset = if options.show_headers {
466        HEADER_HEIGHT
467    } else {
468        0.0
469    };
470
471    let svg_width = (total_width + header_x_offset) * options.scale;
472    let svg_height = (total_height + header_y_offset) * options.scale;
473    validate_finite_nonnegative(svg_width, "SVG width must be finite and non-negative")?;
474    validate_finite_nonnegative(svg_height, "SVG height must be finite and non-negative")?;
475
476    svg.push_str(&format!(
477        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{svg_width}" height="{svg_height}" viewBox="0 0 {} {}" font-family=""#,
478        total_width + header_x_offset,
479        total_height + header_y_offset,
480    ))?;
481    svg.push_str(&default_font_family)?;
482    svg.push_str(&format!(r#"" font-size="{}">"#, options.default_font_size))?;
483
484    // White background
485    svg.push_str(&format!(
486        r#"<rect width="{}" height="{}" fill="white"/>"#,
487        total_width + header_x_offset,
488        total_height + header_y_offset,
489    ))?;
490
491    // Render column headers
492    if options.show_headers {
493        render_column_headers(&mut svg, col_widths, min_col, header_x_offset, options)?;
494        render_row_headers(&mut svg, &row_heights, min_row, header_y_offset, options)?;
495    }
496
497    let layouts = LayoutGrid {
498        col_widths,
499        col_styles: &column_metadata.styles,
500        row_heights: &row_heights,
501        min_col,
502        min_row,
503        x_offset: header_x_offset,
504        y_offset: header_y_offset,
505    };
506
507    // Render cell fills
508    let mut styles = StyleCache::new(stylesheet);
509    render_cell_fills(&mut svg, ws, &mut styles, theme, &layouts)?;
510
511    // Render gridlines
512    if options.show_gridlines {
513        render_gridlines(
514            &mut svg,
515            col_widths,
516            &row_heights,
517            total_width,
518            total_height,
519            header_x_offset,
520            header_y_offset,
521        )?;
522    }
523
524    // Render cell borders
525    render_cell_borders(&mut svg, ws, &mut styles, theme, &layouts, min_col, min_row)?;
526
527    // Render cell text
528    render_cell_text(
529        &mut svg,
530        ws,
531        sst,
532        &mut styles,
533        theme,
534        &layouts,
535        min_col,
536        min_row,
537        options,
538    )?;
539
540    svg.push_str("</svg>")?;
541    Ok(svg.finish())
542}
543
544fn render_checked_rect(
545    min_col: u32,
546    min_row: u32,
547    max_col: u32,
548    max_row: u32,
549    limits: TraversalLimits,
550) -> Result<CheckedRect> {
551    CheckedRect::new(min_row, max_row, min_col, max_col, limits).map_err(|error| match error {
552        Error::ResourceLimitExceeded(metadata) => ResourceLimitError::exceeded(
553            ResourceOperation::Render,
554            ResourceCategory::Traversal,
555            metadata.dimension(),
556            metadata.limit(),
557            metadata.observed(),
558            Some(ResourceStage::Render),
559        )
560        .map(Error::from)
561        .unwrap_or_else(|| Error::Internal("invalid render resource limit".to_string())),
562        other => other,
563    })
564}
565
566/// Determine the range of cells to render.
567fn compute_range(
568    ws: &WorksheetXml,
569    _sst: &SharedStringTable,
570    options: &RenderOptions,
571    limits: TraversalLimits,
572) -> Result<(u32, u32, u32, u32)> {
573    if let Some(ref range) = options.range {
574        let parts: Vec<&str> = range.split(':').collect();
575        if parts.len() != 2 {
576            return Err(Error::InvalidCellReference(format!(
577                "expected range like 'A1:F20', got '{range}'"
578            )));
579        }
580        let (c1, r1) = cell_name_to_coordinates(parts[0])?;
581        let (c2, r2) = cell_name_to_coordinates(parts[1])?;
582        Ok((c1.min(c2), r1.min(r2), c1.max(c2), r1.max(r2)))
583    } else {
584        // Rendering computes bounds from cell presence only, so date
585        // promotion is not relevant here. Skip the lookup.
586        if ws.sheet_data.rows.is_empty() {
587            return Ok((1, 1, 1, 1));
588        }
589        let mut min_col = u32::MAX;
590        let mut max_col = 0u32;
591        let mut min_row = u32::MAX;
592        let mut max_row = 0;
593        let mut visited_rows = 0u64;
594        let mut visited_cells = 0u64;
595        for row in &ws.sheet_data.rows {
596            visited_rows = visited_rows.saturating_add(1);
597            check_render_visit_limit(ResourceDimension::RowCount, limits.max_rows(), visited_rows)?;
598            if row.cells.is_empty() {
599                continue;
600            }
601            min_row = min_row.min(row.r);
602            max_row = max_row.max(row.r);
603            for cell in &row.cells {
604                visited_cells = visited_cells.saturating_add(1);
605                check_render_visit_limit(
606                    ResourceDimension::CellCount,
607                    limits.max_cells(),
608                    visited_cells,
609                )?;
610                let col = if cell.col > 0 {
611                    cell.col
612                } else {
613                    cell_name_to_coordinates(cell.r.as_str())?.0
614                };
615                min_col = min_col.min(col);
616                max_col = max_col.max(col);
617            }
618        }
619        if min_row == u32::MAX {
620            return Ok((1, 1, 1, 1));
621        }
622        if min_col == u32::MAX {
623            min_col = 1;
624        }
625        if max_col == 0 {
626            max_col = 1;
627        }
628        Ok((min_col, min_row, max_col, max_row))
629    }
630}
631
632fn check_render_visit_limit(dimension: ResourceDimension, limit: u64, observed: u64) -> Result<()> {
633    if observed <= limit {
634        return Ok(());
635    }
636    let metadata = ResourceLimitError::exceeded(
637        ResourceOperation::Render,
638        ResourceCategory::Traversal,
639        dimension,
640        limit,
641        observed,
642        Some(ResourceStage::Render),
643    )
644    .ok_or_else(|| Error::Internal("invalid render traversal limit".to_string()))?;
645    Err(metadata.into())
646}
647
648/// Compute pixel heights for each row in the range.
649fn compute_row_heights(ws: &WorksheetXml, min_row: u32, max_row: u32) -> Result<Vec<f64>> {
650    let count = usize::try_from(u64::from(max_row - min_row) + 1)
651        .map_err(|_| Error::Internal("render row count is not addressable".to_string()))?;
652    let mut heights = Vec::new();
653    heights
654        .try_reserve_exact(count)
655        .map_err(|_| Error::Internal("render row layout allocation failed".to_string()))?;
656    for row_num in min_row..=max_row {
657        heights.push(match get_row_height(ws, row_num) {
658            Some(h) => row_height_to_px(h),
659            None => DEFAULT_ROW_HEIGHT_PX,
660        });
661    }
662    Ok(heights)
663}
664
665/// Render column header labels (A, B, C, ...).
666fn render_column_headers(
667    svg: &mut SvgOutput,
668    col_widths: &[f64],
669    min_col: u32,
670    x_offset: f64,
671    _options: &RenderOptions,
672) -> Result<()> {
673    let total_w: f64 = col_widths.iter().sum();
674    svg.push_str(&format!(
675        "<rect x=\"{x_offset}\" y=\"0\" width=\"{total_w}\" height=\"{HEADER_HEIGHT}\" fill=\"{HEADER_BG_COLOR}\"/>",
676    ))?;
677
678    let mut x = x_offset;
679    for (i, &w) in col_widths.iter().enumerate() {
680        let col_num = min_col + i as u32;
681        let col_name = column_number_to_name(col_num).unwrap_or_default();
682        let text_x = x + w / 2.0;
683        let text_y = HEADER_HEIGHT / 2.0 + 4.0;
684        svg.push_str(&format!(
685            "<text x=\"{text_x}\" y=\"{text_y}\" text-anchor=\"middle\" fill=\"{HEADER_TEXT_COLOR}\" font-size=\"10\">{col_name}</text>",
686        ))?;
687        x += w;
688    }
689    Ok(())
690}
691
692/// Render row header labels (1, 2, 3, ...).
693fn render_row_headers(
694    svg: &mut SvgOutput,
695    row_heights: &[f64],
696    min_row: u32,
697    y_offset: f64,
698    _options: &RenderOptions,
699) -> Result<()> {
700    let total_h: f64 = row_heights.iter().sum();
701    svg.push_str(&format!(
702        "<rect x=\"0\" y=\"{y_offset}\" width=\"{HEADER_WIDTH}\" height=\"{total_h}\" fill=\"{HEADER_BG_COLOR}\"/>",
703    ))?;
704
705    let mut y = y_offset;
706    for (i, &h) in row_heights.iter().enumerate() {
707        let row_num = min_row + i as u32;
708        let text_x = HEADER_WIDTH / 2.0;
709        let text_y = y + h / 2.0 + 4.0;
710        svg.push_str(&format!(
711            "<text x=\"{text_x}\" y=\"{text_y}\" text-anchor=\"middle\" fill=\"{HEADER_TEXT_COLOR}\" font-size=\"10\">{row_num}</text>",
712        ))?;
713        y += h;
714    }
715    Ok(())
716}
717
718/// Render cell background fills.
719fn render_cell_fills(
720    svg: &mut SvgOutput,
721    ws: &WorksheetXml,
722    styles: &mut StyleCache<'_>,
723    theme: &ThemeColors,
724    layouts: &LayoutGrid<'_>,
725) -> Result<()> {
726    let mut scratch = String::new();
727    layouts.for_each(|layout| {
728        let style_id = find_cell_style(ws, layout.col, layout.row, layout.column_style);
729        if style_id == 0 {
730            return Ok(());
731        }
732        if let Some(style) = styles.get(style_id) {
733            if let Some(ref fill) = style.fill {
734                if fill.pattern == PatternType::Solid {
735                    if let Some(ref color) = fill.fg_color {
736                        let hex = style_color_to_hex(color, theme)?;
737                        svg.push_fmt(
738                            &mut scratch,
739                            format_args!(
740                                r#"<rect x="{}" y="{}" width="{}" height="{}" fill="{}"/>"#,
741                                layout.x, layout.y, layout.width, layout.height, hex
742                            ),
743                        )?;
744                    }
745                }
746            }
747        }
748        Ok(())
749    })
750}
751
752/// Render gridlines.
753fn render_gridlines(
754    svg: &mut SvgOutput,
755    col_widths: &[f64],
756    row_heights: &[f64],
757    total_width: f64,
758    total_height: f64,
759    x_offset: f64,
760    y_offset: f64,
761) -> Result<()> {
762    let mut y = y_offset;
763    for h in row_heights {
764        y += h;
765        let x2 = x_offset + total_width;
766        svg.push_str(&format!(
767            "<line x1=\"{x_offset}\" y1=\"{y}\" x2=\"{x2}\" y2=\"{y}\" stroke=\"{GRIDLINE_COLOR}\" stroke-width=\"0.5\"/>",
768        ))?;
769    }
770
771    let mut x = x_offset;
772    for w in col_widths {
773        x += w;
774        let y2 = y_offset + total_height;
775        svg.push_str(&format!(
776            "<line x1=\"{x}\" y1=\"{y_offset}\" x2=\"{x}\" y2=\"{y2}\" stroke=\"{GRIDLINE_COLOR}\" stroke-width=\"0.5\"/>",
777        ))?;
778    }
779    Ok(())
780}
781
782/// Render cell borders.
783fn render_cell_borders(
784    svg: &mut SvgOutput,
785    ws: &WorksheetXml,
786    styles: &mut StyleCache<'_>,
787    theme: &ThemeColors,
788    layouts: &LayoutGrid<'_>,
789    _min_col: u32,
790    _min_row: u32,
791) -> Result<()> {
792    let mut scratch = String::new();
793    layouts.for_each(|layout| {
794        let style_id = find_cell_style(ws, layout.col, layout.row, layout.column_style);
795        if style_id == 0 {
796            return Ok(());
797        }
798        let style = match styles.get(style_id) {
799            Some(s) => s,
800            None => return Ok(()),
801        };
802        let border = match &style.border {
803            Some(b) => b,
804            None => return Ok(()),
805        };
806
807        let x1 = layout.x;
808        let y1 = layout.y;
809        let x2 = layout.x + layout.width;
810        let y2 = layout.y + layout.height;
811
812        if let Some(ref left) = border.left {
813            let (sw, color) = border_line_attrs(left.style, left.color.as_ref(), theme)?;
814            svg.push_fmt(&mut scratch, format_args!(
815                r#"<line x1="{x1}" y1="{y1}" x2="{x1}" y2="{y2}" stroke="{color}" stroke-width="{sw}"/>"#,
816            ))?;
817        }
818        if let Some(ref right) = border.right {
819            let (sw, color) = border_line_attrs(right.style, right.color.as_ref(), theme)?;
820            svg.push_fmt(&mut scratch, format_args!(
821                r#"<line x1="{x2}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{color}" stroke-width="{sw}"/>"#,
822            ))?;
823        }
824        if let Some(ref top) = border.top {
825            let (sw, color) = border_line_attrs(top.style, top.color.as_ref(), theme)?;
826            svg.push_fmt(&mut scratch, format_args!(
827                r#"<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y1}" stroke="{color}" stroke-width="{sw}"/>"#,
828            ))?;
829        }
830        if let Some(ref bottom) = border.bottom {
831            let (sw, color) = border_line_attrs(bottom.style, bottom.color.as_ref(), theme)?;
832            svg.push_fmt(&mut scratch, format_args!(
833                r#"<line x1="{x1}" y1="{y2}" x2="{x2}" y2="{y2}" stroke="{color}" stroke-width="{sw}"/>"#,
834            ))?;
835        }
836        Ok(())
837    })
838}
839
840/// Render cell text values.
841#[allow(clippy::too_many_arguments)]
842fn render_cell_text(
843    svg: &mut SvgOutput,
844    ws: &WorksheetXml,
845    sst: &SharedStringTable,
846    styles: &mut StyleCache<'_>,
847    theme: &ThemeColors,
848    layouts: &LayoutGrid<'_>,
849    _min_col: u32,
850    _min_row: u32,
851    options: &RenderOptions,
852) -> Result<()> {
853    let mut scratch = String::new();
854    let mut staged = String::new();
855    // Escaped font-family attribute values keyed by font name.
856    let mut font_families: HashMap<String, String> = HashMap::new();
857    layouts.for_each(|layout| {
858        let Some(cell) = find_cell(ws, layout.col, layout.row) else {
859            return Ok(());
860        };
861        let cell_text = CellText::from_cell(cell, sst);
862        if cell_text.is_empty() {
863            return Ok(());
864        }
865
866        let style_id = find_cell_style(ws, layout.col, layout.row, layout.column_style);
867        let style = styles.get(style_id);
868
869        let font = style.and_then(|s| s.font.as_ref());
870        let alignment = style.and_then(|s| s.alignment.as_ref());
871
872        let (text_x, anchor) = compute_text_x(layout, alignment);
873        let text_y = compute_text_y(layout, alignment, font, options)?;
874
875        let mut attrs = svg.stage_with(std::mem::take(&mut staged));
876        attrs.push_fmt(&mut scratch, format_args!(r#" x="{text_x}" y="{text_y}""#))?;
877        attrs.push_fmt(&mut scratch, format_args!(r#" text-anchor="{anchor}""#))?;
878
879        if let Some(f) = font {
880            if f.bold {
881                attrs.push_str(r#" font-weight="bold""#)?;
882            }
883            if f.italic {
884                attrs.push_str(r#" font-style="italic""#)?;
885            }
886            if let Some(ref name) = f.name {
887                attrs.push_str(r#" font-family=""#)?;
888                // A cached value that fits cannot hit any intermediate limit
889                // in css_font_family_attribute (its staged lengths never
890                // exceed the final escaped length); otherwise recompute so
891                // the outcome, including any error, is unchanged.
892                match font_families.get(name.as_str()) {
893                    Some(escaped) if attrs.fits(escaped.len()) => attrs.push_str(escaped)?,
894                    _ => {
895                        let escaped = css_font_family_attribute(name, &attrs)?;
896                        attrs.push_str(&escaped)?;
897                        font_families.insert(name.clone(), escaped);
898                    }
899                }
900                attrs.push_str("\"")?;
901            }
902            if let Some(size) = f.size {
903                validate_positive_finite(size, "font size must be positive and finite")?;
904                attrs.push_fmt(&mut scratch, format_args!(r#" font-size="{size}""#))?;
905            }
906            if let Some(ref color) = f.color {
907                let hex = style_color_to_hex(color, theme)?;
908                attrs.push_fmt(&mut scratch, format_args!(r#" fill="{hex}""#))?;
909            }
910            let mut decorations = Vec::new();
911            if f.underline {
912                decorations.push("underline");
913            }
914            if f.strikethrough {
915                decorations.push("line-through");
916            }
917            if !decorations.is_empty() {
918                attrs.push_str(&format!(r#" text-decoration="{}""#, decorations.join(" ")))?;
919            }
920        }
921
922        svg.push_str("<text")?;
923        let attrs = attrs.finish();
924        svg.push_str(&attrs)?;
925        staged = attrs;
926        svg.push_str(">")?;
927        cell_text.write_escaped(svg)?;
928        svg.push_str("</text>")?;
929        Ok(())
930    })
931}
932
933enum CellText<'a> {
934    Empty,
935    Borrowed(&'a str),
936    Inline(&'a InlineString),
937    Formula(&'a str),
938    Static(&'static str),
939    Number(f64),
940}
941
942impl<'a> CellText<'a> {
943    fn from_cell(cell: &'a Cell, sst: &'a SharedStringTable) -> Self {
944        if let Some(formula) = cell.f.as_deref() {
945            let expression = formula.value.as_deref().unwrap_or("");
946            return match (cell.t, cell.v.as_deref()) {
947                (CellTypeTag::Boolean, Some(value)) => {
948                    Self::Static(if value == "1" { "TRUE" } else { "FALSE" })
949                }
950                (CellTypeTag::Error | CellTypeTag::FormulaString, Some(value)) => {
951                    Self::Borrowed(value)
952                }
953                (CellTypeTag::SharedString, Some(value)) => sst_text(sst, value),
954                (CellTypeTag::InlineString, _) => {
955                    cell.is.as_deref().map(Self::Inline).unwrap_or(Self::Empty)
956                }
957                (CellTypeTag::None | CellTypeTag::Number | CellTypeTag::Date, Some(value)) => value
958                    .parse::<f64>()
959                    .map(Self::Number)
960                    .unwrap_or(Self::Formula(expression)),
961                _ => Self::Formula(expression),
962            };
963        }
964
965        match (cell.t, cell.v.as_deref()) {
966            (CellTypeTag::SharedString, Some(value)) => sst_text(sst, value),
967            (CellTypeTag::Boolean, Some(value)) => {
968                Self::Static(if value == "1" { "TRUE" } else { "FALSE" })
969            }
970            (CellTypeTag::Error | CellTypeTag::FormulaString, Some(value)) => Self::Borrowed(value),
971            (CellTypeTag::InlineString, _) => {
972                cell.is.as_deref().map(Self::Inline).unwrap_or(Self::Empty)
973            }
974            (CellTypeTag::None | CellTypeTag::Number, Some(value)) => value
975                .parse::<f64>()
976                .map(Self::Number)
977                .unwrap_or(Self::Empty),
978            _ => Self::Empty,
979        }
980    }
981
982    fn is_empty(&self) -> bool {
983        match self {
984            Self::Empty => true,
985            Self::Borrowed(value) | Self::Static(value) => value.is_empty(),
986            Self::Inline(value) => {
987                value.t.as_deref().is_none_or(str::is_empty)
988                    && value.r.iter().all(|run| run.t.value.is_empty())
989            }
990            Self::Formula(_) | Self::Number(_) => false,
991        }
992    }
993
994    fn write_escaped(&self, output: &mut SvgOutput) -> Result<()> {
995        match self {
996            Self::Empty => Ok(()),
997            Self::Borrowed(value) | Self::Static(value) => push_xml_text(output, value),
998            Self::Inline(value) => {
999                let escaped_len = value
1000                    .t
1001                    .as_deref()
1002                    .map(xml_text_escaped_len)
1003                    .transpose()?
1004                    .unwrap_or(0);
1005                let escaped_len = value.r.iter().try_fold(escaped_len, |total, run| {
1006                    Ok::<_, Error>(total.saturating_add(xml_text_escaped_len(&run.t.value)?))
1007                })?;
1008                output.ensure_additional(escaped_len)?;
1009                if let Some(text) = value.t.as_deref() {
1010                    push_xml_text_unchecked(output, text)?;
1011                }
1012                for run in &value.r {
1013                    push_xml_text_unchecked(output, &run.t.value)?;
1014                }
1015                Ok(())
1016            }
1017            Self::Formula(expression) => {
1018                let escaped_len = 1u64.saturating_add(xml_text_escaped_len(expression)?);
1019                output.ensure_additional(escaped_len)?;
1020                output.push_str("=")?;
1021                push_xml_text_unchecked(output, expression)
1022            }
1023            Self::Number(number) => push_xml_text(output, &display_number(*number)),
1024        }
1025    }
1026}
1027
1028fn sst_text<'a>(sst: &'a SharedStringTable, index: &str) -> CellText<'a> {
1029    index
1030        .parse::<usize>()
1031        .ok()
1032        .and_then(|index| sst.get(index))
1033        .map(CellText::Borrowed)
1034        .unwrap_or(CellText::Empty)
1035}
1036
1037fn display_number(number: f64) -> String {
1038    if number.fract() == 0.0 && number.is_finite() {
1039        (number as i64).to_string()
1040    } else {
1041        number.to_string()
1042    }
1043}
1044
1045/// Compute the x position and text-anchor for a cell's text based on alignment.
1046fn compute_text_x(layout: &CellLayout, alignment: Option<&AlignmentStyle>) -> (f64, &'static str) {
1047    let padding = 3.0;
1048    match alignment.and_then(|a| a.horizontal) {
1049        Some(HorizontalAlign::Center) | Some(HorizontalAlign::CenterContinuous) => {
1050            (layout.x + layout.width / 2.0, "middle")
1051        }
1052        Some(HorizontalAlign::Right) => (layout.x + layout.width - padding, "end"),
1053        _ => (layout.x + padding, "start"),
1054    }
1055}
1056
1057/// Compute the y position for a cell's text based on vertical alignment.
1058fn compute_text_y(
1059    layout: &CellLayout,
1060    alignment: Option<&AlignmentStyle>,
1061    font: Option<&FontStyle>,
1062    options: &RenderOptions,
1063) -> Result<f64> {
1064    let font_size = font
1065        .and_then(|f| f.size)
1066        .unwrap_or(options.default_font_size);
1067    validate_positive_finite(font_size, "font size must be positive and finite")?;
1068    Ok(match alignment.and_then(|a| a.vertical) {
1069        Some(VerticalAlign::Top) => layout.y + font_size + 2.0,
1070        Some(VerticalAlign::Center) => layout.y + layout.height / 2.0 + font_size / 3.0,
1071        _ => layout.y + layout.height - 4.0,
1072    })
1073}
1074
1075/// Find the style ID for a cell at the given coordinates.
1076fn find_cell_style(ws: &WorksheetXml, col: u32, row: u32, column_style: u32) -> u32 {
1077    let row_data = ws
1078        .sheet_data
1079        .rows
1080        .binary_search_by_key(&row, |r| r.r)
1081        .ok()
1082        .map(|idx| &ws.sheet_data.rows[idx]);
1083
1084    if let Some(row_data) = row_data {
1085        if let Some(cell) = row_data
1086            .cells
1087            .binary_search_by_key(&col, |c| c.col)
1088            .ok()
1089            .map(|idx| &row_data.cells[idx])
1090        {
1091            if let Some(style) = cell.s {
1092                return style;
1093            }
1094        }
1095        if let Some(style) = row_data.s {
1096            return style;
1097        }
1098    }
1099
1100    column_style
1101}
1102
1103/// Find a cell at the given coordinates without cloning its value.
1104fn find_cell(ws: &WorksheetXml, col: u32, row: u32) -> Option<&Cell> {
1105    ws.sheet_data
1106        .rows
1107        .binary_search_by_key(&row, |r| r.r)
1108        .ok()
1109        .and_then(|idx| {
1110            let row_data = &ws.sheet_data.rows[idx];
1111            row_data
1112                .cells
1113                .binary_search_by_key(&col, |c| c.col)
1114                .ok()
1115                .map(|ci| &row_data.cells[ci])
1116        })
1117}
1118
1119/// Convert a StyleColor to a validated SVG hex color string.
1120fn style_color_to_hex(color: &StyleColor, theme: &ThemeColors) -> Result<String> {
1121    match color {
1122        StyleColor::Rgb(rgb) => rgb_to_svg_hex(rgb),
1123        StyleColor::Theme(index) => match resolve_theme_color(theme, *index, None) {
1124            Some(color) => rgb_to_svg_hex(&color),
1125            None => Ok("#000000".to_string()),
1126        },
1127        StyleColor::Indexed(_) => Ok("#000000".to_string()),
1128    }
1129}
1130
1131fn rgb_to_svg_hex(rgb: &str) -> Result<String> {
1132    let digits = rgb.strip_prefix('#').unwrap_or(rgb);
1133    if !matches!(digits.len(), 6 | 8) || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1134        return Err(Error::InvalidArgument("invalid SVG color".to_string()));
1135    }
1136
1137    let digits = if digits.len() == 8 {
1138        digits
1139            .get(2..)
1140            .ok_or_else(|| Error::InvalidArgument("invalid SVG color".to_string()))?
1141    } else {
1142        digits
1143    };
1144    Ok(format!("#{digits}"))
1145}
1146
1147/// Convert a border line style to SVG stroke-width and color.
1148fn border_line_attrs(
1149    style: BorderLineStyle,
1150    color: Option<&StyleColor>,
1151    theme: &ThemeColors,
1152) -> Result<(f64, String)> {
1153    let stroke_width = match style {
1154        BorderLineStyle::Thin | BorderLineStyle::Hair => 1.0,
1155        BorderLineStyle::Medium
1156        | BorderLineStyle::MediumDashed
1157        | BorderLineStyle::MediumDashDot
1158        | BorderLineStyle::MediumDashDotDot => 2.0,
1159        BorderLineStyle::Thick => 3.0,
1160        _ => 1.0,
1161    };
1162    let color_str = color
1163        .map(|color| style_color_to_hex(color, theme))
1164        .transpose()?
1165        .unwrap_or_else(|| "#000000".to_string());
1166    Ok((stroke_width, color_str))
1167}
1168
1169fn validate_positive_finite(value: f64, message: &'static str) -> Result<()> {
1170    if !value.is_finite() || value <= 0.0 {
1171        return Err(Error::InvalidArgument(message.to_string()));
1172    }
1173    Ok(())
1174}
1175
1176fn validate_finite_nonnegative(value: f64, message: &'static str) -> Result<()> {
1177    if !value.is_finite() || value < 0.0 {
1178        return Err(Error::InvalidArgument(message.to_string()));
1179    }
1180    Ok(())
1181}
1182
1183fn is_xml_char(c: char) -> bool {
1184    matches!(c, '\u{9}' | '\u{A}' | '\u{D}')
1185        || ('\u{20}'..='\u{D7FF}').contains(&c)
1186        || ('\u{E000}'..='\u{FFFD}').contains(&c)
1187        || ('\u{10000}'..='\u{10FFFF}').contains(&c)
1188}
1189
1190fn validate_xml_chars(value: &str, message: &'static str) -> Result<()> {
1191    if value.chars().any(|c| !is_xml_char(c)) {
1192        return Err(Error::InvalidArgument(message.to_string()));
1193    }
1194    Ok(())
1195}
1196
1197/// Escape XML text while preserving printable Unicode.
1198#[cfg(test)]
1199fn xml_text_escape(s: &str) -> Result<String> {
1200    let mut out = SvgOutput::new(MAX_SVG_OUTPUT_BYTES);
1201    push_xml_text(&mut out, s)?;
1202    Ok(out.finish())
1203}
1204
1205fn push_xml_text(output: &mut SvgOutput, value: &str) -> Result<()> {
1206    output.ensure_additional(xml_text_escaped_len(value)?)?;
1207    push_xml_text_unchecked(output, value)
1208}
1209
1210/// Validate XML characters and return the escaped text length in one pass.
1211fn xml_text_escaped_len(value: &str) -> Result<u64> {
1212    let mut length = 0u64;
1213    for c in value.chars() {
1214        if !is_xml_char(c) {
1215            return Err(Error::InvalidArgument(
1216                "SVG text contains an XML-forbidden character".to_string(),
1217            ));
1218        }
1219        length = length.saturating_add(match c {
1220            '&' => 5,
1221            '<' | '>' => 4,
1222            _ => u64::from(c.len_utf8() as u32),
1223        });
1224    }
1225    Ok(length)
1226}
1227
1228fn xml_text_escape_char(c: char) -> Option<&'static str> {
1229    match c {
1230        '&' => Some("&amp;"),
1231        '<' => Some("&lt;"),
1232        '>' => Some("&gt;"),
1233        _ => None,
1234    }
1235}
1236
1237fn push_xml_text_unchecked(out: &mut SvgOutput, s: &str) -> Result<()> {
1238    out.push_escaped(s, xml_text_escape_char)
1239}
1240
1241/// Escape one XML attribute after its CSS value has been encoded.
1242fn xml_attribute_escape(s: &str, parent: &SvgOutput) -> Result<String> {
1243    validate_xml_chars(s, "SVG attribute contains an XML-forbidden character")?;
1244    let mut out = parent.stage();
1245    out.push_escaped(s, |c| match c {
1246        '&' => Some("&amp;"),
1247        '<' => Some("&lt;"),
1248        '>' => Some("&gt;"),
1249        '"' => Some("&quot;"),
1250        '\'' => Some("&apos;"),
1251        _ => None,
1252    })?;
1253    Ok(out.finish())
1254}
1255
1256/// Encode a font family as one CSS string, then as one XML attribute value.
1257fn css_font_family_attribute(value: &str, parent: &SvgOutput) -> Result<String> {
1258    validate_xml_chars(value, "SVG font family contains an XML-forbidden character")?;
1259    let mut css = parent.stage();
1260    css.push_str("\"")?;
1261    css.push_escaped(value, |c| match c {
1262        '"' => Some("\\\""),
1263        '\\' => Some("\\\\"),
1264        '\n' => Some("\\A "),
1265        '\r' => Some("\\D "),
1266        '\t' => Some("\\9 "),
1267        '<' => Some("\\3C "),
1268        '>' => Some("\\3E "),
1269        '&' => Some("\\26 "),
1270        _ => None,
1271    })?;
1272    css.push_str("\"")?;
1273    xml_attribute_escape(&css.finish(), parent)
1274}
1275
1276#[cfg(test)]
1277#[allow(clippy::field_reassign_with_default)]
1278mod tests {
1279    use super::*;
1280    use crate::sst::SharedStringTable;
1281    use crate::style::{add_style, StyleBuilder};
1282    use sheetkit_xml::styles::StyleSheet;
1283    use sheetkit_xml::worksheet::{Cell, CellTypeTag, Col, Cols, Row, SheetData, WorksheetXml};
1284
1285    fn default_options(sheet: &str) -> RenderOptions {
1286        RenderOptions {
1287            sheet_name: sheet.to_string(),
1288            ..RenderOptions::default()
1289        }
1290    }
1291
1292    fn make_num_cell(r: &str, col: u32, v: &str) -> Cell {
1293        Cell {
1294            r: r.try_into().unwrap(),
1295            col,
1296            s: None,
1297            t: CellTypeTag::None,
1298            v: Some(v.to_string()),
1299            f: None,
1300            is: None,
1301        }
1302    }
1303
1304    fn make_sst_cell(r: &str, col: u32, sst_idx: u32) -> Cell {
1305        Cell {
1306            r: r.try_into().unwrap(),
1307            col,
1308            s: None,
1309            t: CellTypeTag::SharedString,
1310            v: Some(sst_idx.to_string()),
1311            f: None,
1312            is: None,
1313        }
1314    }
1315
1316    fn simple_ws_and_sst() -> (WorksheetXml, SharedStringTable) {
1317        let mut sst = SharedStringTable::new();
1318        sst.add("Name"); // 0
1319        sst.add("Score"); // 1
1320        sst.add("Alice"); // 2
1321
1322        let mut ws = WorksheetXml::default();
1323        ws.sheet_data = SheetData {
1324            rows: vec![
1325                Row {
1326                    r: 1,
1327                    spans: None,
1328                    s: None,
1329                    custom_format: None,
1330                    ht: None,
1331                    hidden: None,
1332                    custom_height: None,
1333                    outline_level: None,
1334                    cells: vec![make_sst_cell("A1", 1, 0), make_sst_cell("B1", 2, 1)],
1335                },
1336                Row {
1337                    r: 2,
1338                    spans: None,
1339                    s: None,
1340                    custom_format: None,
1341                    ht: None,
1342                    hidden: None,
1343                    custom_height: None,
1344                    outline_level: None,
1345                    cells: vec![make_sst_cell("A2", 1, 2), make_num_cell("B2", 2, "95")],
1346                },
1347            ],
1348        };
1349        (ws, sst)
1350    }
1351
1352    /// Per-character reference for `SvgOutput::push_escaped`.
1353    fn push_escaped_per_char(
1354        out: &mut SvgOutput,
1355        value: &str,
1356        escape: impl Fn(char) -> Option<&'static str>,
1357    ) -> Result<()> {
1358        for c in value.chars() {
1359            match escape(c) {
1360                Some(replacement) => out.push_str(replacement)?,
1361                None => {
1362                    let mut encoded = [0; 4];
1363                    out.push_str(c.encode_utf8(&mut encoded))?;
1364                }
1365            }
1366        }
1367        Ok(())
1368    }
1369
1370    fn outcome(result: Result<()>, out: SvgOutput) -> std::result::Result<String, (u64, u64)> {
1371        match result {
1372            Ok(()) => Ok(out.finish()),
1373            Err(error) => {
1374                let metadata = error.resource_metadata().unwrap();
1375                Err((metadata.limit(), metadata.observed()))
1376            }
1377        }
1378    }
1379
1380    #[test]
1381    fn push_escaped_matches_per_char_output_and_limit_errors() {
1382        let value = "ab&c<d>e\"f'g\u{e9}\u{d55c}\u{1F600}hij";
1383        for limit in 0..48 {
1384            for prefix in [0usize, 3] {
1385                let mut fast = SvgOutput::new(limit);
1386                let mut slow = SvgOutput::new(limit);
1387                let prefix = "x".repeat(prefix);
1388                let fast_prefix = fast.push_str(&prefix);
1389                let slow_prefix = slow.push_str(&prefix);
1390                assert_eq!(fast_prefix.is_ok(), slow_prefix.is_ok());
1391                if fast_prefix.is_err() {
1392                    continue;
1393                }
1394                let fast_result = fast.push_escaped(value, xml_text_escape_char);
1395                let slow_result = push_escaped_per_char(&mut slow, value, xml_text_escape_char);
1396                assert_eq!(
1397                    outcome(fast_result, fast),
1398                    outcome(slow_result, slow),
1399                    "limit {limit}"
1400                );
1401            }
1402        }
1403    }
1404
1405    #[test]
1406    fn repeated_font_family_matches_first_rendering() {
1407        let (mut ws, sst) = simple_ws_and_sst();
1408        let mut ss = StyleSheet::default();
1409        let style = add_style(
1410            &mut ss,
1411            &StyleBuilder::new()
1412                .font_name("My \"Font\" & <Co>")
1413                .font_size(12.0)
1414                .build(),
1415        )
1416        .unwrap();
1417        for row in &mut ws.sheet_data.rows {
1418            for cell in &mut row.cells {
1419                cell.s = Some(style);
1420            }
1421        }
1422        let svg = render_to_svg(&ws, &sst, &ss, &default_options("Sheet1")).unwrap();
1423        let expected = r#" font-family="&quot;My \&quot;Font\&quot; \26  \3C Co\3E &quot;""#;
1424        assert_eq!(svg.matches(expected).count(), 4, "{svg}");
1425    }
1426
1427    #[test]
1428    fn test_render_produces_valid_svg() {
1429        let (ws, sst) = simple_ws_and_sst();
1430        let ss = StyleSheet::default();
1431        let opts = default_options("Sheet1");
1432
1433        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1434
1435        assert!(svg.starts_with("<svg"));
1436        assert!(svg.ends_with("</svg>"));
1437        assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\""));
1438    }
1439
1440    #[test]
1441    fn render_dense_area_accepts_exact_limit_and_rejects_plus_one() {
1442        let (ws, sst) = simple_ws_and_sst();
1443        let stylesheet = StyleSheet::default();
1444        let mut options = default_options("Sheet1");
1445        options.range = Some("A1:B2".to_string());
1446        let exact = TraversalLimits::new(2, 2, 4, 1024 * 1024).unwrap();
1447        render_to_svg_with_limits(&ws, &sst, &stylesheet, &options, exact).unwrap();
1448
1449        let plus_one = TraversalLimits::new(2, 2, 3, 1024 * 1024).unwrap();
1450        let error =
1451            render_to_svg_with_limits(&ws, &sst, &stylesheet, &options, plus_one).unwrap_err();
1452        let Error::ResourceLimitExceeded(metadata) = error else {
1453            panic!("expected resource limit error");
1454        };
1455        assert_eq!(metadata.operation(), ResourceOperation::Render);
1456        assert_eq!(metadata.dimension(), ResourceDimension::CellCount);
1457        assert_eq!(metadata.limit(), 3);
1458        assert_eq!(metadata.observed(), 4);
1459    }
1460
1461    #[test]
1462    fn range_discovery_charges_duplicate_cell_visits() {
1463        let mut ws = WorksheetXml::default();
1464        ws.sheet_data.rows = vec![Row {
1465            r: 1,
1466            spans: None,
1467            s: None,
1468            custom_format: None,
1469            ht: None,
1470            hidden: None,
1471            custom_height: None,
1472            outline_level: None,
1473            cells: vec![make_num_cell("A1", 1, "1"), make_num_cell("A1", 1, "2")],
1474        }];
1475        let options = default_options("Sheet1");
1476        let exact = TraversalLimits::new(1, 1, 2, 1024 * 1024).unwrap();
1477        render_to_svg_with_limits(
1478            &ws,
1479            &SharedStringTable::new(),
1480            &StyleSheet::default(),
1481            &options,
1482            exact,
1483        )
1484        .unwrap();
1485
1486        let plus_one = TraversalLimits::new(1, 1, 1, 1024 * 1024).unwrap();
1487        let error = render_to_svg_with_limits(
1488            &ws,
1489            &SharedStringTable::new(),
1490            &StyleSheet::default(),
1491            &options,
1492            plus_one,
1493        )
1494        .unwrap_err();
1495        let Error::ResourceLimitExceeded(metadata) = error else {
1496            panic!("expected resource limit error");
1497        };
1498        assert_eq!(metadata.dimension(), ResourceDimension::CellCount);
1499        assert_eq!(metadata.limit(), 1);
1500        assert_eq!(metadata.observed(), 2);
1501    }
1502
1503    #[test]
1504    fn range_discovery_charges_duplicate_row_visits() {
1505        let mut ws = WorksheetXml::default();
1506        let duplicate_row = Row {
1507            r: 1,
1508            spans: None,
1509            s: None,
1510            custom_format: None,
1511            ht: None,
1512            hidden: None,
1513            custom_height: None,
1514            outline_level: None,
1515            cells: vec![make_num_cell("A1", 1, "1")],
1516        };
1517        ws.sheet_data.rows = vec![duplicate_row.clone(), duplicate_row];
1518        let options = default_options("Sheet1");
1519        let exact = TraversalLimits::new(2, 1, 2, 1024 * 1024).unwrap();
1520        render_to_svg_with_limits(
1521            &ws,
1522            &SharedStringTable::new(),
1523            &StyleSheet::default(),
1524            &options,
1525            exact,
1526        )
1527        .unwrap();
1528
1529        let plus_one = TraversalLimits::new(1, 1, 2, 1024 * 1024).unwrap();
1530        let error = render_to_svg_with_limits(
1531            &ws,
1532            &SharedStringTable::new(),
1533            &StyleSheet::default(),
1534            &options,
1535            plus_one,
1536        )
1537        .unwrap_err();
1538        let Error::ResourceLimitExceeded(metadata) = error else {
1539            panic!("expected resource limit error");
1540        };
1541        assert_eq!(metadata.dimension(), ResourceDimension::RowCount);
1542        assert_eq!(metadata.limit(), 1);
1543        assert_eq!(metadata.observed(), 2);
1544    }
1545
1546    #[test]
1547    fn bounded_text_escape_rejects_before_growing_output() {
1548        let text = "<&>".repeat(1_000_000);
1549        let mut output = SvgOutput::new(16);
1550
1551        let error = push_xml_text(&mut output, &text).unwrap_err();
1552
1553        assert!(matches!(error, Error::ResourceLimitExceeded(_)));
1554        assert_eq!(output.value.capacity(), 0);
1555    }
1556
1557    #[test]
1558    fn font_family_helper_uses_the_caller_output_limit() {
1559        let font_family = "<&>".repeat(1_000_000);
1560        let output = SvgOutput::new(16);
1561
1562        let error = css_font_family_attribute(&font_family, &output).unwrap_err();
1563
1564        let Error::ResourceLimitExceeded(metadata) = error else {
1565            panic!("expected resource limit error");
1566        };
1567        assert_eq!(metadata.dimension(), ResourceDimension::OutputBytes);
1568        assert_eq!(metadata.limit(), 16);
1569    }
1570
1571    #[test]
1572    fn render_admits_far_rows_before_layout_allocation() {
1573        let mut ws = WorksheetXml::default();
1574        ws.sheet_data.rows = vec![
1575            Row {
1576                r: 1,
1577                spans: None,
1578                s: None,
1579                custom_format: None,
1580                ht: None,
1581                hidden: None,
1582                custom_height: None,
1583                outline_level: None,
1584                cells: vec![make_num_cell("A1", 1, "1")],
1585            },
1586            Row {
1587                r: 1_048_576,
1588                spans: None,
1589                s: None,
1590                custom_format: None,
1591                ht: None,
1592                hidden: None,
1593                custom_height: None,
1594                outline_level: None,
1595                cells: vec![make_num_cell("A1048576", 1, "2")],
1596            },
1597        ];
1598        let options = default_options("Sheet1");
1599        let limits = TraversalLimits::new(1_048_576, 1, 2, 1024).unwrap();
1600        let error = render_to_svg_with_limits(
1601            &ws,
1602            &SharedStringTable::new(),
1603            &StyleSheet::default(),
1604            &options,
1605            limits,
1606        )
1607        .unwrap_err();
1608        let Error::ResourceLimitExceeded(metadata) = error else {
1609            panic!("expected resource limit error");
1610        };
1611        assert_eq!(metadata.dimension(), ResourceDimension::CellCount);
1612        assert_eq!(metadata.observed(), 1_048_576);
1613    }
1614
1615    #[test]
1616    fn explicit_default_limits_preserve_svg_output() {
1617        let (ws, sst) = simple_ws_and_sst();
1618        let stylesheet = StyleSheet::default();
1619        let options = default_options("Sheet1");
1620        let default_svg = render_to_svg(&ws, &sst, &stylesheet, &options).unwrap();
1621        let explicit_svg =
1622            render_to_svg_with_limits(&ws, &sst, &stylesheet, &options, TraversalLimits::default())
1623                .unwrap();
1624        assert_eq!(default_svg, explicit_svg);
1625
1626        let exact = TraversalLimits::new(2, 2, 4, default_svg.len() as u64).unwrap();
1627        assert_eq!(
1628            render_to_svg_with_limits(&ws, &sst, &stylesheet, &options, exact).unwrap(),
1629            default_svg
1630        );
1631        let too_small = TraversalLimits::new(2, 2, 4, default_svg.len() as u64 - 1).unwrap();
1632        let error =
1633            render_to_svg_with_limits(&ws, &sst, &stylesheet, &options, too_small).unwrap_err();
1634        let Error::ResourceLimitExceeded(metadata) = error else {
1635            panic!("expected resource limit error");
1636        };
1637        assert_eq!(metadata.dimension(), ResourceDimension::OutputBytes);
1638    }
1639
1640    #[test]
1641    fn test_render_contains_cell_text() {
1642        let (ws, sst) = simple_ws_and_sst();
1643        let ss = StyleSheet::default();
1644        let opts = default_options("Sheet1");
1645
1646        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1647
1648        assert!(
1649            svg.contains(">Name<"),
1650            "SVG should contain cell text 'Name'"
1651        );
1652        assert!(
1653            svg.contains(">Score<"),
1654            "SVG should contain cell text 'Score'"
1655        );
1656        assert!(
1657            svg.contains(">Alice<"),
1658            "SVG should contain cell text 'Alice'"
1659        );
1660        assert!(svg.contains(">95<"), "SVG should contain cell text '95'");
1661    }
1662
1663    #[test]
1664    fn test_render_contains_headers() {
1665        let (ws, sst) = simple_ws_and_sst();
1666        let ss = StyleSheet::default();
1667        let opts = default_options("Sheet1");
1668
1669        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1670
1671        assert!(svg.contains(">A<"), "SVG should contain column header 'A'");
1672        assert!(svg.contains(">B<"), "SVG should contain column header 'B'");
1673        assert!(svg.contains(">1<"), "SVG should contain row header '1'");
1674        assert!(svg.contains(">2<"), "SVG should contain row header '2'");
1675    }
1676
1677    #[test]
1678    fn test_render_no_headers() {
1679        let (ws, sst) = simple_ws_and_sst();
1680        let ss = StyleSheet::default();
1681        let mut opts = default_options("Sheet1");
1682        opts.show_headers = false;
1683
1684        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1685
1686        // With headers off, the header background rects should not appear
1687        assert!(
1688            !svg.contains("fill=\"#F0F0F0\""),
1689            "SVG should not contain header backgrounds"
1690        );
1691    }
1692
1693    #[test]
1694    fn test_render_no_gridlines() {
1695        let (ws, sst) = simple_ws_and_sst();
1696        let ss = StyleSheet::default();
1697        let mut opts = default_options("Sheet1");
1698        opts.show_gridlines = false;
1699
1700        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1701
1702        assert!(
1703            !svg.contains("stroke=\"#D0D0D0\""),
1704            "SVG should not contain gridlines"
1705        );
1706    }
1707
1708    #[test]
1709    fn test_render_with_gridlines() {
1710        let (ws, sst) = simple_ws_and_sst();
1711        let ss = StyleSheet::default();
1712        let opts = default_options("Sheet1");
1713
1714        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1715
1716        assert!(
1717            svg.contains("stroke=\"#D0D0D0\""),
1718            "SVG should contain gridlines"
1719        );
1720    }
1721
1722    #[test]
1723    fn test_render_custom_col_widths() {
1724        let (mut ws, sst) = simple_ws_and_sst();
1725        crate::col::set_col_width(&mut ws, "A", 20.0).unwrap();
1726
1727        let ss = StyleSheet::default();
1728        let opts = default_options("Sheet1");
1729
1730        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1731
1732        assert!(svg.starts_with("<svg"));
1733        assert!(svg.contains(">Name<"));
1734    }
1735
1736    #[test]
1737    fn column_metadata_index_resolves_overlaps_once_with_first_definition_winning() {
1738        let mut ws = WorksheetXml::default();
1739        let definition_count = 4_096usize;
1740        let visible_columns = 64usize;
1741        let mut definitions = Vec::with_capacity(definition_count);
1742        for index in 0..definition_count {
1743            definitions.push(Col {
1744                min: 1,
1745                max: visible_columns as u32,
1746                width: Some(10.0 + index as f64),
1747                style: Some(index as u32),
1748                hidden: None,
1749                custom_width: Some(true),
1750                outline_level: None,
1751            });
1752        }
1753        ws.cols = Some(Cols { cols: definitions });
1754
1755        let (metadata, resolution_work) =
1756            ColumnMetadataIndex::build(&ws, 1, visible_columns as u32).unwrap();
1757
1758        assert_eq!(resolution_work, definition_count + visible_columns);
1759        assert_eq!(metadata.widths.len(), visible_columns);
1760        assert_eq!(metadata.styles.len(), visible_columns);
1761        assert!(metadata
1762            .widths
1763            .iter()
1764            .all(|width| *width == col_width_to_px(10.0)));
1765        assert!(metadata.styles.iter().all(|style| *style == 0));
1766
1767        let mut options = default_options("Sheet1");
1768        let last_column = column_number_to_name(visible_columns as u32).unwrap();
1769        options.range = Some(format!("A1:{last_column}64"));
1770        let svg = render_to_svg(
1771            &ws,
1772            &SharedStringTable::new(),
1773            &StyleSheet::default(),
1774            &options,
1775        )
1776        .unwrap();
1777        assert!(svg.ends_with("</svg>"));
1778    }
1779
1780    #[test]
1781    fn test_render_custom_row_heights() {
1782        let (mut ws, sst) = simple_ws_and_sst();
1783        crate::row::set_row_height(&mut ws, 1, 30.0).unwrap();
1784
1785        let ss = StyleSheet::default();
1786        let opts = default_options("Sheet1");
1787
1788        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1789
1790        assert!(svg.starts_with("<svg"));
1791        assert!(svg.contains(">Name<"));
1792    }
1793
1794    #[test]
1795    fn test_render_with_range() {
1796        let (ws, sst) = simple_ws_and_sst();
1797        let ss = StyleSheet::default();
1798        let mut opts = default_options("Sheet1");
1799        opts.range = Some("A1:A2".to_string());
1800
1801        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1802
1803        assert!(svg.contains(">Name<"));
1804        assert!(svg.contains(">Alice<"));
1805        // B column should not appear if the range is just A1:A2
1806        assert!(!svg.contains(">Score<"));
1807    }
1808
1809    #[test]
1810    fn test_render_empty_sheet() {
1811        let ws = WorksheetXml::default();
1812        let sst = SharedStringTable::new();
1813        let ss = StyleSheet::default();
1814        let opts = default_options("Sheet1");
1815
1816        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1817
1818        assert!(svg.starts_with("<svg"));
1819        assert!(svg.ends_with("</svg>"));
1820    }
1821
1822    #[test]
1823    fn test_render_bold_text() {
1824        let (mut ws, sst) = simple_ws_and_sst();
1825        let mut ss = StyleSheet::default();
1826
1827        let bold_style = StyleBuilder::new().bold(true).build();
1828        let style_id = add_style(&mut ss, &bold_style).unwrap();
1829
1830        // Apply style to cell A1
1831        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
1832
1833        let opts = default_options("Sheet1");
1834
1835        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1836
1837        assert!(
1838            svg.contains("font-weight=\"bold\""),
1839            "SVG should contain bold font attribute"
1840        );
1841    }
1842
1843    #[test]
1844    fn test_render_colored_fill() {
1845        let (mut ws, sst) = simple_ws_and_sst();
1846        let mut ss = StyleSheet::default();
1847
1848        let fill_style = StyleBuilder::new().solid_fill("FFFFFF00").build();
1849        let style_id = add_style(&mut ss, &fill_style).unwrap();
1850
1851        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
1852
1853        let opts = default_options("Sheet1");
1854
1855        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1856
1857        assert!(
1858            svg.contains("fill=\"#FFFF00\""),
1859            "SVG should contain yellow fill color"
1860        );
1861    }
1862
1863    #[test]
1864    fn test_render_applies_row_style_when_cell_has_no_style() {
1865        let (mut ws, sst) = simple_ws_and_sst();
1866        let mut ss = StyleSheet::default();
1867        let style_id =
1868            add_style(&mut ss, &StyleBuilder::new().solid_fill("FFFF0000").build()).unwrap();
1869        ws.sheet_data.rows[0].s = Some(style_id);
1870
1871        let svg = render_to_svg(&ws, &sst, &ss, &default_options("Sheet1")).unwrap();
1872
1873        assert!(svg.contains("fill=\"#FF0000\""));
1874    }
1875
1876    #[test]
1877    fn test_render_applies_column_style_when_cell_and_row_have_no_style() {
1878        let (mut ws, sst) = simple_ws_and_sst();
1879        let mut ss = StyleSheet::default();
1880        let style_id =
1881            add_style(&mut ss, &StyleBuilder::new().solid_fill("FF00FF00").build()).unwrap();
1882        ws.cols = Some(Cols {
1883            cols: vec![Col {
1884                min: 1,
1885                max: 1,
1886                width: None,
1887                style: Some(style_id),
1888                hidden: None,
1889                custom_width: None,
1890                outline_level: None,
1891            }],
1892        });
1893
1894        let svg = render_to_svg(&ws, &sst, &ss, &default_options("Sheet1")).unwrap();
1895
1896        assert!(svg.contains("fill=\"#00FF00\""));
1897    }
1898
1899    #[test]
1900    fn test_cell_style_precedence_includes_explicit_default_style() {
1901        let (mut ws, _sst) = simple_ws_and_sst();
1902        ws.sheet_data.rows[0].s = Some(2);
1903        ws.sheet_data.rows[0].cells[0].s = Some(0);
1904        ws.cols = Some(Cols {
1905            cols: vec![Col {
1906                min: 1,
1907                max: 2,
1908                width: None,
1909                style: Some(3),
1910                hidden: None,
1911                custom_width: None,
1912                outline_level: None,
1913            }],
1914        });
1915
1916        assert_eq!(find_cell_style(&ws, 1, 1, 3), 0);
1917        assert_eq!(find_cell_style(&ws, 2, 1, 3), 2);
1918        assert_eq!(find_cell_style(&ws, 1, 3, 3), 3);
1919    }
1920
1921    #[test]
1922    fn test_render_resolves_theme_colors_with_default_theme() {
1923        let (mut ws, sst) = simple_ws_and_sst();
1924        let mut ss = StyleSheet::default();
1925        let style_id = add_style(
1926            &mut ss,
1927            &StyleBuilder::new()
1928                .fill_pattern(PatternType::Solid)
1929                .fill_fg_color(StyleColor::Theme(4))
1930                .font_color(StyleColor::Theme(5))
1931                .border_all(BorderLineStyle::Thin, StyleColor::Theme(6))
1932                .build(),
1933        )
1934        .unwrap();
1935        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
1936
1937        let svg = render_to_svg(&ws, &sst, &ss, &default_options("Sheet1")).unwrap();
1938
1939        assert!(svg.contains("fill=\"#4472C4\""));
1940        assert!(svg.contains("fill=\"#ED7D31\""));
1941        assert!(svg.contains("stroke=\"#A5A5A5\""));
1942    }
1943
1944    #[test]
1945    fn test_render_resolves_theme_colors_with_supplied_theme() {
1946        let (mut ws, sst) = simple_ws_and_sst();
1947        let mut ss = StyleSheet::default();
1948        let style_id = add_style(
1949            &mut ss,
1950            &StyleBuilder::new()
1951                .fill_pattern(PatternType::Solid)
1952                .fill_fg_color(StyleColor::Theme(4))
1953                .font_color(StyleColor::Theme(5))
1954                .border_all(BorderLineStyle::Thin, StyleColor::Theme(6))
1955                .build(),
1956        )
1957        .unwrap();
1958        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
1959        let mut theme = crate::theme::default_theme_colors();
1960        theme.colors[4] = "FF112233".to_string();
1961        theme.colors[5] = "FF445566".to_string();
1962        theme.colors[6] = "FF778899".to_string();
1963
1964        let svg =
1965            render_to_svg_with_theme(&ws, &sst, &ss, &theme, &default_options("Sheet1")).unwrap();
1966
1967        assert!(svg.contains("fill=\"#112233\""));
1968        assert!(svg.contains("fill=\"#445566\""));
1969        assert!(svg.contains("stroke=\"#778899\""));
1970    }
1971
1972    #[test]
1973    fn test_render_font_color() {
1974        let (mut ws, sst) = simple_ws_and_sst();
1975        let mut ss = StyleSheet::default();
1976
1977        let style = StyleBuilder::new().font_color_rgb("FFFF0000").build();
1978        let style_id = add_style(&mut ss, &style).unwrap();
1979
1980        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
1981
1982        let opts = default_options("Sheet1");
1983
1984        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
1985
1986        assert!(
1987            svg.contains("fill=\"#FF0000\""),
1988            "SVG should contain red font color"
1989        );
1990    }
1991
1992    #[test]
1993    fn test_render_with_shared_strings() {
1994        let mut sst = SharedStringTable::new();
1995        sst.add("Hello");
1996        sst.add("World");
1997
1998        let mut ws = WorksheetXml::default();
1999        ws.sheet_data = SheetData {
2000            rows: vec![Row {
2001                r: 1,
2002                spans: None,
2003                s: None,
2004                custom_format: None,
2005                ht: None,
2006                hidden: None,
2007                custom_height: None,
2008                outline_level: None,
2009                cells: vec![
2010                    Cell {
2011                        r: "A1".try_into().unwrap(),
2012                        col: 1,
2013                        s: None,
2014                        t: CellTypeTag::SharedString,
2015                        v: Some("0".to_string()),
2016                        f: None,
2017                        is: None,
2018                    },
2019                    Cell {
2020                        r: "B1".try_into().unwrap(),
2021                        col: 2,
2022                        s: None,
2023                        t: CellTypeTag::SharedString,
2024                        v: Some("1".to_string()),
2025                        f: None,
2026                        is: None,
2027                    },
2028                ],
2029            }],
2030        };
2031
2032        let ss = StyleSheet::default();
2033        let opts = default_options("Sheet1");
2034
2035        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2036
2037        assert!(svg.contains(">Hello<"));
2038        assert!(svg.contains(">World<"));
2039    }
2040
2041    #[test]
2042    fn test_render_xml_escaping() {
2043        let mut ws = WorksheetXml::default();
2044        ws.sheet_data = SheetData {
2045            rows: vec![Row {
2046                r: 1,
2047                spans: None,
2048                s: None,
2049                custom_format: None,
2050                ht: None,
2051                hidden: None,
2052                custom_height: None,
2053                outline_level: None,
2054                cells: vec![],
2055            }],
2056        };
2057
2058        let sst = SharedStringTable::new();
2059        let ss = StyleSheet::default();
2060        let opts = default_options("Sheet1");
2061
2062        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2063
2064        // Verify valid XML - at minimum it parses as SVG
2065        assert!(svg.starts_with("<svg"));
2066        assert!(svg.ends_with("</svg>"));
2067    }
2068
2069    #[test]
2070    fn test_xml_escape_special_chars() {
2071        assert_eq!(xml_text_escape("a&b").unwrap(), "a&amp;b");
2072        assert_eq!(xml_text_escape("a<b").unwrap(), "a&lt;b");
2073        assert_eq!(xml_text_escape("a>b").unwrap(), "a&gt;b");
2074        assert_eq!(xml_text_escape("a\"b").unwrap(), "a\"b");
2075        assert_eq!(xml_text_escape("a'b").unwrap(), "a'b");
2076        assert_eq!(xml_text_escape("normal").unwrap(), "normal");
2077    }
2078
2079    #[test]
2080    fn test_style_color_to_hex_argb() {
2081        let color = StyleColor::Rgb("FFFF0000".to_string());
2082        assert_eq!(
2083            style_color_to_hex(&color, &default_theme_colors()).unwrap(),
2084            "#FF0000"
2085        );
2086    }
2087
2088    #[test]
2089    fn test_style_color_to_hex_rgb() {
2090        let color = StyleColor::Rgb("00FF00".to_string());
2091        assert_eq!(
2092            style_color_to_hex(&color, &default_theme_colors()).unwrap(),
2093            "#00FF00"
2094        );
2095    }
2096
2097    #[test]
2098    fn test_style_color_to_hex_theme_uses_default_theme() {
2099        let color = StyleColor::Theme(4);
2100        assert_eq!(
2101            style_color_to_hex(&color, &default_theme_colors()).unwrap(),
2102            "#4472C4"
2103        );
2104    }
2105
2106    #[test]
2107    fn test_border_line_attrs_thin() {
2108        let (sw, color) =
2109            border_line_attrs(BorderLineStyle::Thin, None, &default_theme_colors()).unwrap();
2110        assert_eq!(sw, 1.0);
2111        assert_eq!(color, "#000000");
2112    }
2113
2114    #[test]
2115    fn test_border_line_attrs_thick_with_color() {
2116        let c = StyleColor::Rgb("FF0000FF".to_string());
2117        let (sw, color) =
2118            border_line_attrs(BorderLineStyle::Thick, Some(&c), &default_theme_colors()).unwrap();
2119        assert_eq!(sw, 3.0);
2120        assert_eq!(color, "#0000FF");
2121    }
2122
2123    #[test]
2124    fn test_render_center_aligned_text() {
2125        let (mut ws, sst) = simple_ws_and_sst();
2126        let mut ss = StyleSheet::default();
2127
2128        let style = StyleBuilder::new()
2129            .horizontal_align(HorizontalAlign::Center)
2130            .build();
2131        let style_id = add_style(&mut ss, &style).unwrap();
2132
2133        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2134
2135        let opts = default_options("Sheet1");
2136
2137        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2138
2139        assert!(
2140            svg.contains("text-anchor=\"middle\""),
2141            "SVG should contain centered text"
2142        );
2143    }
2144
2145    #[test]
2146    fn test_render_right_aligned_text() {
2147        let (mut ws, sst) = simple_ws_and_sst();
2148        let mut ss = StyleSheet::default();
2149
2150        let style = StyleBuilder::new()
2151            .horizontal_align(HorizontalAlign::Right)
2152            .build();
2153        let style_id = add_style(&mut ss, &style).unwrap();
2154
2155        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2156
2157        let opts = default_options("Sheet1");
2158
2159        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2160
2161        assert!(
2162            svg.contains("text-anchor=\"end\""),
2163            "SVG should contain right-aligned text"
2164        );
2165    }
2166
2167    #[test]
2168    fn test_render_italic_text() {
2169        let (mut ws, sst) = simple_ws_and_sst();
2170        let mut ss = StyleSheet::default();
2171
2172        let style = StyleBuilder::new().italic(true).build();
2173        let style_id = add_style(&mut ss, &style).unwrap();
2174
2175        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2176
2177        let opts = default_options("Sheet1");
2178
2179        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2180
2181        assert!(
2182            svg.contains("font-style=\"italic\""),
2183            "SVG should contain italic text"
2184        );
2185    }
2186
2187    #[test]
2188    fn test_render_border_lines() {
2189        let (mut ws, sst) = simple_ws_and_sst();
2190        let mut ss = StyleSheet::default();
2191
2192        let style = StyleBuilder::new()
2193            .border_all(
2194                BorderLineStyle::Thin,
2195                StyleColor::Rgb("FF000000".to_string()),
2196            )
2197            .build();
2198        let style_id = add_style(&mut ss, &style).unwrap();
2199
2200        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2201
2202        let opts = default_options("Sheet1");
2203
2204        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2205
2206        assert!(
2207            svg.contains("stroke=\"#000000\""),
2208            "SVG should contain border lines"
2209        );
2210    }
2211
2212    #[test]
2213    fn test_render_invalid_range_returns_error() {
2214        let (ws, sst) = simple_ws_and_sst();
2215        let ss = StyleSheet::default();
2216        let mut opts = default_options("Sheet1");
2217        opts.range = Some("INVALID".to_string());
2218
2219        let result = render_to_svg(&ws, &sst, &ss, &opts);
2220        assert!(result.is_err());
2221    }
2222
2223    #[test]
2224    fn test_render_scale_affects_dimensions() {
2225        let (ws, sst) = simple_ws_and_sst();
2226        let ss = StyleSheet::default();
2227
2228        let mut opts1 = default_options("Sheet1");
2229        opts1.scale = 1.0;
2230        let svg1 = render_to_svg(&ws, &sst, &ss, &opts1).unwrap();
2231
2232        let mut opts2 = default_options("Sheet1");
2233        opts2.scale = 2.0;
2234        let svg2 = render_to_svg(&ws, &sst, &ss, &opts2).unwrap();
2235
2236        // Extract width from the SVG tag
2237        fn extract_width(svg: &str) -> f64 {
2238            let start = svg.find("width=\"").unwrap() + 7;
2239            let end = svg[start..].find('"').unwrap() + start;
2240            svg[start..end].parse().unwrap()
2241        }
2242
2243        let w1 = extract_width(&svg1);
2244        let w2 = extract_width(&svg2);
2245        assert!(
2246            (w2 - w1 * 2.0).abs() < 0.01,
2247            "scale=2.0 should double the width: {w1} vs {w2}"
2248        );
2249    }
2250
2251    #[test]
2252    fn test_render_underline_text() {
2253        let (mut ws, sst) = simple_ws_and_sst();
2254        let mut ss = StyleSheet::default();
2255
2256        let style = StyleBuilder::new().underline(true).build();
2257        let style_id = add_style(&mut ss, &style).unwrap();
2258
2259        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2260
2261        let opts = default_options("Sheet1");
2262
2263        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2264
2265        assert!(
2266            svg.contains("text-decoration=\"underline\""),
2267            "SVG should contain underlined text"
2268        );
2269    }
2270
2271    #[test]
2272    fn test_render_strikethrough_text() {
2273        let (mut ws, sst) = simple_ws_and_sst();
2274        let mut ss = StyleSheet::default();
2275
2276        let style = StyleBuilder::new().strikethrough(true).build();
2277        let style_id = add_style(&mut ss, &style).unwrap();
2278
2279        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2280
2281        let opts = default_options("Sheet1");
2282
2283        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2284
2285        assert!(
2286            svg.contains("text-decoration=\"line-through\""),
2287            "SVG should contain strikethrough text"
2288        );
2289    }
2290
2291    #[test]
2292    fn test_style_color_to_hex_already_prefixed() {
2293        let color = StyleColor::Rgb("#FF0000".to_string());
2294        assert_eq!(
2295            style_color_to_hex(&color, &default_theme_colors()).unwrap(),
2296            "#FF0000"
2297        );
2298    }
2299
2300    #[test]
2301    fn test_style_color_to_hex_prefixed_argb() {
2302        let color = StyleColor::Rgb("#FFFF0000".to_string());
2303        assert_eq!(
2304            style_color_to_hex(&color, &default_theme_colors()).unwrap(),
2305            "#FF0000"
2306        );
2307    }
2308
2309    #[test]
2310    fn test_style_color_to_hex_no_double_hash() {
2311        let color = StyleColor::Rgb("#00FF00".to_string());
2312        let hex = style_color_to_hex(&color, &default_theme_colors()).unwrap();
2313        assert!(
2314            !hex.starts_with("##"),
2315            "should not produce double hash, got: {hex}"
2316        );
2317        assert_eq!(hex, "#00FF00");
2318    }
2319
2320    #[test]
2321    fn test_render_underline_and_strikethrough_merged() {
2322        let (mut ws, sst) = simple_ws_and_sst();
2323        let mut ss = StyleSheet::default();
2324
2325        let style = StyleBuilder::new()
2326            .underline(true)
2327            .strikethrough(true)
2328            .build();
2329        let style_id = add_style(&mut ss, &style).unwrap();
2330
2331        ws.sheet_data.rows[0].cells[0].s = Some(style_id);
2332
2333        let opts = default_options("Sheet1");
2334        let svg = render_to_svg(&ws, &sst, &ss, &opts).unwrap();
2335
2336        assert!(
2337            svg.contains(r#"text-decoration="underline line-through""#),
2338            "both decorations should be merged in one attribute"
2339        );
2340        let count = svg.matches("text-decoration=").count();
2341        // Only one text-decoration attribute for the cell A1 text element
2342        assert_eq!(
2343            count, 1,
2344            "text-decoration should appear exactly once, found {count}"
2345        );
2346    }
2347
2348    #[test]
2349    fn test_render_scale_zero_returns_error() {
2350        let (ws, sst) = simple_ws_and_sst();
2351        let ss = StyleSheet::default();
2352        let mut opts = default_options("Sheet1");
2353        opts.scale = 0.0;
2354
2355        let result = render_to_svg(&ws, &sst, &ss, &opts);
2356        assert!(result.is_err(), "scale=0 should return an error");
2357        let err_msg = result.unwrap_err().to_string();
2358        assert!(
2359            err_msg.contains("scale must be positive"),
2360            "error should mention scale: {err_msg}"
2361        );
2362    }
2363
2364    #[test]
2365    fn test_render_scale_negative_returns_error() {
2366        let (ws, sst) = simple_ws_and_sst();
2367        let ss = StyleSheet::default();
2368        let mut opts = default_options("Sheet1");
2369        opts.scale = -1.0;
2370
2371        let result = render_to_svg(&ws, &sst, &ss, &opts);
2372        assert!(result.is_err(), "negative scale should return an error");
2373        let err_msg = result.unwrap_err().to_string();
2374        assert!(
2375            err_msg.contains("scale must be positive"),
2376            "error should mention scale: {err_msg}"
2377        );
2378    }
2379
2380    #[test]
2381    fn svg_output_limit_accepts_exact_bytes_and_rejects_plus_one() {
2382        let mut exact = SvgOutput::new(3);
2383        exact.push_str("abc").unwrap();
2384        assert_eq!(exact.finish(), "abc");
2385
2386        let mut over = SvgOutput::new(3);
2387        over.push_str("abc").unwrap();
2388        let error = over.push_str("d").unwrap_err();
2389        let Error::ResourceLimitExceeded(metadata) = error else {
2390            panic!("expected resource limit error");
2391        };
2392        assert_eq!(metadata.operation(), ResourceOperation::Render);
2393        assert_eq!(metadata.category(), ResourceCategory::Output);
2394        assert_eq!(metadata.dimension(), ResourceDimension::OutputBytes);
2395        assert_eq!(metadata.limit(), 3);
2396        assert_eq!(metadata.observed(), 4);
2397        assert_eq!(metadata.stage(), Some(ResourceStage::Render));
2398        assert_eq!(over.finish(), "abc");
2399    }
2400}