use crate::geometry::Color;
use crate::text::layout::TextMetrics;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
#[default]
Left,
Center,
Right,
Justify,
}
pub(crate) const HANGING_ASCENT_RATIO: f64 = 0.8;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextBaseline {
Top,
Hanging,
#[default]
Alphabetic,
Middle,
Ideographic,
Bottom,
}
impl TextBaseline {
pub(crate) fn anchor_offset(&self, m: &TextMetrics) -> f64 {
match self {
TextBaseline::Top => 0.0,
TextBaseline::Hanging => m.hanging_baseline,
TextBaseline::Alphabetic => m.alphabetic_baseline,
TextBaseline::Middle => m.alphabetic_baseline - m.em_height_ascent * 0.5,
TextBaseline::Ideographic => m.ideographic_baseline,
TextBaseline::Bottom => m.height,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FontStyle {
#[default]
Normal,
Italic,
Oblique,
}
impl FontStyle {
pub fn as_str(self) -> &'static str {
match self {
FontStyle::Normal => "normal",
FontStyle::Italic => "italic",
FontStyle::Oblique => "oblique",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
let t = s.trim().to_ascii_lowercase();
let t = t.replace(['-', '_'], "");
match t.as_str() {
"normal" | "n" => Some(FontStyle::Normal),
"italic" | "i" => Some(FontStyle::Italic),
"oblique" | "o" => Some(FontStyle::Oblique),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FontWeight {
Thin,
ExtraLight,
Light,
#[default]
Normal,
Medium,
SemiBold,
Bold,
ExtraBold,
Black,
}
impl FontWeight {
pub fn value(self) -> f32 {
match self {
FontWeight::Thin => 100.0,
FontWeight::ExtraLight => 200.0,
FontWeight::Light => 300.0,
FontWeight::Normal => 400.0,
FontWeight::Medium => 500.0,
FontWeight::SemiBold => 600.0,
FontWeight::Bold => 700.0,
FontWeight::ExtraBold => 800.0,
FontWeight::Black => 900.0,
}
}
pub fn from_value(weight: f32) -> Self {
let step = (weight.clamp(100.0, 900.0) / 100.0).round() as i32 * 100;
match step {
100 => FontWeight::Thin,
200 => FontWeight::ExtraLight,
300 => FontWeight::Light,
400 => FontWeight::Normal,
500 => FontWeight::Medium,
600 => FontWeight::SemiBold,
700 => FontWeight::Bold,
800 => FontWeight::ExtraBold,
900 => FontWeight::Black,
_ => FontWeight::Normal,
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
let t = s.trim().to_ascii_lowercase();
let t = t.replace(['-', '_'], "");
match t.as_str() {
"thin" => Some(FontWeight::Thin),
"extralight" => Some(FontWeight::ExtraLight),
"light" => Some(FontWeight::Light),
"normal" => Some(FontWeight::Normal),
"medium" => Some(FontWeight::Medium),
"semibold" => Some(FontWeight::SemiBold),
"bold" => Some(FontWeight::Bold),
"extrabold" => Some(FontWeight::ExtraBold),
"black" => Some(FontWeight::Black),
_ => {
let w = t.parse::<f32>().ok()?;
if !(100.0..=900.0).contains(&w) {
return None;
}
Some(FontWeight::from_value(w))
}
}
}
}
impl std::str::FromStr for FontWeight {
type Err = FontWeightParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
FontWeight::parse(s).ok_or(FontWeightParseError)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FontWeightParseError;
impl std::fmt::Display for FontWeightParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("invalid font weight")
}
}
impl std::error::Error for FontWeightParseError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FontWidth {
UltraCondensed,
ExtraCondensed,
Condensed,
SemiCondensed,
#[default]
Normal,
SemiExpanded,
Expanded,
ExtraExpanded,
UltraExpanded,
}
impl FontWidth {
pub fn ratio(self) -> f32 {
match self {
FontWidth::UltraCondensed => 0.5,
FontWidth::ExtraCondensed => 0.625,
FontWidth::Condensed => 0.75,
FontWidth::SemiCondensed => 0.875,
FontWidth::Normal => 1.0,
FontWidth::SemiExpanded => 1.125,
FontWidth::Expanded => 1.25,
FontWidth::ExtraExpanded => 1.5,
FontWidth::UltraExpanded => 2.0,
}
}
pub fn from_ratio(ratio: f32) -> Self {
let r = ratio.clamp(0.5, 2.0);
if r < 0.5625 {
FontWidth::UltraCondensed
} else if r < 0.6875 {
FontWidth::ExtraCondensed
} else if r < 0.8125 {
FontWidth::Condensed
} else if r < 0.9375 {
FontWidth::SemiCondensed
} else if r < 1.0625 {
FontWidth::Normal
} else if r < 1.1875 {
FontWidth::SemiExpanded
} else if r < 1.375 {
FontWidth::Expanded
} else if r < 1.75 {
FontWidth::ExtraExpanded
} else {
FontWidth::UltraExpanded
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextStyle {
pub color: Color,
pub font_family: String,
pub font_size: f64,
pub font_weight: FontWeight,
pub font_style: FontStyle,
pub font_width: FontWidth,
pub line_height: Option<f64>,
pub letter_spacing: f64,
pub underline: bool,
pub underline_color: Option<Color>,
pub strikethrough: bool,
pub strikethrough_color: Option<Color>,
pub baseline_shift: f64,
pub background_color: Option<Color>,
pub url: Option<String>,
pub rotation: f64,
pub max_width: Option<f64>,
pub align: TextAlign,
pub baseline: TextBaseline,
}
impl TextStyle {
#[must_use]
pub fn new(color: Color, font_size: f64, font_family: impl Into<String>) -> Self {
Self {
color,
font_family: font_family.into(),
font_size,
font_weight: FontWeight::Normal,
font_style: FontStyle::Normal,
font_width: FontWidth::Normal,
line_height: None,
letter_spacing: 0.0,
underline: false,
underline_color: None,
strikethrough: false,
strikethrough_color: None,
baseline_shift: 0.0,
background_color: None,
url: None,
rotation: 0.0,
max_width: None,
align: TextAlign::Left,
baseline: TextBaseline::Alphabetic,
}
}
#[must_use]
pub fn with_align(mut self, align: TextAlign) -> Self {
self.align = align;
self
}
#[must_use]
pub fn with_baseline(mut self, baseline: TextBaseline) -> Self {
self.baseline = baseline;
self
}
#[must_use]
pub fn with_weight(mut self, weight: FontWeight) -> Self {
self.font_weight = weight;
self
}
#[must_use]
pub fn with_style(mut self, style: FontStyle) -> Self {
self.font_style = style;
self
}
#[must_use]
pub fn with_font_width(mut self, width: FontWidth) -> Self {
self.font_width = width;
self
}
#[must_use]
pub fn with_letter_spacing(mut self, spacing: f64) -> Self {
self.letter_spacing = spacing;
self
}
#[must_use]
pub fn with_underline(mut self, underline: bool) -> Self {
self.underline = underline;
self
}
#[must_use]
pub fn with_underline_color(mut self, color: Option<Color>) -> Self {
self.underline_color = color;
self
}
#[must_use]
pub fn with_strikethrough(mut self, strikethrough: bool) -> Self {
self.strikethrough = strikethrough;
self
}
#[must_use]
pub fn with_strikethrough_color(mut self, color: Option<Color>) -> Self {
self.strikethrough_color = color;
self
}
#[must_use]
pub fn with_baseline_shift(mut self, shift: f64) -> Self {
self.baseline_shift = shift;
self
}
#[must_use]
pub fn with_background_color(mut self, color: Option<Color>) -> Self {
self.background_color = color;
self
}
#[must_use]
pub fn with_url(mut self, url: Option<String>) -> Self {
self.url = url;
self
}
#[must_use]
pub fn with_line_height(mut self, height: f64) -> Self {
self.line_height = Some(height);
self
}
#[must_use]
pub fn with_rotation(mut self, rotation: f64) -> Self {
self.rotation = rotation;
self
}
#[must_use]
pub fn with_max_width(mut self, width: f64) -> Self {
self.max_width = Some(width);
self
}
#[must_use]
pub fn font_family_css(&self) -> String {
normalize_font_family_list(&self.font_family)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RichSpan {
pub text: String,
pub style: TextStyle,
}
impl RichSpan {
#[must_use]
pub fn new(text: impl Into<String>, style: TextStyle) -> Self {
Self {
text: text.into(),
style,
}
}
}
fn normalize_font_family_list(raw: &str) -> String {
raw.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(normalize_family)
.collect::<Vec<_>>()
.join(", ")
}
fn normalize_family(raw: &str) -> String {
let name = strip_family_quotes(raw);
if is_generic_family(name) || is_css_ident(name) {
name.to_string()
} else {
format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
}
}
fn strip_family_quotes(s: &str) -> &str {
if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
&s[1..s.len() - 1]
} else {
s
}
}
fn is_generic_family(s: &str) -> bool {
matches!(
s.to_ascii_lowercase().as_str(),
"serif"
| "sans-serif"
| "monospace"
| "cursive"
| "fantasy"
| "system-ui"
| "ui-serif"
| "ui-sans-serif"
| "ui-monospace"
| "ui-rounded"
| "emoji"
| "math"
| "fangsong"
)
}
fn is_css_ident(s: &str) -> bool {
!s.is_empty()
&& !matches!(
s,
"inherit" | "initial" | "unset" | "revert" | "revert-layer" | "default"
)
&& s.chars().enumerate().all(|(i, c)| {
if i == 0 {
c.is_ascii_alphabetic() || c == '_' || c == '-'
} else {
c.is_ascii_alphanumeric() || c == '_' || c == '-'
}
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextDecoration {
#[default]
None,
Underline,
LineThrough,
}