1use std::{iter, mem, ops::Range};
2
3use crate::{
4 black, phi, point, quad, rems, AbsoluteLength, BorrowWindow, Bounds, ContentMask, Corners,
5 CornersRefinement, CursorStyle, DefiniteLength, Edges, EdgesRefinement, Font, FontFeatures,
6 FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba, SharedString, Size,
7 SizeRefinement, Styled, TextRun, WindowContext,
8};
9use collections::HashSet;
10use refineable::{Cascade, Refineable};
11use smallvec::SmallVec;
12pub use taffy::style::{
13 AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
14 Overflow, Position,
15};
16
17#[cfg(debug_assertions)]
18pub struct DebugBelow;
19
20pub type StyleCascade = Cascade<Style>;
21
22#[derive(Clone, Refineable, Debug)]
23#[refineable(Debug)]
24pub struct Style {
25 /// What layout strategy should be used?
26 pub display: Display,
27
28 /// Should the element be painted on screen?
29 pub visibility: Visibility,
30
31 // Overflow properties
32 /// How children overflowing their container should affect layout
33 #[refineable]
34 pub overflow: Point<Overflow>,
35 /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
36 pub scrollbar_width: f32,
37
38 // Position properties
39 /// What should the `position` value of this struct use as a base offset?
40 pub position: Position,
41 /// How should the position of this element be tweaked relative to the layout defined?
42 #[refineable]
43 pub inset: Edges<Length>,
44
45 // Size properies
46 /// Sets the initial size of the item
47 #[refineable]
48 pub size: Size<Length>,
49 /// Controls the minimum size of the item
50 #[refineable]
51 pub min_size: Size<Length>,
52 /// Controls the maximum size of the item
53 #[refineable]
54 pub max_size: Size<Length>,
55 /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
56 pub aspect_ratio: Option<f32>,
57
58 // Spacing Properties
59 /// How large should the margin be on each side?
60 #[refineable]
61 pub margin: Edges<Length>,
62 /// How large should the padding be on each side?
63 #[refineable]
64 pub padding: Edges<DefiniteLength>,
65 /// How large should the border be on each side?
66 #[refineable]
67 pub border_widths: Edges<AbsoluteLength>,
68
69 // Alignment properties
70 /// How this node's children aligned in the cross/block axis?
71 pub align_items: Option<AlignItems>,
72 /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
73 pub align_self: Option<AlignSelf>,
74 /// How should content contained within this item be aligned in the cross/block axis
75 pub align_content: Option<AlignContent>,
76 /// How should contained within this item be aligned in the main/inline axis
77 pub justify_content: Option<JustifyContent>,
78 /// How large should the gaps between items in a flex container be?
79 #[refineable]
80 pub gap: Size<DefiniteLength>,
81
82 // Flexbox properies
83 /// Which direction does the main axis flow in?
84 pub flex_direction: FlexDirection,
85 /// Should elements wrap, or stay in a single line?
86 pub flex_wrap: FlexWrap,
87 /// Sets the initial main axis size of the item
88 pub flex_basis: Length,
89 /// The relative rate at which this item grows when it is expanding to fill space, 0.0 is the default value, and this value must be positive.
90 pub flex_grow: f32,
91 /// The relative rate at which this item shrinks when it is contracting to fit into space, 1.0 is the default value, and this value must be positive.
92 pub flex_shrink: f32,
93
94 /// The fill color of this element
95 pub background: Option<Fill>,
96
97 /// The border color of this element
98 pub border_color: Option<Hsla>,
99
100 /// The radius of the corners of this element
101 #[refineable]
102 pub corner_radii: Corners<AbsoluteLength>,
103
104 /// Box Shadow of the element
105 pub box_shadow: SmallVec<[BoxShadow; 2]>,
106
107 /// TEXT
108 pub text: TextStyleRefinement,
109
110 /// The mouse cursor style shown when the mouse pointer is over an element.
111 pub mouse_cursor: Option<CursorStyle>,
112
113 pub z_index: Option<u8>,
114
115 #[cfg(debug_assertions)]
116 pub debug: bool,
117 #[cfg(debug_assertions)]
118 pub debug_below: bool,
119}
120
121impl Styled for StyleRefinement {
122 fn style(&mut self) -> &mut StyleRefinement {
123 self
124 }
125}
126
127#[derive(Default, Clone, Copy, Debug, Eq, PartialEq)]
128pub enum Visibility {
129 #[default]
130 Visible,
131 Hidden,
132}
133
134#[derive(Clone, Debug)]
135pub struct BoxShadow {
136 pub color: Hsla,
137 pub offset: Point<Pixels>,
138 pub blur_radius: Pixels,
139 pub spread_radius: Pixels,
140}
141
142#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
143pub enum WhiteSpace {
144 #[default]
145 Normal,
146 Nowrap,
147}
148
149#[derive(Refineable, Clone, Debug)]
150#[refineable(Debug)]
151pub struct TextStyle {
152 pub color: Hsla,
153 pub font_family: SharedString,
154 pub font_features: FontFeatures,
155 pub font_size: AbsoluteLength,
156 pub line_height: DefiniteLength,
157 pub font_weight: FontWeight,
158 pub font_style: FontStyle,
159 pub background_color: Option<Hsla>,
160 pub underline: Option<UnderlineStyle>,
161 pub white_space: WhiteSpace,
162}
163
164impl Default for TextStyle {
165 fn default() -> Self {
166 TextStyle {
167 color: black(),
168 font_family: "Helvetica".into(), // todo!("Get a font we know exists on the system")
169 font_features: FontFeatures::default(),
170 font_size: rems(1.).into(),
171 line_height: phi(),
172 font_weight: FontWeight::default(),
173 font_style: FontStyle::default(),
174 background_color: None,
175 underline: None,
176 white_space: WhiteSpace::Normal,
177 }
178 }
179}
180
181impl TextStyle {
182 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
183 let style = style.into();
184 if let Some(weight) = style.font_weight {
185 self.font_weight = weight;
186 }
187 if let Some(style) = style.font_style {
188 self.font_style = style;
189 }
190
191 if let Some(color) = style.color {
192 self.color = self.color.blend(color);
193 }
194
195 if let Some(factor) = style.fade_out {
196 self.color.fade_out(factor);
197 }
198
199 if let Some(background_color) = style.background_color {
200 self.background_color = Some(background_color);
201 }
202
203 if let Some(underline) = style.underline {
204 self.underline = Some(underline);
205 }
206
207 self
208 }
209
210 pub fn font(&self) -> Font {
211 Font {
212 family: self.font_family.clone(),
213 features: self.font_features.clone(),
214 weight: self.font_weight,
215 style: self.font_style,
216 }
217 }
218
219 /// Returns the rounded line height in pixels.
220 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
221 self.line_height.to_pixels(self.font_size, rem_size).round()
222 }
223
224 pub fn to_run(&self, len: usize) -> TextRun {
225 TextRun {
226 len,
227 font: Font {
228 family: self.font_family.clone(),
229 features: Default::default(),
230 weight: self.font_weight,
231 style: self.font_style,
232 },
233 color: self.color,
234 background_color: self.background_color,
235 underline: self.underline.clone(),
236 }
237 }
238}
239
240#[derive(Copy, Clone, Debug, Default, PartialEq)]
241pub struct HighlightStyle {
242 pub color: Option<Hsla>,
243 pub font_weight: Option<FontWeight>,
244 pub font_style: Option<FontStyle>,
245 pub background_color: Option<Hsla>,
246 pub underline: Option<UnderlineStyle>,
247 pub fade_out: Option<f32>,
248}
249
250impl Eq for HighlightStyle {}
251
252impl Style {
253 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
254 if self.text.is_some() {
255 Some(&self.text)
256 } else {
257 None
258 }
259 }
260
261 pub fn overflow_mask(
262 &self,
263 bounds: Bounds<Pixels>,
264 rem_size: Pixels,
265 ) -> Option<ContentMask<Pixels>> {
266 match self.overflow {
267 Point {
268 x: Overflow::Visible,
269 y: Overflow::Visible,
270 } => None,
271 _ => {
272 let mut min = bounds.origin;
273 let mut max = bounds.lower_right();
274
275 if self
276 .border_color
277 .map_or(false, |color| !color.is_transparent())
278 {
279 min.x += self.border_widths.left.to_pixels(rem_size);
280 max.x -= self.border_widths.right.to_pixels(rem_size);
281 min.y += self.border_widths.top.to_pixels(rem_size);
282 max.y -= self.border_widths.bottom.to_pixels(rem_size);
283 }
284
285 let bounds = match (
286 self.overflow.x == Overflow::Visible,
287 self.overflow.y == Overflow::Visible,
288 ) {
289 // x and y both visible
290 (true, true) => return None,
291 // x visible, y hidden
292 (true, false) => Bounds::from_corners(
293 point(min.x, bounds.origin.y),
294 point(max.x, bounds.lower_right().y),
295 ),
296 // x hidden, y visible
297 (false, true) => Bounds::from_corners(
298 point(bounds.origin.x, min.y),
299 point(bounds.lower_right().x, max.y),
300 ),
301 // both hidden
302 (false, false) => Bounds::from_corners(min, max),
303 };
304
305 Some(ContentMask { bounds })
306 }
307 }
308 }
309
310 // pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
311 // where
312 // C: BorrowAppContext,
313 // F: FnOnce(&mut C) -> R,
314 // {
315 // if self.text.is_some() {
316 // cx.with_text_style(Some(self.text.clone()), f)
317 // } else {
318 // f(cx)
319 // }
320 // }
321
322 // /// Apply overflow to content mask
323 // pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
324 // where
325 // C: BorrowWindow,
326 // F: FnOnce(&mut C) -> R,
327 // {
328 // let current_mask = cx.content_mask();
329
330 // let min = current_mask.bounds.origin;
331 // let max = current_mask.bounds.lower_right();
332
333 // let mask_bounds = match (
334 // self.overflow.x == Overflow::Visible,
335 // self.overflow.y == Overflow::Visible,
336 // ) {
337 // // x and y both visible
338 // (true, true) => return f(cx),
339 // // x visible, y hidden
340 // (true, false) => Bounds::from_corners(
341 // point(min.x, bounds.origin.y),
342 // point(max.x, bounds.lower_right().y),
343 // ),
344 // // x hidden, y visible
345 // (false, true) => Bounds::from_corners(
346 // point(bounds.origin.x, min.y),
347 // point(bounds.lower_right().x, max.y),
348 // ),
349 // // both hidden
350 // (false, false) => bounds,
351 // };
352 // let mask = ContentMask {
353 // bounds: mask_bounds,
354 // };
355
356 // cx.with_content_mask(Some(mask), f)
357 // }
358
359 /// Paints the background of an element styled with this style.
360 pub fn paint(
361 &self,
362 bounds: Bounds<Pixels>,
363 cx: &mut WindowContext,
364 continuation: impl FnOnce(&mut WindowContext),
365 ) {
366 #[cfg(debug_assertions)]
367 if self.debug_below {
368 cx.set_global(DebugBelow)
369 }
370
371 #[cfg(debug_assertions)]
372 if self.debug || cx.has_global::<DebugBelow>() {
373 cx.paint_quad(crate::outline(bounds, crate::red()));
374 }
375
376 let rem_size = cx.rem_size();
377
378 cx.with_z_index(0, |cx| {
379 cx.paint_shadows(
380 bounds,
381 self.corner_radii.to_pixels(bounds.size, rem_size),
382 &self.box_shadow,
383 );
384 });
385
386 let background_color = self.background.as_ref().and_then(Fill::color);
387 if background_color.is_some() {
388 cx.with_z_index(1, |cx| {
389 cx.paint_quad(quad(
390 bounds,
391 self.corner_radii.to_pixels(bounds.size, rem_size),
392 background_color.unwrap_or_default(),
393 Edges::default(),
394 Hsla::transparent_black(),
395 ));
396 });
397 }
398
399 cx.with_z_index(2, |cx| {
400 continuation(cx);
401 });
402
403 if self.is_border_visible() {
404 cx.with_z_index(3, |cx| {
405 let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
406 let border_widths = self.border_widths.to_pixels(rem_size);
407 let max_border_width = border_widths.max();
408 let max_corner_radius = corner_radii.max();
409
410 let top_bounds = Bounds::from_corners(
411 bounds.origin,
412 bounds.upper_right()
413 + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
414 );
415 let bottom_bounds = Bounds::from_corners(
416 bounds.lower_left()
417 - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
418 bounds.lower_right(),
419 );
420 let left_bounds = Bounds::from_corners(
421 top_bounds.lower_left(),
422 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
423 );
424 let right_bounds = Bounds::from_corners(
425 top_bounds.lower_right() - point(max_border_width, Pixels::ZERO),
426 bottom_bounds.upper_right(),
427 );
428
429 let quad = quad(
430 bounds,
431 corner_radii,
432 Hsla::transparent_black(),
433 border_widths,
434 self.border_color.unwrap_or_default(),
435 );
436
437 cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
438 cx.paint_quad(quad.clone());
439 });
440 cx.with_content_mask(
441 Some(ContentMask {
442 bounds: right_bounds,
443 }),
444 |cx| {
445 cx.paint_quad(quad.clone());
446 },
447 );
448 cx.with_content_mask(
449 Some(ContentMask {
450 bounds: bottom_bounds,
451 }),
452 |cx| {
453 cx.paint_quad(quad.clone());
454 },
455 );
456 cx.with_content_mask(
457 Some(ContentMask {
458 bounds: left_bounds,
459 }),
460 |cx| {
461 cx.paint_quad(quad);
462 },
463 );
464 });
465 }
466
467 #[cfg(debug_assertions)]
468 if self.debug_below {
469 cx.remove_global::<DebugBelow>();
470 }
471 }
472
473 fn is_border_visible(&self) -> bool {
474 self.border_color
475 .map_or(false, |color| !color.is_transparent())
476 && self.border_widths.any(|length| !length.is_zero())
477 }
478}
479
480impl Default for Style {
481 fn default() -> Self {
482 Style {
483 display: Display::Block,
484 visibility: Visibility::Visible,
485 overflow: Point {
486 x: Overflow::Visible,
487 y: Overflow::Visible,
488 },
489 scrollbar_width: 0.0,
490 position: Position::Relative,
491 inset: Edges::auto(),
492 margin: Edges::<Length>::zero(),
493 padding: Edges::<DefiniteLength>::zero(),
494 border_widths: Edges::<AbsoluteLength>::zero(),
495 size: Size::auto(),
496 min_size: Size::auto(),
497 max_size: Size::auto(),
498 aspect_ratio: None,
499 gap: Size::default(),
500 // Aligment
501 align_items: None,
502 align_self: None,
503 align_content: None,
504 justify_content: None,
505 // Flexbox
506 flex_direction: FlexDirection::Row,
507 flex_wrap: FlexWrap::NoWrap,
508 flex_grow: 0.0,
509 flex_shrink: 1.0,
510 flex_basis: Length::Auto,
511 background: None,
512 border_color: None,
513 corner_radii: Corners::default(),
514 box_shadow: Default::default(),
515 text: TextStyleRefinement::default(),
516 mouse_cursor: None,
517 z_index: None,
518
519 #[cfg(debug_assertions)]
520 debug: false,
521 #[cfg(debug_assertions)]
522 debug_below: false,
523 }
524 }
525}
526
527#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
528#[refineable(Debug)]
529pub struct UnderlineStyle {
530 pub thickness: Pixels,
531 pub color: Option<Hsla>,
532 pub wavy: bool,
533}
534
535#[derive(Clone, Debug)]
536pub enum Fill {
537 Color(Hsla),
538}
539
540impl Fill {
541 pub fn color(&self) -> Option<Hsla> {
542 match self {
543 Fill::Color(color) => Some(*color),
544 }
545 }
546}
547
548impl Default for Fill {
549 fn default() -> Self {
550 Self::Color(Hsla::default())
551 }
552}
553
554impl From<Hsla> for Fill {
555 fn from(color: Hsla) -> Self {
556 Self::Color(color)
557 }
558}
559
560impl From<TextStyle> for HighlightStyle {
561 fn from(other: TextStyle) -> Self {
562 Self::from(&other)
563 }
564}
565
566impl From<&TextStyle> for HighlightStyle {
567 fn from(other: &TextStyle) -> Self {
568 Self {
569 color: Some(other.color),
570 font_weight: Some(other.font_weight),
571 font_style: Some(other.font_style),
572 background_color: other.background_color,
573 underline: other.underline.clone(),
574 fade_out: None,
575 }
576 }
577}
578
579impl HighlightStyle {
580 pub fn highlight(&mut self, other: HighlightStyle) {
581 match (self.color, other.color) {
582 (Some(self_color), Some(other_color)) => {
583 self.color = Some(Hsla::blend(other_color, self_color));
584 }
585 (None, Some(other_color)) => {
586 self.color = Some(other_color);
587 }
588 _ => {}
589 }
590
591 if other.font_weight.is_some() {
592 self.font_weight = other.font_weight;
593 }
594
595 if other.font_style.is_some() {
596 self.font_style = other.font_style;
597 }
598
599 if other.background_color.is_some() {
600 self.background_color = other.background_color;
601 }
602
603 if other.underline.is_some() {
604 self.underline = other.underline;
605 }
606
607 match (other.fade_out, self.fade_out) {
608 (Some(source_fade), None) => self.fade_out = Some(source_fade),
609 (Some(source_fade), Some(dest_fade)) => {
610 self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
611 }
612 _ => {}
613 }
614 }
615}
616
617impl From<Hsla> for HighlightStyle {
618 fn from(color: Hsla) -> Self {
619 Self {
620 color: Some(color),
621 ..Default::default()
622 }
623 }
624}
625
626impl From<FontWeight> for HighlightStyle {
627 fn from(font_weight: FontWeight) -> Self {
628 Self {
629 font_weight: Some(font_weight),
630 ..Default::default()
631 }
632 }
633}
634
635impl From<FontStyle> for HighlightStyle {
636 fn from(font_style: FontStyle) -> Self {
637 Self {
638 font_style: Some(font_style),
639 ..Default::default()
640 }
641 }
642}
643
644impl From<Rgba> for HighlightStyle {
645 fn from(color: Rgba) -> Self {
646 Self {
647 color: Some(color.into()),
648 ..Default::default()
649 }
650 }
651}
652
653pub fn combine_highlights(
654 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
655 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
656) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
657 let mut endpoints = Vec::new();
658 let mut highlights = Vec::new();
659 for (range, highlight) in a.into_iter().chain(b) {
660 if !range.is_empty() {
661 let highlight_id = highlights.len();
662 endpoints.push((range.start, highlight_id, true));
663 endpoints.push((range.end, highlight_id, false));
664 highlights.push(highlight);
665 }
666 }
667 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
668 let mut endpoints = endpoints.into_iter().peekable();
669
670 let mut active_styles = HashSet::default();
671 let mut ix = 0;
672 iter::from_fn(move || {
673 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
674 let prev_index = mem::replace(&mut ix, *endpoint_ix);
675 if ix > prev_index && !active_styles.is_empty() {
676 let mut current_style = HighlightStyle::default();
677 for highlight_id in &active_styles {
678 current_style.highlight(highlights[*highlight_id]);
679 }
680 return Some((prev_index..ix, current_style));
681 }
682
683 if *is_start {
684 active_styles.insert(*highlight_id);
685 } else {
686 active_styles.remove(highlight_id);
687 }
688 endpoints.next();
689 }
690 None
691 })
692}
693
694#[cfg(test)]
695mod tests {
696 use crate::{blue, green, red, yellow};
697
698 use super::*;
699
700 #[test]
701 fn test_combine_highlights() {
702 assert_eq!(
703 combine_highlights(
704 [
705 (0..5, green().into()),
706 (4..10, FontWeight::BOLD.into()),
707 (15..20, yellow().into()),
708 ],
709 [
710 (2..6, FontStyle::Italic.into()),
711 (1..3, blue().into()),
712 (21..23, red().into()),
713 ]
714 )
715 .collect::<Vec<_>>(),
716 [
717 (
718 0..1,
719 HighlightStyle {
720 color: Some(green()),
721 ..Default::default()
722 }
723 ),
724 (
725 1..2,
726 HighlightStyle {
727 color: Some(green()),
728 ..Default::default()
729 }
730 ),
731 (
732 2..3,
733 HighlightStyle {
734 color: Some(green()),
735 font_style: Some(FontStyle::Italic),
736 ..Default::default()
737 }
738 ),
739 (
740 3..4,
741 HighlightStyle {
742 color: Some(green()),
743 font_style: Some(FontStyle::Italic),
744 ..Default::default()
745 }
746 ),
747 (
748 4..5,
749 HighlightStyle {
750 color: Some(green()),
751 font_weight: Some(FontWeight::BOLD),
752 font_style: Some(FontStyle::Italic),
753 ..Default::default()
754 }
755 ),
756 (
757 5..6,
758 HighlightStyle {
759 font_weight: Some(FontWeight::BOLD),
760 font_style: Some(FontStyle::Italic),
761 ..Default::default()
762 }
763 ),
764 (
765 6..10,
766 HighlightStyle {
767 font_weight: Some(FontWeight::BOLD),
768 ..Default::default()
769 }
770 ),
771 (
772 15..20,
773 HighlightStyle {
774 color: Some(yellow()),
775 ..Default::default()
776 }
777 ),
778 (
779 21..23,
780 HighlightStyle {
781 color: Some(red()),
782 ..Default::default()
783 }
784 )
785 ]
786 );
787 }
788}