1use super::{child_id, text};
5use crate::{Button, ButtonSize};
6use arc_motion::{
7 LayoutSnapshot, arc_spring_with_options, layout::layout_scope_key, sample_shared_layout,
8};
9use arc_tokens::{ActiveArcTheme as _, BlockTokens, Shadows, Spacing, Typography};
10use gpui_kit::{
11 App, BorderStyle, Bounds, Edges, ElementId, FocusHandle, InteractiveElement as _, IntoElement,
12 KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, ScrollHandle, SharedString,
13 StatefulInteractiveElement as _, Styled, TestSupportExt as _, Window,
14 base::{ElementExt as _, StyledExt as _},
15 bounds, canvas, div, point, px, quad,
16};
17use std::{cell::RefCell, rc::Rc, time::Duration};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub enum EmptyScene {
21 #[default]
22 Search,
23 Offline,
24 Inbox,
25 NotFound,
26}
27impl EmptyScene {
28 fn index(self) -> usize {
29 match self {
30 Self::Search => 0,
31 Self::Offline => 1,
32 Self::Inbox => 2,
33 Self::NotFound => 3,
34 }
35 }
36 fn tab_label(self) -> &'static str {
37 match self {
38 Self::Search => "No results",
39 Self::Offline => "Offline",
40 Self::Inbox => "Caught up",
41 Self::NotFound => "Not found",
42 }
43 }
44 fn title(self) -> &'static str {
45 match self {
46 Self::Search => "No results for “Q3 roadmap”",
47 Self::Offline => "You are offline",
48 Self::Inbox => "All caught up",
49 Self::NotFound => "Page not found",
50 }
51 }
52 fn body(self) -> &'static str {
53 match self {
54 Self::Search => "Two filters are on: owner is Emma Collins and status is archived.",
55 Self::Offline => "Edits are saved on this device and sync when the connection returns.",
56 Self::Inbox => "You have read every message in Inbox. New mail lands here first.",
57 Self::NotFound => "The link to /projects/atlas-2023 is broken, or the page has moved.",
58 }
59 }
60 fn action(self) -> &'static str {
61 match self {
62 Self::Search => "Clear filters",
63 Self::Offline => "Try again",
64 Self::Inbox => "Check for mail",
65 Self::NotFound => "Find the page",
66 }
67 }
68 fn done_title(self) -> &'static str {
69 match self {
70 Self::Search => "12 results for “Q3 roadmap”",
71 Self::Offline => "Back online",
72 Self::Inbox => "Still all caught up",
73 Self::NotFound => "Found it in Archive",
74 }
75 }
76}
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78pub(super) enum Phase {
79 #[default]
80 Idle,
81 Loading,
82 Done,
83}
84struct State {
85 scene: EmptyScene,
86 phase: Phase,
87 from: Phase,
88 generation: u64,
89 tab_bounds: Rc<RefCell<[Option<Bounds<Pixels>>; 4]>>,
90 tab_focus: [FocusHandle; 4],
91 tab_scroll: ScrollHandle,
92 container_width: f32,
93}
94impl State {
95 fn choose(&mut self, scene: EmptyScene) {
96 if self.scene != scene {
98 self.scene = scene;
99 self.phase = Phase::Idle;
100 self.from = Phase::Idle;
101 self.generation += 1;
102 }
103 }
104}
105type Action = Rc<dyn Fn(EmptyScene, &mut Window, &mut App)>;
106#[derive(IntoElement)]
107pub struct EmptyStates {
108 id: ElementId,
109 scene: Option<EmptyScene>,
110 loading: bool,
111 on_action: Option<Action>,
112}
113impl EmptyStates {
114 pub fn new(id: impl Into<ElementId>) -> Self {
115 Self {
116 id: id.into(),
117 scene: None,
118 loading: false,
119 on_action: None,
120 }
121 }
122 pub fn scene(mut self, v: EmptyScene) -> Self {
123 self.scene = Some(v);
124 self
125 }
126 pub fn loading(mut self, v: bool) -> Self {
127 self.loading = v;
128 self
129 }
130 pub fn on_action(mut self, f: impl Fn(EmptyScene, &mut Window, &mut App) + 'static) -> Self {
131 self.on_action = Some(Rc::new(f));
132 self
133 }
134}
135#[path = "empty_art.rs"]
136mod empty_art;
137use empty_art::artwork;
138
139impl RenderOnce for EmptyStates {
140 fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
141 let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, cx| State {
142 scene: self.scene.unwrap_or_default(),
143 phase: Phase::Idle,
144 from: Phase::Idle,
145 generation: 0,
146 tab_bounds: Rc::new(RefCell::new([None; 4])),
147 tab_focus: std::array::from_fn(|index| cx.focus_handle().tab_stop(index == 0)),
148 tab_scroll: ScrollHandle::new(),
149 container_width: f32::from(BlockTokens::PANEL_WIDTH),
150 });
151 if let Some(scene) = self.scene
152 && scene != state.read(cx).scene
153 {
154 state.update(cx, |s, _| {
155 s.scene = scene;
156 s.phase = Phase::Idle;
157 s.from = Phase::Idle;
158 s.generation += 1;
159 });
160 }
161 let scene = state.read(cx).scene;
162 let phase = if self.loading {
163 Phase::Loading
164 } else {
165 state.read(cx).phase
166 };
167 let colors = cx.arc_theme().colors;
168 let motion = cx.arc_theme().motion;
169 let scenes = [
172 EmptyScene::Search,
173 EmptyScene::Offline,
174 EmptyScene::Inbox,
175 EmptyScene::NotFound,
176 ];
177 let tab_bounds = state.read(cx).tab_bounds.clone();
178 let tab_focus = state.read(cx).tab_focus.clone();
179 let tab_scroll = state.read(cx).tab_scroll.clone();
180 let container_width = state.read(cx).container_width;
181 let compact = container_width <= BlockTokens::EMPTY_TABS_COMPACT_AT;
182 let tab_padding = if compact {
183 BlockTokens::EMPTY_TAB_COMPACT_PADDING
184 } else {
185 px(
186 (container_width * BlockTokens::EMPTY_TAB_PADDING_RATIO).clamp(
187 BlockTokens::EMPTY_TAB_PADDING_MIN,
188 BlockTokens::EMPTY_TAB_PADDING_MAX,
189 ),
190 )
191 };
192 let tab_text_size = if compact {
193 Typography::TEXT_XS
194 } else {
195 Typography::TEXT_SM
196 };
197 let tab_min_w = state
201 .read(cx)
202 .tab_bounds
203 .borrow()
204 .iter()
205 .flatten()
206 .map(|b| b.size.width)
207 .max()
208 .unwrap_or(px(0.0));
209 let selected_scene = scene;
210 let scope = layout_scope_key(&self.id);
211 let highlight_bg = colors.surface;
212 let highlight_border = colors.border;
213 let highlight_shadow = Shadows::resting(cx.arc_theme().mode);
214 let morph = motion.spring.morph;
215 let highlight = canvas(
216 |_, _, _| {},
217 move |list_rect, _, window, cx| {
218 let Some(tab_rect) = tab_bounds.borrow()[selected_scene.index()] else {
219 window.request_animation_frame();
220 return;
221 };
222 let target = LayoutSnapshot::uniform_radius(
223 bounds(tab_rect.origin - list_rect.origin, tab_rect.size),
224 BlockTokens::EMPTY_TAB_RADIUS,
225 );
226 let flip = sample_shared_layout(
227 scope.clone(),
228 "selection",
229 target,
230 Some(morph),
231 window,
232 cx,
233 );
234 let paint_bounds = bounds(
235 point(
236 list_rect.origin.x + flip.bounds.origin.x,
237 list_rect.origin.y + flip.bounds.origin.y,
238 ),
239 flip.bounds.size,
240 );
241 window.paint_drop_shadows(paint_bounds, flip.corner_radii, &highlight_shadow);
242 window.paint_quad(quad(
243 paint_bounds,
244 flip.corner_radii,
245 highlight_bg,
246 Edges::all(px(1.0)),
247 highlight_border,
248 BorderStyle::Solid,
249 ));
250 },
251 )
252 .absolute()
253 .inset_0();
254 let key_state = state.clone();
255 let key_focus = tab_focus.clone();
256 let key_scroll = tab_scroll.clone();
257 let mut tabs = div()
258 .id(child_id(&self.id, "tabs"))
259 .test_support()
260 .role(Role::TabList)
261 .aria_label("Empty state")
262 .relative()
263 .flex()
264 .flex_row()
265 .gap(BlockTokens::EMPTY_TABS_GAP)
270 .w_full()
271 .max_w(BlockTokens::EMPTY_TABS_WIDTH)
272 .overflow_x_scroll()
273 .track_scroll(&tab_scroll)
274 .on_key_down(move |event: &KeyDownEvent, w, cx| {
275 let index = key_state.read(cx).scene.index();
276 let next = match event.keystroke.key.as_str() {
277 "right" => (index + 1) % scenes.len(),
278 "left" => (index + scenes.len() - 1) % scenes.len(),
279 "home" => 0,
280 "end" => scenes.len() - 1,
281 "enter" | "space" => index,
282 _ => return,
283 };
284 key_state.update(cx, |s, _| s.choose(scenes[next]));
285 key_focus[next].focus(w, cx);
286 key_scroll.scroll_to_item(next + 1);
288 cx.stop_propagation();
289 w.refresh();
290 })
291 .p(BlockTokens::EMPTY_TABS_PADDING)
292 .rounded(BlockTokens::EMPTY_TABS_RADIUS)
293 .border_1()
294 .border_color(colors.border)
295 .bg(colors.surface_muted)
296 .child(highlight);
297 for next in scenes {
298 let selected = scene == next;
299 let st = state.clone();
300 let focus = tab_focus[next.index()].clone().tab_stop(selected);
301 let click_focus = focus.clone();
302 let click_scroll = tab_scroll.clone();
303 let measured = state.read(cx).tab_bounds.clone();
304 let measure_index = next.index();
305 let measure = canvas(
306 move |bounds, _, _| {
307 measured.borrow_mut()[measure_index] = Some(bounds);
308 },
309 |_, _, _, _| {},
310 )
311 .absolute()
312 .inset_0();
313 let tab = div()
316 .id(child_id(&self.id, format!("scene-{}", next.index())))
317 .test_support()
318 .role(Role::Tab)
319 .aria_selected(selected)
320 .tab_index(if selected { 0 } else { -1 })
321 .tab_stop(selected)
322 .track_focus(&focus)
323 .cursor_pointer()
324 .relative()
325 .min_h(BlockTokens::EMPTY_TAB_HEIGHT)
326 .px(tab_padding);
327 let tab = if compact {
328 tab.flex_grow(0.0).flex_shrink(0.0)
329 } else {
330 tab.flex_grow(1.0)
331 .flex_basis(px(0.0))
332 .flex_shrink(1.0)
333 .min_w(tab_min_w)
334 };
335 tabs = tabs.child(
338 tab.flex()
339 .items_center()
340 .justify_center()
341 .rounded(BlockTokens::EMPTY_TAB_RADIUS)
342 .text_size(tab_text_size)
343 .whitespace_nowrap()
344 .font_medium()
345 .text_color(if selected {
346 colors.foreground
347 } else {
348 colors.text_muted
349 })
350 .hover(|s| s.text_color(colors.foreground))
351 .on_click(move |_, w, cx| {
352 st.update(cx, |s, _| s.choose(next));
353 click_focus.focus(w, cx);
354 click_scroll.scroll_to_item(next.index() + 1);
355 w.refresh();
356 })
357 .child(measure)
358 .child(next.tab_label()),
359 );
360 }
361 let copy_done =
363 phase == Phase::Done || (phase == Phase::Loading && state.read(cx).from == Phase::Done);
364 let title = if copy_done {
365 scene.done_title()
366 } else {
367 scene.title()
368 };
369 let line = match (scene, phase) {
370 (EmptyScene::Offline, Phase::Loading) => "Reaching sync.northwind.example…",
371 (EmptyScene::Inbox, Phase::Loading) => "Checking for new mail…",
372 (EmptyScene::NotFound, Phase::Loading) => "Searching the workspace for Atlas…",
373 (EmptyScene::Search, Phase::Done) => {
374 "Filters cleared. Showing matches from every owner and status."
375 }
376 (EmptyScene::Offline, Phase::Done) => {
377 "Three edits synced to the Northwind workspace just now."
378 }
379 (EmptyScene::Inbox, Phase::Done) => {
380 "Checked just now. Nothing new since 8:30 this morning."
381 }
382 (EmptyScene::NotFound, Phase::Done) => {
383 "Atlas 2023 roadmap moved to /archive/atlas-2023 in March."
384 }
385 _ => scene.body(),
386 };
387 let title_rise = arc_spring_with_options(
390 (child_id(&self.id, "title-rise"), SharedString::from(title)),
391 0.0,
392 arc_motion::spring::SpringOptions::new(motion.spring.snappy)
393 .with_initial_value(BlockTokens::EMPTY_COPY_ENTER_Y),
394 w,
395 cx,
396 );
397 let line_rise = arc_spring_with_options(
398 (child_id(&self.id, "line-rise"), SharedString::from(line)),
399 0.0,
400 arc_motion::spring::SpringOptions::new(motion.spring.snappy)
401 .with_initial_value(BlockTokens::EMPTY_COPY_ENTER_Y),
402 w,
403 cx,
404 );
405 if !title_rise.settled || !line_rise.settled {
406 w.request_animation_frame();
407 }
408 let rise_opacity = |v: f32| (1.0 - v / BlockTokens::EMPTY_COPY_ENTER_Y).clamp(0.0, 1.0);
409 let action_label = if copy_done {
410 match scene {
411 EmptyScene::Search => "Restore filters",
412 EmptyScene::Offline => "Go offline",
413 EmptyScene::Inbox => "Check again",
414 EmptyScene::NotFound => "Show broken link",
415 }
416 } else {
417 scene.action()
418 };
419 let st = state.clone();
420 let size_state = state.clone();
421 let cb = self.on_action;
422 super::surface(cx)
423 .id(self.id.clone())
424 .role(Role::Region)
425 .aria_label("Empty states")
426 .relative()
427 .on_prepaint(move |bounds, window, cx| {
428 let width = f32::from(bounds.size.width);
429 if (size_state.read(cx).container_width - width).abs() > 0.5 {
430 size_state.update(cx, |s, _| s.container_width = width);
431 window.refresh();
432 }
433 })
434 .test_support()
435 .py(px((container_width * 0.05).clamp(16.0, 48.0)))
436 .px(px((container_width * 0.04).clamp(16.0, 40.0)))
437 .gap(px((container_width * 0.04).clamp(20.0, 32.0)))
438 .items_center()
439 .child(tabs)
440 .child(
441 div()
442 .flex()
443 .flex_col()
444 .items_center()
445 .gap(Spacing::S5)
446 .w_full()
447 .max_w(px(480.0))
448 .child(artwork(
449 &self.id,
450 scene,
451 phase,
452 container_width - 2.0 * (container_width * 0.04).clamp(16.0, 40.0) - 2.0,
453 w,
454 cx,
455 ))
456 .child(
457 div()
458 .flex()
459 .flex_col()
460 .items_center()
461 .w_full()
462 .gap(Spacing::S4)
463 .child(
464 div()
465 .flex()
466 .flex_col()
467 .items_center()
468 .id(child_id(&self.id, "copy"))
469 .test_support()
470 .gap(px(6.0))
471 .w_full()
472 .px(Spacing::S2)
473 .text_center()
474 .child(
475 div()
476 .id(child_id(&self.id, "status"))
477 .test_support()
478 .role(Role::Status)
479 .aria_label(title)
480 .text_size(if container_width >= 560.0 {
481 Typography::TEXT_XL
482 } else {
483 Typography::TEXT_LG
484 })
485 .font_medium()
486 .text_color(colors.foreground)
487 .relative()
488 .top(px(title_rise.value))
489 .opacity(rise_opacity(title_rise.value))
490 .child(title),
491 )
492 .child(
493 text(line, cx)
494 .text_size(Typography::TEXT_SM)
495 .max_w(px(360.0))
496 .relative()
497 .top(px(line_rise.value))
498 .opacity(rise_opacity(line_rise.value)),
499 ),
500 )
501 .child(
502 div().w_full().flex().justify_center().child(
503 Button::new(child_id(&self.id, "action"))
504 .label(action_label)
505 .loading(phase == Phase::Loading)
506 .disabled(phase == Phase::Loading)
507 .size(ButtonSize::Sm)
508 .on_click(move |_, w, cx| {
509 let wait = BlockTokens::EMPTY_WAITS_MS[scene.index()];
510 let generation = st.update(cx, |s, _| {
511 s.generation += 1;
512 s.from = phase;
513 s.phase = if phase == Phase::Done
514 && scene != EmptyScene::Inbox
515 {
516 Phase::Idle
517 } else if wait == 0 {
518 Phase::Done
519 } else {
520 Phase::Loading
521 };
522 s.generation
523 });
524 if st.read(cx).phase == Phase::Loading {
525 let weak = st.downgrade();
526 w.spawn(cx, async move |cx| {
527 cx.background_executor()
528 .timer(Duration::from_millis(wait))
529 .await;
530 let _ = cx.update(|w, cx| {
531 let _ = weak.update(cx, |s, _| {
532 if s.generation == generation {
533 s.phase = Phase::Done;
534 }
535 });
536 w.refresh();
537 });
538 })
539 .detach();
540 }
541 if let Some(cb) = &cb {
542 cb(scene, w, cx);
543 }
544 w.refresh();
545 }),
546 ),
547 ),
548 ),
549 )
550 .rounded(px(20.0))
551 }
552}
553#[cfg(test)]
554mod tests {
555 use super::*;
556 #[test]
557 fn scenes_have_distinct_actions_and_completion_copy() {
558 for scene in [
559 EmptyScene::Search,
560 EmptyScene::Offline,
561 EmptyScene::Inbox,
562 EmptyScene::NotFound,
563 ] {
564 assert!(!scene.action().is_empty());
565 assert_ne!(scene.title(), scene.done_title());
566 }
567 }
568}