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 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
212 self.line_height.to_pixels(self.font_size, rem_size)
213 }
214
215 pub fn to_run(&self, len: usize) -> TextRun {
216 TextRun {
217 len,
218 font: Font {
219 family: self.font_family.clone(),
220 features: Default::default(),
221 weight: self.font_weight,
222 style: self.font_style,
223 },
224 color: self.color,
225 background_color: self.background_color,
226 underline: self.underline.clone(),
227 }
228 }
229}
230
231#[derive(Copy, Clone, Debug, Default, PartialEq)]
232pub struct HighlightStyle {
233 pub color: Option<Hsla>,
234 pub font_weight: Option<FontWeight>,
235 pub font_style: Option<FontStyle>,
236 pub background_color: Option<Hsla>,
237 pub underline: Option<UnderlineStyle>,
238 pub fade_out: Option<f32>,
239}
240
241impl Eq for HighlightStyle {}
242
243impl Style {
244 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
245 if self.text.is_some() {
246 Some(&self.text)
247 } else {
248 None
249 }
250 }
251
252 pub fn overflow_mask(&self, bounds: Bounds<Pixels>) -> Option<ContentMask<Pixels>> {
253 match self.overflow {
254 Point {
255 x: Overflow::Visible,
256 y: Overflow::Visible,
257 } => None,
258 _ => {
259 let current_mask = bounds;
260 let min = current_mask.origin;
261 let max = current_mask.lower_right();
262 let bounds = match (
263 self.overflow.x == Overflow::Visible,
264 self.overflow.y == Overflow::Visible,
265 ) {
266 // x and y both visible
267 (true, true) => return None,
268 // x visible, y hidden
269 (true, false) => Bounds::from_corners(
270 point(min.x, bounds.origin.y),
271 point(max.x, bounds.lower_right().y),
272 ),
273 // x hidden, y visible
274 (false, true) => Bounds::from_corners(
275 point(bounds.origin.x, min.y),
276 point(bounds.lower_right().x, max.y),
277 ),
278 // both hidden
279 (false, false) => bounds,
280 };
281 Some(ContentMask { bounds })
282 }
283 }
284 }
285
286 pub fn apply_text_style<C, F, R>(&self, cx: &mut C, f: F) -> R
287 where
288 C: BorrowAppContext,
289 F: FnOnce(&mut C) -> R,
290 {
291 if self.text.is_some() {
292 cx.with_text_style(Some(self.text.clone()), f)
293 } else {
294 f(cx)
295 }
296 }
297
298 /// Apply overflow to content mask
299 pub fn apply_overflow<C, F, R>(&self, bounds: Bounds<Pixels>, cx: &mut C, f: F) -> R
300 where
301 C: BorrowWindow,
302 F: FnOnce(&mut C) -> R,
303 {
304 let current_mask = cx.content_mask();
305
306 let min = current_mask.bounds.origin;
307 let max = current_mask.bounds.lower_right();
308
309 let mask_bounds = match (
310 self.overflow.x == Overflow::Visible,
311 self.overflow.y == Overflow::Visible,
312 ) {
313 // x and y both visible
314 (true, true) => return f(cx),
315 // x visible, y hidden
316 (true, false) => Bounds::from_corners(
317 point(min.x, bounds.origin.y),
318 point(max.x, bounds.lower_right().y),
319 ),
320 // x hidden, y visible
321 (false, true) => Bounds::from_corners(
322 point(bounds.origin.x, min.y),
323 point(bounds.lower_right().x, max.y),
324 ),
325 // both hidden
326 (false, false) => bounds,
327 };
328 let mask = ContentMask {
329 bounds: mask_bounds,
330 };
331
332 cx.with_content_mask(Some(mask), f)
333 }
334
335 /// Paints the background of an element styled with this style.
336 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
337 let rem_size = cx.rem_size();
338
339 cx.with_z_index(0, |cx| {
340 cx.paint_shadows(
341 bounds,
342 self.corner_radii.to_pixels(bounds.size, rem_size),
343 &self.box_shadow,
344 );
345 });
346
347 let background_color = self.background.as_ref().and_then(Fill::color);
348 if background_color.is_some() || self.is_border_visible() {
349 cx.with_z_index(1, |cx| {
350 cx.paint_quad(
351 bounds,
352 self.corner_radii.to_pixels(bounds.size, rem_size),
353 background_color.unwrap_or_default(),
354 self.border_widths.to_pixels(rem_size),
355 self.border_color.unwrap_or_default(),
356 );
357 });
358 }
359 }
360
361 fn is_border_visible(&self) -> bool {
362 self.border_color
363 .map_or(false, |color| !color.is_transparent())
364 && self.border_widths.any(|length| !length.is_zero())
365 }
366}
367
368impl Default for Style {
369 fn default() -> Self {
370 Style {
371 display: Display::Block,
372 visibility: Visibility::Visible,
373 overflow: Point {
374 x: Overflow::Visible,
375 y: Overflow::Visible,
376 },
377 scrollbar_width: 0.0,
378 position: Position::Relative,
379 inset: Edges::auto(),
380 margin: Edges::<Length>::zero(),
381 padding: Edges::<DefiniteLength>::zero(),
382 border_widths: Edges::<AbsoluteLength>::zero(),
383 size: Size::auto(),
384 min_size: Size::auto(),
385 max_size: Size::auto(),
386 aspect_ratio: None,
387 gap: Size::zero(),
388 // Aligment
389 align_items: None,
390 align_self: None,
391 align_content: None,
392 justify_content: None,
393 // Flexbox
394 flex_direction: FlexDirection::Row,
395 flex_wrap: FlexWrap::NoWrap,
396 flex_grow: 0.0,
397 flex_shrink: 1.0,
398 flex_basis: Length::Auto,
399 background: None,
400 border_color: None,
401 corner_radii: Corners::default(),
402 box_shadow: Default::default(),
403 text: TextStyleRefinement::default(),
404 mouse_cursor: None,
405 z_index: None,
406 }
407 }
408}
409
410#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
411#[refineable(Debug)]
412pub struct UnderlineStyle {
413 pub thickness: Pixels,
414 pub color: Option<Hsla>,
415 pub wavy: bool,
416}
417
418#[derive(Clone, Debug)]
419pub enum Fill {
420 Color(Hsla),
421}
422
423impl Fill {
424 pub fn color(&self) -> Option<Hsla> {
425 match self {
426 Fill::Color(color) => Some(*color),
427 }
428 }
429}
430
431impl Default for Fill {
432 fn default() -> Self {
433 Self::Color(Hsla::default())
434 }
435}
436
437impl From<Hsla> for Fill {
438 fn from(color: Hsla) -> Self {
439 Self::Color(color)
440 }
441}
442
443impl From<TextStyle> for HighlightStyle {
444 fn from(other: TextStyle) -> Self {
445 Self::from(&other)
446 }
447}
448
449impl From<&TextStyle> for HighlightStyle {
450 fn from(other: &TextStyle) -> Self {
451 Self {
452 color: Some(other.color),
453 font_weight: Some(other.font_weight),
454 font_style: Some(other.font_style),
455 background_color: other.background_color,
456 underline: other.underline.clone(),
457 fade_out: None,
458 }
459 }
460}
461
462impl HighlightStyle {
463 pub fn highlight(&mut self, other: HighlightStyle) {
464 match (self.color, other.color) {
465 (Some(self_color), Some(other_color)) => {
466 self.color = Some(Hsla::blend(other_color, self_color));
467 }
468 (None, Some(other_color)) => {
469 self.color = Some(other_color);
470 }
471 _ => {}
472 }
473
474 if other.font_weight.is_some() {
475 self.font_weight = other.font_weight;
476 }
477
478 if other.font_style.is_some() {
479 self.font_style = other.font_style;
480 }
481
482 if other.background_color.is_some() {
483 self.background_color = other.background_color;
484 }
485
486 if other.underline.is_some() {
487 self.underline = other.underline;
488 }
489
490 match (other.fade_out, self.fade_out) {
491 (Some(source_fade), None) => self.fade_out = Some(source_fade),
492 (Some(source_fade), Some(dest_fade)) => {
493 self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
494 }
495 _ => {}
496 }
497 }
498}
499
500impl From<Hsla> for HighlightStyle {
501 fn from(color: Hsla) -> Self {
502 Self {
503 color: Some(color),
504 ..Default::default()
505 }
506 }
507}
508
509impl From<FontWeight> for HighlightStyle {
510 fn from(font_weight: FontWeight) -> Self {
511 Self {
512 font_weight: Some(font_weight),
513 ..Default::default()
514 }
515 }
516}
517
518impl From<FontStyle> for HighlightStyle {
519 fn from(font_style: FontStyle) -> Self {
520 Self {
521 font_style: Some(font_style),
522 ..Default::default()
523 }
524 }
525}
526
527impl From<Rgba> for HighlightStyle {
528 fn from(color: Rgba) -> Self {
529 Self {
530 color: Some(color.into()),
531 ..Default::default()
532 }
533 }
534}
535
536pub fn combine_highlights(
537 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
538 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
539) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
540 let mut endpoints = Vec::new();
541 let mut highlights = Vec::new();
542 for (range, highlight) in a.into_iter().chain(b) {
543 if !range.is_empty() {
544 let highlight_id = highlights.len();
545 endpoints.push((range.start, highlight_id, true));
546 endpoints.push((range.end, highlight_id, false));
547 highlights.push(highlight);
548 }
549 }
550 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
551 let mut endpoints = endpoints.into_iter().peekable();
552
553 let mut active_styles = HashSet::default();
554 let mut ix = 0;
555 iter::from_fn(move || {
556 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
557 let prev_index = mem::replace(&mut ix, *endpoint_ix);
558 if ix > prev_index && !active_styles.is_empty() {
559 let mut current_style = HighlightStyle::default();
560 for highlight_id in &active_styles {
561 current_style.highlight(highlights[*highlight_id]);
562 }
563 return Some((prev_index..ix, current_style));
564 }
565
566 if *is_start {
567 active_styles.insert(*highlight_id);
568 } else {
569 active_styles.remove(highlight_id);
570 }
571 endpoints.next();
572 }
573 None
574 })
575}
576
577#[cfg(test)]
578mod tests {
579 use crate::{blue, green, red, yellow};
580
581 use super::*;
582
583 #[test]
584 fn test_combine_highlights() {
585 assert_eq!(
586 combine_highlights(
587 [
588 (0..5, green().into()),
589 (4..10, FontWeight::BOLD.into()),
590 (15..20, yellow().into()),
591 ],
592 [
593 (2..6, FontStyle::Italic.into()),
594 (1..3, blue().into()),
595 (21..23, red().into()),
596 ]
597 )
598 .collect::<Vec<_>>(),
599 [
600 (
601 0..1,
602 HighlightStyle {
603 color: Some(green()),
604 ..Default::default()
605 }
606 ),
607 (
608 1..2,
609 HighlightStyle {
610 color: Some(blue()),
611 ..Default::default()
612 }
613 ),
614 (
615 2..3,
616 HighlightStyle {
617 color: Some(blue()),
618 font_style: Some(FontStyle::Italic),
619 ..Default::default()
620 }
621 ),
622 (
623 3..4,
624 HighlightStyle {
625 color: Some(green()),
626 font_style: Some(FontStyle::Italic),
627 ..Default::default()
628 }
629 ),
630 (
631 4..5,
632 HighlightStyle {
633 color: Some(green()),
634 font_weight: Some(FontWeight::BOLD),
635 font_style: Some(FontStyle::Italic),
636 ..Default::default()
637 }
638 ),
639 (
640 5..6,
641 HighlightStyle {
642 font_weight: Some(FontWeight::BOLD),
643 font_style: Some(FontStyle::Italic),
644 ..Default::default()
645 }
646 ),
647 (
648 6..10,
649 HighlightStyle {
650 font_weight: Some(FontWeight::BOLD),
651 ..Default::default()
652 }
653 ),
654 (
655 15..20,
656 HighlightStyle {
657 color: Some(yellow()),
658 ..Default::default()
659 }
660 ),
661 (
662 21..23,
663 HighlightStyle {
664 color: Some(red()),
665 ..Default::default()
666 }
667 )
668 ]
669 );
670 }
671}