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(Clone, Refineable, Debug)]
143#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
144pub struct Style {
145 pub display: Display,
147
148 pub visibility: Visibility,
150
151 #[refineable]
154 pub overflow: Point<Overflow>,
155 pub scrollbar_width: AbsoluteLength,
157 pub allow_concurrent_scroll: bool,
159 pub restrict_scroll_to_axis: bool,
181
182 pub position: Position,
185 #[refineable]
187 pub inset: Edges<Length>,
188
189 #[refineable]
192 pub size: Size<Length>,
193 #[refineable]
195 pub min_size: Size<Length>,
196 #[refineable]
198 pub max_size: Size<Length>,
199 pub aspect_ratio: Option<f32>,
201
202 #[refineable]
205 pub margin: Edges<Length>,
206 #[refineable]
208 pub padding: Edges<DefiniteLength>,
209 #[refineable]
211 pub border_widths: Edges<AbsoluteLength>,
212
213 pub align_items: Option<AlignItems>,
216 pub align_self: Option<AlignSelf>,
218 pub align_content: Option<AlignContent>,
220 pub justify_content: Option<JustifyContent>,
222 #[refineable]
224 pub gap: Size<DefiniteLength>,
225
226 pub flex_direction: FlexDirection,
229 pub flex_wrap: FlexWrap,
231 pub flex_basis: Length,
233 pub flex_grow: f32,
235 pub flex_shrink: f32,
237
238 pub background: Option<Fill>,
240
241 pub border_color: Option<Hsla>,
243
244 pub border_style: BorderStyle,
246
247 #[refineable]
249 pub corner_radii: Corners<AbsoluteLength>,
250
251 pub box_shadow: Vec<BoxShadow>,
253
254 #[refineable]
256 pub text: TextStyleRefinement,
257
258 pub mouse_cursor: Option<CursorStyle>,
260
261 pub opacity: Option<f32>,
263
264 pub grid_cols: Option<u16>,
267
268 pub grid_cols_min_content: Option<u16>,
271
272 pub grid_rows: Option<u16>,
275
276 pub grid_location: Option<GridLocation>,
278
279 #[cfg(debug_assertions)]
281 pub debug: bool,
282
283 #[cfg(debug_assertions)]
285 pub debug_below: bool,
286}
287
288impl Styled for StyleRefinement {
289 fn style(&mut self) -> &mut StyleRefinement {
290 self
291 }
292}
293
294impl StyleRefinement {
295 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
297 self.grid_location.get_or_insert_default()
298 }
299}
300
301#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
303pub enum Visibility {
304 #[default]
306 Visible,
307 Hidden,
309}
310
311#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
313pub struct BoxShadow {
314 pub color: Hsla,
316 pub offset: Point<Pixels>,
318 pub blur_radius: Pixels,
320 pub spread_radius: Pixels,
322}
323
324#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
326pub enum WhiteSpace {
327 #[default]
329 Normal,
330 Nowrap,
332}
333
334#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
336pub enum TextOverflow {
337 Truncate(SharedString),
340 TruncateStart(SharedString),
344}
345
346#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
348pub enum TextAlign {
349 #[default]
351 Left,
352
353 Center,
355
356 Right,
358}
359
360#[derive(Refineable, Clone, Debug, PartialEq)]
362#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
363pub struct TextStyle {
364 pub color: Hsla,
366
367 pub font_family: SharedString,
369
370 pub font_features: FontFeatures,
372
373 pub font_fallbacks: Option<FontFallbacks>,
375
376 pub font_size: AbsoluteLength,
378
379 pub line_height: DefiniteLength,
381
382 pub font_weight: FontWeight,
384
385 pub font_style: FontStyle,
387
388 pub background_color: Option<Hsla>,
390
391 pub underline: Option<UnderlineStyle>,
393
394 pub strikethrough: Option<StrikethroughStyle>,
396
397 pub white_space: WhiteSpace,
399
400 pub text_overflow: Option<TextOverflow>,
402
403 pub text_align: TextAlign,
405
406 pub line_clamp: Option<usize>,
408}
409
410impl Default for TextStyle {
411 fn default() -> Self {
412 TextStyle {
413 color: black(),
414 font_family: ".SystemUIFont".into(),
416 font_features: FontFeatures::default(),
417 font_fallbacks: None,
418 font_size: rems(1.).into(),
419 line_height: phi(),
420 font_weight: FontWeight::default(),
421 font_style: FontStyle::default(),
422 background_color: None,
423 underline: None,
424 strikethrough: None,
425 white_space: WhiteSpace::Normal,
426 text_overflow: None,
427 text_align: TextAlign::default(),
428 line_clamp: None,
429 }
430 }
431}
432
433impl TextStyle {
434 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
436 let style = style.into();
437 if let Some(weight) = style.font_weight {
438 self.font_weight = weight;
439 }
440 if let Some(style) = style.font_style {
441 self.font_style = style;
442 }
443
444 if let Some(color) = style.color {
445 self.color = self.color.blend(color);
446 }
447
448 if let Some(factor) = style.fade_out {
449 self.color.fade_out(factor);
450 }
451
452 if let Some(background_color) = style.background_color {
453 self.background_color = Some(background_color);
454 }
455
456 if let Some(underline) = style.underline {
457 self.underline = Some(underline);
458 }
459
460 if let Some(strikethrough) = style.strikethrough {
461 self.strikethrough = Some(strikethrough);
462 }
463
464 self
465 }
466
467 pub fn font(&self) -> Font {
469 Font {
470 family: self.font_family.clone(),
471 features: self.font_features.clone(),
472 fallbacks: self.font_fallbacks.clone(),
473 weight: self.font_weight,
474 style: self.font_style,
475 }
476 }
477
478 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
480 self.line_height.to_pixels(self.font_size, rem_size).round()
481 }
482
483 pub fn to_run(&self, len: usize) -> TextRun {
485 TextRun {
486 len,
487 font: Font {
488 family: self.font_family.clone(),
489 features: self.font_features.clone(),
490 fallbacks: self.font_fallbacks.clone(),
491 weight: self.font_weight,
492 style: self.font_style,
493 },
494 color: self.color,
495 background_color: self.background_color,
496 underline: self.underline,
497 strikethrough: self.strikethrough,
498 }
499 }
500}
501
502#[derive(Copy, Clone, Debug, Default, PartialEq)]
505pub struct HighlightStyle {
506 pub color: Option<Hsla>,
508
509 pub font_weight: Option<FontWeight>,
511
512 pub font_style: Option<FontStyle>,
514
515 pub background_color: Option<Hsla>,
517
518 pub underline: Option<UnderlineStyle>,
520
521 pub strikethrough: Option<StrikethroughStyle>,
523
524 pub fade_out: Option<f32>,
526}
527
528impl Eq for HighlightStyle {}
529
530impl Hash for HighlightStyle {
531 fn hash<H: Hasher>(&self, state: &mut H) {
532 self.color.hash(state);
533 self.font_weight.hash(state);
534 self.font_style.hash(state);
535 self.background_color.hash(state);
536 self.underline.hash(state);
537 self.strikethrough.hash(state);
538 state.write_u32(u32::from_be_bytes(
539 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
540 ));
541 }
542}
543
544impl Style {
545 pub fn has_opaque_background(&self) -> bool {
547 self.background
548 .as_ref()
549 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
550 }
551
552 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
554 if self.text.is_some() {
555 Some(&self.text)
556 } else {
557 None
558 }
559 }
560
561 pub fn overflow_mask(
564 &self,
565 bounds: Bounds<Pixels>,
566 rem_size: Pixels,
567 ) -> Option<ContentMask<Pixels>> {
568 match self.overflow {
569 Point {
570 x: Overflow::Visible,
571 y: Overflow::Visible,
572 } => None,
573 _ => {
574 let mut min = bounds.origin;
575 let mut max = bounds.bottom_right();
576
577 if self
578 .border_color
579 .is_some_and(|color| !color.is_transparent())
580 {
581 min.x += self.border_widths.left.to_pixels(rem_size);
582 max.x -= self.border_widths.right.to_pixels(rem_size);
583 min.y += self.border_widths.top.to_pixels(rem_size);
584 max.y -= self.border_widths.bottom.to_pixels(rem_size);
585 }
586
587 let bounds = match (
588 self.overflow.x == Overflow::Visible,
589 self.overflow.y == Overflow::Visible,
590 ) {
591 (true, true) => return None,
593 (true, false) => Bounds::from_corners(
595 point(min.x, bounds.origin.y),
596 point(max.x, bounds.bottom_right().y),
597 ),
598 (false, true) => Bounds::from_corners(
600 point(bounds.origin.x, min.y),
601 point(bounds.bottom_right().x, max.y),
602 ),
603 (false, false) => Bounds::from_corners(min, max),
605 };
606
607 Some(ContentMask { bounds })
608 }
609 }
610 }
611
612 pub fn paint(
614 &self,
615 bounds: Bounds<Pixels>,
616 window: &mut Window,
617 cx: &mut App,
618 continuation: impl FnOnce(&mut Window, &mut App),
619 ) {
620 #[cfg(debug_assertions)]
621 if self.debug_below {
622 cx.set_global(DebugBelow)
623 }
624
625 #[cfg(debug_assertions)]
626 if self.debug || cx.has_global::<DebugBelow>() {
627 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
628 }
629
630 let rem_size = window.rem_size();
631 let corner_radii = self
632 .corner_radii
633 .to_pixels(rem_size)
634 .clamp_radii_for_quad_size(bounds.size);
635
636 window.paint_shadows(bounds, corner_radii, &self.box_shadow);
637
638 let background_color = self.background.as_ref().and_then(Fill::color);
639 if background_color.is_some_and(|color| !color.is_transparent()) {
640 let mut border_color = match background_color {
641 Some(color) => match color.tag {
642 BackgroundTag::Solid => color.solid,
643 BackgroundTag::LinearGradient => color
644 .colors
645 .first()
646 .map(|stop| stop.color)
647 .unwrap_or_default(),
648 BackgroundTag::PatternSlash => color.solid,
649 },
650 None => Hsla::default(),
651 };
652 border_color.a = 0.;
653 window.paint_quad(quad(
654 bounds,
655 corner_radii,
656 background_color.unwrap_or_default(),
657 Edges::default(),
658 border_color,
659 self.border_style,
660 ));
661 }
662
663 continuation(window, cx);
664
665 if self.is_border_visible() {
666 let border_widths = self.border_widths.to_pixels(rem_size);
667 let max_border_width = border_widths.max();
668 let max_corner_radius = corner_radii.max();
669
670 let top_bounds = Bounds::from_corners(
671 bounds.origin,
672 bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
673 );
674 let bottom_bounds = Bounds::from_corners(
675 bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
676 bounds.bottom_right(),
677 );
678 let left_bounds = Bounds::from_corners(
679 top_bounds.bottom_left(),
680 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
681 );
682 let right_bounds = Bounds::from_corners(
683 top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
684 bottom_bounds.top_right(),
685 );
686
687 let mut background = self.border_color.unwrap_or_default();
688 background.a = 0.;
689 let quad = quad(
690 bounds,
691 corner_radii,
692 background,
693 border_widths,
694 self.border_color.unwrap_or_default(),
695 self.border_style,
696 );
697
698 window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
699 window.paint_quad(quad.clone());
700 });
701 window.with_content_mask(
702 Some(ContentMask {
703 bounds: right_bounds,
704 }),
705 |window| {
706 window.paint_quad(quad.clone());
707 },
708 );
709 window.with_content_mask(
710 Some(ContentMask {
711 bounds: bottom_bounds,
712 }),
713 |window| {
714 window.paint_quad(quad.clone());
715 },
716 );
717 window.with_content_mask(
718 Some(ContentMask {
719 bounds: left_bounds,
720 }),
721 |window| {
722 window.paint_quad(quad);
723 },
724 );
725 }
726
727 #[cfg(debug_assertions)]
728 if self.debug_below {
729 cx.remove_global::<DebugBelow>();
730 }
731 }
732
733 fn is_border_visible(&self) -> bool {
734 self.border_color
735 .is_some_and(|color| !color.is_transparent())
736 && self.border_widths.any(|length| !length.is_zero())
737 }
738}
739
740impl Default for Style {
741 fn default() -> Self {
742 Style {
743 display: Display::Block,
744 visibility: Visibility::Visible,
745 overflow: Point {
746 x: Overflow::Visible,
747 y: Overflow::Visible,
748 },
749 allow_concurrent_scroll: false,
750 restrict_scroll_to_axis: false,
751 scrollbar_width: AbsoluteLength::default(),
752 position: Position::Relative,
753 inset: Edges::auto(),
754 margin: Edges::<Length>::zero(),
755 padding: Edges::<DefiniteLength>::zero(),
756 border_widths: Edges::<AbsoluteLength>::zero(),
757 size: Size::auto(),
758 min_size: Size::auto(),
759 max_size: Size::auto(),
760 aspect_ratio: None,
761 gap: Size::default(),
762 align_items: None,
764 align_self: None,
765 align_content: None,
766 justify_content: None,
767 flex_direction: FlexDirection::Row,
769 flex_wrap: FlexWrap::NoWrap,
770 flex_grow: 0.0,
771 flex_shrink: 1.0,
772 flex_basis: Length::Auto,
773 background: None,
774 border_color: None,
775 border_style: BorderStyle::default(),
776 corner_radii: Corners::default(),
777 box_shadow: Default::default(),
778 text: TextStyleRefinement::default(),
779 mouse_cursor: None,
780 opacity: None,
781 grid_rows: None,
782 grid_cols: None,
783 grid_cols_min_content: None,
784 grid_location: None,
785
786 #[cfg(debug_assertions)]
787 debug: false,
788 #[cfg(debug_assertions)]
789 debug_below: false,
790 }
791 }
792}
793
794#[derive(
796 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
797)]
798pub struct UnderlineStyle {
799 pub thickness: Pixels,
801
802 pub color: Option<Hsla>,
804
805 pub wavy: bool,
807}
808
809#[derive(
811 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
812)]
813pub struct StrikethroughStyle {
814 pub thickness: Pixels,
816
817 pub color: Option<Hsla>,
819}
820
821#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
823pub enum Fill {
824 Color(Background),
826}
827
828impl Fill {
829 pub fn color(&self) -> Option<Background> {
833 match self {
834 Fill::Color(color) => Some(*color),
835 }
836 }
837}
838
839impl Default for Fill {
840 fn default() -> Self {
841 Self::Color(Background::default())
842 }
843}
844
845impl From<Hsla> for Fill {
846 fn from(color: Hsla) -> Self {
847 Self::Color(color.into())
848 }
849}
850
851impl From<Rgba> for Fill {
852 fn from(color: Rgba) -> Self {
853 Self::Color(color.into())
854 }
855}
856
857impl From<Background> for Fill {
858 fn from(background: Background) -> Self {
859 Self::Color(background)
860 }
861}
862
863impl From<TextStyle> for HighlightStyle {
864 fn from(other: TextStyle) -> Self {
865 Self::from(&other)
866 }
867}
868
869impl From<&TextStyle> for HighlightStyle {
870 fn from(other: &TextStyle) -> Self {
871 Self {
872 color: Some(other.color),
873 font_weight: Some(other.font_weight),
874 font_style: Some(other.font_style),
875 background_color: other.background_color,
876 underline: other.underline,
877 strikethrough: other.strikethrough,
878 fade_out: None,
879 }
880 }
881}
882
883impl HighlightStyle {
884 pub fn color(color: Hsla) -> Self {
886 Self {
887 color: Some(color),
888 ..Default::default()
889 }
890 }
891 #[must_use]
894 pub fn highlight(self, other: HighlightStyle) -> Self {
895 Self {
896 color: other
897 .color
898 .map(|other_color| {
899 if let Some(color) = self.color {
900 color.blend(other_color)
901 } else {
902 other_color
903 }
904 })
905 .or(self.color),
906 font_weight: other.font_weight.or(self.font_weight),
907 font_style: other.font_style.or(self.font_style),
908 background_color: other.background_color.or(self.background_color),
909 underline: other.underline.or(self.underline),
910 strikethrough: other.strikethrough.or(self.strikethrough),
911 fade_out: other
912 .fade_out
913 .map(|source_fade| {
914 self.fade_out
915 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
916 .unwrap_or(source_fade)
917 })
918 .or(self.fade_out),
919 }
920 }
921}
922
923impl From<Hsla> for HighlightStyle {
924 fn from(color: Hsla) -> Self {
925 Self {
926 color: Some(color),
927 ..Default::default()
928 }
929 }
930}
931
932impl From<FontWeight> for HighlightStyle {
933 fn from(font_weight: FontWeight) -> Self {
934 Self {
935 font_weight: Some(font_weight),
936 ..Default::default()
937 }
938 }
939}
940
941impl From<FontStyle> for HighlightStyle {
942 fn from(font_style: FontStyle) -> Self {
943 Self {
944 font_style: Some(font_style),
945 ..Default::default()
946 }
947 }
948}
949
950impl From<Rgba> for HighlightStyle {
951 fn from(color: Rgba) -> Self {
952 Self {
953 color: Some(color.into()),
954 ..Default::default()
955 }
956 }
957}
958
959pub fn combine_highlights(
961 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
962 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
963) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
964 let mut endpoints = Vec::new();
965 let mut highlights = Vec::new();
966 for (range, highlight) in a.into_iter().chain(b) {
967 if !range.is_empty() {
968 let highlight_id = highlights.len();
969 endpoints.push((range.start, highlight_id, true));
970 endpoints.push((range.end, highlight_id, false));
971 highlights.push(highlight);
972 }
973 }
974 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
975 let mut endpoints = endpoints.into_iter().peekable();
976
977 let mut active_styles = HashSet::default();
978 let mut ix = 0;
979 iter::from_fn(move || {
980 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
981 let prev_index = mem::replace(&mut ix, *endpoint_ix);
982 if ix > prev_index && !active_styles.is_empty() {
983 let current_style = active_styles
984 .iter()
985 .fold(HighlightStyle::default(), |acc, highlight_id| {
986 acc.highlight(highlights[*highlight_id])
987 });
988 return Some((prev_index..ix, current_style));
989 }
990
991 if *is_start {
992 active_styles.insert(*highlight_id);
993 } else {
994 active_styles.remove(highlight_id);
995 }
996 endpoints.next();
997 }
998 None
999 })
1000}
1001
1002#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1008pub enum AlignItems {
1010 Start,
1012 End,
1014 FlexStart,
1019 FlexEnd,
1024 Center,
1026 Baseline,
1028 Stretch,
1030}
1031pub type JustifyItems = AlignItems;
1037pub type AlignSelf = AlignItems;
1044pub type JustifySelf = AlignItems;
1051
1052#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1058pub enum AlignContent {
1060 Start,
1062 End,
1064 FlexStart,
1069 FlexEnd,
1074 Center,
1076 Stretch,
1078 SpaceBetween,
1081 SpaceEvenly,
1084 SpaceAround,
1087}
1088
1089pub type JustifyContent = AlignContent;
1095
1096#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1100pub enum Display {
1102 Block,
1104 #[default]
1106 Flex,
1107 Grid,
1109 None,
1111}
1112
1113#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1119pub enum FlexWrap {
1121 #[default]
1123 NoWrap,
1124 Wrap,
1126 WrapReverse,
1128}
1129
1130#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1142pub enum FlexDirection {
1144 #[default]
1148 Row,
1149 Column,
1153 RowReverse,
1157 ColumnReverse,
1161}
1162
1163#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1177pub enum Overflow {
1179 #[default]
1182 Visible,
1183 Clip,
1186 Hidden,
1189 Scroll,
1193}
1194
1195#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1205pub enum Position {
1207 #[default]
1210 Relative,
1211 Absolute,
1217}
1218
1219impl From<AlignItems> for taffy::style::AlignItems {
1220 fn from(value: AlignItems) -> Self {
1221 match value {
1222 AlignItems::Start => Self::Start,
1223 AlignItems::End => Self::End,
1224 AlignItems::FlexStart => Self::FlexStart,
1225 AlignItems::FlexEnd => Self::FlexEnd,
1226 AlignItems::Center => Self::Center,
1227 AlignItems::Baseline => Self::Baseline,
1228 AlignItems::Stretch => Self::Stretch,
1229 }
1230 }
1231}
1232
1233impl From<AlignContent> for taffy::style::AlignContent {
1234 fn from(value: AlignContent) -> Self {
1235 match value {
1236 AlignContent::Start => Self::Start,
1237 AlignContent::End => Self::End,
1238 AlignContent::FlexStart => Self::FlexStart,
1239 AlignContent::FlexEnd => Self::FlexEnd,
1240 AlignContent::Center => Self::Center,
1241 AlignContent::Stretch => Self::Stretch,
1242 AlignContent::SpaceBetween => Self::SpaceBetween,
1243 AlignContent::SpaceEvenly => Self::SpaceEvenly,
1244 AlignContent::SpaceAround => Self::SpaceAround,
1245 }
1246 }
1247}
1248
1249impl From<Display> for taffy::style::Display {
1250 fn from(value: Display) -> Self {
1251 match value {
1252 Display::Block => Self::Block,
1253 Display::Flex => Self::Flex,
1254 Display::Grid => Self::Grid,
1255 Display::None => Self::None,
1256 }
1257 }
1258}
1259
1260impl From<FlexWrap> for taffy::style::FlexWrap {
1261 fn from(value: FlexWrap) -> Self {
1262 match value {
1263 FlexWrap::NoWrap => Self::NoWrap,
1264 FlexWrap::Wrap => Self::Wrap,
1265 FlexWrap::WrapReverse => Self::WrapReverse,
1266 }
1267 }
1268}
1269
1270impl From<FlexDirection> for taffy::style::FlexDirection {
1271 fn from(value: FlexDirection) -> Self {
1272 match value {
1273 FlexDirection::Row => Self::Row,
1274 FlexDirection::Column => Self::Column,
1275 FlexDirection::RowReverse => Self::RowReverse,
1276 FlexDirection::ColumnReverse => Self::ColumnReverse,
1277 }
1278 }
1279}
1280
1281impl From<Overflow> for taffy::style::Overflow {
1282 fn from(value: Overflow) -> Self {
1283 match value {
1284 Overflow::Visible => Self::Visible,
1285 Overflow::Clip => Self::Clip,
1286 Overflow::Hidden => Self::Hidden,
1287 Overflow::Scroll => Self::Scroll,
1288 }
1289 }
1290}
1291
1292impl From<Position> for taffy::style::Position {
1293 fn from(value: Position) -> Self {
1294 match value {
1295 Position::Relative => Self::Relative,
1296 Position::Absolute => Self::Absolute,
1297 }
1298 }
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303 use crate::{blue, green, px, red, yellow};
1304
1305 use super::*;
1306
1307 use util_macros::perf;
1308
1309 #[perf]
1310 fn test_basic_highlight_style_combination() {
1311 let style_a = HighlightStyle::default();
1312 let style_b = HighlightStyle::default();
1313 let style_a = style_a.highlight(style_b);
1314 assert_eq!(
1315 style_a,
1316 HighlightStyle::default(),
1317 "Combining empty styles should not produce a non-empty style."
1318 );
1319
1320 let mut style_b = HighlightStyle {
1321 color: Some(red()),
1322 strikethrough: Some(StrikethroughStyle {
1323 thickness: px(2.),
1324 color: Some(blue()),
1325 }),
1326 fade_out: Some(0.),
1327 font_style: Some(FontStyle::Italic),
1328 font_weight: Some(FontWeight(300.)),
1329 background_color: Some(yellow()),
1330 underline: Some(UnderlineStyle {
1331 thickness: px(2.),
1332 color: Some(red()),
1333 wavy: true,
1334 }),
1335 };
1336 let expected_style = style_b;
1337
1338 let style_a = style_a.highlight(style_b);
1339 assert_eq!(
1340 style_a, expected_style,
1341 "Blending an empty style with another style should return the other style"
1342 );
1343
1344 let style_b = style_b.highlight(Default::default());
1345 assert_eq!(
1346 style_b, expected_style,
1347 "Blending a style with an empty style should not change the style."
1348 );
1349
1350 let mut style_c = expected_style;
1351
1352 let style_d = HighlightStyle {
1353 color: Some(blue().alpha(0.7)),
1354 strikethrough: Some(StrikethroughStyle {
1355 thickness: px(4.),
1356 color: Some(crate::red()),
1357 }),
1358 fade_out: Some(0.),
1359 font_style: Some(FontStyle::Oblique),
1360 font_weight: Some(FontWeight(800.)),
1361 background_color: Some(green()),
1362 underline: Some(UnderlineStyle {
1363 thickness: px(4.),
1364 color: None,
1365 wavy: false,
1366 }),
1367 };
1368
1369 let expected_style = HighlightStyle {
1370 color: Some(red().blend(blue().alpha(0.7))),
1371 strikethrough: Some(StrikethroughStyle {
1372 thickness: px(4.),
1373 color: Some(red()),
1374 }),
1375 fade_out: Some(0.),
1377 font_style: Some(FontStyle::Oblique),
1378 font_weight: Some(FontWeight(800.)),
1379 background_color: Some(green()),
1380 underline: Some(UnderlineStyle {
1381 thickness: px(4.),
1382 color: None,
1383 wavy: false,
1384 }),
1385 };
1386
1387 let style_c = style_c.highlight(style_d);
1388 assert_eq!(
1389 style_c, expected_style,
1390 "Blending styles should blend properties where possible and override all others"
1391 );
1392 }
1393
1394 #[perf]
1395 fn test_combine_highlights() {
1396 assert_eq!(
1397 combine_highlights(
1398 [
1399 (0..5, green().into()),
1400 (4..10, FontWeight::BOLD.into()),
1401 (15..20, yellow().into()),
1402 ],
1403 [
1404 (2..6, FontStyle::Italic.into()),
1405 (1..3, blue().into()),
1406 (21..23, red().into()),
1407 ]
1408 )
1409 .collect::<Vec<_>>(),
1410 [
1411 (
1412 0..1,
1413 HighlightStyle {
1414 color: Some(green()),
1415 ..Default::default()
1416 }
1417 ),
1418 (
1419 1..2,
1420 HighlightStyle {
1421 color: Some(blue()),
1422 ..Default::default()
1423 }
1424 ),
1425 (
1426 2..3,
1427 HighlightStyle {
1428 color: Some(blue()),
1429 font_style: Some(FontStyle::Italic),
1430 ..Default::default()
1431 }
1432 ),
1433 (
1434 3..4,
1435 HighlightStyle {
1436 color: Some(green()),
1437 font_style: Some(FontStyle::Italic),
1438 ..Default::default()
1439 }
1440 ),
1441 (
1442 4..5,
1443 HighlightStyle {
1444 color: Some(green()),
1445 font_weight: Some(FontWeight::BOLD),
1446 font_style: Some(FontStyle::Italic),
1447 ..Default::default()
1448 }
1449 ),
1450 (
1451 5..6,
1452 HighlightStyle {
1453 font_weight: Some(FontWeight::BOLD),
1454 font_style: Some(FontStyle::Italic),
1455 ..Default::default()
1456 }
1457 ),
1458 (
1459 6..10,
1460 HighlightStyle {
1461 font_weight: Some(FontWeight::BOLD),
1462 ..Default::default()
1463 }
1464 ),
1465 (
1466 15..20,
1467 HighlightStyle {
1468 color: Some(yellow()),
1469 ..Default::default()
1470 }
1471 ),
1472 (
1473 21..23,
1474 HighlightStyle {
1475 color: Some(red()),
1476 ..Default::default()
1477 }
1478 )
1479 ]
1480 );
1481 }
1482
1483 #[perf]
1484 fn test_text_style_refinement() {
1485 let mut style = Style::default();
1486 style.refine(&StyleRefinement::default().text_size(px(20.0)));
1487 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1488
1489 assert_eq!(
1490 Some(AbsoluteLength::from(px(20.0))),
1491 style.text_style().unwrap().font_size
1492 );
1493
1494 assert_eq!(
1495 Some(FontWeight::SEMIBOLD),
1496 style.text_style().unwrap().font_weight
1497 );
1498 }
1499}