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