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