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