Skip to content

Commit

Permalink
fix(svg): Add configurable padding
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Feb 20, 2024
1 parent 07f1dbd commit e24e1c3
Show file tree
Hide file tree
Showing 3 changed files with 1,383 additions and 1,380 deletions.
13 changes: 8 additions & 5 deletions crates/anstyle-svg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub struct Term {
background: bool,
font_family: &'static str,
min_width_px: usize,
padding_px: usize,
}

impl Term {
Expand All @@ -36,6 +37,7 @@ impl Term {
background: true,
font_family: "SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace",
min_width_px: 720,
padding_px: 10,
}
}

Expand Down Expand Up @@ -98,14 +100,14 @@ impl Term {
let font_family = self.font_family;

let line_height = 18;
let height = styled_lines.len() * line_height;
let height = styled_lines.len() * line_height + self.padding_px * 2;
let max_width = styled_lines
.iter()
.map(|l| l.iter().map(|(_, t)| t.width()).sum())
.max()
.unwrap_or(0);
let width_px = (max_width as f64 * 8.4).ceil() as usize;
let width_px = std::cmp::max(width_px, self.min_width_px);
let width_px = std::cmp::max(width_px, self.min_width_px) + self.padding_px * 2;

use std::fmt::Write as _;
let mut buffer = String::new();
Expand Down Expand Up @@ -209,11 +211,12 @@ impl Term {
}
writeln!(&mut buffer).unwrap();

let mut text_y = line_height;
let text_x = self.padding_px;
let mut text_y = self.padding_px + line_height;
writeln!(&mut buffer, r#" <text class="container {FG}">"#).unwrap();
for line in &styled_lines {
if line.iter().any(|(s, _)| s.get_bg_color().is_some()) {
write!(&mut buffer, r#" <tspan x="0px" y="{text_y}px">"#).unwrap();
write!(&mut buffer, r#" <tspan x="{text_x}px" y="{text_y}px">"#).unwrap();
for (style, fragment) in line {
if fragment.is_empty() {
continue;
Expand All @@ -225,7 +228,7 @@ impl Term {
writeln!(&mut buffer, r#"</tspan>"#).unwrap();
}

write!(&mut buffer, r#" <tspan x="0px" y="{text_y}px">"#).unwrap();
write!(&mut buffer, r#" <tspan x="{text_x}px" y="{text_y}px">"#).unwrap();
for (style, fragment) in line {
if fragment.is_empty() {
continue;
Expand Down
Loading

0 comments on commit e24e1c3

Please sign in to comment.