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