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, 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 TemplateColumnMinSize {
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: TemplateColumnMinSize,
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,
217
218 pub position: Position,
221 #[refineable]
223 pub inset: Edges<Length>,
224
225 #[refineable]
228 pub size: Size<Length>,
229 #[refineable]
231 pub min_size: Size<Length>,
232 #[refineable]
234 pub max_size: Size<Length>,
235 pub aspect_ratio: Option<f32>,
237
238 #[refineable]
241 pub margin: Edges<Length>,
242 #[refineable]
244 pub padding: Edges<DefiniteLength>,
245 #[refineable]
247 pub border_widths: Edges<AbsoluteLength>,
248
249 pub align_items: Option<AlignItems>,
252 pub align_self: Option<AlignSelf>,
254 pub align_content: Option<AlignContent>,
256 pub justify_content: Option<JustifyContent>,
258 #[refineable]
260 pub gap: Size<DefiniteLength>,
261
262 pub flex_direction: FlexDirection,
265 pub flex_wrap: FlexWrap,
267 pub flex_basis: Length,
269 pub flex_grow: f32,
271 pub flex_shrink: f32,
273
274 pub background: Option<Fill>,
276
277 pub border_color: Option<Hsla>,
279
280 pub border_style: BorderStyle,
282
283 #[refineable]
285 pub corner_radii: Corners<AbsoluteLength>,
286
287 pub box_shadow: Vec<BoxShadow>,
289
290 #[refineable]
292 pub text: TextStyleRefinement,
293
294 pub mouse_cursor: Option<CursorStyle>,
296
297 pub opacity: Option<f32>,
299
300 pub grid_cols: Option<GridTemplate>,
303
304 pub grid_rows: Option<GridTemplate>,
307
308 pub grid_location: Option<GridLocation>,
310
311 #[cfg(debug_assertions)]
313 pub debug: bool,
314
315 #[cfg(debug_assertions)]
317 pub debug_below: bool,
318}
319
320impl Styled for StyleRefinement {
321 fn style(&mut self) -> &mut StyleRefinement {
322 self
323 }
324}
325
326impl StyleRefinement {
327 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
329 self.grid_location.get_or_insert_default()
330 }
331}
332
333#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
335pub enum Visibility {
336 #[default]
338 Visible,
339 Hidden,
341}
342
343#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
345pub struct BoxShadow {
346 pub color: Hsla,
348 pub offset: Point<Pixels>,
350 pub blur_radius: Pixels,
352 pub spread_radius: Pixels,
354}
355
356#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
358pub enum WhiteSpace {
359 #[default]
361 Normal,
362 Nowrap,
364}
365
366#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
368pub enum TextOverflow {
369 Truncate(SharedString),
372 TruncateStart(SharedString),
376}
377
378#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
380pub enum TextAlign {
381 #[default]
383 Left,
384
385 Center,
387
388 Right,
390}
391
392#[derive(Refineable, Clone, Debug, PartialEq)]
394#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
395pub struct TextStyle {
396 pub color: Hsla,
398
399 pub font_family: SharedString,
401
402 pub font_features: FontFeatures,
404
405 pub font_fallbacks: Option<FontFallbacks>,
407
408 pub font_size: AbsoluteLength,
410
411 pub line_height: DefiniteLength,
413
414 pub font_weight: FontWeight,
416
417 pub font_style: FontStyle,
419
420 pub background_color: Option<Hsla>,
422
423 pub underline: Option<UnderlineStyle>,
425
426 pub strikethrough: Option<StrikethroughStyle>,
428
429 pub white_space: WhiteSpace,
431
432 pub text_overflow: Option<TextOverflow>,
434
435 pub text_align: TextAlign,
437
438 pub line_clamp: Option<usize>,
440}
441
442impl Default for TextStyle {
443 fn default() -> Self {
444 TextStyle {
445 color: black(),
446 font_family: ".SystemUIFont".into(),
448 font_features: FontFeatures::default(),
449 font_fallbacks: None,
450 font_size: rems(1.).into(),
451 line_height: phi(),
452 font_weight: FontWeight::default(),
453 font_style: FontStyle::default(),
454 background_color: None,
455 underline: None,
456 strikethrough: None,
457 white_space: WhiteSpace::Normal,
458 text_overflow: None,
459 text_align: TextAlign::default(),
460 line_clamp: None,
461 }
462 }
463}
464
465impl TextStyle {
466 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
468 let style = style.into();
469 if let Some(weight) = style.font_weight {
470 self.font_weight = weight;
471 }
472 if let Some(style) = style.font_style {
473 self.font_style = style;
474 }
475
476 if let Some(color) = style.color {
477 self.color = self.color.blend(color);
478 }
479
480 if let Some(factor) = style.fade_out {
481 self.color.fade_out(factor);
482 }
483
484 if let Some(background_color) = style.background_color {
485 self.background_color = Some(background_color);
486 }
487
488 if let Some(underline) = style.underline {
489 self.underline = Some(underline);
490 }
491
492 if let Some(strikethrough) = style.strikethrough {
493 self.strikethrough = Some(strikethrough);
494 }
495
496 self
497 }
498
499 pub fn font(&self) -> Font {
501 Font {
502 family: self.font_family.clone(),
503 features: self.font_features.clone(),
504 fallbacks: self.font_fallbacks.clone(),
505 weight: self.font_weight,
506 style: self.font_style,
507 }
508 }
509
510 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
512 self.line_height.to_pixels(self.font_size, rem_size).round()
513 }
514
515 pub fn to_run(&self, len: usize) -> TextRun {
517 TextRun {
518 len,
519 font: Font {
520 family: self.font_family.clone(),
521 features: self.font_features.clone(),
522 fallbacks: self.font_fallbacks.clone(),
523 weight: self.font_weight,
524 style: self.font_style,
525 },
526 color: self.color,
527 background_color: self.background_color,
528 underline: self.underline,
529 strikethrough: self.strikethrough,
530 }
531 }
532}
533
534#[derive(Copy, Clone, Debug, Default, PartialEq)]
537pub struct HighlightStyle {
538 pub color: Option<Hsla>,
540
541 pub font_weight: Option<FontWeight>,
543
544 pub font_style: Option<FontStyle>,
546
547 pub background_color: Option<Hsla>,
549
550 pub underline: Option<UnderlineStyle>,
552
553 pub strikethrough: Option<StrikethroughStyle>,
555
556 pub fade_out: Option<f32>,
558}
559
560impl Eq for HighlightStyle {}
561
562impl Hash for HighlightStyle {
563 fn hash<H: Hasher>(&self, state: &mut H) {
564 self.color.hash(state);
565 self.font_weight.hash(state);
566 self.font_style.hash(state);
567 self.background_color.hash(state);
568 self.underline.hash(state);
569 self.strikethrough.hash(state);
570 state.write_u32(u32::from_be_bytes(
571 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
572 ));
573 }
574}
575
576impl Style {
577 pub fn has_opaque_background(&self) -> bool {
579 self.background
580 .as_ref()
581 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
582 }
583
584 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
586 if self.text.is_some() {
587 Some(&self.text)
588 } else {
589 None
590 }
591 }
592
593 pub fn overflow_mask(
596 &self,
597 bounds: Bounds<Pixels>,
598 rem_size: Pixels,
599 ) -> Option<ContentMask<Pixels>> {
600 match self.overflow {
601 Point {
602 x: Overflow::Visible,
603 y: Overflow::Visible,
604 } => None,
605 _ => {
606 let mut min = bounds.origin;
607 let mut max = bounds.bottom_right();
608
609 if self
610 .border_color
611 .is_some_and(|color| !color.is_transparent())
612 {
613 min.x += self.border_widths.left.to_pixels(rem_size);
614 max.x -= self.border_widths.right.to_pixels(rem_size);
615 min.y += self.border_widths.top.to_pixels(rem_size);
616 max.y -= self.border_widths.bottom.to_pixels(rem_size);
617 }
618
619 let bounds = match (
620 self.overflow.x == Overflow::Visible,
621 self.overflow.y == Overflow::Visible,
622 ) {
623 (true, true) => return None,
625 (true, false) => Bounds::from_corners(
627 point(min.x, bounds.origin.y),
628 point(max.x, bounds.bottom_right().y),
629 ),
630 (false, true) => Bounds::from_corners(
632 point(bounds.origin.x, min.y),
633 point(bounds.bottom_right().x, max.y),
634 ),
635 (false, false) => Bounds::from_corners(min, max),
637 };
638
639 Some(ContentMask { bounds })
640 }
641 }
642 }
643
644 pub fn paint(
646 &self,
647 bounds: Bounds<Pixels>,
648 window: &mut Window,
649 cx: &mut App,
650 continuation: impl FnOnce(&mut Window, &mut App),
651 ) {
652 #[cfg(debug_assertions)]
653 if self.debug_below {
654 cx.set_global(DebugBelow)
655 }
656
657 #[cfg(debug_assertions)]
658 if self.debug || cx.has_global::<DebugBelow>() {
659 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
660 }
661
662 let rem_size = window.rem_size();
663 let corner_radii = self
664 .corner_radii
665 .to_pixels(rem_size)
666 .clamp_radii_for_quad_size(bounds.size);
667
668 window.paint_shadows(bounds, corner_radii, &self.box_shadow);
669
670 let background_color = self.background.as_ref().and_then(Fill::color);
671 if background_color.is_some_and(|color| !color.is_transparent()) {
672 let mut border_color = match background_color {
673 Some(color) => match color.tag {
674 BackgroundTag::Solid
675 | BackgroundTag::PatternSlash
676 | BackgroundTag::Checkerboard => color.solid,
677
678 BackgroundTag::LinearGradient => color
679 .colors
680 .first()
681 .map(|stop| stop.color)
682 .unwrap_or_default(),
683 },
684 None => Hsla::default(),
685 };
686 border_color.a = 0.;
687 window.paint_quad(quad(
688 bounds,
689 corner_radii,
690 background_color.unwrap_or_default(),
691 Edges::default(),
692 border_color,
693 self.border_style,
694 ));
695 }
696
697 continuation(window, cx);
698
699 if self.is_border_visible() {
700 let border_widths = self.border_widths.to_pixels(rem_size);
701 let mut background = self.border_color.unwrap_or_default();
702 background.a = 0.;
703 window.paint_quad(quad(
704 bounds,
705 corner_radii,
706 background,
707 border_widths,
708 self.border_color.unwrap_or_default(),
709 self.border_style,
710 ));
711 }
712
713 #[cfg(debug_assertions)]
714 if self.debug_below {
715 cx.remove_global::<DebugBelow>();
716 }
717 }
718
719 fn is_border_visible(&self) -> bool {
720 self.border_color
721 .is_some_and(|color| !color.is_transparent())
722 && self.border_widths.any(|length| !length.is_zero())
723 }
724}
725
726impl Default for Style {
727 fn default() -> Self {
728 Style {
729 display: Display::Block,
730 visibility: Visibility::Visible,
731 overflow: Point {
732 x: Overflow::Visible,
733 y: Overflow::Visible,
734 },
735 allow_concurrent_scroll: false,
736 restrict_scroll_to_axis: false,
737 scrollbar_width: AbsoluteLength::default(),
738 position: Position::Relative,
739 inset: Edges::auto(),
740 margin: Edges::<Length>::zero(),
741 padding: Edges::<DefiniteLength>::zero(),
742 border_widths: Edges::<AbsoluteLength>::zero(),
743 size: Size::auto(),
744 min_size: Size::auto(),
745 max_size: Size::auto(),
746 aspect_ratio: None,
747 gap: Size::default(),
748 align_items: None,
750 align_self: None,
751 align_content: None,
752 justify_content: None,
753 flex_direction: FlexDirection::Row,
755 flex_wrap: FlexWrap::NoWrap,
756 flex_grow: 0.0,
757 flex_shrink: 1.0,
758 flex_basis: Length::Auto,
759 background: None,
760 border_color: None,
761 border_style: BorderStyle::default(),
762 corner_radii: Corners::default(),
763 box_shadow: Default::default(),
764 text: TextStyleRefinement::default(),
765 mouse_cursor: None,
766 opacity: None,
767 grid_rows: None,
768 grid_cols: None,
769 grid_location: None,
770
771 #[cfg(debug_assertions)]
772 debug: false,
773 #[cfg(debug_assertions)]
774 debug_below: false,
775 }
776 }
777}
778
779#[derive(
781 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
782)]
783pub struct UnderlineStyle {
784 pub thickness: Pixels,
786
787 pub color: Option<Hsla>,
789
790 pub wavy: bool,
792}
793
794#[derive(
796 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
797)]
798pub struct StrikethroughStyle {
799 pub thickness: Pixels,
801
802 pub color: Option<Hsla>,
804}
805
806#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
808pub enum Fill {
809 Color(Background),
811}
812
813impl Fill {
814 pub fn color(&self) -> Option<Background> {
818 match self {
819 Fill::Color(color) => Some(*color),
820 }
821 }
822}
823
824impl Default for Fill {
825 fn default() -> Self {
826 Self::Color(Background::default())
827 }
828}
829
830impl From<Hsla> for Fill {
831 fn from(color: Hsla) -> Self {
832 Self::Color(color.into())
833 }
834}
835
836impl From<Rgba> for Fill {
837 fn from(color: Rgba) -> Self {
838 Self::Color(color.into())
839 }
840}
841
842impl From<Background> for Fill {
843 fn from(background: Background) -> Self {
844 Self::Color(background)
845 }
846}
847
848impl From<TextStyle> for HighlightStyle {
849 fn from(other: TextStyle) -> Self {
850 Self::from(&other)
851 }
852}
853
854impl From<&TextStyle> for HighlightStyle {
855 fn from(other: &TextStyle) -> Self {
856 Self {
857 color: Some(other.color),
858 font_weight: Some(other.font_weight),
859 font_style: Some(other.font_style),
860 background_color: other.background_color,
861 underline: other.underline,
862 strikethrough: other.strikethrough,
863 fade_out: None,
864 }
865 }
866}
867
868impl HighlightStyle {
869 pub fn color(color: Hsla) -> Self {
871 Self {
872 color: Some(color),
873 ..Default::default()
874 }
875 }
876 #[must_use]
879 pub fn highlight(self, other: HighlightStyle) -> Self {
880 Self {
881 color: other
882 .color
883 .map(|other_color| {
884 if let Some(color) = self.color {
885 color.blend(other_color)
886 } else {
887 other_color
888 }
889 })
890 .or(self.color),
891 font_weight: other.font_weight.or(self.font_weight),
892 font_style: other.font_style.or(self.font_style),
893 background_color: other.background_color.or(self.background_color),
894 underline: other.underline.or(self.underline),
895 strikethrough: other.strikethrough.or(self.strikethrough),
896 fade_out: other
897 .fade_out
898 .map(|source_fade| {
899 self.fade_out
900 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
901 .unwrap_or(source_fade)
902 })
903 .or(self.fade_out),
904 }
905 }
906}
907
908impl From<Hsla> for HighlightStyle {
909 fn from(color: Hsla) -> Self {
910 Self {
911 color: Some(color),
912 ..Default::default()
913 }
914 }
915}
916
917impl From<FontWeight> for HighlightStyle {
918 fn from(font_weight: FontWeight) -> Self {
919 Self {
920 font_weight: Some(font_weight),
921 ..Default::default()
922 }
923 }
924}
925
926impl From<FontStyle> for HighlightStyle {
927 fn from(font_style: FontStyle) -> Self {
928 Self {
929 font_style: Some(font_style),
930 ..Default::default()
931 }
932 }
933}
934
935impl From<Rgba> for HighlightStyle {
936 fn from(color: Rgba) -> Self {
937 Self {
938 color: Some(color.into()),
939 ..Default::default()
940 }
941 }
942}
943
944pub fn combine_highlights(
946 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
947 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
948) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
949 let mut endpoints = Vec::new();
950 let mut highlights = Vec::new();
951 for (range, highlight) in a.into_iter().chain(b) {
952 if !range.is_empty() {
953 let highlight_id = highlights.len();
954 endpoints.push((range.start, highlight_id, true));
955 endpoints.push((range.end, highlight_id, false));
956 highlights.push(highlight);
957 }
958 }
959 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
960 let mut endpoints = endpoints.into_iter().peekable();
961
962 let mut active_styles = HashSet::default();
963 let mut ix = 0;
964 iter::from_fn(move || {
965 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
966 let prev_index = mem::replace(&mut ix, *endpoint_ix);
967 if ix > prev_index && !active_styles.is_empty() {
968 let current_style = active_styles
969 .iter()
970 .fold(HighlightStyle::default(), |acc, highlight_id| {
971 acc.highlight(highlights[*highlight_id])
972 });
973 return Some((prev_index..ix, current_style));
974 }
975
976 if *is_start {
977 active_styles.insert(*highlight_id);
978 } else {
979 active_styles.remove(highlight_id);
980 }
981 endpoints.next();
982 }
983 None
984 })
985}
986
987#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
993pub enum AlignItems {
995 Start,
997 End,
999 FlexStart,
1004 FlexEnd,
1009 Center,
1011 Baseline,
1013 Stretch,
1015}
1016pub type JustifyItems = AlignItems;
1022pub type AlignSelf = AlignItems;
1029pub type JustifySelf = AlignItems;
1036
1037#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1043pub enum AlignContent {
1045 Start,
1047 End,
1049 FlexStart,
1054 FlexEnd,
1059 Center,
1061 Stretch,
1063 SpaceBetween,
1066 SpaceEvenly,
1069 SpaceAround,
1072}
1073
1074pub type JustifyContent = AlignContent;
1080
1081#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1085pub enum Display {
1087 Block,
1089 #[default]
1091 Flex,
1092 Grid,
1094 None,
1096}
1097
1098#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1104pub enum FlexWrap {
1106 #[default]
1108 NoWrap,
1109 Wrap,
1111 WrapReverse,
1113}
1114
1115#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1127pub enum FlexDirection {
1129 #[default]
1133 Row,
1134 Column,
1138 RowReverse,
1142 ColumnReverse,
1146}
1147
1148#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1162pub enum Overflow {
1164 #[default]
1167 Visible,
1168 Clip,
1171 Hidden,
1174 Scroll,
1178}
1179
1180#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1190pub enum Position {
1192 #[default]
1195 Relative,
1196 Absolute,
1202}
1203
1204impl From<AlignItems> for taffy::style::AlignItems {
1205 fn from(value: AlignItems) -> Self {
1206 match value {
1207 AlignItems::Start => Self::Start,
1208 AlignItems::End => Self::End,
1209 AlignItems::FlexStart => Self::FlexStart,
1210 AlignItems::FlexEnd => Self::FlexEnd,
1211 AlignItems::Center => Self::Center,
1212 AlignItems::Baseline => Self::Baseline,
1213 AlignItems::Stretch => Self::Stretch,
1214 }
1215 }
1216}
1217
1218impl From<AlignContent> for taffy::style::AlignContent {
1219 fn from(value: AlignContent) -> Self {
1220 match value {
1221 AlignContent::Start => Self::Start,
1222 AlignContent::End => Self::End,
1223 AlignContent::FlexStart => Self::FlexStart,
1224 AlignContent::FlexEnd => Self::FlexEnd,
1225 AlignContent::Center => Self::Center,
1226 AlignContent::Stretch => Self::Stretch,
1227 AlignContent::SpaceBetween => Self::SpaceBetween,
1228 AlignContent::SpaceEvenly => Self::SpaceEvenly,
1229 AlignContent::SpaceAround => Self::SpaceAround,
1230 }
1231 }
1232}
1233
1234impl From<Display> for taffy::style::Display {
1235 fn from(value: Display) -> Self {
1236 match value {
1237 Display::Block => Self::Block,
1238 Display::Flex => Self::Flex,
1239 Display::Grid => Self::Grid,
1240 Display::None => Self::None,
1241 }
1242 }
1243}
1244
1245impl From<FlexWrap> for taffy::style::FlexWrap {
1246 fn from(value: FlexWrap) -> Self {
1247 match value {
1248 FlexWrap::NoWrap => Self::NoWrap,
1249 FlexWrap::Wrap => Self::Wrap,
1250 FlexWrap::WrapReverse => Self::WrapReverse,
1251 }
1252 }
1253}
1254
1255impl From<FlexDirection> for taffy::style::FlexDirection {
1256 fn from(value: FlexDirection) -> Self {
1257 match value {
1258 FlexDirection::Row => Self::Row,
1259 FlexDirection::Column => Self::Column,
1260 FlexDirection::RowReverse => Self::RowReverse,
1261 FlexDirection::ColumnReverse => Self::ColumnReverse,
1262 }
1263 }
1264}
1265
1266impl From<Overflow> for taffy::style::Overflow {
1267 fn from(value: Overflow) -> Self {
1268 match value {
1269 Overflow::Visible => Self::Visible,
1270 Overflow::Clip => Self::Clip,
1271 Overflow::Hidden => Self::Hidden,
1272 Overflow::Scroll => Self::Scroll,
1273 }
1274 }
1275}
1276
1277impl From<Position> for taffy::style::Position {
1278 fn from(value: Position) -> Self {
1279 match value {
1280 Position::Relative => Self::Relative,
1281 Position::Absolute => Self::Absolute,
1282 }
1283 }
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288 use crate::{blue, green, px, red, yellow};
1289
1290 use super::*;
1291
1292 use util_macros::perf;
1293
1294 #[perf]
1295 fn test_basic_highlight_style_combination() {
1296 let style_a = HighlightStyle::default();
1297 let style_b = HighlightStyle::default();
1298 let style_a = style_a.highlight(style_b);
1299 assert_eq!(
1300 style_a,
1301 HighlightStyle::default(),
1302 "Combining empty styles should not produce a non-empty style."
1303 );
1304
1305 let mut style_b = HighlightStyle {
1306 color: Some(red()),
1307 strikethrough: Some(StrikethroughStyle {
1308 thickness: px(2.),
1309 color: Some(blue()),
1310 }),
1311 fade_out: Some(0.),
1312 font_style: Some(FontStyle::Italic),
1313 font_weight: Some(FontWeight(300.)),
1314 background_color: Some(yellow()),
1315 underline: Some(UnderlineStyle {
1316 thickness: px(2.),
1317 color: Some(red()),
1318 wavy: true,
1319 }),
1320 };
1321 let expected_style = style_b;
1322
1323 let style_a = style_a.highlight(style_b);
1324 assert_eq!(
1325 style_a, expected_style,
1326 "Blending an empty style with another style should return the other style"
1327 );
1328
1329 let style_b = style_b.highlight(Default::default());
1330 assert_eq!(
1331 style_b, expected_style,
1332 "Blending a style with an empty style should not change the style."
1333 );
1334
1335 let mut style_c = expected_style;
1336
1337 let style_d = HighlightStyle {
1338 color: Some(blue().alpha(0.7)),
1339 strikethrough: Some(StrikethroughStyle {
1340 thickness: px(4.),
1341 color: Some(crate::red()),
1342 }),
1343 fade_out: Some(0.),
1344 font_style: Some(FontStyle::Oblique),
1345 font_weight: Some(FontWeight(800.)),
1346 background_color: Some(green()),
1347 underline: Some(UnderlineStyle {
1348 thickness: px(4.),
1349 color: None,
1350 wavy: false,
1351 }),
1352 };
1353
1354 let expected_style = HighlightStyle {
1355 color: Some(red().blend(blue().alpha(0.7))),
1356 strikethrough: Some(StrikethroughStyle {
1357 thickness: px(4.),
1358 color: Some(red()),
1359 }),
1360 fade_out: Some(0.),
1362 font_style: Some(FontStyle::Oblique),
1363 font_weight: Some(FontWeight(800.)),
1364 background_color: Some(green()),
1365 underline: Some(UnderlineStyle {
1366 thickness: px(4.),
1367 color: None,
1368 wavy: false,
1369 }),
1370 };
1371
1372 let style_c = style_c.highlight(style_d);
1373 assert_eq!(
1374 style_c, expected_style,
1375 "Blending styles should blend properties where possible and override all others"
1376 );
1377 }
1378
1379 #[perf]
1380 fn test_combine_highlights() {
1381 assert_eq!(
1382 combine_highlights(
1383 [
1384 (0..5, green().into()),
1385 (4..10, FontWeight::BOLD.into()),
1386 (15..20, yellow().into()),
1387 ],
1388 [
1389 (2..6, FontStyle::Italic.into()),
1390 (1..3, blue().into()),
1391 (21..23, red().into()),
1392 ]
1393 )
1394 .collect::<Vec<_>>(),
1395 [
1396 (
1397 0..1,
1398 HighlightStyle {
1399 color: Some(green()),
1400 ..Default::default()
1401 }
1402 ),
1403 (
1404 1..2,
1405 HighlightStyle {
1406 color: Some(blue()),
1407 ..Default::default()
1408 }
1409 ),
1410 (
1411 2..3,
1412 HighlightStyle {
1413 color: Some(blue()),
1414 font_style: Some(FontStyle::Italic),
1415 ..Default::default()
1416 }
1417 ),
1418 (
1419 3..4,
1420 HighlightStyle {
1421 color: Some(green()),
1422 font_style: Some(FontStyle::Italic),
1423 ..Default::default()
1424 }
1425 ),
1426 (
1427 4..5,
1428 HighlightStyle {
1429 color: Some(green()),
1430 font_weight: Some(FontWeight::BOLD),
1431 font_style: Some(FontStyle::Italic),
1432 ..Default::default()
1433 }
1434 ),
1435 (
1436 5..6,
1437 HighlightStyle {
1438 font_weight: Some(FontWeight::BOLD),
1439 font_style: Some(FontStyle::Italic),
1440 ..Default::default()
1441 }
1442 ),
1443 (
1444 6..10,
1445 HighlightStyle {
1446 font_weight: Some(FontWeight::BOLD),
1447 ..Default::default()
1448 }
1449 ),
1450 (
1451 15..20,
1452 HighlightStyle {
1453 color: Some(yellow()),
1454 ..Default::default()
1455 }
1456 ),
1457 (
1458 21..23,
1459 HighlightStyle {
1460 color: Some(red()),
1461 ..Default::default()
1462 }
1463 )
1464 ]
1465 );
1466 }
1467
1468 #[perf]
1469 fn test_text_style_refinement() {
1470 let mut style = Style::default();
1471 style.refine(&StyleRefinement::default().text_size(px(20.0)));
1472 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1473
1474 assert_eq!(
1475 Some(AbsoluteLength::from(px(20.0))),
1476 style.text_style().unwrap().font_size
1477 );
1478
1479 assert_eq!(
1480 Some(FontWeight::SEMIBOLD),
1481 style.text_style().unwrap().font_weight
1482 );
1483 }
1484}