1use std::{iter, mem, ops::Range};
2
3use crate::{
4 black, phi, point, quad, rems, AbsoluteLength, BorrowAppContext, BorrowWindow, Bounds,
5 ContentMask, Corners, CornersRefinement, CursorStyle, DefiniteLength, Edges, EdgesRefinement,
6 Font, FontFeatures, FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba,
7 SharedString, Size, 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 cx.paint_quad(quad(
406 bounds,
407 self.corner_radii.to_pixels(bounds.size, rem_size),
408 Hsla::transparent_black(),
409 self.border_widths.to_pixels(rem_size),
410 self.border_color.unwrap_or_default(),
411 ));
412 });
413 }
414
415 #[cfg(debug_assertions)]
416 if self.debug_below {
417 cx.remove_global::<DebugBelow>();
418 }
419 }
420
421 fn is_border_visible(&self) -> bool {
422 self.border_color
423 .map_or(false, |color| !color.is_transparent())
424 && self.border_widths.any(|length| !length.is_zero())
425 }
426}
427
428impl Default for Style {
429 fn default() -> Self {
430 Style {
431 display: Display::Block,
432 visibility: Visibility::Visible,
433 overflow: Point {
434 x: Overflow::Visible,
435 y: Overflow::Visible,
436 },
437 scrollbar_width: 0.0,
438 position: Position::Relative,
439 inset: Edges::auto(),
440 margin: Edges::<Length>::zero(),
441 padding: Edges::<DefiniteLength>::zero(),
442 border_widths: Edges::<AbsoluteLength>::zero(),
443 size: Size::auto(),
444 min_size: Size::auto(),
445 max_size: Size::auto(),
446 aspect_ratio: None,
447 gap: Size::default(),
448 // Aligment
449 align_items: None,
450 align_self: None,
451 align_content: None,
452 justify_content: None,
453 // Flexbox
454 flex_direction: FlexDirection::Row,
455 flex_wrap: FlexWrap::NoWrap,
456 flex_grow: 0.0,
457 flex_shrink: 1.0,
458 flex_basis: Length::Auto,
459 background: None,
460 border_color: None,
461 corner_radii: Corners::default(),
462 box_shadow: Default::default(),
463 text: TextStyleRefinement::default(),
464 mouse_cursor: None,
465 z_index: None,
466
467 #[cfg(debug_assertions)]
468 debug: false,
469 #[cfg(debug_assertions)]
470 debug_below: false,
471 }
472 }
473}
474
475#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
476#[refineable(Debug)]
477pub struct UnderlineStyle {
478 pub thickness: Pixels,
479 pub color: Option<Hsla>,
480 pub wavy: bool,
481}
482
483#[derive(Clone, Debug)]
484pub enum Fill {
485 Color(Hsla),
486}
487
488impl Fill {
489 pub fn color(&self) -> Option<Hsla> {
490 match self {
491 Fill::Color(color) => Some(*color),
492 }
493 }
494}
495
496impl Default for Fill {
497 fn default() -> Self {
498 Self::Color(Hsla::default())
499 }
500}
501
502impl From<Hsla> for Fill {
503 fn from(color: Hsla) -> Self {
504 Self::Color(color)
505 }
506}
507
508impl From<TextStyle> for HighlightStyle {
509 fn from(other: TextStyle) -> Self {
510 Self::from(&other)
511 }
512}
513
514impl From<&TextStyle> for HighlightStyle {
515 fn from(other: &TextStyle) -> Self {
516 Self {
517 color: Some(other.color),
518 font_weight: Some(other.font_weight),
519 font_style: Some(other.font_style),
520 background_color: other.background_color,
521 underline: other.underline.clone(),
522 fade_out: None,
523 }
524 }
525}
526
527impl HighlightStyle {
528 pub fn highlight(&mut self, other: HighlightStyle) {
529 match (self.color, other.color) {
530 (Some(self_color), Some(other_color)) => {
531 self.color = Some(Hsla::blend(other_color, self_color));
532 }
533 (None, Some(other_color)) => {
534 self.color = Some(other_color);
535 }
536 _ => {}
537 }
538
539 if other.font_weight.is_some() {
540 self.font_weight = other.font_weight;
541 }
542
543 if other.font_style.is_some() {
544 self.font_style = other.font_style;
545 }
546
547 if other.background_color.is_some() {
548 self.background_color = other.background_color;
549 }
550
551 if other.underline.is_some() {
552 self.underline = other.underline;
553 }
554
555 match (other.fade_out, self.fade_out) {
556 (Some(source_fade), None) => self.fade_out = Some(source_fade),
557 (Some(source_fade), Some(dest_fade)) => {
558 self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
559 }
560 _ => {}
561 }
562 }
563}
564
565impl From<Hsla> for HighlightStyle {
566 fn from(color: Hsla) -> Self {
567 Self {
568 color: Some(color),
569 ..Default::default()
570 }
571 }
572}
573
574impl From<FontWeight> for HighlightStyle {
575 fn from(font_weight: FontWeight) -> Self {
576 Self {
577 font_weight: Some(font_weight),
578 ..Default::default()
579 }
580 }
581}
582
583impl From<FontStyle> for HighlightStyle {
584 fn from(font_style: FontStyle) -> Self {
585 Self {
586 font_style: Some(font_style),
587 ..Default::default()
588 }
589 }
590}
591
592impl From<Rgba> for HighlightStyle {
593 fn from(color: Rgba) -> Self {
594 Self {
595 color: Some(color.into()),
596 ..Default::default()
597 }
598 }
599}
600
601pub fn combine_highlights(
602 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
603 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
604) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
605 let mut endpoints = Vec::new();
606 let mut highlights = Vec::new();
607 for (range, highlight) in a.into_iter().chain(b) {
608 if !range.is_empty() {
609 let highlight_id = highlights.len();
610 endpoints.push((range.start, highlight_id, true));
611 endpoints.push((range.end, highlight_id, false));
612 highlights.push(highlight);
613 }
614 }
615 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
616 let mut endpoints = endpoints.into_iter().peekable();
617
618 let mut active_styles = HashSet::default();
619 let mut ix = 0;
620 iter::from_fn(move || {
621 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
622 let prev_index = mem::replace(&mut ix, *endpoint_ix);
623 if ix > prev_index && !active_styles.is_empty() {
624 let mut current_style = HighlightStyle::default();
625 for highlight_id in &active_styles {
626 current_style.highlight(highlights[*highlight_id]);
627 }
628 return Some((prev_index..ix, current_style));
629 }
630
631 if *is_start {
632 active_styles.insert(*highlight_id);
633 } else {
634 active_styles.remove(highlight_id);
635 }
636 endpoints.next();
637 }
638 None
639 })
640}
641
642#[cfg(test)]
643mod tests {
644 use crate::{blue, green, red, yellow};
645
646 use super::*;
647
648 #[test]
649 fn test_combine_highlights() {
650 assert_eq!(
651 combine_highlights(
652 [
653 (0..5, green().into()),
654 (4..10, FontWeight::BOLD.into()),
655 (15..20, yellow().into()),
656 ],
657 [
658 (2..6, FontStyle::Italic.into()),
659 (1..3, blue().into()),
660 (21..23, red().into()),
661 ]
662 )
663 .collect::<Vec<_>>(),
664 [
665 (
666 0..1,
667 HighlightStyle {
668 color: Some(green()),
669 ..Default::default()
670 }
671 ),
672 (
673 1..2,
674 HighlightStyle {
675 color: Some(green()),
676 ..Default::default()
677 }
678 ),
679 (
680 2..3,
681 HighlightStyle {
682 color: Some(green()),
683 font_style: Some(FontStyle::Italic),
684 ..Default::default()
685 }
686 ),
687 (
688 3..4,
689 HighlightStyle {
690 color: Some(green()),
691 font_style: Some(FontStyle::Italic),
692 ..Default::default()
693 }
694 ),
695 (
696 4..5,
697 HighlightStyle {
698 color: Some(green()),
699 font_weight: Some(FontWeight::BOLD),
700 font_style: Some(FontStyle::Italic),
701 ..Default::default()
702 }
703 ),
704 (
705 5..6,
706 HighlightStyle {
707 font_weight: Some(FontWeight::BOLD),
708 font_style: Some(FontStyle::Italic),
709 ..Default::default()
710 }
711 ),
712 (
713 6..10,
714 HighlightStyle {
715 font_weight: Some(FontWeight::BOLD),
716 ..Default::default()
717 }
718 ),
719 (
720 15..20,
721 HighlightStyle {
722 color: Some(yellow()),
723 ..Default::default()
724 }
725 ),
726 (
727 21..23,
728 HighlightStyle {
729 color: Some(red()),
730 ..Default::default()
731 }
732 )
733 ]
734 );
735 }
736}