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/// Use this struct for interfacing with the 'debug_below' styling from your own elements.
20/// If a parent element has this style set on it, then this struct will be set as a global in
21/// GPUI.
22#[cfg(debug_assertions)]
23pub struct DebugBelow;
24
25#[cfg(debug_assertions)]
26impl crate::Global for DebugBelow {}
27
28/// How to fit the image into the bounds of the element.
29pub enum ObjectFit {
30 /// The image will be stretched to fill the bounds of the element.
31 Fill,
32 /// The image will be scaled to fit within the bounds of the element.
33 Contain,
34 /// The image will be scaled to cover the bounds of the element.
35 Cover,
36 /// The image will be scaled down to fit within the bounds of the element.
37 ScaleDown,
38 /// The image will maintain its original size.
39 None,
40}
41
42impl ObjectFit {
43 /// Get the bounds of the image within the given bounds.
44 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 // Check if the image is larger than the bounds in either dimension.
78 if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
79 // If the image is larger, use the same logic as Contain to scale it down.
80 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 // If the image is smaller than or equal to the container, display it at its original size,
101 // centered within the container.
102 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/// The CSS styling that can be applied to an element via the `Styled` trait
142#[derive(Clone, Refineable, Debug)]
143#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
144pub struct Style {
145 /// What layout strategy should be used?
146 pub display: Display,
147
148 /// Should the element be painted on screen?
149 pub visibility: Visibility,
150
151 // Overflow properties
152 /// How children overflowing their container should affect layout
153 #[refineable]
154 pub overflow: Point<Overflow>,
155 /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
156 pub scrollbar_width: AbsoluteLength,
157 /// Whether both x and y axis should be scrollable at the same time.
158 pub allow_concurrent_scroll: bool,
159 /// Whether scrolling should be restricted to the axis indicated by the mouse wheel.
160 ///
161 /// This means that:
162 /// - The mouse wheel alone will only ever scroll the Y axis.
163 /// - Holding `Shift` and using the mouse wheel will scroll the X axis.
164 ///
165 /// ## Motivation
166 ///
167 /// On the web when scrolling with the mouse wheel, scrolling up and down will always scroll the Y axis, even when
168 /// the mouse is over a horizontally-scrollable element.
169 ///
170 /// The only way to scroll horizontally is to hold down `Shift` while scrolling, which then changes the scroll axis
171 /// to the X axis.
172 ///
173 /// Currently, GPUI operates differently from the web in that it will scroll an element in either the X or Y axis
174 /// when scrolling with just the mouse wheel. This causes problems when scrolling in a vertical list that contains
175 /// horizontally-scrollable elements, as when you get to the horizontally-scrollable elements the scroll will be
176 /// hijacked.
177 ///
178 /// Ideally we would match the web's behavior and not have a need for this, but right now we're adding this opt-in
179 /// style property to limit the potential blast radius.
180 pub restrict_scroll_to_axis: bool,
181
182 // Position properties
183 /// What should the `position` value of this struct use as a base offset?
184 pub position: Position,
185 /// How should the position of this element be tweaked relative to the layout defined?
186 #[refineable]
187 pub inset: Edges<Length>,
188
189 // Size properties
190 /// Sets the initial size of the item
191 #[refineable]
192 pub size: Size<Length>,
193 /// Controls the minimum size of the item
194 #[refineable]
195 pub min_size: Size<Length>,
196 /// Controls the maximum size of the item
197 #[refineable]
198 pub max_size: Size<Length>,
199 /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
200 pub aspect_ratio: Option<f32>,
201
202 // Spacing Properties
203 /// How large should the margin be on each side?
204 #[refineable]
205 pub margin: Edges<Length>,
206 /// How large should the padding be on each side?
207 #[refineable]
208 pub padding: Edges<DefiniteLength>,
209 /// How large should the border be on each side?
210 #[refineable]
211 pub border_widths: Edges<AbsoluteLength>,
212
213 // Alignment properties
214 /// How this node's children aligned in the cross/block axis?
215 pub align_items: Option<AlignItems>,
216 /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
217 pub align_self: Option<AlignSelf>,
218 /// How should content contained within this item be aligned in the cross/block axis
219 pub align_content: Option<AlignContent>,
220 /// How should contained within this item be aligned in the main/inline axis
221 pub justify_content: Option<JustifyContent>,
222 /// How large should the gaps between items in a flex container be?
223 #[refineable]
224 pub gap: Size<DefiniteLength>,
225
226 // Flexbox properties
227 /// Which direction does the main axis flow in?
228 pub flex_direction: FlexDirection,
229 /// Should elements wrap, or stay in a single line?
230 pub flex_wrap: FlexWrap,
231 /// Sets the initial main axis size of the item
232 pub flex_basis: Length,
233 /// 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.
234 pub flex_grow: f32,
235 /// 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.
236 pub flex_shrink: f32,
237
238 /// The fill color of this element
239 pub background: Option<Fill>,
240
241 /// The border color of this element
242 pub border_color: Option<Hsla>,
243
244 /// The border style of this element
245 pub border_style: BorderStyle,
246
247 /// The radius of the corners of this element
248 #[refineable]
249 pub corner_radii: Corners<AbsoluteLength>,
250
251 /// Box shadow of the element
252 pub box_shadow: Vec<BoxShadow>,
253
254 /// The text style of this element
255 #[refineable]
256 pub text: TextStyleRefinement,
257
258 /// The mouse cursor style shown when the mouse pointer is over an element.
259 pub mouse_cursor: Option<CursorStyle>,
260
261 /// The opacity of this element
262 pub opacity: Option<f32>,
263
264 /// The grid columns of this element
265 /// Equivalent to the Tailwind `grid-cols-<number>`
266 pub grid_cols: Option<u16>,
267
268 /// The row span of this element
269 /// Equivalent to the Tailwind `grid-rows-<number>`
270 pub grid_rows: Option<u16>,
271
272 /// The grid location of this element
273 pub grid_location: Option<GridLocation>,
274
275 /// Whether to draw a red debugging outline around this element
276 #[cfg(debug_assertions)]
277 pub debug: bool,
278
279 /// Whether to draw a red debugging outline around this element and all of its conforming children
280 #[cfg(debug_assertions)]
281 pub debug_below: bool,
282}
283
284impl Styled for StyleRefinement {
285 fn style(&mut self) -> &mut StyleRefinement {
286 self
287 }
288}
289
290impl StyleRefinement {
291 /// The grid location of this element
292 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
293 self.grid_location.get_or_insert_default()
294 }
295}
296
297/// The value of the visibility property, similar to the CSS property `visibility`
298#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
299pub enum Visibility {
300 /// The element should be drawn as normal.
301 #[default]
302 Visible,
303 /// The element should not be drawn, but should still take up space in the layout.
304 Hidden,
305}
306
307/// The possible values of the box-shadow property
308#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
309pub struct BoxShadow {
310 /// What color should the shadow have?
311 pub color: Hsla,
312 /// How should it be offset from its element?
313 pub offset: Point<Pixels>,
314 /// How much should the shadow be blurred?
315 pub blur_radius: Pixels,
316 /// How much should the shadow spread?
317 pub spread_radius: Pixels,
318}
319
320/// How to handle whitespace in text
321#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
322pub enum WhiteSpace {
323 /// Normal line wrapping when text overflows the width of the element
324 #[default]
325 Normal,
326 /// No line wrapping, text will overflow the width of the element
327 Nowrap,
328}
329
330/// How to truncate text that overflows the width of the element
331#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
332pub enum TextOverflow {
333 /// Truncate the text when it doesn't fit, and represent this truncation by displaying the
334 /// provided string.
335 Truncate(SharedString),
336}
337
338/// How to align text within the element
339#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
340pub enum TextAlign {
341 /// Align the text to the left of the element
342 #[default]
343 Left,
344
345 /// Center the text within the element
346 Center,
347
348 /// Align the text to the right of the element
349 Right,
350}
351
352/// The properties that can be used to style text in GPUI
353#[derive(Refineable, Clone, Debug, PartialEq)]
354#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
355pub struct TextStyle {
356 /// The color of the text
357 pub color: Hsla,
358
359 /// The font family to use
360 pub font_family: SharedString,
361
362 /// The font features to use
363 pub font_features: FontFeatures,
364
365 /// The fallback fonts to use
366 pub font_fallbacks: Option<FontFallbacks>,
367
368 /// The font size to use, in pixels or rems.
369 pub font_size: AbsoluteLength,
370
371 /// The line height to use, in pixels or fractions
372 pub line_height: DefiniteLength,
373
374 /// The font weight, e.g. bold
375 pub font_weight: FontWeight,
376
377 /// The font style, e.g. italic
378 pub font_style: FontStyle,
379
380 /// The background color of the text
381 pub background_color: Option<Hsla>,
382
383 /// The underline style of the text
384 pub underline: Option<UnderlineStyle>,
385
386 /// The strikethrough style of the text
387 pub strikethrough: Option<StrikethroughStyle>,
388
389 /// How to handle whitespace in the text
390 pub white_space: WhiteSpace,
391
392 /// The text should be truncated if it overflows the width of the element
393 pub text_overflow: Option<TextOverflow>,
394
395 /// How the text should be aligned within the element
396 pub text_align: TextAlign,
397
398 /// The number of lines to display before truncating the text
399 pub line_clamp: Option<usize>,
400}
401
402impl Default for TextStyle {
403 fn default() -> Self {
404 TextStyle {
405 color: black(),
406 // todo(linux) make this configurable or choose better default
407 font_family: ".SystemUIFont".into(),
408 font_features: FontFeatures::default(),
409 font_fallbacks: None,
410 font_size: rems(1.).into(),
411 line_height: phi(),
412 font_weight: FontWeight::default(),
413 font_style: FontStyle::default(),
414 background_color: None,
415 underline: None,
416 strikethrough: None,
417 white_space: WhiteSpace::Normal,
418 text_overflow: None,
419 text_align: TextAlign::default(),
420 line_clamp: None,
421 }
422 }
423}
424
425impl TextStyle {
426 /// Create a new text style with the given highlighting applied.
427 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
428 let style = style.into();
429 if let Some(weight) = style.font_weight {
430 self.font_weight = weight;
431 }
432 if let Some(style) = style.font_style {
433 self.font_style = style;
434 }
435
436 if let Some(color) = style.color {
437 self.color = self.color.blend(color);
438 }
439
440 if let Some(factor) = style.fade_out {
441 self.color.fade_out(factor);
442 }
443
444 if let Some(background_color) = style.background_color {
445 self.background_color = Some(background_color);
446 }
447
448 if let Some(underline) = style.underline {
449 self.underline = Some(underline);
450 }
451
452 if let Some(strikethrough) = style.strikethrough {
453 self.strikethrough = Some(strikethrough);
454 }
455
456 self
457 }
458
459 /// Get the font configured for this text style.
460 pub fn font(&self) -> Font {
461 Font {
462 family: self.font_family.clone(),
463 features: self.font_features.clone(),
464 fallbacks: self.font_fallbacks.clone(),
465 weight: self.font_weight,
466 style: self.font_style,
467 }
468 }
469
470 /// Returns the rounded line height in pixels.
471 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
472 self.line_height.to_pixels(self.font_size, rem_size).round()
473 }
474
475 /// Convert this text style into a [`TextRun`], for the given length of the text.
476 pub fn to_run(&self, len: usize) -> TextRun {
477 TextRun {
478 len,
479 font: Font {
480 family: self.font_family.clone(),
481 features: self.font_features.clone(),
482 fallbacks: self.font_fallbacks.clone(),
483 weight: self.font_weight,
484 style: self.font_style,
485 },
486 color: self.color,
487 background_color: self.background_color,
488 underline: self.underline,
489 strikethrough: self.strikethrough,
490 }
491 }
492}
493
494/// A highlight style to apply, similar to a `TextStyle` except
495/// for a single font, uniformly sized and spaced text.
496#[derive(Copy, Clone, Debug, Default, PartialEq)]
497pub struct HighlightStyle {
498 /// The color of the text
499 pub color: Option<Hsla>,
500
501 /// The font weight, e.g. bold
502 pub font_weight: Option<FontWeight>,
503
504 /// The font style, e.g. italic
505 pub font_style: Option<FontStyle>,
506
507 /// The background color of the text
508 pub background_color: Option<Hsla>,
509
510 /// The underline style of the text
511 pub underline: Option<UnderlineStyle>,
512
513 /// The underline style of the text
514 pub strikethrough: Option<StrikethroughStyle>,
515
516 /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
517 pub fade_out: Option<f32>,
518}
519
520impl Eq for HighlightStyle {}
521
522impl Hash for HighlightStyle {
523 fn hash<H: Hasher>(&self, state: &mut H) {
524 self.color.hash(state);
525 self.font_weight.hash(state);
526 self.font_style.hash(state);
527 self.background_color.hash(state);
528 self.underline.hash(state);
529 self.strikethrough.hash(state);
530 state.write_u32(u32::from_be_bytes(
531 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
532 ));
533 }
534}
535
536impl Style {
537 /// Returns true if the style is visible and the background is opaque.
538 pub fn has_opaque_background(&self) -> bool {
539 self.background
540 .as_ref()
541 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
542 }
543
544 /// Get the text style in this element style.
545 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
546 if self.text.is_some() {
547 Some(&self.text)
548 } else {
549 None
550 }
551 }
552
553 /// Get the content mask for this element style, based on the given bounds.
554 /// If the element does not hide its overflow, this will return `None`.
555 pub fn overflow_mask(
556 &self,
557 bounds: Bounds<Pixels>,
558 rem_size: Pixels,
559 ) -> Option<ContentMask<Pixels>> {
560 match self.overflow {
561 Point {
562 x: Overflow::Visible,
563 y: Overflow::Visible,
564 } => None,
565 _ => {
566 let mut min = bounds.origin;
567 let mut max = bounds.bottom_right();
568
569 if self
570 .border_color
571 .is_some_and(|color| !color.is_transparent())
572 {
573 min.x += self.border_widths.left.to_pixels(rem_size);
574 max.x -= self.border_widths.right.to_pixels(rem_size);
575 min.y += self.border_widths.top.to_pixels(rem_size);
576 max.y -= self.border_widths.bottom.to_pixels(rem_size);
577 }
578
579 let bounds = match (
580 self.overflow.x == Overflow::Visible,
581 self.overflow.y == Overflow::Visible,
582 ) {
583 // x and y both visible
584 (true, true) => return None,
585 // x visible, y hidden
586 (true, false) => Bounds::from_corners(
587 point(min.x, bounds.origin.y),
588 point(max.x, bounds.bottom_right().y),
589 ),
590 // x hidden, y visible
591 (false, true) => Bounds::from_corners(
592 point(bounds.origin.x, min.y),
593 point(bounds.bottom_right().x, max.y),
594 ),
595 // both hidden
596 (false, false) => Bounds::from_corners(min, max),
597 };
598
599 Some(ContentMask { bounds })
600 }
601 }
602 }
603
604 /// Paints the background of an element styled with this style.
605 pub fn paint(
606 &self,
607 bounds: Bounds<Pixels>,
608 window: &mut Window,
609 cx: &mut App,
610 continuation: impl FnOnce(&mut Window, &mut App),
611 ) {
612 #[cfg(debug_assertions)]
613 if self.debug_below {
614 cx.set_global(DebugBelow)
615 }
616
617 #[cfg(debug_assertions)]
618 if self.debug || cx.has_global::<DebugBelow>() {
619 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
620 }
621
622 let rem_size = window.rem_size();
623 let corner_radii = self
624 .corner_radii
625 .to_pixels(rem_size)
626 .clamp_radii_for_quad_size(bounds.size);
627
628 window.paint_shadows(bounds, corner_radii, &self.box_shadow);
629
630 let background_color = self.background.as_ref().and_then(Fill::color);
631 if background_color.is_some_and(|color| !color.is_transparent()) {
632 let mut border_color = match background_color {
633 Some(color) => match color.tag {
634 BackgroundTag::Solid => color.solid,
635 BackgroundTag::LinearGradient => color
636 .colors
637 .first()
638 .map(|stop| stop.color)
639 .unwrap_or_default(),
640 BackgroundTag::PatternSlash => color.solid,
641 },
642 None => Hsla::default(),
643 };
644 border_color.a = 0.;
645 window.paint_quad(quad(
646 bounds,
647 corner_radii,
648 background_color.unwrap_or_default(),
649 Edges::default(),
650 border_color,
651 self.border_style,
652 ));
653 }
654
655 continuation(window, cx);
656
657 if self.is_border_visible() {
658 let border_widths = self.border_widths.to_pixels(rem_size);
659 let max_border_width = border_widths.max();
660 let max_corner_radius = corner_radii.max();
661
662 let top_bounds = Bounds::from_corners(
663 bounds.origin,
664 bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
665 );
666 let bottom_bounds = Bounds::from_corners(
667 bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
668 bounds.bottom_right(),
669 );
670 let left_bounds = Bounds::from_corners(
671 top_bounds.bottom_left(),
672 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
673 );
674 let right_bounds = Bounds::from_corners(
675 top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
676 bottom_bounds.top_right(),
677 );
678
679 let mut background = self.border_color.unwrap_or_default();
680 background.a = 0.;
681 let quad = quad(
682 bounds,
683 corner_radii,
684 background,
685 border_widths,
686 self.border_color.unwrap_or_default(),
687 self.border_style,
688 );
689
690 window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
691 window.paint_quad(quad.clone());
692 });
693 window.with_content_mask(
694 Some(ContentMask {
695 bounds: right_bounds,
696 }),
697 |window| {
698 window.paint_quad(quad.clone());
699 },
700 );
701 window.with_content_mask(
702 Some(ContentMask {
703 bounds: bottom_bounds,
704 }),
705 |window| {
706 window.paint_quad(quad.clone());
707 },
708 );
709 window.with_content_mask(
710 Some(ContentMask {
711 bounds: left_bounds,
712 }),
713 |window| {
714 window.paint_quad(quad);
715 },
716 );
717 }
718
719 #[cfg(debug_assertions)]
720 if self.debug_below {
721 cx.remove_global::<DebugBelow>();
722 }
723 }
724
725 fn is_border_visible(&self) -> bool {
726 self.border_color
727 .is_some_and(|color| !color.is_transparent())
728 && self.border_widths.any(|length| !length.is_zero())
729 }
730}
731
732impl Default for Style {
733 fn default() -> Self {
734 Style {
735 display: Display::Block,
736 visibility: Visibility::Visible,
737 overflow: Point {
738 x: Overflow::Visible,
739 y: Overflow::Visible,
740 },
741 allow_concurrent_scroll: false,
742 restrict_scroll_to_axis: false,
743 scrollbar_width: AbsoluteLength::default(),
744 position: Position::Relative,
745 inset: Edges::auto(),
746 margin: Edges::<Length>::zero(),
747 padding: Edges::<DefiniteLength>::zero(),
748 border_widths: Edges::<AbsoluteLength>::zero(),
749 size: Size::auto(),
750 min_size: Size::auto(),
751 max_size: Size::auto(),
752 aspect_ratio: None,
753 gap: Size::default(),
754 // Alignment
755 align_items: None,
756 align_self: None,
757 align_content: None,
758 justify_content: None,
759 // Flexbox
760 flex_direction: FlexDirection::Row,
761 flex_wrap: FlexWrap::NoWrap,
762 flex_grow: 0.0,
763 flex_shrink: 1.0,
764 flex_basis: Length::Auto,
765 background: None,
766 border_color: None,
767 border_style: BorderStyle::default(),
768 corner_radii: Corners::default(),
769 box_shadow: Default::default(),
770 text: TextStyleRefinement::default(),
771 mouse_cursor: None,
772 opacity: None,
773 grid_rows: None,
774 grid_cols: None,
775 grid_location: None,
776
777 #[cfg(debug_assertions)]
778 debug: false,
779 #[cfg(debug_assertions)]
780 debug_below: false,
781 }
782 }
783}
784
785/// The properties that can be applied to an underline.
786#[derive(
787 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
788)]
789pub struct UnderlineStyle {
790 /// The thickness of the underline.
791 pub thickness: Pixels,
792
793 /// The color of the underline.
794 pub color: Option<Hsla>,
795
796 /// Whether the underline should be wavy, like in a spell checker.
797 pub wavy: bool,
798}
799
800/// The properties that can be applied to a strikethrough.
801#[derive(
802 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
803)]
804pub struct StrikethroughStyle {
805 /// The thickness of the strikethrough.
806 pub thickness: Pixels,
807
808 /// The color of the strikethrough.
809 pub color: Option<Hsla>,
810}
811
812/// The kinds of fill that can be applied to a shape.
813#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
814pub enum Fill {
815 /// A solid color fill.
816 Color(Background),
817}
818
819impl Fill {
820 /// Unwrap this fill into a solid color, if it is one.
821 ///
822 /// If the fill is not a solid color, this method returns `None`.
823 pub fn color(&self) -> Option<Background> {
824 match self {
825 Fill::Color(color) => Some(*color),
826 }
827 }
828}
829
830impl Default for Fill {
831 fn default() -> Self {
832 Self::Color(Background::default())
833 }
834}
835
836impl From<Hsla> for Fill {
837 fn from(color: Hsla) -> Self {
838 Self::Color(color.into())
839 }
840}
841
842impl From<Rgba> for Fill {
843 fn from(color: Rgba) -> Self {
844 Self::Color(color.into())
845 }
846}
847
848impl From<Background> for Fill {
849 fn from(background: Background) -> Self {
850 Self::Color(background)
851 }
852}
853
854impl From<TextStyle> for HighlightStyle {
855 fn from(other: TextStyle) -> Self {
856 Self::from(&other)
857 }
858}
859
860impl From<&TextStyle> for HighlightStyle {
861 fn from(other: &TextStyle) -> Self {
862 Self {
863 color: Some(other.color),
864 font_weight: Some(other.font_weight),
865 font_style: Some(other.font_style),
866 background_color: other.background_color,
867 underline: other.underline,
868 strikethrough: other.strikethrough,
869 fade_out: None,
870 }
871 }
872}
873
874impl HighlightStyle {
875 /// Create a highlight style with just a color
876 pub fn color(color: Hsla) -> Self {
877 Self {
878 color: Some(color),
879 ..Default::default()
880 }
881 }
882 /// Blend this highlight style with another.
883 /// Non-continuous properties, like font_weight and font_style, are overwritten.
884 #[must_use]
885 pub fn highlight(self, other: HighlightStyle) -> Self {
886 Self {
887 color: other
888 .color
889 .map(|other_color| {
890 if let Some(color) = self.color {
891 color.blend(other_color)
892 } else {
893 other_color
894 }
895 })
896 .or(self.color),
897 font_weight: other.font_weight.or(self.font_weight),
898 font_style: other.font_style.or(self.font_style),
899 background_color: other.background_color.or(self.background_color),
900 underline: other.underline.or(self.underline),
901 strikethrough: other.strikethrough.or(self.strikethrough),
902 fade_out: other
903 .fade_out
904 .map(|source_fade| {
905 self.fade_out
906 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
907 .unwrap_or(source_fade)
908 })
909 .or(self.fade_out),
910 }
911 }
912}
913
914impl From<Hsla> for HighlightStyle {
915 fn from(color: Hsla) -> Self {
916 Self {
917 color: Some(color),
918 ..Default::default()
919 }
920 }
921}
922
923impl From<FontWeight> for HighlightStyle {
924 fn from(font_weight: FontWeight) -> Self {
925 Self {
926 font_weight: Some(font_weight),
927 ..Default::default()
928 }
929 }
930}
931
932impl From<FontStyle> for HighlightStyle {
933 fn from(font_style: FontStyle) -> Self {
934 Self {
935 font_style: Some(font_style),
936 ..Default::default()
937 }
938 }
939}
940
941impl From<Rgba> for HighlightStyle {
942 fn from(color: Rgba) -> Self {
943 Self {
944 color: Some(color.into()),
945 ..Default::default()
946 }
947 }
948}
949
950/// Combine and merge the highlights and ranges in the two iterators.
951pub fn combine_highlights(
952 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
953 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
954) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
955 let mut endpoints = Vec::new();
956 let mut highlights = Vec::new();
957 for (range, highlight) in a.into_iter().chain(b) {
958 if !range.is_empty() {
959 let highlight_id = highlights.len();
960 endpoints.push((range.start, highlight_id, true));
961 endpoints.push((range.end, highlight_id, false));
962 highlights.push(highlight);
963 }
964 }
965 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
966 let mut endpoints = endpoints.into_iter().peekable();
967
968 let mut active_styles = HashSet::default();
969 let mut ix = 0;
970 iter::from_fn(move || {
971 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
972 let prev_index = mem::replace(&mut ix, *endpoint_ix);
973 if ix > prev_index && !active_styles.is_empty() {
974 let current_style = active_styles
975 .iter()
976 .fold(HighlightStyle::default(), |acc, highlight_id| {
977 acc.highlight(highlights[*highlight_id])
978 });
979 return Some((prev_index..ix, current_style));
980 }
981
982 if *is_start {
983 active_styles.insert(*highlight_id);
984 } else {
985 active_styles.remove(highlight_id);
986 }
987 endpoints.next();
988 }
989 None
990 })
991}
992
993/// Used to control how child nodes are aligned.
994/// For Flexbox it controls alignment in the cross axis
995/// For Grid it controls alignment in the block axis
996///
997/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
998#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
999// Copy of taffy::style type of the same name, to derive JsonSchema.
1000pub enum AlignItems {
1001 /// Items are packed toward the start of the axis
1002 Start,
1003 /// Items are packed toward the end of the axis
1004 End,
1005 /// Items are packed towards the flex-relative start of the axis.
1006 ///
1007 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1008 /// to End. In all other cases it is equivalent to Start.
1009 FlexStart,
1010 /// Items are packed towards the flex-relative end of the axis.
1011 ///
1012 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1013 /// to Start. In all other cases it is equivalent to End.
1014 FlexEnd,
1015 /// Items are packed along the center of the cross axis
1016 Center,
1017 /// Items are aligned such as their baselines align
1018 Baseline,
1019 /// Stretch to fill the container
1020 Stretch,
1021}
1022/// Used to control how child nodes are aligned.
1023/// Does not apply to Flexbox, and will be ignored if specified on a flex container
1024/// For Grid it controls alignment in the inline axis
1025///
1026/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
1027pub type JustifyItems = AlignItems;
1028/// Used to control how the specified nodes is aligned.
1029/// Overrides the parent Node's `AlignItems` property.
1030/// For Flexbox it controls alignment in the cross axis
1031/// For Grid it controls alignment in the block axis
1032///
1033/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
1034pub type AlignSelf = AlignItems;
1035/// Used to control how the specified nodes is aligned.
1036/// Overrides the parent Node's `JustifyItems` property.
1037/// Does not apply to Flexbox, and will be ignored if specified on a flex child
1038/// For Grid it controls alignment in the inline axis
1039///
1040/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
1041pub type JustifySelf = AlignItems;
1042
1043/// Sets the distribution of space between and around content items
1044/// For Flexbox it controls alignment in the cross axis
1045/// For Grid it controls alignment in the block axis
1046///
1047/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
1048#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1049// Copy of taffy::style type of the same name, to derive JsonSchema.
1050pub enum AlignContent {
1051 /// Items are packed toward the start of the axis
1052 Start,
1053 /// Items are packed toward the end of the axis
1054 End,
1055 /// Items are packed towards the flex-relative start of the axis.
1056 ///
1057 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1058 /// to End. In all other cases it is equivalent to Start.
1059 FlexStart,
1060 /// Items are packed towards the flex-relative end of the axis.
1061 ///
1062 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1063 /// to Start. In all other cases it is equivalent to End.
1064 FlexEnd,
1065 /// Items are centered around the middle of the axis
1066 Center,
1067 /// Items are stretched to fill the container
1068 Stretch,
1069 /// The first and last items are aligned flush with the edges of the container (no gap)
1070 /// The gap between items is distributed evenly.
1071 SpaceBetween,
1072 /// The gap between the first and last items is exactly THE SAME as the gap between items.
1073 /// The gaps are distributed evenly
1074 SpaceEvenly,
1075 /// The gap between the first and last items is exactly HALF the gap between items.
1076 /// The gaps are distributed evenly in proportion to these ratios.
1077 SpaceAround,
1078}
1079
1080/// Sets the distribution of space between and around content items
1081/// For Flexbox it controls alignment in the main axis
1082/// For Grid it controls alignment in the inline axis
1083///
1084/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
1085pub type JustifyContent = AlignContent;
1086
1087/// Sets the layout used for the children of this node
1088///
1089/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
1090#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1091// Copy of taffy::style type of the same name, to derive JsonSchema.
1092pub enum Display {
1093 /// The children will follow the block layout algorithm
1094 Block,
1095 /// The children will follow the flexbox layout algorithm
1096 #[default]
1097 Flex,
1098 /// The children will follow the CSS Grid layout algorithm
1099 Grid,
1100 /// The children will not be laid out, and will follow absolute positioning
1101 None,
1102}
1103
1104/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
1105///
1106/// Defaults to [`FlexWrap::NoWrap`]
1107///
1108/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
1109#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1110// Copy of taffy::style type of the same name, to derive JsonSchema.
1111pub enum FlexWrap {
1112 /// Items will not wrap and stay on a single line
1113 #[default]
1114 NoWrap,
1115 /// Items will wrap according to this item's [`FlexDirection`]
1116 Wrap,
1117 /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
1118 WrapReverse,
1119}
1120
1121/// The direction of the flexbox layout main axis.
1122///
1123/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
1124/// Adding items will cause them to be positioned adjacent to each other along the main axis.
1125/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
1126///
1127/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
1128///
1129/// The default behavior is [`FlexDirection::Row`].
1130///
1131/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
1132#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1133// Copy of taffy::style type of the same name, to derive JsonSchema.
1134pub enum FlexDirection {
1135 /// Defines +x as the main axis
1136 ///
1137 /// Items will be added from left to right in a row.
1138 #[default]
1139 Row,
1140 /// Defines +y as the main axis
1141 ///
1142 /// Items will be added from top to bottom in a column.
1143 Column,
1144 /// Defines -x as the main axis
1145 ///
1146 /// Items will be added from right to left in a row.
1147 RowReverse,
1148 /// Defines -y as the main axis
1149 ///
1150 /// Items will be added from bottom to top in a column.
1151 ColumnReverse,
1152}
1153
1154/// How children overflowing their container should affect layout
1155///
1156/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
1157/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
1158/// the main ones being:
1159///
1160/// - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
1161/// - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
1162///
1163/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
1164/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
1165///
1166/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
1167#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1168// Copy of taffy::style type of the same name, to derive JsonSchema.
1169pub enum Overflow {
1170 /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1171 /// Content that overflows this node *should* contribute to the scroll region of its parent.
1172 #[default]
1173 Visible,
1174 /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1175 /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1176 Clip,
1177 /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
1178 /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1179 Hidden,
1180 /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
1181 /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
1182 /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1183 Scroll,
1184}
1185
1186/// The positioning strategy for this item.
1187///
1188/// This controls both how the origin is determined for the [`Style::position`] field,
1189/// and whether or not the item will be controlled by flexbox's layout algorithm.
1190///
1191/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
1192/// which can be unintuitive.
1193///
1194/// [`Position::Relative`] is the default value, in contrast to the default behavior in CSS.
1195#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1196// Copy of taffy::style type of the same name, to derive JsonSchema.
1197pub enum Position {
1198 /// The offset is computed relative to the final position given by the layout algorithm.
1199 /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
1200 #[default]
1201 Relative,
1202 /// The offset is computed relative to this item's closest positioned ancestor, if any.
1203 /// Otherwise, it is placed relative to the origin.
1204 /// No space is created for the item in the page layout, and its size will not be altered.
1205 ///
1206 /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
1207 Absolute,
1208}
1209
1210impl From<AlignItems> for taffy::style::AlignItems {
1211 fn from(value: AlignItems) -> Self {
1212 match value {
1213 AlignItems::Start => Self::Start,
1214 AlignItems::End => Self::End,
1215 AlignItems::FlexStart => Self::FlexStart,
1216 AlignItems::FlexEnd => Self::FlexEnd,
1217 AlignItems::Center => Self::Center,
1218 AlignItems::Baseline => Self::Baseline,
1219 AlignItems::Stretch => Self::Stretch,
1220 }
1221 }
1222}
1223
1224impl From<AlignContent> for taffy::style::AlignContent {
1225 fn from(value: AlignContent) -> Self {
1226 match value {
1227 AlignContent::Start => Self::Start,
1228 AlignContent::End => Self::End,
1229 AlignContent::FlexStart => Self::FlexStart,
1230 AlignContent::FlexEnd => Self::FlexEnd,
1231 AlignContent::Center => Self::Center,
1232 AlignContent::Stretch => Self::Stretch,
1233 AlignContent::SpaceBetween => Self::SpaceBetween,
1234 AlignContent::SpaceEvenly => Self::SpaceEvenly,
1235 AlignContent::SpaceAround => Self::SpaceAround,
1236 }
1237 }
1238}
1239
1240impl From<Display> for taffy::style::Display {
1241 fn from(value: Display) -> Self {
1242 match value {
1243 Display::Block => Self::Block,
1244 Display::Flex => Self::Flex,
1245 Display::Grid => Self::Grid,
1246 Display::None => Self::None,
1247 }
1248 }
1249}
1250
1251impl From<FlexWrap> for taffy::style::FlexWrap {
1252 fn from(value: FlexWrap) -> Self {
1253 match value {
1254 FlexWrap::NoWrap => Self::NoWrap,
1255 FlexWrap::Wrap => Self::Wrap,
1256 FlexWrap::WrapReverse => Self::WrapReverse,
1257 }
1258 }
1259}
1260
1261impl From<FlexDirection> for taffy::style::FlexDirection {
1262 fn from(value: FlexDirection) -> Self {
1263 match value {
1264 FlexDirection::Row => Self::Row,
1265 FlexDirection::Column => Self::Column,
1266 FlexDirection::RowReverse => Self::RowReverse,
1267 FlexDirection::ColumnReverse => Self::ColumnReverse,
1268 }
1269 }
1270}
1271
1272impl From<Overflow> for taffy::style::Overflow {
1273 fn from(value: Overflow) -> Self {
1274 match value {
1275 Overflow::Visible => Self::Visible,
1276 Overflow::Clip => Self::Clip,
1277 Overflow::Hidden => Self::Hidden,
1278 Overflow::Scroll => Self::Scroll,
1279 }
1280 }
1281}
1282
1283impl From<Position> for taffy::style::Position {
1284 fn from(value: Position) -> Self {
1285 match value {
1286 Position::Relative => Self::Relative,
1287 Position::Absolute => Self::Absolute,
1288 }
1289 }
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294 use crate::{blue, green, px, red, yellow};
1295
1296 use super::*;
1297
1298 use util_macros::perf;
1299
1300 #[perf]
1301 fn test_basic_highlight_style_combination() {
1302 let style_a = HighlightStyle::default();
1303 let style_b = HighlightStyle::default();
1304 let style_a = style_a.highlight(style_b);
1305 assert_eq!(
1306 style_a,
1307 HighlightStyle::default(),
1308 "Combining empty styles should not produce a non-empty style."
1309 );
1310
1311 let mut style_b = HighlightStyle {
1312 color: Some(red()),
1313 strikethrough: Some(StrikethroughStyle {
1314 thickness: px(2.),
1315 color: Some(blue()),
1316 }),
1317 fade_out: Some(0.),
1318 font_style: Some(FontStyle::Italic),
1319 font_weight: Some(FontWeight(300.)),
1320 background_color: Some(yellow()),
1321 underline: Some(UnderlineStyle {
1322 thickness: px(2.),
1323 color: Some(red()),
1324 wavy: true,
1325 }),
1326 };
1327 let expected_style = style_b;
1328
1329 let style_a = style_a.highlight(style_b);
1330 assert_eq!(
1331 style_a, expected_style,
1332 "Blending an empty style with another style should return the other style"
1333 );
1334
1335 let style_b = style_b.highlight(Default::default());
1336 assert_eq!(
1337 style_b, expected_style,
1338 "Blending a style with an empty style should not change the style."
1339 );
1340
1341 let mut style_c = expected_style;
1342
1343 let style_d = HighlightStyle {
1344 color: Some(blue().alpha(0.7)),
1345 strikethrough: Some(StrikethroughStyle {
1346 thickness: px(4.),
1347 color: Some(crate::red()),
1348 }),
1349 fade_out: Some(0.),
1350 font_style: Some(FontStyle::Oblique),
1351 font_weight: Some(FontWeight(800.)),
1352 background_color: Some(green()),
1353 underline: Some(UnderlineStyle {
1354 thickness: px(4.),
1355 color: None,
1356 wavy: false,
1357 }),
1358 };
1359
1360 let expected_style = HighlightStyle {
1361 color: Some(red().blend(blue().alpha(0.7))),
1362 strikethrough: Some(StrikethroughStyle {
1363 thickness: px(4.),
1364 color: Some(red()),
1365 }),
1366 // TODO this does not seem right
1367 fade_out: Some(0.),
1368 font_style: Some(FontStyle::Oblique),
1369 font_weight: Some(FontWeight(800.)),
1370 background_color: Some(green()),
1371 underline: Some(UnderlineStyle {
1372 thickness: px(4.),
1373 color: None,
1374 wavy: false,
1375 }),
1376 };
1377
1378 let style_c = style_c.highlight(style_d);
1379 assert_eq!(
1380 style_c, expected_style,
1381 "Blending styles should blend properties where possible and override all others"
1382 );
1383 }
1384
1385 #[perf]
1386 fn test_combine_highlights() {
1387 assert_eq!(
1388 combine_highlights(
1389 [
1390 (0..5, green().into()),
1391 (4..10, FontWeight::BOLD.into()),
1392 (15..20, yellow().into()),
1393 ],
1394 [
1395 (2..6, FontStyle::Italic.into()),
1396 (1..3, blue().into()),
1397 (21..23, red().into()),
1398 ]
1399 )
1400 .collect::<Vec<_>>(),
1401 [
1402 (
1403 0..1,
1404 HighlightStyle {
1405 color: Some(green()),
1406 ..Default::default()
1407 }
1408 ),
1409 (
1410 1..2,
1411 HighlightStyle {
1412 color: Some(blue()),
1413 ..Default::default()
1414 }
1415 ),
1416 (
1417 2..3,
1418 HighlightStyle {
1419 color: Some(blue()),
1420 font_style: Some(FontStyle::Italic),
1421 ..Default::default()
1422 }
1423 ),
1424 (
1425 3..4,
1426 HighlightStyle {
1427 color: Some(green()),
1428 font_style: Some(FontStyle::Italic),
1429 ..Default::default()
1430 }
1431 ),
1432 (
1433 4..5,
1434 HighlightStyle {
1435 color: Some(green()),
1436 font_weight: Some(FontWeight::BOLD),
1437 font_style: Some(FontStyle::Italic),
1438 ..Default::default()
1439 }
1440 ),
1441 (
1442 5..6,
1443 HighlightStyle {
1444 font_weight: Some(FontWeight::BOLD),
1445 font_style: Some(FontStyle::Italic),
1446 ..Default::default()
1447 }
1448 ),
1449 (
1450 6..10,
1451 HighlightStyle {
1452 font_weight: Some(FontWeight::BOLD),
1453 ..Default::default()
1454 }
1455 ),
1456 (
1457 15..20,
1458 HighlightStyle {
1459 color: Some(yellow()),
1460 ..Default::default()
1461 }
1462 ),
1463 (
1464 21..23,
1465 HighlightStyle {
1466 color: Some(red()),
1467 ..Default::default()
1468 }
1469 )
1470 ]
1471 );
1472 }
1473
1474 #[perf]
1475 fn test_text_style_refinement() {
1476 let mut style = Style::default();
1477 style.refine(&StyleRefinement::default().text_size(px(20.0)));
1478 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1479
1480 assert_eq!(
1481 Some(AbsoluteLength::from(px(20.0))),
1482 style.text_style().unwrap().font_size
1483 );
1484
1485 assert_eq!(
1486 Some(FontWeight::SEMIBOLD),
1487 style.text_style().unwrap().font_weight
1488 );
1489 }
1490}