fc_ui/capabilities/effects/
gradient_text.rs1use crate::capabilities::motion::animations::lerp_color;
2use gpui::{prelude::FluentBuilder as _, *};
3
4#[derive(IntoElement)]
5pub struct GradientText {
6 text: SharedString,
7 start_color: Option<Hsla>,
8 end_color: Option<Hsla>,
9 text_size: Option<Pixels>,
10 font_weight: Option<FontWeight>,
11 font_family: Option<SharedString>,
12 style: StyleRefinement,
13}
14
15impl GradientText {
16 pub fn new(text: impl Into<SharedString>) -> Self {
17 Self {
18 text: text.into(),
19 start_color: None,
20 end_color: None,
21 text_size: None,
22 font_weight: None,
23 font_family: None,
24 style: StyleRefinement::default(),
25 }
26 }
27
28 pub fn start_color(mut self, color: Hsla) -> Self {
29 self.start_color = Some(color);
30 self
31 }
32
33 pub fn end_color(mut self, color: Hsla) -> Self {
34 self.end_color = Some(color);
35 self
36 }
37
38 pub fn text_size(mut self, size: Pixels) -> Self {
39 self.text_size = Some(size);
40 self
41 }
42
43 pub fn font_weight(mut self, weight: FontWeight) -> Self {
44 self.font_weight = Some(weight);
45 self
46 }
47
48 pub fn font_family(mut self, family: impl Into<SharedString>) -> Self {
49 self.font_family = Some(family.into());
50 self
51 }
52}
53
54impl Styled for GradientText {
55 fn style(&mut self) -> &mut StyleRefinement {
56 &mut self.style
57 }
58}
59
60impl RenderOnce for GradientText {
61 fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
62 let start = self.start_color.unwrap_or(hsla(0.6, 0.8, 0.6, 1.0));
63 let end = self.end_color.unwrap_or(hsla(0.8, 0.8, 0.6, 1.0));
64
65 let chars: Vec<char> = self.text.chars().collect();
66 let count = chars.len();
67 let max_index = if count > 1 { count - 1 } else { 1 };
68
69 let text_size = self.text_size;
70 let font_weight = self.font_weight;
71 let font_family = self.font_family;
72 let user_style = self.style;
73
74 let mut row = div().flex().flex_row().items_center().map(|mut el| {
75 el.style().refine(&user_style);
76 el
77 });
78
79 for (i, ch) in chars.into_iter().enumerate() {
80 let t = i as f32 / max_index as f32;
81 let color = lerp_color(start, end, t);
82 let s: SharedString = ch.to_string().into();
83
84 let mut span = div().text_color(color).child(s);
85
86 if let Some(size) = text_size {
87 span = span.text_size(size);
88 }
89 if let Some(weight) = font_weight {
90 span = span.font_weight(weight);
91 }
92 if let Some(ref family) = font_family {
93 span = span.font_family(family.clone());
94 }
95
96 row = row.child(span);
97 }
98
99 row
100 }
101}