1use std::{
2 hash::{Hash, Hasher},
3 iter, mem,
4 ops::Range,
5};
6
7use crate::{
8 AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, Corners,
9 CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement, Font,
10 FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
11 PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
12 point, px, quad, rems, size,
13};
14use collections::HashSet;
15use refineable::Refineable;
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19#[cfg(debug_assertions)]
23pub struct DebugBelow;
24
25#[cfg(debug_assertions)]
26impl crate::Global for DebugBelow {}
27
28pub enum ObjectFit {
30 Fill,
32 Contain,
34 Cover,
36 ScaleDown,
38 None,
40}
41
42impl ObjectFit {
43 pub fn get_bounds(
45 &self,
46 bounds: Bounds<Pixels>,
47 image_size: Size<DevicePixels>,
48 ) -> Bounds<Pixels> {
49 let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
50 let image_ratio = image_size.width / image_size.height;
51 let bounds_ratio = bounds.size.width / bounds.size.height;
52
53 match self {
54 ObjectFit::Fill => bounds,
55 ObjectFit::Contain => {
56 let new_size = if bounds_ratio > image_ratio {
57 size(
58 image_size.width * (bounds.size.height / image_size.height),
59 bounds.size.height,
60 )
61 } else {
62 size(
63 bounds.size.width,
64 image_size.height * (bounds.size.width / image_size.width),
65 )
66 };
67
68 Bounds {
69 origin: point(
70 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
71 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
72 ),
73 size: new_size,
74 }
75 }
76 ObjectFit::ScaleDown => {
77 if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
79 let new_size = if bounds_ratio > image_ratio {
81 size(
82 image_size.width * (bounds.size.height / image_size.height),
83 bounds.size.height,
84 )
85 } else {
86 size(
87 bounds.size.width,
88 image_size.height * (bounds.size.width / image_size.width),
89 )
90 };
91
92 Bounds {
93 origin: point(
94 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
95 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
96 ),
97 size: new_size,
98 }
99 } else {
100 let original_size = size(image_size.width, image_size.height);
103 Bounds {
104 origin: point(
105 bounds.origin.x + (bounds.size.width - original_size.width) / 2.0,
106 bounds.origin.y + (bounds.size.height - original_size.height) / 2.0,
107 ),
108 size: original_size,
109 }
110 }
111 }
112 ObjectFit::Cover => {
113 let new_size = if bounds_ratio > image_ratio {
114 size(
115 bounds.size.width,
116 image_size.height * (bounds.size.width / image_size.width),
117 )
118 } else {
119 size(
120 image_size.width * (bounds.size.height / image_size.height),
121 bounds.size.height,
122 )
123 };
124
125 Bounds {
126 origin: point(
127 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
128 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
129 ),
130 size: new_size,
131 }
132 }
133 ObjectFit::None => Bounds {
134 origin: bounds.origin,
135 size: image_size,
136 },
137 }
138 }
139}
140
141#[derive(
143 Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, JsonSchema, Serialize, Deserialize,
144)]
145pub enum GridTemplateMinSize {
146 #[default]
148 Zero,
149 MinContent,
151 MaxContent,
153}
154
155#[derive(
157 Copy,
158 Clone,
159 Refineable,
160 PartialEq,
161 Eq,
162 PartialOrd,
163 Ord,
164 Debug,
165 Default,
166 JsonSchema,
167 Serialize,
168 Deserialize,
169)]
170pub struct GridTemplate {
171 pub repeat: u16,
173 pub min_size: GridTemplateMinSize,
175}
176
177#[derive(Clone, Refineable, Debug)]
179#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
180pub struct Style {
181 pub display: Display,
183
184 pub visibility: Visibility,
186
187 #[refineable]
190 pub overflow: Point<Overflow>,
191 pub scrollbar_width: AbsoluteLength,
193 pub allow_concurrent_scroll: bool,
195 pub restrict_scroll_to_axis: bool,
221
222 pub position: Position,
225 #[refineable]
227 pub inset: Edges<Length>,
228
229 #[refineable]
232 pub size: Size<Length>,
233 #[refineable]
235 pub min_size: Size<Length>,
236 #[refineable]
238 pub max_size: Size<Length>,
239 pub aspect_ratio: Option<f32>,
241
242 #[refineable]
245 pub margin: Edges<Length>,
246 #[refineable]
248 pub padding: Edges<DefiniteLength>,
249 #[refineable]
251 pub border_widths: Edges<AbsoluteLength>,
252
253 pub align_items: Option<AlignItems>,
256 pub align_self: Option<AlignSelf>,
258 pub align_content: Option<AlignContent>,
260 pub justify_content: Option<JustifyContent>,
262 #[refineable]
264 pub gap: Size<DefiniteLength>,
265
266 pub flex_direction: FlexDirection,
269 pub flex_wrap: FlexWrap,
271 pub flex_basis: Length,
273 pub flex_grow: f32,
275 pub flex_shrink: f32,
277
278 pub background: Option<Fill>,
280
281 pub border_color: Option<Hsla>,
283
284 pub border_style: BorderStyle,
286
287 #[refineable]
289 pub corner_radii: Corners<AbsoluteLength>,
290
291 pub box_shadow: Vec<BoxShadow>,
293
294 #[refineable]
296 pub text: TextStyleRefinement,
297
298 pub mouse_cursor: Option<CursorStyle>,
300
301 pub opacity: Option<f32>,
303
304 pub grid_cols: Option<GridTemplate>,
307
308 pub grid_rows: Option<GridTemplate>,
311
312 pub grid_location: Option<GridLocation>,
314
315 #[cfg(debug_assertions)]
317 pub debug: bool,
318
319 #[cfg(debug_assertions)]
321 pub debug_below: bool,
322}
323
324impl Styled for StyleRefinement {
325 fn style(&mut self) -> &mut StyleRefinement {
326 self
327 }
328}
329
330impl StyleRefinement {
331 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
333 self.grid_location.get_or_insert_default()
334 }
335}
336
337#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
339pub enum Visibility {
340 #[default]
342 Visible,
343 Hidden,
345}
346
347#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
349pub struct BoxShadow {
350 pub color: Hsla,
352 pub offset: Point<Pixels>,
354 pub blur_radius: Pixels,
356 pub spread_radius: Pixels,
358 pub inset: bool,
360}
361
362impl BoxShadow {
363 pub fn new(offset_x: Pixels, offset_y: Pixels, color: Hsla) -> Self {
367 Self {
368 color,
369 offset: point(offset_x, offset_y),
370 blur_radius: px(0.),
371 spread_radius: px(0.),
372 inset: false,
373 }
374 }
375
376 pub fn blur_radius(mut self, blur_radius: Pixels) -> Self {
378 self.blur_radius = blur_radius;
379 self
380 }
381
382 pub fn spread_radius(mut self, spread_radius: Pixels) -> Self {
384 self.spread_radius = spread_radius;
385 self
386 }
387
388 pub fn inset(mut self) -> Self {
390 self.inset = true;
391 self
392 }
393}
394
395#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
397pub enum WhiteSpace {
398 #[default]
400 Normal,
401 Nowrap,
403}
404
405#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
407pub enum TextOverflow {
408 Truncate(SharedString),
411 TruncateStart(SharedString),
415 TruncateMiddle(SharedString),
419}
420
421#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
423pub enum TextAlign {
424 #[default]
426 Left,
427
428 Center,
430
431 Right,
433}
434
435#[derive(Refineable, Clone, Debug, PartialEq)]
437#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
438pub struct TextStyle {
439 pub color: Hsla,
441
442 pub font_family: SharedString,
444
445 pub font_features: FontFeatures,
447
448 pub font_fallbacks: Option<FontFallbacks>,
450
451 pub font_size: AbsoluteLength,
453
454 pub line_height: DefiniteLength,
456
457 pub font_weight: FontWeight,
459
460 pub font_style: FontStyle,
462
463 pub background_color: Option<Hsla>,
465
466 pub underline: Option<UnderlineStyle>,
468
469 pub strikethrough: Option<StrikethroughStyle>,
471
472 pub white_space: WhiteSpace,
474
475 pub text_overflow: Option<TextOverflow>,
477
478 pub text_align: TextAlign,
480
481 pub line_clamp: Option<usize>,
483}
484
485impl Default for TextStyle {
486 fn default() -> Self {
487 TextStyle {
488 color: black(),
489 font_family: ".SystemUIFont".into(),
491 font_features: FontFeatures::default(),
492 font_fallbacks: None,
493 font_size: rems(1.).into(),
494 line_height: phi(),
495 font_weight: FontWeight::default(),
496 font_style: FontStyle::default(),
497 background_color: None,
498 underline: None,
499 strikethrough: None,
500 white_space: WhiteSpace::Normal,
501 text_overflow: None,
502 text_align: TextAlign::default(),
503 line_clamp: None,
504 }
505 }
506}
507
508impl TextStyle {
509 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
511 let style = style.into();
512 if let Some(weight) = style.font_weight {
513 self.font_weight = weight;
514 }
515 if let Some(style) = style.font_style {
516 self.font_style = style;
517 }
518
519 if let Some(color) = style.color {
520 self.color = self.color.blend(color);
521 }
522
523 if let Some(factor) = style.fade_out {
524 self.color.fade_out(factor);
525 }
526
527 if let Some(background_color) = style.background_color {
528 self.background_color = Some(background_color);
529 }
530
531 if let Some(underline) = style.underline {
532 self.underline = Some(underline);
533 }
534
535 if let Some(strikethrough) = style.strikethrough {
536 self.strikethrough = Some(strikethrough);
537 }
538
539 self
540 }
541
542 pub fn font(&self) -> Font {
544 Font {
545 family: self.font_family.clone(),
546 features: self.font_features.clone(),
547 fallbacks: self.font_fallbacks.clone(),
548 weight: self.font_weight,
549 style: self.font_style,
550 }
551 }
552
553 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
555 self.line_height.to_pixels(self.font_size, rem_size).round()
556 }
557
558 pub fn to_run(&self, len: usize) -> TextRun {
560 TextRun {
561 len,
562 font: Font {
563 family: self.font_family.clone(),
564 features: self.font_features.clone(),
565 fallbacks: self.font_fallbacks.clone(),
566 weight: self.font_weight,
567 style: self.font_style,
568 },
569 color: self.color,
570 background_color: self.background_color,
571 underline: self.underline,
572 strikethrough: self.strikethrough,
573 }
574 }
575}
576
577#[derive(Copy, Clone, Debug, Default, PartialEq)]
580pub struct HighlightStyle {
581 pub color: Option<Hsla>,
583
584 pub font_weight: Option<FontWeight>,
586
587 pub font_style: Option<FontStyle>,
589
590 pub background_color: Option<Hsla>,
592
593 pub underline: Option<UnderlineStyle>,
595
596 pub strikethrough: Option<StrikethroughStyle>,
598
599 pub fade_out: Option<f32>,
601}
602
603impl Eq for HighlightStyle {}
604
605impl Hash for HighlightStyle {
606 fn hash<H: Hasher>(&self, state: &mut H) {
607 self.color.hash(state);
608 self.font_weight.hash(state);
609 self.font_style.hash(state);
610 self.background_color.hash(state);
611 self.underline.hash(state);
612 self.strikethrough.hash(state);
613 state.write_u32(u32::from_be_bytes(
614 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
615 ));
616 }
617}
618
619impl Style {
620 pub fn has_opaque_background(&self) -> bool {
622 self.background
623 .as_ref()
624 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
625 }
626
627 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
629 if self.text.is_some() {
630 Some(&self.text)
631 } else {
632 None
633 }
634 }
635
636 pub fn overflow_mask(
639 &self,
640 bounds: Bounds<Pixels>,
641 rem_size: Pixels,
642 ) -> Option<ContentMask<Pixels>> {
643 match self.overflow {
644 Point {
645 x: Overflow::Visible,
646 y: Overflow::Visible,
647 } => None,
648 _ => {
649 let mut min = bounds.origin;
650 let mut max = bounds.bottom_right();
651
652 if self
653 .border_color
654 .is_some_and(|color| !color.is_transparent())
655 {
656 min.x += self.border_widths.left.to_pixels(rem_size);
657 max.x -= self.border_widths.right.to_pixels(rem_size);
658 min.y += self.border_widths.top.to_pixels(rem_size);
659 max.y -= self.border_widths.bottom.to_pixels(rem_size);
660 }
661
662 let bounds = match (
663 self.overflow.x == Overflow::Visible,
664 self.overflow.y == Overflow::Visible,
665 ) {
666 (true, true) => return None,
668 (true, false) => Bounds::from_corners(
670 point(bounds.origin.x, min.y),
671 point(bounds.bottom_right().x, max.y),
672 ),
673 (false, true) => Bounds::from_corners(
675 point(min.x, bounds.origin.y),
676 point(max.x, bounds.bottom_right().y),
677 ),
678 (false, false) => Bounds::from_corners(min, max),
680 };
681
682 Some(ContentMask { bounds })
683 }
684 }
685 }
686
687 pub fn paint(
689 &self,
690 bounds: Bounds<Pixels>,
691 window: &mut Window,
692 cx: &mut App,
693 continuation: impl FnOnce(&mut Window, &mut App),
694 ) {
695 #[cfg(debug_assertions)]
696 if self.debug_below {
697 cx.set_global(DebugBelow)
698 }
699
700 #[cfg(debug_assertions)]
701 if self.debug || cx.has_global::<DebugBelow>() {
702 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
703 }
704
705 let rem_size = window.rem_size();
706 let corner_radii = self
707 .corner_radii
708 .to_pixels(rem_size)
709 .clamp_radii_for_quad_size(bounds.size);
710
711 window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
712
713 let background_color = self.background.as_ref().and_then(Fill::color);
714 if background_color.is_some_and(|color| !color.is_transparent()) {
715 let mut border_color = match background_color {
716 Some(color) => match color.tag {
717 BackgroundTag::Solid
718 | BackgroundTag::PatternSlash
719 | BackgroundTag::Checkerboard => color.solid,
720
721 BackgroundTag::LinearGradient => color
722 .colors
723 .first()
724 .map(|stop| stop.color)
725 .unwrap_or_default(),
726 },
727 None => Hsla::default(),
728 };
729 border_color.a = 0.;
730 window.paint_quad(quad(
731 bounds,
732 corner_radii,
733 background_color.unwrap_or_default(),
734 Edges::default(),
735 border_color,
736 self.border_style,
737 ));
738 }
739
740 window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
741
742 continuation(window, cx);
743
744 if self.is_border_visible() {
745 let border_widths = self.border_widths.to_pixels(rem_size);
746 let mut background = self.border_color.unwrap_or_default();
747 background.a = 0.;
748 window.paint_quad(quad(
749 bounds,
750 corner_radii,
751 background,
752 border_widths,
753 self.border_color.unwrap_or_default(),
754 self.border_style,
755 ));
756 }
757
758 #[cfg(debug_assertions)]
759 if self.debug_below {
760 cx.remove_global::<DebugBelow>();
761 }
762 }
763
764 fn is_border_visible(&self) -> bool {
765 self.border_color
766 .is_some_and(|color| !color.is_transparent())
767 && self.border_widths.any(|length| !length.is_zero())
768 }
769}
770
771impl Default for Style {
772 fn default() -> Self {
773 Style {
774 display: Display::Block,
775 visibility: Visibility::Visible,
776 overflow: Point {
777 x: Overflow::Visible,
778 y: Overflow::Visible,
779 },
780 allow_concurrent_scroll: false,
781 restrict_scroll_to_axis: false,
782 scrollbar_width: AbsoluteLength::default(),
783 position: Position::Relative,
784 inset: Edges::auto(),
785 margin: Edges::<Length>::zero(),
786 padding: Edges::<DefiniteLength>::zero(),
787 border_widths: Edges::<AbsoluteLength>::zero(),
788 size: Size::auto(),
789 min_size: Size::auto(),
790 max_size: Size::auto(),
791 aspect_ratio: None,
792 gap: Size::default(),
793 align_items: None,
795 align_self: None,
796 align_content: None,
797 justify_content: None,
798 flex_direction: FlexDirection::Row,
800 flex_wrap: FlexWrap::NoWrap,
801 flex_grow: 0.0,
802 flex_shrink: 1.0,
803 flex_basis: Length::Auto,
804 background: None,
805 border_color: None,
806 border_style: BorderStyle::default(),
807 corner_radii: Corners::default(),
808 box_shadow: Default::default(),
809 text: TextStyleRefinement::default(),
810 mouse_cursor: None,
811 opacity: None,
812 grid_rows: None,
813 grid_cols: None,
814 grid_location: None,
815
816 #[cfg(debug_assertions)]
817 debug: false,
818 #[cfg(debug_assertions)]
819 debug_below: false,
820 }
821 }
822}
823
824#[derive(
826 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
827)]
828pub struct UnderlineStyle {
829 pub thickness: Pixels,
831
832 pub color: Option<Hsla>,
834
835 pub wavy: bool,
837}
838
839#[derive(
841 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
842)]
843pub struct StrikethroughStyle {
844 pub thickness: Pixels,
846
847 pub color: Option<Hsla>,
849}
850
851#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
853pub enum Fill {
854 Color(Background),
856}
857
858impl Fill {
859 pub fn color(&self) -> Option<Background> {
863 match self {
864 Fill::Color(color) => Some(*color),
865 }
866 }
867}
868
869impl Default for Fill {
870 fn default() -> Self {
871 Self::Color(Background::default())
872 }
873}
874
875impl From<Hsla> for Fill {
876 fn from(color: Hsla) -> Self {
877 Self::Color(color.into())
878 }
879}
880
881impl From<Rgba> for Fill {
882 fn from(color: Rgba) -> Self {
883 Self::Color(color.into())
884 }
885}
886
887impl From<Background> for Fill {
888 fn from(background: Background) -> Self {
889 Self::Color(background)
890 }
891}
892
893impl From<TextStyle> for HighlightStyle {
894 fn from(other: TextStyle) -> Self {
895 Self::from(&other)
896 }
897}
898
899impl From<&TextStyle> for HighlightStyle {
900 fn from(other: &TextStyle) -> Self {
901 Self {
902 color: Some(other.color),
903 font_weight: Some(other.font_weight),
904 font_style: Some(other.font_style),
905 background_color: other.background_color,
906 underline: other.underline,
907 strikethrough: other.strikethrough,
908 fade_out: None,
909 }
910 }
911}
912
913impl HighlightStyle {
914 pub fn color(color: Hsla) -> Self {
916 Self {
917 color: Some(color),
918 ..Default::default()
919 }
920 }
921 #[must_use]
924 pub fn highlight(self, other: HighlightStyle) -> Self {
925 Self {
926 color: other
927 .color
928 .map(|other_color| {
929 if let Some(color) = self.color {
930 color.blend(other_color)
931 } else {
932 other_color
933 }
934 })
935 .or(self.color),
936 font_weight: other.font_weight.or(self.font_weight),
937 font_style: other.font_style.or(self.font_style),
938 background_color: other.background_color.or(self.background_color),
939 underline: other.underline.or(self.underline),
940 strikethrough: other.strikethrough.or(self.strikethrough),
941 fade_out: other
942 .fade_out
943 .map(|source_fade| {
944 self.fade_out
945 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
946 .unwrap_or(source_fade)
947 })
948 .or(self.fade_out),
949 }
950 }
951}
952
953impl From<Hsla> for HighlightStyle {
954 fn from(color: Hsla) -> Self {
955 Self {
956 color: Some(color),
957 ..Default::default()
958 }
959 }
960}
961
962impl From<FontWeight> for HighlightStyle {
963 fn from(font_weight: FontWeight) -> Self {
964 Self {
965 font_weight: Some(font_weight),
966 ..Default::default()
967 }
968 }
969}
970
971impl From<FontStyle> for HighlightStyle {
972 fn from(font_style: FontStyle) -> Self {
973 Self {
974 font_style: Some(font_style),
975 ..Default::default()
976 }
977 }
978}
979
980impl From<Rgba> for HighlightStyle {
981 fn from(color: Rgba) -> Self {
982 Self {
983 color: Some(color.into()),
984 ..Default::default()
985 }
986 }
987}
988
989pub fn combine_highlights(
991 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
992 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
993) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
994 let mut endpoints = Vec::new();
995 let mut highlights = Vec::new();
996 for (range, highlight) in a.into_iter().chain(b) {
997 if !range.is_empty() {
998 let highlight_id = highlights.len();
999 endpoints.push((range.start, highlight_id, true));
1000 endpoints.push((range.end, highlight_id, false));
1001 highlights.push(highlight);
1002 }
1003 }
1004 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
1005 let mut endpoints = endpoints.into_iter().peekable();
1006
1007 let mut active_styles = HashSet::default();
1008 let mut ix = 0;
1009 iter::from_fn(move || {
1010 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
1011 let prev_index = mem::replace(&mut ix, *endpoint_ix);
1012 if ix > prev_index && !active_styles.is_empty() {
1013 let current_style = active_styles
1014 .iter()
1015 .fold(HighlightStyle::default(), |acc, highlight_id| {
1016 acc.highlight(highlights[*highlight_id])
1017 });
1018 return Some((prev_index..ix, current_style));
1019 }
1020
1021 if *is_start {
1022 active_styles.insert(*highlight_id);
1023 } else {
1024 active_styles.remove(highlight_id);
1025 }
1026 endpoints.next();
1027 }
1028 None
1029 })
1030}
1031
1032#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1038pub enum AlignItems {
1040 Start,
1042 End,
1044 FlexStart,
1049 FlexEnd,
1054 Center,
1056 Baseline,
1058 Stretch,
1060}
1061pub type JustifyItems = AlignItems;
1067pub type AlignSelf = AlignItems;
1074pub type JustifySelf = AlignItems;
1081
1082#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1088pub enum AlignContent {
1090 Start,
1092 End,
1094 FlexStart,
1099 FlexEnd,
1104 Center,
1106 Stretch,
1108 SpaceBetween,
1111 SpaceEvenly,
1114 SpaceAround,
1117}
1118
1119pub type JustifyContent = AlignContent;
1125
1126#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1130pub enum Display {
1132 Block,
1134 #[default]
1136 Flex,
1137 Grid,
1139 None,
1141}
1142
1143#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1149pub enum FlexWrap {
1151 #[default]
1153 NoWrap,
1154 Wrap,
1156 WrapReverse,
1158}
1159
1160#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1172pub enum FlexDirection {
1174 #[default]
1178 Row,
1179 Column,
1183 RowReverse,
1187 ColumnReverse,
1191}
1192
1193#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1207pub enum Overflow {
1209 #[default]
1212 Visible,
1213 Clip,
1216 Hidden,
1219 Scroll,
1223}
1224
1225#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1235pub enum Position {
1237 #[default]
1240 Relative,
1241 Absolute,
1247}
1248
1249impl From<AlignItems> for taffy::style::AlignItems {
1250 fn from(value: AlignItems) -> Self {
1251 match value {
1252 AlignItems::Start => Self::START,
1253 AlignItems::End => Self::END,
1254 AlignItems::FlexStart => Self::FLEX_START,
1255 AlignItems::FlexEnd => Self::FLEX_END,
1256 AlignItems::Center => Self::CENTER,
1257 AlignItems::Baseline => Self::BASELINE,
1258 AlignItems::Stretch => Self::STRETCH,
1259 }
1260 }
1261}
1262
1263impl From<AlignContent> for taffy::style::AlignContent {
1264 fn from(value: AlignContent) -> Self {
1265 match value {
1266 AlignContent::Start => Self::START,
1267 AlignContent::End => Self::END,
1268 AlignContent::FlexStart => Self::FLEX_START,
1269 AlignContent::FlexEnd => Self::FLEX_END,
1270 AlignContent::Center => Self::CENTER,
1271 AlignContent::Stretch => Self::STRETCH,
1272 AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
1273 AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
1274 AlignContent::SpaceAround => Self::SPACE_AROUND,
1275 }
1276 }
1277}
1278
1279impl From<Display> for taffy::style::Display {
1280 fn from(value: Display) -> Self {
1281 match value {
1282 Display::Block => Self::Block,
1283 Display::Flex => Self::Flex,
1284 Display::Grid => Self::Grid,
1285 Display::None => Self::None,
1286 }
1287 }
1288}
1289
1290impl From<FlexWrap> for taffy::style::FlexWrap {
1291 fn from(value: FlexWrap) -> Self {
1292 match value {
1293 FlexWrap::NoWrap => Self::NoWrap,
1294 FlexWrap::Wrap => Self::Wrap,
1295 FlexWrap::WrapReverse => Self::WrapReverse,
1296 }
1297 }
1298}
1299
1300impl From<FlexDirection> for taffy::style::FlexDirection {
1301 fn from(value: FlexDirection) -> Self {
1302 match value {
1303 FlexDirection::Row => Self::Row,
1304 FlexDirection::Column => Self::Column,
1305 FlexDirection::RowReverse => Self::RowReverse,
1306 FlexDirection::ColumnReverse => Self::ColumnReverse,
1307 }
1308 }
1309}
1310
1311impl From<Overflow> for taffy::style::Overflow {
1312 fn from(value: Overflow) -> Self {
1313 match value {
1314 Overflow::Visible => Self::Visible,
1315 Overflow::Clip => Self::Clip,
1316 Overflow::Hidden => Self::Hidden,
1317 Overflow::Scroll => Self::Scroll,
1318 }
1319 }
1320}
1321
1322impl From<Position> for taffy::style::Position {
1323 fn from(value: Position) -> Self {
1324 match value {
1325 Position::Relative => Self::Relative,
1326 Position::Absolute => Self::Absolute,
1327 }
1328 }
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333 use crate::{blue, green, px, red, yellow};
1334
1335 use super::*;
1336
1337 use util_macros::perf;
1338
1339 #[test]
1342 fn overflow_mask_insets_only_hidden_axes_for_native_borders() {
1343 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(80.)));
1344 let mut style = Style {
1345 border_color: Some(red()),
1346 border_widths: Edges {
1347 left: px(2.).into(),
1348 right: px(4.).into(),
1349 top: px(6.).into(),
1350 bottom: px(8.).into(),
1351 },
1352 ..Default::default()
1353 };
1354 style.overflow = point(Overflow::Visible, Overflow::Hidden);
1355 assert_eq!(
1356 style.overflow_mask(bounds, px(16.)).unwrap().bounds,
1357 Bounds::new(point(px(10.), px(26.)), size(px(100.), px(66.)))
1358 );
1359 style.overflow = point(Overflow::Hidden, Overflow::Visible);
1360 assert_eq!(
1361 style.overflow_mask(bounds, px(16.)).unwrap().bounds,
1362 Bounds::new(point(px(12.), px(20.)), size(px(94.), px(80.)))
1363 );
1364 style.border_color = Some(crate::transparent_black());
1365 assert_eq!(style.overflow_mask(bounds, px(16.)).unwrap().bounds, bounds);
1366 }
1367
1368 #[perf]
1369 fn test_basic_highlight_style_combination() {
1370 let style_a = HighlightStyle::default();
1371 let style_b = HighlightStyle::default();
1372 let style_a = style_a.highlight(style_b);
1373 assert_eq!(
1374 style_a,
1375 HighlightStyle::default(),
1376 "Combining empty styles should not produce a non-empty style."
1377 );
1378
1379 let mut style_b = HighlightStyle {
1380 color: Some(red()),
1381 strikethrough: Some(StrikethroughStyle {
1382 thickness: px(2.),
1383 color: Some(blue()),
1384 }),
1385 fade_out: Some(0.),
1386 font_style: Some(FontStyle::Italic),
1387 font_weight: Some(FontWeight(300.)),
1388 background_color: Some(yellow()),
1389 underline: Some(UnderlineStyle {
1390 thickness: px(2.),
1391 color: Some(red()),
1392 wavy: true,
1393 }),
1394 };
1395 let expected_style = style_b;
1396
1397 let style_a = style_a.highlight(style_b);
1398 assert_eq!(
1399 style_a, expected_style,
1400 "Blending an empty style with another style should return the other style"
1401 );
1402
1403 let style_b = style_b.highlight(Default::default());
1404 assert_eq!(
1405 style_b, expected_style,
1406 "Blending a style with an empty style should not change the style."
1407 );
1408
1409 let mut style_c = expected_style;
1410
1411 let style_d = HighlightStyle {
1412 color: Some(blue().alpha(0.7)),
1413 strikethrough: Some(StrikethroughStyle {
1414 thickness: px(4.),
1415 color: Some(crate::red()),
1416 }),
1417 fade_out: Some(0.),
1418 font_style: Some(FontStyle::Oblique),
1419 font_weight: Some(FontWeight(800.)),
1420 background_color: Some(green()),
1421 underline: Some(UnderlineStyle {
1422 thickness: px(4.),
1423 color: None,
1424 wavy: false,
1425 }),
1426 };
1427
1428 let expected_style = HighlightStyle {
1429 color: Some(red().blend(blue().alpha(0.7))),
1430 strikethrough: Some(StrikethroughStyle {
1431 thickness: px(4.),
1432 color: Some(red()),
1433 }),
1434 fade_out: Some(0.),
1436 font_style: Some(FontStyle::Oblique),
1437 font_weight: Some(FontWeight(800.)),
1438 background_color: Some(green()),
1439 underline: Some(UnderlineStyle {
1440 thickness: px(4.),
1441 color: None,
1442 wavy: false,
1443 }),
1444 };
1445
1446 let style_c = style_c.highlight(style_d);
1447 assert_eq!(
1448 style_c, expected_style,
1449 "Blending styles should blend properties where possible and override all others"
1450 );
1451 }
1452
1453 #[perf]
1454 fn test_combine_highlights() {
1455 assert_eq!(
1456 combine_highlights(
1457 [
1458 (0..5, green().into()),
1459 (4..10, FontWeight::BOLD.into()),
1460 (15..20, yellow().into()),
1461 ],
1462 [
1463 (2..6, FontStyle::Italic.into()),
1464 (1..3, blue().into()),
1465 (21..23, red().into()),
1466 ]
1467 )
1468 .collect::<Vec<_>>(),
1469 [
1470 (
1471 0..1,
1472 HighlightStyle {
1473 color: Some(green()),
1474 ..Default::default()
1475 }
1476 ),
1477 (
1478 1..2,
1479 HighlightStyle {
1480 color: Some(blue()),
1481 ..Default::default()
1482 }
1483 ),
1484 (
1485 2..3,
1486 HighlightStyle {
1487 color: Some(blue()),
1488 font_style: Some(FontStyle::Italic),
1489 ..Default::default()
1490 }
1491 ),
1492 (
1493 3..4,
1494 HighlightStyle {
1495 color: Some(green()),
1496 font_style: Some(FontStyle::Italic),
1497 ..Default::default()
1498 }
1499 ),
1500 (
1501 4..5,
1502 HighlightStyle {
1503 color: Some(green()),
1504 font_weight: Some(FontWeight::BOLD),
1505 font_style: Some(FontStyle::Italic),
1506 ..Default::default()
1507 }
1508 ),
1509 (
1510 5..6,
1511 HighlightStyle {
1512 font_weight: Some(FontWeight::BOLD),
1513 font_style: Some(FontStyle::Italic),
1514 ..Default::default()
1515 }
1516 ),
1517 (
1518 6..10,
1519 HighlightStyle {
1520 font_weight: Some(FontWeight::BOLD),
1521 ..Default::default()
1522 }
1523 ),
1524 (
1525 15..20,
1526 HighlightStyle {
1527 color: Some(yellow()),
1528 ..Default::default()
1529 }
1530 ),
1531 (
1532 21..23,
1533 HighlightStyle {
1534 color: Some(red()),
1535 ..Default::default()
1536 }
1537 )
1538 ]
1539 );
1540 }
1541
1542 #[perf]
1543 fn test_text_style_refinement() {
1544 let mut style = Style::default();
1545 style.refine(&StyleRefinement::default().text_size(px(20.0)));
1546 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1547
1548 assert_eq!(
1549 Some(AbsoluteLength::from(px(20.0))),
1550 style.text_style().unwrap().font_size
1551 );
1552
1553 assert_eq!(
1554 Some(FontWeight::SEMIBOLD),
1555 style.text_style().unwrap().font_weight
1556 );
1557 }
1558}