use crate::{
AbsoluteLength, App, Background, BorderStyle, Bounds, ColorExt, ContentMask, Corners,
CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement, Font,
FontFallbacks, FontFeatures, FontStyle, FontWeight, FontWidth, GridLocation, Length, PaintQuad,
Pixels, Point, PointRefinement, ScaledPixels, SharedString, Size, SizeRefinement, Styled,
TextRun, Window, black, phi, point, px, rems, size,
};
use collections::HashSet;
use palette::{Hsla, IntoColor, rgb::Rgba};
use refineable::Refineable;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{iter, mem, ops::Range};
#[cfg(debug_assertions)]
pub struct DebugBelow;
#[cfg(debug_assertions)]
impl crate::Global for DebugBelow {}
pub enum ObjectFit {
Fill,
Contain,
Cover,
ScaleDown,
None,
}
impl ObjectFit {
pub fn get_bounds(
&self,
bounds: Bounds<Pixels>,
image_size: Size<DevicePixels>,
) -> Bounds<Pixels> {
let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
let image_ratio = image_size.width / image_size.height;
let bounds_ratio = bounds.size.width / bounds.size.height;
match self {
ObjectFit::Fill => bounds,
ObjectFit::Contain => {
let new_size = if bounds_ratio > image_ratio {
size(
image_size.width * (bounds.size.height / image_size.height),
bounds.size.height,
)
} else {
size(
bounds.size.width,
image_size.height * (bounds.size.width / image_size.width),
)
};
Bounds {
origin: point(
bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
),
size: new_size,
}
}
ObjectFit::ScaleDown => {
if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
let new_size = if bounds_ratio > image_ratio {
size(
image_size.width * (bounds.size.height / image_size.height),
bounds.size.height,
)
} else {
size(
bounds.size.width,
image_size.height * (bounds.size.width / image_size.width),
)
};
Bounds {
origin: point(
bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
),
size: new_size,
}
} else {
let original_size = size(image_size.width, image_size.height);
Bounds {
origin: point(
bounds.origin.x + (bounds.size.width - original_size.width) / 2.0,
bounds.origin.y + (bounds.size.height - original_size.height) / 2.0,
),
size: original_size,
}
}
}
ObjectFit::Cover => {
let new_size = if bounds_ratio > image_ratio {
size(
bounds.size.width,
image_size.height * (bounds.size.width / image_size.width),
)
} else {
size(
image_size.width * (bounds.size.height / image_size.height),
bounds.size.height,
)
};
Bounds {
origin: point(
bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
),
size: new_size,
}
}
ObjectFit::None => Bounds {
origin: bounds.origin,
size: image_size,
},
}
}
}
#[derive(
Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, JsonSchema, Serialize, Deserialize,
)]
pub enum GridTemplateMinSize {
#[default]
Zero,
MinContent,
MaxContent,
}
#[derive(
Copy,
Clone,
Refineable,
PartialEq,
Eq,
PartialOrd,
Ord,
Debug,
Default,
JsonSchema,
Serialize,
Deserialize,
)]
pub struct GridTemplate {
pub repeat: u16,
pub min_size: GridTemplateMinSize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum RingColor {
#[default]
CurrentColor,
Color(Background),
}
impl RingColor {
fn resolve(self, current_color: Hsla) -> Background {
match self {
Self::CurrentColor => current_color.into(),
Self::Color(color) => color,
}
}
}
#[derive(Refineable, Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[refineable(Debug, PartialEq, Serialize, Deserialize)]
pub struct RingStyle {
pub width: Pixels,
pub color: RingColor,
}
impl RingStyle {
fn outer_quad(
self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
current_color: Hsla,
) -> Option<PaintQuad> {
(self.width > Pixels::ZERO).then(|| {
PaintQuad::new(bounds.dilate(self.width))
.corner_radii(corner_radii.map(|radius| *radius + self.width))
.border_widths(Edges::all(self.width))
.border_color(self.color.resolve(current_color))
})
}
fn inset_shadow(self, current_color: Hsla) -> Option<BoxShadow> {
(self.width > Pixels::ZERO).then(|| {
BoxShadow::new(px(0.), px(0.), self.color.resolve(current_color))
.spread_radius(self.width)
.inset()
})
}
}
#[derive(Clone, Refineable, Debug)]
#[refineable(Debug, PartialEq, Serialize, Deserialize)]
pub struct Style {
pub display: Display,
pub visibility: Visibility,
pub direction: LayoutDirection,
pub unicode_bidi: UnicodeBidi,
#[doc(hidden)]
pub unicode_bidi_explicit: bool,
#[refineable]
pub overflow: Point<Overflow>,
#[refineable]
pub overflow_fade: Edges<AbsoluteLength>,
pub scrollbar_width: AbsoluteLength,
pub allow_concurrent_scroll: bool,
pub restrict_scroll_to_axis: bool,
pub position: Position,
#[refineable]
pub inset: Edges<Length>,
#[refineable]
pub size: Size<Length>,
#[refineable]
pub min_size: Size<Length>,
#[refineable]
pub max_size: Size<Length>,
pub aspect_ratio: Option<f32>,
#[refineable]
pub margin: Edges<Length>,
#[refineable]
pub padding: Edges<DefiniteLength>,
#[refineable]
pub border_widths: Edges<AbsoluteLength>,
pub align_items: Option<AlignItems>,
pub align_self: Option<AlignSelf>,
pub vertical_align: VerticalAlign,
pub align_content: Option<AlignContent>,
pub justify_content: Option<JustifyContent>,
#[refineable]
pub gap: Size<DefiniteLength>,
pub flex_direction: FlexDirection,
pub flex_wrap: FlexWrap,
pub flex_basis: Length,
pub flex_grow: f32,
pub flex_shrink: f32,
pub background: Option<Fill>,
pub border_color: Option<Background>,
pub border_style: BorderStyle,
pub border_dashed_length: f32,
pub border_dashed_gap: f32,
#[refineable]
pub corner_radii: Corners<AbsoluteLength>,
pub corner_smoothing: Option<f32>,
pub box_shadow: Vec<BoxShadow>,
#[refineable]
pub ring: RingStyle,
#[refineable]
pub inset_ring: RingStyle,
pub filter: Vec<Filter>,
pub backdrop_filter: Vec<Filter>,
#[refineable]
pub text: TextStyleRefinement,
pub mouse_cursor: Option<CursorStyle>,
pub opacity: Option<f32>,
pub grid_cols: Option<GridTemplate>,
pub grid_rows: Option<GridTemplate>,
pub grid_location: Option<GridLocation>,
#[cfg(debug_assertions)]
pub debug: bool,
#[cfg(debug_assertions)]
pub debug_below: bool,
}
impl Styled for StyleRefinement {
fn style(&mut self) -> &mut StyleRefinement {
self
}
}
impl StyleRefinement {
pub fn grid_location_mut(&mut self) -> &mut GridLocation {
self.grid_location.get_or_insert_default()
}
}
#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum Visibility {
#[default]
Visible,
Hidden,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum LayoutDirection {
#[default]
Inherit,
LeftToRight,
RightToLeft,
Auto,
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ResolvedDirection {
#[default]
LeftToRight,
RightToLeft,
}
impl ResolvedDirection {
pub fn is_rtl(self) -> bool {
self == Self::RightToLeft
}
pub(crate) fn from_first_strong(text: &str) -> Option<Self> {
use unicode_bidi::BidiClass;
text.chars()
.find_map(|character| match unicode_bidi::bidi_class(character) {
BidiClass::L => Some(Self::LeftToRight),
BidiClass::R | BidiClass::AL => Some(Self::RightToLeft),
_ => None,
})
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum UnicodeBidi {
#[default]
Normal,
Embed,
Isolate,
BidiOverride,
IsolateOverride,
Plaintext,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, derive_setters::Setters)]
#[setters(generate = false)]
pub struct BoxShadow {
pub color: Background,
pub offset: Point<Pixels>,
#[setters(generate)]
pub blur_radius: Pixels,
#[setters(generate)]
pub spread_radius: Pixels,
#[setters(generate, bool)]
pub inset: bool,
}
impl BoxShadow {
pub fn new(offset_x: Pixels, offset_y: Pixels, color: impl Into<Background>) -> Self {
Self {
color: color.into(),
offset: point(offset_x, offset_y),
blur_radius: px(0.),
spread_radius: px(0.),
inset: false,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum Filter {
Blur(Pixels),
}
impl Filter {
pub fn is_identity(&self) -> bool {
match self {
Filter::Blur(radius) => *radius <= Pixels::ZERO,
}
}
pub fn scale(&self, factor: f32) -> ScaledFilter {
match self {
Filter::Blur(radius) => ScaledFilter::Blur(radius.scale(factor)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScaledFilter {
Blur(ScaledPixels),
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum WhiteSpace {
#[default]
Normal,
Nowrap,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum TextOverflow {
Truncate(SharedString),
TruncateStart(SharedString),
TruncateMiddle(SharedString),
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum TextAlign {
#[default]
Start,
End,
Left,
Center,
Right,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum TextTransform {
#[default]
None,
Uppercase,
Lowercase,
Capitalize,
}
#[derive(Refineable, Clone, Debug, PartialEq)]
#[refineable(Debug, PartialEq, Serialize, Deserialize)]
pub struct TextStyle {
pub color: Hsla,
pub font_family: SharedString,
pub font_features: FontFeatures,
pub font_fallbacks: Option<FontFallbacks>,
pub font_size: AbsoluteLength,
pub line_height: DefiniteLength,
pub font_weight: FontWeight,
pub font_width: FontWidth,
pub font_style: FontStyle,
pub background_color: Option<Hsla>,
pub underline: Option<UnderlineStyle>,
pub strikethrough: Option<StrikethroughStyle>,
pub white_space: WhiteSpace,
pub text_overflow: Option<TextOverflow>,
pub text_align: TextAlign,
pub line_clamp: Option<usize>,
pub letter_spacing: Option<Pixels>,
pub text_transform: Option<TextTransform>,
}
impl Default for TextStyle {
fn default() -> Self {
TextStyle {
color: black(),
font_family: ".SystemUIFont".into(),
font_features: FontFeatures::default(),
font_fallbacks: None,
font_size: rems(1.).into(),
line_height: phi().into(),
font_weight: FontWeight::default(),
font_width: FontWidth::default(),
font_style: FontStyle::default(),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
text_overflow: None,
text_align: TextAlign::default(),
line_clamp: None,
letter_spacing: None,
text_transform: None,
}
}
}
impl TextStyle {
pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
let style = style.into();
if let Some(weight) = style.font_weight {
self.font_weight = weight;
}
if let Some(width) = style.font_width {
self.font_width = width;
}
if let Some(style) = style.font_style {
self.font_style = style;
}
if let Some(color) = style.color {
self.color = self.color.blend(&color);
}
if let Some(factor) = style.fade_out {
self.color.fade_out(factor);
}
if let Some(background_color) = style.background_color {
self.background_color = Some(background_color);
}
if let Some(underline) = style.underline {
self.underline = Some(underline);
}
if let Some(strikethrough) = style.strikethrough {
self.strikethrough = Some(strikethrough);
}
self
}
pub fn font(&self) -> Font {
Font {
family: self.font_family.clone(),
features: self.font_features.clone(),
fallbacks: self.font_fallbacks.clone(),
weight: self.font_weight,
width: self.font_width,
style: self.font_style,
}
}
pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
self.line_height.to_pixels(self.font_size, rem_size).round()
}
pub fn to_run(&self, len: usize) -> TextRun {
TextRun {
len,
font: Font {
family: self.font_family.clone(),
features: self.font_features.clone(),
fallbacks: self.font_fallbacks.clone(),
weight: self.font_weight,
width: self.font_width,
style: self.font_style,
},
color: self.color,
background_color: self.background_color,
underline: self.underline,
strikethrough: self.strikethrough,
letter_spacing: self.letter_spacing,
}
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct HighlightStyle {
pub color: Option<Hsla>,
pub font_weight: Option<FontWeight>,
pub font_width: Option<FontWidth>,
pub font_style: Option<FontStyle>,
pub background_color: Option<Hsla>,
pub underline: Option<UnderlineStyle>,
pub strikethrough: Option<StrikethroughStyle>,
pub fade_out: Option<f32>,
}
impl Style {
#[doc(hidden)]
pub fn effective_unicode_bidi(&self) -> UnicodeBidi {
if self.unicode_bidi_explicit {
self.unicode_bidi
} else if self.direction == LayoutDirection::Inherit {
UnicodeBidi::Normal
} else {
UnicodeBidi::Isolate
}
}
pub fn has_opaque_background(&self) -> bool {
self.background
.as_ref()
.is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
}
pub fn text_style(&self) -> Option<&TextStyleRefinement> {
if self.text.is_some() {
Some(&self.text)
} else {
None
}
}
pub fn overflow_mask(
&self,
bounds: Bounds<Pixels>,
rem_size: Pixels,
) -> Option<ContentMask<Pixels>> {
match self.overflow {
Point {
x: Overflow::Visible,
y: Overflow::Visible,
} => None,
_ => {
let mut min = bounds.origin;
let mut max = bounds.bottom_right();
if self
.border_color
.is_some_and(|background| !background.is_transparent())
{
min.x += self.border_widths.left.to_pixels(rem_size);
max.x -= self.border_widths.right.to_pixels(rem_size);
min.y += self.border_widths.top.to_pixels(rem_size);
max.y -= self.border_widths.bottom.to_pixels(rem_size);
}
let bounds = match (
self.overflow.x == Overflow::Visible,
self.overflow.y == Overflow::Visible,
) {
(true, true) => return None,
(true, false) => Bounds::from_corners(
point(min.x, bounds.origin.y),
point(max.x, bounds.bottom_right().y),
),
(false, true) => Bounds::from_corners(
point(bounds.origin.x, min.y),
point(bounds.bottom_right().x, max.y),
),
(false, false) => Bounds::from_corners(min, max),
};
let mut fade_out = self.overflow_fade.to_pixels(rem_size);
if self.overflow.x == Overflow::Visible {
fade_out.left = Pixels::ZERO;
fade_out.right = Pixels::ZERO;
}
if self.overflow.y == Overflow::Visible {
fade_out.top = Pixels::ZERO;
fade_out.bottom = Pixels::ZERO;
}
Some(ContentMask { bounds, fade_out })
}
}
}
pub fn scroll_mask(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> ContentMask<Pixels> {
let scroll_style = Style {
overflow: Point {
x: self.overflow.x,
y: Overflow::Scroll,
},
border_color: self.border_color,
border_widths: self.border_widths,
overflow_fade: self.overflow_fade,
..Style::default()
};
scroll_style
.overflow_mask(bounds, rem_size)
.expect("vertical scrolling always clips")
}
pub fn paint(
&self,
bounds: Bounds<Pixels>,
window: &mut Window,
cx: &mut App,
continuation: impl FnOnce(&mut Window, &mut App),
) {
window.with_element_opacity(self.opacity, |window| {
if let Some(fragments) = window.current_inline_fragments.clone() {
for fragment in fragments.iter() {
self.paint_box(*fragment, window, cx, |_, _| {});
}
continuation(window, cx);
return;
}
self.paint_box(bounds, window, cx, continuation);
});
}
fn paint_box(
&self,
bounds: Bounds<Pixels>,
window: &mut Window,
cx: &mut App,
continuation: impl FnOnce(&mut Window, &mut App),
) {
#[cfg(debug_assertions)]
if self.debug_below {
cx.set_global(DebugBelow)
}
#[cfg(debug_assertions)]
if self.debug || cx.has_global::<DebugBelow>() {
window.paint_quad(
PaintQuad::new(bounds)
.border_widths(px(1.))
.border_color(crate::red()),
);
}
let rem_size = window.rem_size();
let corner_radii = self
.corner_radii
.to_pixels(rem_size)
.clamp_radii_for_quad_size(bounds.size);
let corner_smoothing = self.corner_smoothing.unwrap_or_default();
let current_color = self.text.color.unwrap_or_else(|| window.text_style().color);
window.paint_drop_shadows(bounds, corner_radii, corner_smoothing, &self.box_shadow);
if let Some(ring) = self.ring.outer_quad(bounds, corner_radii, current_color) {
window.paint_quad(ring.corner_smoothing(corner_smoothing));
}
if !self.backdrop_filter.is_empty() {
window.paint_backdrop_filter(
bounds,
corner_radii,
corner_smoothing,
&self.backdrop_filter,
);
}
let paint_box = |window: &mut Window, cx: &mut App| {
let background_color = self.background.as_ref().and_then(Fill::color);
if background_color.is_some_and(|color| !color.is_transparent()) {
let background_color = background_color.unwrap_or_default();
window.paint_quad(
PaintQuad::new(bounds)
.corner_radii(corner_radii)
.background(background_color)
.border_color(background_color.opacity(0.))
.border_style(self.border_style)
.corner_smoothing(corner_smoothing),
);
}
if let Some(ring) = self.inset_ring.inset_shadow(current_color) {
window.paint_inset_shadows(
bounds,
corner_radii,
corner_smoothing,
std::slice::from_ref(&ring),
);
}
window.paint_inset_shadows(bounds, corner_radii, corner_smoothing, &self.box_shadow);
continuation(window, cx);
if self.is_border_visible() {
let border_widths = self.border_widths.to_pixels(rem_size);
let border_color = self.border_color.unwrap_or_default();
window.paint_quad(
PaintQuad::new(bounds)
.corner_radii(corner_radii)
.background(border_color.opacity(0.))
.border_widths(border_widths)
.border_color(border_color)
.border_style(self.border_style)
.corner_smoothing(corner_smoothing)
.border_dashed_length(self.border_dashed_length)
.border_dashed_gap(self.border_dashed_gap),
);
}
};
if self.filter.is_empty() {
paint_box(window, cx);
} else {
window.with_filter_layer(
bounds,
corner_radii,
corner_smoothing,
&self.filter,
|window| {
paint_box(window, cx);
},
);
}
#[cfg(debug_assertions)]
if self.debug_below {
cx.remove_global::<DebugBelow>();
}
}
fn is_border_visible(&self) -> bool {
self.border_color
.is_some_and(|background| !background.is_transparent())
&& self.border_widths.any(|length| !length.is_zero())
}
}
impl Default for Style {
fn default() -> Self {
Style {
display: Display::Block,
visibility: Visibility::Visible,
direction: LayoutDirection::Inherit,
unicode_bidi: UnicodeBidi::Normal,
unicode_bidi_explicit: false,
overflow: Point {
x: Overflow::Visible,
y: Overflow::Visible,
},
overflow_fade: Edges::<AbsoluteLength>::zero(),
allow_concurrent_scroll: false,
restrict_scroll_to_axis: false,
scrollbar_width: AbsoluteLength::default(),
position: Position::Relative,
inset: Edges::auto(),
margin: Edges::<Length>::zero(),
padding: Edges::<DefiniteLength>::zero(),
border_widths: Edges::<AbsoluteLength>::zero(),
size: Size::auto(),
min_size: Size::auto(),
max_size: Size::auto(),
aspect_ratio: None,
gap: Size::default(),
align_items: None,
align_self: None,
vertical_align: VerticalAlign::Baseline,
align_content: None,
justify_content: None,
flex_direction: FlexDirection::Row,
flex_wrap: FlexWrap::NoWrap,
flex_grow: 0.0,
flex_shrink: 1.0,
flex_basis: Length::Auto,
background: None,
border_color: None,
border_style: BorderStyle::default(),
border_dashed_length: crate::scene::DEFAULT_BORDER_DASHED_LENGTH,
border_dashed_gap: crate::scene::DEFAULT_BORDER_DASHED_GAP,
corner_radii: Corners::default(),
corner_smoothing: None,
box_shadow: Default::default(),
ring: Default::default(),
inset_ring: Default::default(),
filter: Default::default(),
backdrop_filter: Default::default(),
text: TextStyleRefinement::default(),
mouse_cursor: None,
opacity: None,
grid_rows: None,
grid_cols: None,
grid_location: None,
#[cfg(debug_assertions)]
debug: false,
#[cfg(debug_assertions)]
debug_below: false,
}
}
}
#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct UnderlineStyle {
pub thickness: Pixels,
pub color: Option<Hsla>,
pub wavy: bool,
}
#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct StrikethroughStyle {
pub thickness: Pixels,
pub color: Option<Hsla>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum Fill {
Color(Background),
}
impl Fill {
pub fn color(&self) -> Option<Background> {
match self {
Fill::Color(color) => Some(*color),
}
}
}
impl Default for Fill {
fn default() -> Self {
Self::Color(Background::default())
}
}
impl<T: Into<Background>> From<T> for Fill {
fn from(color: T) -> Self {
Self::Color(color.into())
}
}
impl From<TextStyle> for HighlightStyle {
fn from(other: TextStyle) -> Self {
Self::from(&other)
}
}
impl From<&TextStyle> for HighlightStyle {
fn from(other: &TextStyle) -> Self {
Self {
color: Some(other.color),
font_weight: Some(other.font_weight),
font_width: Some(other.font_width),
font_style: Some(other.font_style),
background_color: other.background_color,
underline: other.underline,
strikethrough: other.strikethrough,
fade_out: None,
}
}
}
impl HighlightStyle {
pub fn color(color: Hsla) -> Self {
Self {
color: Some(color),
..Default::default()
}
}
#[must_use]
pub fn highlight(self, other: HighlightStyle) -> Self {
Self {
color: other
.color
.map(|other_color| {
if let Some(color) = self.color {
color.blend(&other_color)
} else {
other_color
}
})
.or(self.color),
font_weight: other.font_weight.or(self.font_weight),
font_width: other.font_width.or(self.font_width),
font_style: other.font_style.or(self.font_style),
background_color: other.background_color.or(self.background_color),
underline: other.underline.or(self.underline),
strikethrough: other.strikethrough.or(self.strikethrough),
fade_out: other
.fade_out
.map(|source_fade| {
self.fade_out
.map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
.unwrap_or(source_fade)
})
.or(self.fade_out),
}
}
}
impl From<Hsla> for HighlightStyle {
fn from(color: Hsla) -> Self {
Self {
color: Some(color),
..Default::default()
}
}
}
impl From<FontWeight> for HighlightStyle {
fn from(font_weight: FontWeight) -> Self {
Self {
font_weight: Some(font_weight),
..Default::default()
}
}
}
impl From<FontStyle> for HighlightStyle {
fn from(font_style: FontStyle) -> Self {
Self {
font_style: Some(font_style),
..Default::default()
}
}
}
impl From<Rgba> for HighlightStyle {
fn from(color: Rgba) -> Self {
Self {
color: Some(color.into_color()),
..Default::default()
}
}
}
pub fn combine_highlights(
a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
let mut endpoints = Vec::new();
let mut highlights = Vec::new();
for (range, highlight) in a.into_iter().chain(b) {
if !range.is_empty() {
let highlight_id = highlights.len();
endpoints.push((range.start, highlight_id, true));
endpoints.push((range.end, highlight_id, false));
highlights.push(highlight);
}
}
endpoints.sort_unstable_by_key(|(position, _, _)| *position);
let mut endpoints = endpoints.into_iter().peekable();
let mut active_styles = HashSet::default();
let mut ix = 0;
iter::from_fn(move || {
while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
let prev_index = mem::replace(&mut ix, *endpoint_ix);
if ix > prev_index && !active_styles.is_empty() {
let current_style = active_styles
.iter()
.fold(HighlightStyle::default(), |acc, highlight_id| {
acc.highlight(highlights[*highlight_id])
});
return Some((prev_index..ix, current_style));
}
if *is_start {
active_styles.insert(*highlight_id);
} else {
active_styles.remove(highlight_id);
}
endpoints.next();
}
None
})
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
pub enum AlignItems {
Start,
End,
FlexStart,
FlexEnd,
Center,
Baseline,
Stretch,
}
pub type JustifyItems = AlignItems;
pub type AlignSelf = AlignItems;
pub type JustifySelf = AlignItems;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub enum VerticalAlign {
#[default]
Baseline,
Middle,
Top,
Bottom,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
pub enum AlignContent {
Start,
End,
FlexStart,
FlexEnd,
Center,
Stretch,
SpaceBetween,
SpaceEvenly,
SpaceAround,
}
pub type JustifyContent = AlignContent;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub enum Display {
Block,
#[default]
Flex,
Grid,
Inline,
InlineFlex,
None,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub enum FlexWrap {
#[default]
NoWrap,
Wrap,
WrapReverse,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub enum FlexDirection {
#[default]
Row,
Column,
RowReverse,
ColumnReverse,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub enum Overflow {
#[default]
Visible,
Clip,
Hidden,
Scroll,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub enum Position {
#[default]
Relative,
Absolute,
}
impl From<AlignItems> for taffy::style::AlignItems {
fn from(value: AlignItems) -> Self {
match value {
AlignItems::Start => Self::START,
AlignItems::End => Self::END,
AlignItems::FlexStart => Self::FLEX_START,
AlignItems::FlexEnd => Self::FLEX_END,
AlignItems::Center => Self::CENTER,
AlignItems::Baseline => Self::BASELINE,
AlignItems::Stretch => Self::STRETCH,
}
}
}
impl From<AlignContent> for taffy::style::AlignContent {
fn from(value: AlignContent) -> Self {
match value {
AlignContent::Start => Self::START,
AlignContent::End => Self::END,
AlignContent::FlexStart => Self::FLEX_START,
AlignContent::FlexEnd => Self::FLEX_END,
AlignContent::Center => Self::CENTER,
AlignContent::Stretch => Self::STRETCH,
AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
AlignContent::SpaceAround => Self::SPACE_AROUND,
}
}
}
impl From<Display> for taffy::style::Display {
fn from(value: Display) -> Self {
match value {
Display::Block | Display::Inline => Self::Block,
Display::Flex | Display::InlineFlex => Self::Flex,
Display::Grid => Self::Grid,
Display::None => Self::None,
}
}
}
impl From<FlexWrap> for taffy::style::FlexWrap {
fn from(value: FlexWrap) -> Self {
match value {
FlexWrap::NoWrap => Self::NoWrap,
FlexWrap::Wrap => Self::Wrap,
FlexWrap::WrapReverse => Self::WrapReverse,
}
}
}
impl From<FlexDirection> for taffy::style::FlexDirection {
fn from(value: FlexDirection) -> Self {
match value {
FlexDirection::Row => Self::Row,
FlexDirection::Column => Self::Column,
FlexDirection::RowReverse => Self::RowReverse,
FlexDirection::ColumnReverse => Self::ColumnReverse,
}
}
}
impl From<Overflow> for taffy::style::Overflow {
fn from(value: Overflow) -> Self {
match value {
Overflow::Visible => Self::Visible,
Overflow::Clip => Self::Clip,
Overflow::Hidden => Self::Hidden,
Overflow::Scroll => Self::Scroll,
}
}
}
impl From<Position> for taffy::style::Position {
fn from(value: Position) -> Self {
match value {
Position::Relative => Self::Relative,
Position::Absolute => Self::Absolute,
}
}
}
#[cfg(test)]
mod tests {
use crate::{blue, green, hsla, linear_color_stop, linear_gradient, px, red, yellow};
use palette::WithAlpha;
use super::*;
fn ring_gradient() -> Background {
linear_gradient(
90.,
linear_color_stop(red(), 0.),
linear_color_stop(blue(), 1.),
)
}
#[test]
fn border_color_accepts_backgrounds_and_solid_colors() {
let gradient = linear_gradient(
90.0,
linear_color_stop(red(), 0.0),
linear_color_stop(blue(), 1.0),
);
let gradient_style = StyleRefinement::default().border_color(gradient);
assert_eq!(gradient_style.border_color, Some(gradient));
let solid_style = StyleRefinement::default().border_color(red());
assert_eq!(solid_style.border_color, Some(red().into()));
}
#[test]
fn test_basic_highlight_style_combination() {
let style_a = HighlightStyle::default();
let style_b = HighlightStyle::default();
let style_a = style_a.highlight(style_b);
assert_eq!(
style_a,
HighlightStyle::default(),
"Combining empty styles should not produce a non-empty style."
);
let mut style_b = HighlightStyle {
color: Some(red()),
strikethrough: Some(StrikethroughStyle {
thickness: px(2.),
color: Some(blue()),
}),
fade_out: Some(0.),
font_style: Some(FontStyle::Italic),
font_weight: Some(FontWeight(300.)),
font_width: Some(FontWidth::CONDENSED),
background_color: Some(yellow()),
underline: Some(UnderlineStyle {
thickness: px(2.),
color: Some(red()),
wavy: true,
}),
};
let expected_style = style_b;
assert_eq!(
TextStyle::default().highlight(style_b).font_width,
FontWidth::CONDENSED
);
let style_a = style_a.highlight(style_b);
assert_eq!(
style_a, expected_style,
"Blending an empty style with another style should return the other style"
);
let style_b = style_b.highlight(Default::default());
assert_eq!(
style_b, expected_style,
"Blending a style with an empty style should not change the style."
);
let mut style_c = expected_style;
let style_d = HighlightStyle {
color: Some(blue().with_alpha(0.7)),
strikethrough: Some(StrikethroughStyle {
thickness: px(4.),
color: Some(crate::red()),
}),
fade_out: Some(0.),
font_style: Some(FontStyle::Oblique),
font_weight: Some(FontWeight(800.)),
font_width: Some(FontWidth::EXPANDED),
background_color: Some(green()),
underline: Some(UnderlineStyle {
thickness: px(4.),
color: None,
wavy: false,
}),
};
let expected_style = HighlightStyle {
color: Some(red().blend(&blue().with_alpha(0.7))),
strikethrough: Some(StrikethroughStyle {
thickness: px(4.),
color: Some(red()),
}),
fade_out: Some(0.),
font_style: Some(FontStyle::Oblique),
font_weight: Some(FontWeight(800.)),
font_width: Some(FontWidth::EXPANDED),
background_color: Some(green()),
underline: Some(UnderlineStyle {
thickness: px(4.),
color: None,
wavy: false,
}),
};
let style_c = style_c.highlight(style_d);
assert_eq!(
style_c, expected_style,
"Blending styles should blend properties where possible and override all others"
);
}
#[test]
fn test_combine_highlights() {
assert_eq!(
combine_highlights(
[
(0..5, green().into()),
(4..10, FontWeight::BOLD.into()),
(15..20, yellow().into()),
],
[
(2..6, FontStyle::Italic.into()),
(1..3, blue().into()),
(21..23, red().into()),
]
)
.collect::<Vec<_>>(),
[
(
0..1,
HighlightStyle {
color: Some(green()),
..Default::default()
}
),
(
1..2,
HighlightStyle {
color: Some(blue()),
..Default::default()
}
),
(
2..3,
HighlightStyle {
color: Some(blue()),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
3..4,
HighlightStyle {
color: Some(green()),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
4..5,
HighlightStyle {
color: Some(green()),
font_weight: Some(FontWeight::BOLD),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
5..6,
HighlightStyle {
font_weight: Some(FontWeight::BOLD),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
6..10,
HighlightStyle {
font_weight: Some(FontWeight::BOLD),
..Default::default()
}
),
(
15..20,
HighlightStyle {
color: Some(yellow()),
..Default::default()
}
),
(
21..23,
HighlightStyle {
color: Some(red()),
..Default::default()
}
)
]
);
}
#[test]
fn test_text_style_refinement() {
let mut style = Style::default();
style.refine(&StyleRefinement::default().text_size(px(20.0)));
style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
style.refine(&StyleRefinement::default().font_width(87.5));
assert_eq!(
Some(AbsoluteLength::from(px(20.0))),
style.text_style().unwrap().font_size
);
assert_eq!(
Some(FontWeight::SEMIBOLD),
style.text_style().unwrap().font_weight
);
let mut resolved = TextStyle::default();
resolved.refine(style.text_style().unwrap());
let inherited = resolved.highlight(HighlightStyle::color(red()));
assert_eq!(inherited.font().width, FontWidth::SEMI_CONDENSED);
assert_eq!(inherited.to_run(4).font.width, FontWidth::SEMI_CONDENSED);
assert_eq!(
HighlightStyle::from(&inherited).font_width,
Some(FontWidth::SEMI_CONDENSED)
);
let mut element = crate::div()
.font_width(FontWidth::CONDENSED)
.font(crate::font("IBM Plex Sans"));
assert_eq!(element.text_style().font_width, Some(FontWidth::NORMAL));
}
#[test]
fn dashed_border_pattern_has_legacy_defaults_and_refines_independently() {
let mut style = Style::default();
assert_eq!(
style.border_dashed_length,
crate::scene::DEFAULT_BORDER_DASHED_LENGTH
);
assert_eq!(
style.border_dashed_gap,
crate::scene::DEFAULT_BORDER_DASHED_GAP
);
style.refine(
&StyleRefinement::default()
.border_dashed_length(4.0)
.border_dashed_gap(0.5),
);
assert_eq!(style.border_dashed_length, 4.0);
assert_eq!(style.border_dashed_gap, 0.5);
assert_eq!(style.border_style, BorderStyle::Solid);
style.refine(&StyleRefinement::default().border_dashed());
assert_eq!(style.border_style, BorderStyle::Dashed);
}
#[test]
fn outer_ring_is_hollow_and_composes_with_shadows() {
let drop_shadow = BoxShadow::new(px(0.), px(2.), blue()).blur_radius(px(4.));
let mut style = Style::default();
style.refine(
&StyleRefinement::default()
.ring_2()
.shadow(vec![drop_shadow.clone()]),
);
let current_color = hsla(0.7, 0.5, 0.4, 0.8);
style.refine(&StyleRefinement::default().ring(px(3.5)));
let element_bounds = Bounds {
origin: point(px(10.), px(20.)),
size: size(px(100.), px(40.)),
};
let element_radii = Corners {
top_left: px(0.),
top_right: px(4.),
bottom_right: px(10.),
bottom_left: px(20.),
};
let ring = style
.ring
.outer_quad(element_bounds, element_radii, current_color)
.unwrap();
assert_eq!(ring.bounds.dilate(-px(3.5)), element_bounds);
assert_eq!(ring.border_widths, Edges::all(px(3.5)));
assert_eq!(
ring.corner_radii.map(|radius| *radius - px(3.5)),
element_radii
);
assert!(ring.background.is_transparent());
assert_eq!(ring.border_color, current_color.into());
assert_eq!(ring.border_style, BorderStyle::Solid);
assert_eq!(style.box_shadow, vec![drop_shadow]);
let gradient = ring_gradient();
style.refine(&StyleRefinement::default().ring_color(gradient));
assert_eq!(
style
.ring
.outer_quad(element_bounds, element_radii, current_color)
.unwrap()
.border_color,
gradient
);
style.refine(&StyleRefinement::default().ring_0());
assert!(
style
.ring
.outer_quad(element_bounds, element_radii, current_color)
.is_none()
);
assert_eq!(style.box_shadow.len(), 1);
}
#[test]
fn inset_ring_utility_refines_independently_and_lowers_to_an_inset_shadow() {
let gradient = ring_gradient();
let mut style = Style::default();
style.refine(
&StyleRefinement::default()
.inset_ring(px(1.))
.inset_ring_color(gradient),
);
style.refine(&StyleRefinement::default().inset_ring_4());
let inset = style.inset_ring.inset_shadow(blue()).unwrap();
assert_eq!(inset.offset, point(px(0.), px(0.)));
assert_eq!(inset.blur_radius, px(0.));
assert_eq!(inset.spread_radius, px(4.));
assert_eq!(inset.color, gradient);
assert!(inset.inset);
assert_eq!(style.ring, RingStyle::default());
}
}