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