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