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