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