fc_ui/capabilities/navigation/
segmented_nav.rs1use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5use std::time::Duration;
6
7use crate::capabilities::foundation::theme::use_theme;
8use crate::capabilities::motion::animations::{durations, easings};
9
10#[derive(Clone)]
11struct SegmentedNavItem {
12 id: SharedString,
13 label: SharedString,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
17pub enum SegmentedNavSize {
18 Sm,
19 #[default]
20 Md,
21 Lg,
22}
23
24impl SegmentedNavSize {
25 fn height(&self) -> Pixels {
26 match self {
27 Self::Sm => px(32.0),
28 Self::Md => px(40.0),
29 Self::Lg => px(48.0),
30 }
31 }
32
33 fn text_size(&self) -> Pixels {
34 match self {
35 Self::Sm => px(12.0),
36 Self::Md => px(14.0),
37 Self::Lg => px(16.0),
38 }
39 }
40
41 fn padding_x(&self) -> Pixels {
42 match self {
43 Self::Sm => px(8.0),
44 Self::Md => px(12.0),
45 Self::Lg => px(16.0),
46 }
47 }
48}
49
50pub struct SegmentedNavState {
51 active: SharedString,
52 previous_active: Option<SharedString>,
53 animation_version: usize,
54}
55
56impl SegmentedNavState {
57 pub fn new(active: impl Into<SharedString>) -> Self {
58 Self {
59 active: active.into(),
60 previous_active: None,
61 animation_version: 0,
62 }
63 }
64
65 pub fn set_active(&mut self, id: impl Into<SharedString>, cx: &mut Context<Self>) {
66 let new_id = id.into();
67 if self.active != new_id {
68 self.previous_active = Some(self.active.clone());
69 self.active = new_id;
70 self.animation_version = self.animation_version.wrapping_add(1);
71 cx.notify();
72 }
73 }
74
75 pub fn active(&self) -> &SharedString {
76 &self.active
77 }
78}
79
80#[derive(IntoElement)]
81pub struct SegmentedNav {
82 id: ElementId,
83 state: Entity<SegmentedNavState>,
84 items: Vec<SegmentedNavItem>,
85 nav_size: SegmentedNavSize,
86 on_change: Option<Rc<dyn Fn(SharedString, &mut Window, &mut App)>>,
87 duration: Duration,
88 style: StyleRefinement,
89}
90
91impl SegmentedNav {
92 pub fn new(id: impl Into<ElementId>, state: Entity<SegmentedNavState>) -> Self {
93 Self {
94 id: id.into(),
95 state,
96 items: Vec::new(),
97 nav_size: SegmentedNavSize::default(),
98 on_change: None,
99 duration: durations::NORMAL,
100 style: StyleRefinement::default(),
101 }
102 }
103
104 pub fn item(mut self, id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
105 self.items.push(SegmentedNavItem {
106 id: id.into(),
107 label: label.into(),
108 });
109 self
110 }
111
112 pub fn size(mut self, size: SegmentedNavSize) -> Self {
113 self.nav_size = size;
114 self
115 }
116
117 pub fn duration(mut self, duration: Duration) -> Self {
118 self.duration = duration;
119 self
120 }
121
122 pub fn on_change<F>(mut self, handler: F) -> Self
123 where
124 F: Fn(SharedString, &mut Window, &mut App) + 'static,
125 {
126 self.on_change = Some(Rc::new(handler));
127 self
128 }
129}
130
131impl Styled for SegmentedNav {
132 fn style(&mut self) -> &mut StyleRefinement {
133 &mut self.style
134 }
135}
136
137impl RenderOnce for SegmentedNav {
138 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
139 let theme = use_theme(cx);
140 let user_style = self.style;
141 let state = self.state.read(cx);
142 let active_id = state.active.clone();
143 let previous_id = state.previous_active.clone();
144 let item_count = self.items.len();
145 let active_index = self.items.iter().position(|i| i.id == active_id);
146 let previous_index = previous_id
147 .as_ref()
148 .and_then(|id| self.items.iter().position(|i| &i.id == id));
149 let animation_version = state.animation_version;
150 let duration = self.duration;
151
152 let item_fraction = if item_count > 0 {
153 1.0 / item_count as f32
154 } else {
155 1.0
156 };
157
158 div()
159 .id(self.id)
160 .flex()
161 .items_center()
162 .relative()
163 .bg(theme.tokens.muted)
164 .rounded(theme.tokens.radius_md)
165 .p(px(4.0))
166 .h(self.nav_size.height())
167 .when(active_index.is_some(), |this| {
168 let idx = active_index.unwrap();
169 this.child(
170 div()
171 .id("segmented-indicator")
172 .absolute()
173 .top(px(4.0))
174 .bottom(px(4.0))
175 .rounded(theme.tokens.radius_sm)
176 .bg(theme.tokens.background)
177 .shadow(smallvec::smallvec![BoxShadow {
178 color: hsla(0.0, 0.0, 0.0, 0.08),
179 offset: point(px(0.0), px(1.0)),
180 blur_radius: px(3.0),
181 spread_radius: px(0.0),
182 inset: false,
183 }])
184 .with_animation(
185 ElementId::Name(format!("seg-slide-{}", animation_version).into()),
186 Animation::new(duration).with_easing(easings::ease_out_cubic),
187 move |el, delta| {
188 let frac = item_fraction;
189 let cur_pct = idx as f32 * frac * 100.0;
190 let start_pct = previous_index
191 .map(|prev| prev as f32 * frac * 100.0)
192 .unwrap_or(cur_pct);
193 let width_pct = frac * 100.0;
194 let left_pct = start_pct + (cur_pct - start_pct) * delta;
195 el.left(relative(left_pct / 100.0))
196 .w(relative(width_pct / 100.0))
197 },
198 ),
199 )
200 })
201 .children(self.items.iter().enumerate().map(|(idx, item)| {
202 let item_id = item.id.clone();
203 let is_active = item.id == active_id;
204 let on_change = self.on_change.clone();
205 let state = self.state.clone();
206 let click_id = item_id.clone();
207
208 div()
209 .id(ElementId::Name(format!("seg-item-{}", idx).into()))
210 .flex_1()
211 .flex()
212 .items_center()
213 .justify_center()
214 .h_full()
215 .px(self.nav_size.padding_x())
216 .text_size(self.nav_size.text_size())
217 .font_weight(if is_active {
218 FontWeight::MEDIUM
219 } else {
220 FontWeight::NORMAL
221 })
222 .text_color(if is_active {
223 theme.tokens.foreground
224 } else {
225 theme.tokens.muted_foreground
226 })
227 .cursor_pointer()
228 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
229 state.update(cx, |state, cx| {
230 state.set_active(click_id.clone(), cx);
231 });
232 if let Some(handler) = on_change.as_ref() {
233 handler(item_id.clone(), window, cx);
234 }
235 })
236 .child(item.label.clone())
237 }))
238 .map(|this| {
239 let mut el = this;
240 el.style().refine(&user_style);
241 el
242 })
243 }
244}