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 => color.solid,
643 BackgroundTag::LinearGradient => color
644 .colors
645 .first()
646 .map(|stop| stop.color)
647 .unwrap_or_default(),
648 BackgroundTag::PatternSlash => color.solid,
649 },
650 None => Hsla::default(),
651 };
652 border_color.a = 0.;
653 window.paint_quad(quad(
654 bounds,
655 corner_radii,
656 background_color.unwrap_or_default(),
657 Edges::default(),
658 border_color,
659 self.border_style,
660 ));
661 }
662
663 continuation(window, cx);
664
665 if self.is_border_visible() {
666 let border_widths = self.border_widths.to_pixels(rem_size);
667 let max_border_width = border_widths.max();
668 let max_corner_radius = corner_radii.max();
669 let zero_size = Size {
670 width: Pixels::ZERO,
671 height: Pixels::ZERO,
672 };
673
674 let mut top_bounds = Bounds::from_corners(
675 bounds.origin,
676 bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
677 );
678 top_bounds.size = top_bounds.size.max(&zero_size);
679 let mut bottom_bounds = Bounds::from_corners(
680 bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
681 bounds.bottom_right(),
682 );
683 bottom_bounds.size = bottom_bounds.size.max(&zero_size);
684 let mut left_bounds = Bounds::from_corners(
685 top_bounds.bottom_left(),
686 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
687 );
688 left_bounds.size = left_bounds.size.max(&zero_size);
689 let mut right_bounds = Bounds::from_corners(
690 top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
691 bottom_bounds.top_right(),
692 );
693 right_bounds.size = right_bounds.size.max(&zero_size);
694
695 let mut background = self.border_color.unwrap_or_default();
696 background.a = 0.;
697 let quad = quad(
698 bounds,
699 corner_radii,
700 background,
701 border_widths,
702 self.border_color.unwrap_or_default(),
703 self.border_style,
704 );
705
706 window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
707 window.paint_quad(quad.clone());
708 });
709 window.with_content_mask(
710 Some(ContentMask {
711 bounds: right_bounds,
712 }),
713 |window| {
714 window.paint_quad(quad.clone());
715 },
716 );
717 window.with_content_mask(
718 Some(ContentMask {
719 bounds: bottom_bounds,
720 }),
721 |window| {
722 window.paint_quad(quad.clone());
723 },
724 );
725 window.with_content_mask(
726 Some(ContentMask {
727 bounds: left_bounds,
728 }),
729 |window| {
730 window.paint_quad(quad);
731 },
732 );
733 }
734
735 #[cfg(debug_assertions)]
736 if self.debug_below {
737 cx.remove_global::<DebugBelow>();
738 }
739 }
740
741 fn is_border_visible(&self) -> bool {
742 self.border_color
743 .is_some_and(|color| !color.is_transparent())
744 && self.border_widths.any(|length| !length.is_zero())
745 }
746}
747
748impl Default for Style {
749 fn default() -> Self {
750 Style {
751 display: Display::Block,
752 visibility: Visibility::Visible,
753 overflow: Point {
754 x: Overflow::Visible,
755 y: Overflow::Visible,
756 },
757 allow_concurrent_scroll: false,
758 restrict_scroll_to_axis: false,
759 scrollbar_width: AbsoluteLength::default(),
760 position: Position::Relative,
761 inset: Edges::auto(),
762 margin: Edges::<Length>::zero(),
763 padding: Edges::<DefiniteLength>::zero(),
764 border_widths: Edges::<AbsoluteLength>::zero(),
765 size: Size::auto(),
766 min_size: Size::auto(),
767 max_size: Size::auto(),
768 aspect_ratio: None,
769 gap: Size::default(),
770 // Alignment
771 align_items: None,
772 align_self: None,
773 align_content: None,
774 justify_content: None,
775 // Flexbox
776 flex_direction: FlexDirection::Row,
777 flex_wrap: FlexWrap::NoWrap,
778 flex_grow: 0.0,
779 flex_shrink: 1.0,
780 flex_basis: Length::Auto,
781 background: None,
782 border_color: None,
783 border_style: BorderStyle::default(),
784 corner_radii: Corners::default(),
785 box_shadow: Default::default(),
786 text: TextStyleRefinement::default(),
787 mouse_cursor: None,
788 opacity: None,
789 grid_rows: None,
790 grid_cols: None,
791 grid_cols_min_content: None,
792 grid_location: None,
793
794 #[cfg(debug_assertions)]
795 debug: false,
796 #[cfg(debug_assertions)]
797 debug_below: false,
798 }
799 }
800}
801
802/// The properties that can be applied to an underline.
803#[derive(
804 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
805)]
806pub struct UnderlineStyle {
807 /// The thickness of the underline.
808 pub thickness: Pixels,
809
810 /// The color of the underline.
811 pub color: Option<Hsla>,
812
813 /// Whether the underline should be wavy, like in a spell checker.
814 pub wavy: bool,
815}
816
817/// The properties that can be applied to a strikethrough.
818#[derive(
819 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
820)]
821pub struct StrikethroughStyle {
822 /// The thickness of the strikethrough.
823 pub thickness: Pixels,
824
825 /// The color of the strikethrough.
826 pub color: Option<Hsla>,
827}
828
829/// The kinds of fill that can be applied to a shape.
830#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
831pub enum Fill {
832 /// A solid color fill.
833 Color(Background),
834}
835
836impl Fill {
837 /// Unwrap this fill into a solid color, if it is one.
838 ///
839 /// If the fill is not a solid color, this method returns `None`.
840 pub fn color(&self) -> Option<Background> {
841 match self {
842 Fill::Color(color) => Some(*color),
843 }
844 }
845}
846
847impl Default for Fill {
848 fn default() -> Self {
849 Self::Color(Background::default())
850 }
851}
852
853impl From<Hsla> for Fill {
854 fn from(color: Hsla) -> Self {
855 Self::Color(color.into())
856 }
857}
858
859impl From<Rgba> for Fill {
860 fn from(color: Rgba) -> Self {
861 Self::Color(color.into())
862 }
863}
864
865impl From<Background> for Fill {
866 fn from(background: Background) -> Self {
867 Self::Color(background)
868 }
869}
870
871impl From<TextStyle> for HighlightStyle {
872 fn from(other: TextStyle) -> Self {
873 Self::from(&other)
874 }
875}
876
877impl From<&TextStyle> for HighlightStyle {
878 fn from(other: &TextStyle) -> Self {
879 Self {
880 color: Some(other.color),
881 font_weight: Some(other.font_weight),
882 font_style: Some(other.font_style),
883 background_color: other.background_color,
884 underline: other.underline,
885 strikethrough: other.strikethrough,
886 fade_out: None,
887 }
888 }
889}
890
891impl HighlightStyle {
892 /// Create a highlight style with just a color
893 pub fn color(color: Hsla) -> Self {
894 Self {
895 color: Some(color),
896 ..Default::default()
897 }
898 }
899 /// Blend this highlight style with another.
900 /// Non-continuous properties, like font_weight and font_style, are overwritten.
901 #[must_use]
902 pub fn highlight(self, other: HighlightStyle) -> Self {
903 Self {
904 color: other
905 .color
906 .map(|other_color| {
907 if let Some(color) = self.color {
908 color.blend(other_color)
909 } else {
910 other_color
911 }
912 })
913 .or(self.color),
914 font_weight: other.font_weight.or(self.font_weight),
915 font_style: other.font_style.or(self.font_style),
916 background_color: other.background_color.or(self.background_color),
917 underline: other.underline.or(self.underline),
918 strikethrough: other.strikethrough.or(self.strikethrough),
919 fade_out: other
920 .fade_out
921 .map(|source_fade| {
922 self.fade_out
923 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
924 .unwrap_or(source_fade)
925 })
926 .or(self.fade_out),
927 }
928 }
929}
930
931impl From<Hsla> for HighlightStyle {
932 fn from(color: Hsla) -> Self {
933 Self {
934 color: Some(color),
935 ..Default::default()
936 }
937 }
938}
939
940impl From<FontWeight> for HighlightStyle {
941 fn from(font_weight: FontWeight) -> Self {
942 Self {
943 font_weight: Some(font_weight),
944 ..Default::default()
945 }
946 }
947}
948
949impl From<FontStyle> for HighlightStyle {
950 fn from(font_style: FontStyle) -> Self {
951 Self {
952 font_style: Some(font_style),
953 ..Default::default()
954 }
955 }
956}
957
958impl From<Rgba> for HighlightStyle {
959 fn from(color: Rgba) -> Self {
960 Self {
961 color: Some(color.into()),
962 ..Default::default()
963 }
964 }
965}
966
967/// Combine and merge the highlights and ranges in the two iterators.
968pub fn combine_highlights(
969 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
970 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
971) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
972 let mut endpoints = Vec::new();
973 let mut highlights = Vec::new();
974 for (range, highlight) in a.into_iter().chain(b) {
975 if !range.is_empty() {
976 let highlight_id = highlights.len();
977 endpoints.push((range.start, highlight_id, true));
978 endpoints.push((range.end, highlight_id, false));
979 highlights.push(highlight);
980 }
981 }
982 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
983 let mut endpoints = endpoints.into_iter().peekable();
984
985 let mut active_styles = HashSet::default();
986 let mut ix = 0;
987 iter::from_fn(move || {
988 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
989 let prev_index = mem::replace(&mut ix, *endpoint_ix);
990 if ix > prev_index && !active_styles.is_empty() {
991 let current_style = active_styles
992 .iter()
993 .fold(HighlightStyle::default(), |acc, highlight_id| {
994 acc.highlight(highlights[*highlight_id])
995 });
996 return Some((prev_index..ix, current_style));
997 }
998
999 if *is_start {
1000 active_styles.insert(*highlight_id);
1001 } else {
1002 active_styles.remove(highlight_id);
1003 }
1004 endpoints.next();
1005 }
1006 None
1007 })
1008}
1009
1010/// Used to control how child nodes are aligned.
1011/// For Flexbox it controls alignment in the cross axis
1012/// For Grid it controls alignment in the block axis
1013///
1014/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
1015#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1016// Copy of taffy::style type of the same name, to derive JsonSchema.
1017pub enum AlignItems {
1018 /// Items are packed toward the start of the axis
1019 Start,
1020 /// Items are packed toward the end of the axis
1021 End,
1022 /// Items are packed towards the flex-relative start of the axis.
1023 ///
1024 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1025 /// to End. In all other cases it is equivalent to Start.
1026 FlexStart,
1027 /// Items are packed towards the flex-relative end of the axis.
1028 ///
1029 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1030 /// to Start. In all other cases it is equivalent to End.
1031 FlexEnd,
1032 /// Items are packed along the center of the cross axis
1033 Center,
1034 /// Items are aligned such as their baselines align
1035 Baseline,
1036 /// Stretch to fill the container
1037 Stretch,
1038}
1039/// Used to control how child nodes are aligned.
1040/// Does not apply to Flexbox, and will be ignored if specified on a flex container
1041/// For Grid it controls alignment in the inline axis
1042///
1043/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
1044pub type JustifyItems = AlignItems;
1045/// Used to control how the specified nodes is aligned.
1046/// Overrides the parent Node's `AlignItems` property.
1047/// For Flexbox it controls alignment in the cross axis
1048/// For Grid it controls alignment in the block axis
1049///
1050/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
1051pub type AlignSelf = AlignItems;
1052/// Used to control how the specified nodes is aligned.
1053/// Overrides the parent Node's `JustifyItems` property.
1054/// Does not apply to Flexbox, and will be ignored if specified on a flex child
1055/// For Grid it controls alignment in the inline axis
1056///
1057/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
1058pub type JustifySelf = AlignItems;
1059
1060/// Sets the distribution of space between and around content items
1061/// For Flexbox it controls alignment in the cross axis
1062/// For Grid it controls alignment in the block axis
1063///
1064/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
1065#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1066// Copy of taffy::style type of the same name, to derive JsonSchema.
1067pub enum AlignContent {
1068 /// Items are packed toward the start of the axis
1069 Start,
1070 /// Items are packed toward the end of the axis
1071 End,
1072 /// Items are packed towards the flex-relative start of the axis.
1073 ///
1074 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1075 /// to End. In all other cases it is equivalent to Start.
1076 FlexStart,
1077 /// Items are packed towards the flex-relative end of the axis.
1078 ///
1079 /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1080 /// to Start. In all other cases it is equivalent to End.
1081 FlexEnd,
1082 /// Items are centered around the middle of the axis
1083 Center,
1084 /// Items are stretched to fill the container
1085 Stretch,
1086 /// The first and last items are aligned flush with the edges of the container (no gap)
1087 /// The gap between items is distributed evenly.
1088 SpaceBetween,
1089 /// The gap between the first and last items is exactly THE SAME as the gap between items.
1090 /// The gaps are distributed evenly
1091 SpaceEvenly,
1092 /// The gap between the first and last items is exactly HALF the gap between items.
1093 /// The gaps are distributed evenly in proportion to these ratios.
1094 SpaceAround,
1095}
1096
1097/// Sets the distribution of space between and around content items
1098/// For Flexbox it controls alignment in the main axis
1099/// For Grid it controls alignment in the inline axis
1100///
1101/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
1102pub type JustifyContent = AlignContent;
1103
1104/// Sets the layout used for the children of this node
1105///
1106/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
1107#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1108// Copy of taffy::style type of the same name, to derive JsonSchema.
1109pub enum Display {
1110 /// The children will follow the block layout algorithm
1111 Block,
1112 /// The children will follow the flexbox layout algorithm
1113 #[default]
1114 Flex,
1115 /// The children will follow the CSS Grid layout algorithm
1116 Grid,
1117 /// The children will not be laid out, and will follow absolute positioning
1118 None,
1119}
1120
1121/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
1122///
1123/// Defaults to [`FlexWrap::NoWrap`]
1124///
1125/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
1126#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1127// Copy of taffy::style type of the same name, to derive JsonSchema.
1128pub enum FlexWrap {
1129 /// Items will not wrap and stay on a single line
1130 #[default]
1131 NoWrap,
1132 /// Items will wrap according to this item's [`FlexDirection`]
1133 Wrap,
1134 /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
1135 WrapReverse,
1136}
1137
1138/// The direction of the flexbox layout main axis.
1139///
1140/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
1141/// Adding items will cause them to be positioned adjacent to each other along the main axis.
1142/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
1143///
1144/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
1145///
1146/// The default behavior is [`FlexDirection::Row`].
1147///
1148/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
1149#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1150// Copy of taffy::style type of the same name, to derive JsonSchema.
1151pub enum FlexDirection {
1152 /// Defines +x as the main axis
1153 ///
1154 /// Items will be added from left to right in a row.
1155 #[default]
1156 Row,
1157 /// Defines +y as the main axis
1158 ///
1159 /// Items will be added from top to bottom in a column.
1160 Column,
1161 /// Defines -x as the main axis
1162 ///
1163 /// Items will be added from right to left in a row.
1164 RowReverse,
1165 /// Defines -y as the main axis
1166 ///
1167 /// Items will be added from bottom to top in a column.
1168 ColumnReverse,
1169}
1170
1171/// How children overflowing their container should affect layout
1172///
1173/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
1174/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
1175/// the main ones being:
1176///
1177/// - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
1178/// - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
1179///
1180/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
1181/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
1182///
1183/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
1184#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1185// Copy of taffy::style type of the same name, to derive JsonSchema.
1186pub enum Overflow {
1187 /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1188 /// Content that overflows this node *should* contribute to the scroll region of its parent.
1189 #[default]
1190 Visible,
1191 /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1192 /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1193 Clip,
1194 /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
1195 /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1196 Hidden,
1197 /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
1198 /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
1199 /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1200 Scroll,
1201}
1202
1203/// The positioning strategy for this item.
1204///
1205/// This controls both how the origin is determined for the [`Style::position`] field,
1206/// and whether or not the item will be controlled by flexbox's layout algorithm.
1207///
1208/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
1209/// which can be unintuitive.
1210///
1211/// [`Position::Relative`] is the default value, in contrast to the default behavior in CSS.
1212#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1213// Copy of taffy::style type of the same name, to derive JsonSchema.
1214pub enum Position {
1215 /// The offset is computed relative to the final position given by the layout algorithm.
1216 /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
1217 #[default]
1218 Relative,
1219 /// The offset is computed relative to this item's closest positioned ancestor, if any.
1220 /// Otherwise, it is placed relative to the origin.
1221 /// No space is created for the item in the page layout, and its size will not be altered.
1222 ///
1223 /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
1224 Absolute,
1225}
1226
1227impl From<AlignItems> for taffy::style::AlignItems {
1228 fn from(value: AlignItems) -> Self {
1229 match value {
1230 AlignItems::Start => Self::Start,
1231 AlignItems::End => Self::End,
1232 AlignItems::FlexStart => Self::FlexStart,
1233 AlignItems::FlexEnd => Self::FlexEnd,
1234 AlignItems::Center => Self::Center,
1235 AlignItems::Baseline => Self::Baseline,
1236 AlignItems::Stretch => Self::Stretch,
1237 }
1238 }
1239}
1240
1241impl From<AlignContent> for taffy::style::AlignContent {
1242 fn from(value: AlignContent) -> Self {
1243 match value {
1244 AlignContent::Start => Self::Start,
1245 AlignContent::End => Self::End,
1246 AlignContent::FlexStart => Self::FlexStart,
1247 AlignContent::FlexEnd => Self::FlexEnd,
1248 AlignContent::Center => Self::Center,
1249 AlignContent::Stretch => Self::Stretch,
1250 AlignContent::SpaceBetween => Self::SpaceBetween,
1251 AlignContent::SpaceEvenly => Self::SpaceEvenly,
1252 AlignContent::SpaceAround => Self::SpaceAround,
1253 }
1254 }
1255}
1256
1257impl From<Display> for taffy::style::Display {
1258 fn from(value: Display) -> Self {
1259 match value {
1260 Display::Block => Self::Block,
1261 Display::Flex => Self::Flex,
1262 Display::Grid => Self::Grid,
1263 Display::None => Self::None,
1264 }
1265 }
1266}
1267
1268impl From<FlexWrap> for taffy::style::FlexWrap {
1269 fn from(value: FlexWrap) -> Self {
1270 match value {
1271 FlexWrap::NoWrap => Self::NoWrap,
1272 FlexWrap::Wrap => Self::Wrap,
1273 FlexWrap::WrapReverse => Self::WrapReverse,
1274 }
1275 }
1276}
1277
1278impl From<FlexDirection> for taffy::style::FlexDirection {
1279 fn from(value: FlexDirection) -> Self {
1280 match value {
1281 FlexDirection::Row => Self::Row,
1282 FlexDirection::Column => Self::Column,
1283 FlexDirection::RowReverse => Self::RowReverse,
1284 FlexDirection::ColumnReverse => Self::ColumnReverse,
1285 }
1286 }
1287}
1288
1289impl From<Overflow> for taffy::style::Overflow {
1290 fn from(value: Overflow) -> Self {
1291 match value {
1292 Overflow::Visible => Self::Visible,
1293 Overflow::Clip => Self::Clip,
1294 Overflow::Hidden => Self::Hidden,
1295 Overflow::Scroll => Self::Scroll,
1296 }
1297 }
1298}
1299
1300impl From<Position> for taffy::style::Position {
1301 fn from(value: Position) -> Self {
1302 match value {
1303 Position::Relative => Self::Relative,
1304 Position::Absolute => Self::Absolute,
1305 }
1306 }
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311 use crate::{blue, green, px, red, yellow};
1312
1313 use super::*;
1314
1315 use util_macros::perf;
1316
1317 #[perf]
1318 fn test_basic_highlight_style_combination() {
1319 let style_a = HighlightStyle::default();
1320 let style_b = HighlightStyle::default();
1321 let style_a = style_a.highlight(style_b);
1322 assert_eq!(
1323 style_a,
1324 HighlightStyle::default(),
1325 "Combining empty styles should not produce a non-empty style."
1326 );
1327
1328 let mut style_b = HighlightStyle {
1329 color: Some(red()),
1330 strikethrough: Some(StrikethroughStyle {
1331 thickness: px(2.),
1332 color: Some(blue()),
1333 }),
1334 fade_out: Some(0.),
1335 font_style: Some(FontStyle::Italic),
1336 font_weight: Some(FontWeight(300.)),
1337 background_color: Some(yellow()),
1338 underline: Some(UnderlineStyle {
1339 thickness: px(2.),
1340 color: Some(red()),
1341 wavy: true,
1342 }),
1343 };
1344 let expected_style = style_b;
1345
1346 let style_a = style_a.highlight(style_b);
1347 assert_eq!(
1348 style_a, expected_style,
1349 "Blending an empty style with another style should return the other style"
1350 );
1351
1352 let style_b = style_b.highlight(Default::default());
1353 assert_eq!(
1354 style_b, expected_style,
1355 "Blending a style with an empty style should not change the style."
1356 );
1357
1358 let mut style_c = expected_style;
1359
1360 let style_d = HighlightStyle {
1361 color: Some(blue().alpha(0.7)),
1362 strikethrough: Some(StrikethroughStyle {
1363 thickness: px(4.),
1364 color: Some(crate::red()),
1365 }),
1366 fade_out: Some(0.),
1367 font_style: Some(FontStyle::Oblique),
1368 font_weight: Some(FontWeight(800.)),
1369 background_color: Some(green()),
1370 underline: Some(UnderlineStyle {
1371 thickness: px(4.),
1372 color: None,
1373 wavy: false,
1374 }),
1375 };
1376
1377 let expected_style = HighlightStyle {
1378 color: Some(red().blend(blue().alpha(0.7))),
1379 strikethrough: Some(StrikethroughStyle {
1380 thickness: px(4.),
1381 color: Some(red()),
1382 }),
1383 // TODO this does not seem right
1384 fade_out: Some(0.),
1385 font_style: Some(FontStyle::Oblique),
1386 font_weight: Some(FontWeight(800.)),
1387 background_color: Some(green()),
1388 underline: Some(UnderlineStyle {
1389 thickness: px(4.),
1390 color: None,
1391 wavy: false,
1392 }),
1393 };
1394
1395 let style_c = style_c.highlight(style_d);
1396 assert_eq!(
1397 style_c, expected_style,
1398 "Blending styles should blend properties where possible and override all others"
1399 );
1400 }
1401
1402 #[perf]
1403 fn test_combine_highlights() {
1404 assert_eq!(
1405 combine_highlights(
1406 [
1407 (0..5, green().into()),
1408 (4..10, FontWeight::BOLD.into()),
1409 (15..20, yellow().into()),
1410 ],
1411 [
1412 (2..6, FontStyle::Italic.into()),
1413 (1..3, blue().into()),
1414 (21..23, red().into()),
1415 ]
1416 )
1417 .collect::<Vec<_>>(),
1418 [
1419 (
1420 0..1,
1421 HighlightStyle {
1422 color: Some(green()),
1423 ..Default::default()
1424 }
1425 ),
1426 (
1427 1..2,
1428 HighlightStyle {
1429 color: Some(blue()),
1430 ..Default::default()
1431 }
1432 ),
1433 (
1434 2..3,
1435 HighlightStyle {
1436 color: Some(blue()),
1437 font_style: Some(FontStyle::Italic),
1438 ..Default::default()
1439 }
1440 ),
1441 (
1442 3..4,
1443 HighlightStyle {
1444 color: Some(green()),
1445 font_style: Some(FontStyle::Italic),
1446 ..Default::default()
1447 }
1448 ),
1449 (
1450 4..5,
1451 HighlightStyle {
1452 color: Some(green()),
1453 font_weight: Some(FontWeight::BOLD),
1454 font_style: Some(FontStyle::Italic),
1455 ..Default::default()
1456 }
1457 ),
1458 (
1459 5..6,
1460 HighlightStyle {
1461 font_weight: Some(FontWeight::BOLD),
1462 font_style: Some(FontStyle::Italic),
1463 ..Default::default()
1464 }
1465 ),
1466 (
1467 6..10,
1468 HighlightStyle {
1469 font_weight: Some(FontWeight::BOLD),
1470 ..Default::default()
1471 }
1472 ),
1473 (
1474 15..20,
1475 HighlightStyle {
1476 color: Some(yellow()),
1477 ..Default::default()
1478 }
1479 ),
1480 (
1481 21..23,
1482 HighlightStyle {
1483 color: Some(red()),
1484 ..Default::default()
1485 }
1486 )
1487 ]
1488 );
1489 }
1490
1491 #[perf]
1492 fn test_text_style_refinement() {
1493 let mut style = Style::default();
1494 style.refine(&StyleRefinement::default().text_size(px(20.0)));
1495 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1496
1497 assert_eq!(
1498 Some(AbsoluteLength::from(px(20.0))),
1499 style.text_style().unwrap().font_size
1500 );
1501
1502 assert_eq!(
1503 Some(FontWeight::SEMIBOLD),
1504 style.text_style().unwrap().font_weight
1505 );
1506 }
1507}