BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / title_bar.rs

title_bar.rs

title_bar.rs 13.4 KiB Download Raw
1use std::sync::{Arc, OnceLock};
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::{TitleBar, h_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7
8use super::widgets::icon;
9use crate::app_state::Mode;
10use crate::appearance::AppIcon;
11use crate::theme;
12use crate::updater::UpdateStatus;
13
14pub const TITLE_BAR_HEIGHT: f32 = 40.;
15const SEARCH_WIDTH: f32 = 380.;
16const SEARCH_MIN_WIDTH: f32 = 240.;
17const SEARCH_MIN_VISIBLE_WIDTH: f32 = 36.;
18const SEARCH_HEIGHT: f32 = 28.;
19const SEARCH_GAP: f32 = 8.;
20const SHORTCUT_MIN_WIDTH: f32 = 200.;
21const SEARCH_HINT: &str = "Search chats, people and channels";
22const SHORTCUT_HINT: &str = "Ctrl K";
23const APP_ICON_SIZE: f32 = 18.;
24
25pub fn app_icon_image(app_icon: AppIcon) -> Arc<Image> {
26 static IMAGES: [OnceLock<Arc<Image>>; AppIcon::ALL.len()] =
27 [const { OnceLock::new() }; AppIcon::ALL.len()];
28 let index = AppIcon::ALL
29 .iter()
30 .position(|candidate| *candidate == app_icon)
31 .unwrap_or(0);
32 IMAGES[index]
33 .get_or_init(|| Arc::new(Image::from_bytes(ImageFormat::Png, app_icon.png().to_vec())))
34 .clone()
35}
36
37fn mode_pill(label: &'static str) -> Div {
38 div()
39 .debug_selector(|| "shell/title-bar/mode-pill".into())
40 .flex_none()
41 .px(px(8.))
42 .h(px(18.))
43 .flex()
44 .items_center()
45 .rounded_full()
46 .bg(theme::amber().opacity(0.14))
47 .text_size(px(11.))
48 .font_weight(FontWeight::SEMIBOLD)
49 .text_color(theme::amber())
50 .child(label)
51}
52
53pub fn mode_label(mode: Mode) -> Option<&'static str> {
54 if mode.demo {
55 Some("Demo")
56 } else if mode.read_only {
57 Some("Read-only")
58 } else {
59 None
60 }
61}
62
63pub fn update_button(
64 update: &UpdateStatus,
65 on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
66) -> Option<AnyElement> {
67 let installing = match update {
68 UpdateStatus::Ready => false,
69 UpdateStatus::Installing => true,
70 UpdateStatus::UpToDate | UpdateStatus::Failed(_) => return None,
71 };
72 Some(
73 div()
74 .id("title-update-restart")
75 .debug_selector(|| "shell/title-bar/update".into())
76 .flex_none()
77 .h(px(24.))
78 .px(px(10.))
79 .flex()
80 .items_center()
81 .rounded(px(6.))
82 .bg(theme::accent())
83 .text_color(theme::on_accent())
84 .text_size(px(12.))
85 .font_weight(FontWeight::SEMIBOLD)
86 .when(!installing, |button| {
87 button
88 .cursor_pointer()
89 .hover(|button| button.bg(theme::accent_text()))
90 .on_click(on_restart)
91 })
92 .when(installing, |button| button.opacity(0.7))
93 .child(if installing {
94 "Restarting..."
95 } else {
96 "Restart to update"
97 })
98 .into_any_element(),
99 )
100}
101
102#[derive(Clone, Copy, Debug, PartialEq)]
103struct SearchSpan {
104 left: f32,
105 width: f32,
106}
107
108fn search_span(window_width: f32, leading_end: f32, trailing_start: f32) -> Option<SearchSpan> {
109 let start = leading_end + SEARCH_GAP;
110 let end = trailing_start - SEARCH_GAP;
111 let room = end - start;
112 if room < SEARCH_MIN_VISIBLE_WIDTH {
113 return None;
114 }
115 let center = window_width / 2.;
116 let centered_width = (2. * (center - start).min(end - center)).min(SEARCH_WIDTH);
117 let width = centered_width.max(SEARCH_MIN_WIDTH).min(room);
118 let left = (center - width / 2.).clamp(start, end - width);
119 Some(SearchSpan { left, width })
120}
121
122#[derive(Clone, Copy, PartialEq)]
123struct Reserved {
124 leading_end: f32,
125 trailing_from_right: f32,
126}
127
128#[derive(IntoElement)]
129struct TitleBarRow {
130 app_icon: AppIcon,
131 mode_label: Option<&'static str>,
132 controls: Vec<AnyElement>,
133 on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
134}
135
136pub fn render_title_bar(
137 app_icon: AppIcon,
138 mode_label: Option<&'static str>,
139 controls: impl IntoIterator<Item = AnyElement>,
140 on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
141) -> impl IntoElement {
142 TitleBarRow {
143 app_icon,
144 mode_label,
145 controls: controls.into_iter().collect(),
146 on_search: Box::new(on_search),
147 }
148}
149
150// The Windows caption hit-test takes every point the Drag area reaches, so a control without occlusion never gets its click.
151fn outside_caption(control: AnyElement) -> Div {
152 div().flex_none().occlude().child(control)
153}
154
155fn search_box(
156 span: SearchSpan,
157 on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
158) -> impl IntoElement {
159 h_flex()
160 .id("title-search")
161 .debug_selector(|| "shell/title-bar/search".into())
162 .occlude()
163 .absolute()
164 .top(px((TITLE_BAR_HEIGHT - SEARCH_HEIGHT) / 2.))
165 .left(px(span.left))
166 .w(px(span.width))
167 .h(px(SEARCH_HEIGHT))
168 .px(px(10.))
169 .gap(px(8.))
170 .items_center()
171 .overflow_hidden()
172 .rounded(px(6.))
173 .bg(theme::surface())
174 .cursor_pointer()
175 .text_size(px(12.))
176 .text_color(theme::text_muted())
177 .child(
178 div()
179 .flex_none()
180 .child(icon(IconName::Search, 14., theme::text_muted())),
181 )
182 .child(div().flex_1().min_w_0().truncate().child(SEARCH_HINT))
183 .when(span.width >= SHORTCUT_MIN_WIDTH, |search| {
184 search.child(
185 div()
186 .flex_none()
187 .px(px(6.))
188 .py(px(1.))
189 .rounded(px(4.))
190 .bg(theme::surface_raised())
191 .text_size(px(11.))
192 .child(SHORTCUT_HINT),
193 )
194 })
195 .on_click(move |event, window, cx| on_search(event, window, cx))
196}
197
198impl RenderOnce for TitleBarRow {
199 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
200 let reserved = window.use_keyed_state("title-bar-reserved", cx, |_, _| None::<Reserved>);
201 let window_width = f32::from(window.viewport_size().width);
202 let span = (*reserved.read(cx)).and_then(|reserved| {
203 search_span(
204 window_width,
205 reserved.leading_end,
206 window_width - reserved.trailing_from_right,
207 )
208 });
209 let leading = h_flex()
210 .debug_selector(|| "shell/title-bar/leading".into())
211 .flex_none()
212 .h_full()
213 .gap(px(12.))
214 .items_center()
215 .child(
216 img(app_icon_image(self.app_icon))
217 .size(px(APP_ICON_SIZE))
218 .flex_none(),
219 )
220 .child(
221 div()
222 .text_size(px(13.))
223 .font_weight(FontWeight::SEMIBOLD)
224 .text_color(theme::text())
225 .child(app_base::APP_NAME),
226 )
227 .children(self.mode_label.map(mode_pill));
228 let trailing = h_flex()
229 .debug_selector(|| "shell/title-bar/trailing".into())
230 .flex_none()
231 .h_full()
232 .gap(px(12.))
233 .items_center()
234 .children(self.controls.into_iter().map(outside_caption))
235 .child(div().w(px(4.)));
236 let row = h_flex()
237 .flex_1()
238 .h_full()
239 .gap(px(12.))
240 .items_center()
241 .child(leading)
242 .child(div().flex_1())
243 .child(trailing)
244 .on_children_prepainted(move |children, window, cx| {
245 let [leading, _, trailing] = children[..] else {
246 return;
247 };
248 let measured = Reserved {
249 leading_end: f32::from(leading.right()),
250 trailing_from_right: f32::from(window.viewport_size().width - trailing.left()),
251 };
252 reserved.update(cx, |current, cx| {
253 let unchanged = current.is_some_and(|current| {
254 (current.leading_end - measured.leading_end).abs() < 0.5
255 && (current.trailing_from_right - measured.trailing_from_right).abs()
256 < 0.5
257 });
258 if !unchanged {
259 *current = Some(measured);
260 cx.notify();
261 }
262 });
263 });
264 let bar = TitleBar::new()
265 .h(px(TITLE_BAR_HEIGHT))
266 .border_b_0()
267 .bg(theme::background())
268 .child(row);
269 let on_search = self.on_search;
270 div()
271 .debug_selector(|| "shell/title-bar".into())
272 .relative()
273 .flex_none()
274 .w_full()
275 .child(bar)
276 .children(span.map(|span| search_box(span, on_search)))
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use std::cell::{Cell, RefCell};
283 use std::rc::Rc;
284
285 use gpui_kit::component::button::{Button, ButtonVariants as _};
286 use gpui_kit::{
287 Context, Hitbox, HitboxBehavior, InteractiveElement as _, IntoElement, Modifiers,
288 ParentElement, Render, Styled, TestAppContext, Window, canvas, div, px, size,
289 };
290
291 use super::{
292 AppIcon, SEARCH_MIN_WIDTH, SEARCH_WIDTH, UpdateStatus, render_title_bar, search_span,
293 update_button,
294 };
295
296 struct CaptionHarness {
297 caption: Rc<RefCell<Option<Hitbox>>>,
298 restarts: Rc<Cell<usize>>,
299 }
300
301 impl Render for CaptionHarness {
302 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
303 let caption = self.caption.clone();
304 let restarts = self.restarts.clone();
305 let own = div()
306 .debug_selector(|| "shell/title-bar/own-status".into())
307 .child(Button::new("own").ghost().size(px(32.)).child("O"))
308 .into_any_element();
309 div()
310 .relative()
311 .size_full()
312 .child(
313 canvas(
314 |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
315 move |_, hitbox, _, _| *caption.borrow_mut() = Some(hitbox),
316 )
317 .absolute()
318 .size_full(),
319 )
320 .child(render_title_bar(
321 AppIcon::ALL[0],
322 Some("Demo"),
323 [
324 update_button(&UpdateStatus::Ready, move |_, _, _| {
325 restarts.set(restarts.get() + 1)
326 }),
327 Some(own),
328 ]
329 .into_iter()
330 .flatten(),
331 |_, _, _| {},
332 ))
333 }
334 }
335
336 #[gpui_kit::test]
337 fn title_bar_controls_stay_out_of_the_caption(cx: &mut TestAppContext) {
338 cx.update(gpui_kit::init);
339 cx.update(crate::theme::apply);
340 let caption = Rc::new(RefCell::new(None));
341 let restarts = Rc::new(Cell::new(0));
342 let (_, window_cx) = cx.add_window_view({
343 let caption = caption.clone();
344 let restarts = restarts.clone();
345 move |_, _| CaptionHarness { caption, restarts }
346 });
347 window_cx.simulate_resize(size(px(1280.), px(800.)));
348 for _ in 0..2 {
349 window_cx.update(|window, cx| window.draw(cx).clear(cx));
350 }
351 let mut found = Vec::new();
352 for (selector, caption_expected) in [
353 ("shell/title-bar/update", false),
354 ("shell/title-bar/own-status", false),
355 ("shell/title-bar/search", false),
356 ("shell/title-bar/leading", true),
357 ] {
358 let Some(bounds) = window_cx.debug_bounds(selector) else {
359 found.push(format!("{selector} was not rendered"));
360 continue;
361 };
362 let center = bounds.center();
363 let in_caption = window_cx.update(|window, _| {
364 caption
365 .borrow()
366 .as_ref()
367 .is_some_and(|hitbox| hitbox.is_hovered_at(center, window))
368 });
369 if in_caption != caption_expected {
370 found.push(format!("{selector} in caption: {in_caption}"));
371 }
372 }
373 assert!(found.is_empty(), "{}", found.join("\n"));
374 let update = window_cx
375 .debug_bounds("shell/title-bar/update")
376 .expect("update button rendered");
377 window_cx.simulate_click(update.center(), Modifiers::default());
378 assert_eq!(restarts.get(), 1);
379 }
380
381 #[test]
382 fn search_stays_centered_while_it_fits() {
383 let span = search_span(1280., 200., 1080.).expect("visible");
384 assert_eq!(span.width, SEARCH_WIDTH);
385 assert_eq!(span.left + span.width / 2., 640.);
386 }
387
388 #[test]
389 fn search_shrinks_centered_before_it_shifts() {
390 let span = search_span(800., 200., 580.).expect("visible");
391 assert_eq!(span.left + span.width / 2., 400.);
392 assert_eq!(span.width, 344.);
393 let shifted = search_span(800., 200., 500.).expect("visible");
394 assert_eq!(shifted.width, SEARCH_MIN_WIDTH);
395 assert_eq!(shifted.left + shifted.width, 492.);
396 }
397
398 #[test]
399 fn search_takes_the_room_left_and_hides_without_any() {
400 let span = search_span(640., 200., 400.).expect("visible");
401 assert_eq!((span.left, span.width), (208., 184.));
402 assert_eq!(search_span(640., 300., 340.), None);
403 }
404}