use super::{child_id, text};
use crate::{Button, ButtonSize};
use arc_motion::{
LayoutSnapshot, arc_spring_with_options, layout::layout_scope_key, sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, BlockTokens, Shadows, Spacing, Typography};
use gpui_kit::{
App, BorderStyle, Bounds, Edges, ElementId, FocusHandle, InteractiveElement as _, IntoElement,
KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, ScrollHandle, SharedString,
StatefulInteractiveElement as _, Styled, TestSupportExt as _, Window,
base::{ElementExt as _, StyledExt as _},
bounds, canvas, div, point, px, quad,
};
use std::{cell::RefCell, rc::Rc, time::Duration};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EmptyScene {
#[default]
Search,
Offline,
Inbox,
NotFound,
}
impl EmptyScene {
fn index(self) -> usize {
match self {
Self::Search => 0,
Self::Offline => 1,
Self::Inbox => 2,
Self::NotFound => 3,
}
}
fn tab_label(self) -> &'static str {
match self {
Self::Search => "No results",
Self::Offline => "Offline",
Self::Inbox => "Caught up",
Self::NotFound => "Not found",
}
}
fn title(self) -> &'static str {
match self {
Self::Search => "No results for “Q3 roadmap”",
Self::Offline => "You are offline",
Self::Inbox => "All caught up",
Self::NotFound => "Page not found",
}
}
fn body(self) -> &'static str {
match self {
Self::Search => "Two filters are on: owner is Emma Collins and status is archived.",
Self::Offline => "Edits are saved on this device and sync when the connection returns.",
Self::Inbox => "You have read every message in Inbox. New mail lands here first.",
Self::NotFound => "The link to /projects/atlas-2023 is broken, or the page has moved.",
}
}
fn action(self) -> &'static str {
match self {
Self::Search => "Clear filters",
Self::Offline => "Try again",
Self::Inbox => "Check for mail",
Self::NotFound => "Find the page",
}
}
fn done_title(self) -> &'static str {
match self {
Self::Search => "12 results for “Q3 roadmap”",
Self::Offline => "Back online",
Self::Inbox => "Still all caught up",
Self::NotFound => "Found it in Archive",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Phase {
#[default]
Idle,
Loading,
Done,
}
struct State {
scene: EmptyScene,
phase: Phase,
from: Phase,
generation: u64,
tab_bounds: Rc<RefCell<[Option<Bounds<Pixels>>; 4]>>,
tab_focus: [FocusHandle; 4],
tab_scroll: ScrollHandle,
container_width: f32,
}
impl State {
fn choose(&mut self, scene: EmptyScene) {
if self.scene != scene {
self.scene = scene;
self.phase = Phase::Idle;
self.from = Phase::Idle;
self.generation += 1;
}
}
}
type Action = Rc<dyn Fn(EmptyScene, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct EmptyStates {
id: ElementId,
scene: Option<EmptyScene>,
loading: bool,
on_action: Option<Action>,
}
impl EmptyStates {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
scene: None,
loading: false,
on_action: None,
}
}
pub fn scene(mut self, v: EmptyScene) -> Self {
self.scene = Some(v);
self
}
pub fn loading(mut self, v: bool) -> Self {
self.loading = v;
self
}
pub fn on_action(mut self, f: impl Fn(EmptyScene, &mut Window, &mut App) + 'static) -> Self {
self.on_action = Some(Rc::new(f));
self
}
}
#[path = "empty_art.rs"]
mod empty_art;
use empty_art::artwork;
impl RenderOnce for EmptyStates {
fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, cx| State {
scene: self.scene.unwrap_or_default(),
phase: Phase::Idle,
from: Phase::Idle,
generation: 0,
tab_bounds: Rc::new(RefCell::new([None; 4])),
tab_focus: std::array::from_fn(|index| cx.focus_handle().tab_stop(index == 0)),
tab_scroll: ScrollHandle::new(),
container_width: f32::from(BlockTokens::PANEL_WIDTH),
});
if let Some(scene) = self.scene
&& scene != state.read(cx).scene
{
state.update(cx, |s, _| {
s.scene = scene;
s.phase = Phase::Idle;
s.from = Phase::Idle;
s.generation += 1;
});
}
let scene = state.read(cx).scene;
let phase = if self.loading {
Phase::Loading
} else {
state.read(cx).phase
};
let colors = cx.arc_theme().colors;
let motion = cx.arc_theme().motion;
let scenes = [
EmptyScene::Search,
EmptyScene::Offline,
EmptyScene::Inbox,
EmptyScene::NotFound,
];
let tab_bounds = state.read(cx).tab_bounds.clone();
let tab_focus = state.read(cx).tab_focus.clone();
let tab_scroll = state.read(cx).tab_scroll.clone();
let container_width = state.read(cx).container_width;
let compact = container_width <= BlockTokens::EMPTY_TABS_COMPACT_AT;
let tab_padding = if compact {
BlockTokens::EMPTY_TAB_COMPACT_PADDING
} else {
px(
(container_width * BlockTokens::EMPTY_TAB_PADDING_RATIO).clamp(
BlockTokens::EMPTY_TAB_PADDING_MIN,
BlockTokens::EMPTY_TAB_PADDING_MAX,
),
)
};
let tab_text_size = if compact {
Typography::TEXT_XS
} else {
Typography::TEXT_SM
};
let tab_min_w = state
.read(cx)
.tab_bounds
.borrow()
.iter()
.flatten()
.map(|b| b.size.width)
.max()
.unwrap_or(px(0.0));
let selected_scene = scene;
let scope = layout_scope_key(&self.id);
let highlight_bg = colors.surface;
let highlight_border = colors.border;
let highlight_shadow = Shadows::resting(cx.arc_theme().mode);
let morph = motion.spring.morph;
let highlight = canvas(
|_, _, _| {},
move |list_rect, _, window, cx| {
let Some(tab_rect) = tab_bounds.borrow()[selected_scene.index()] else {
window.request_animation_frame();
return;
};
let target = LayoutSnapshot::uniform_radius(
bounds(tab_rect.origin - list_rect.origin, tab_rect.size),
BlockTokens::EMPTY_TAB_RADIUS,
);
let flip = sample_shared_layout(
scope.clone(),
"selection",
target,
Some(morph),
window,
cx,
);
let paint_bounds = bounds(
point(
list_rect.origin.x + flip.bounds.origin.x,
list_rect.origin.y + flip.bounds.origin.y,
),
flip.bounds.size,
);
window.paint_drop_shadows(paint_bounds, flip.corner_radii, &highlight_shadow);
window.paint_quad(quad(
paint_bounds,
flip.corner_radii,
highlight_bg,
Edges::all(px(1.0)),
highlight_border,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let key_state = state.clone();
let key_focus = tab_focus.clone();
let key_scroll = tab_scroll.clone();
let mut tabs = div()
.id(child_id(&self.id, "tabs"))
.test_support()
.role(Role::TabList)
.aria_label("Empty state")
.relative()
.flex()
.flex_row()
.gap(BlockTokens::EMPTY_TABS_GAP)
.w_full()
.max_w(BlockTokens::EMPTY_TABS_WIDTH)
.overflow_x_scroll()
.track_scroll(&tab_scroll)
.on_key_down(move |event: &KeyDownEvent, w, cx| {
let index = key_state.read(cx).scene.index();
let next = match event.keystroke.key.as_str() {
"right" => (index + 1) % scenes.len(),
"left" => (index + scenes.len() - 1) % scenes.len(),
"home" => 0,
"end" => scenes.len() - 1,
"enter" | "space" => index,
_ => return,
};
key_state.update(cx, |s, _| s.choose(scenes[next]));
key_focus[next].focus(w, cx);
key_scroll.scroll_to_item(next + 1);
cx.stop_propagation();
w.refresh();
})
.p(BlockTokens::EMPTY_TABS_PADDING)
.rounded(BlockTokens::EMPTY_TABS_RADIUS)
.border_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.child(highlight);
for next in scenes {
let selected = scene == next;
let st = state.clone();
let focus = tab_focus[next.index()].clone().tab_stop(selected);
let click_focus = focus.clone();
let click_scroll = tab_scroll.clone();
let measured = state.read(cx).tab_bounds.clone();
let measure_index = next.index();
let measure = canvas(
move |bounds, _, _| {
measured.borrow_mut()[measure_index] = Some(bounds);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let tab = div()
.id(child_id(&self.id, format!("scene-{}", next.index())))
.test_support()
.role(Role::Tab)
.aria_selected(selected)
.tab_index(if selected { 0 } else { -1 })
.tab_stop(selected)
.track_focus(&focus)
.cursor_pointer()
.relative()
.min_h(BlockTokens::EMPTY_TAB_HEIGHT)
.px(tab_padding);
let tab = if compact {
tab.flex_grow(0.0).flex_shrink(0.0)
} else {
tab.flex_grow(1.0)
.flex_basis(px(0.0))
.flex_shrink(1.0)
.min_w(tab_min_w)
};
tabs = tabs.child(
tab.flex()
.items_center()
.justify_center()
.rounded(BlockTokens::EMPTY_TAB_RADIUS)
.text_size(tab_text_size)
.whitespace_nowrap()
.font_medium()
.text_color(if selected {
colors.foreground
} else {
colors.text_muted
})
.hover(|s| s.text_color(colors.foreground))
.on_click(move |_, w, cx| {
st.update(cx, |s, _| s.choose(next));
click_focus.focus(w, cx);
click_scroll.scroll_to_item(next.index() + 1);
w.refresh();
})
.child(measure)
.child(next.tab_label()),
);
}
let copy_done =
phase == Phase::Done || (phase == Phase::Loading && state.read(cx).from == Phase::Done);
let title = if copy_done {
scene.done_title()
} else {
scene.title()
};
let line = match (scene, phase) {
(EmptyScene::Offline, Phase::Loading) => "Reaching sync.northwind.example…",
(EmptyScene::Inbox, Phase::Loading) => "Checking for new mail…",
(EmptyScene::NotFound, Phase::Loading) => "Searching the workspace for Atlas…",
(EmptyScene::Search, Phase::Done) => {
"Filters cleared. Showing matches from every owner and status."
}
(EmptyScene::Offline, Phase::Done) => {
"Three edits synced to the Northwind workspace just now."
}
(EmptyScene::Inbox, Phase::Done) => {
"Checked just now. Nothing new since 8:30 this morning."
}
(EmptyScene::NotFound, Phase::Done) => {
"Atlas 2023 roadmap moved to /archive/atlas-2023 in March."
}
_ => scene.body(),
};
let title_rise = arc_spring_with_options(
(child_id(&self.id, "title-rise"), SharedString::from(title)),
0.0,
arc_motion::spring::SpringOptions::new(motion.spring.snappy)
.with_initial_value(BlockTokens::EMPTY_COPY_ENTER_Y),
w,
cx,
);
let line_rise = arc_spring_with_options(
(child_id(&self.id, "line-rise"), SharedString::from(line)),
0.0,
arc_motion::spring::SpringOptions::new(motion.spring.snappy)
.with_initial_value(BlockTokens::EMPTY_COPY_ENTER_Y),
w,
cx,
);
if !title_rise.settled || !line_rise.settled {
w.request_animation_frame();
}
let rise_opacity = |v: f32| (1.0 - v / BlockTokens::EMPTY_COPY_ENTER_Y).clamp(0.0, 1.0);
let action_label = if copy_done {
match scene {
EmptyScene::Search => "Restore filters",
EmptyScene::Offline => "Go offline",
EmptyScene::Inbox => "Check again",
EmptyScene::NotFound => "Show broken link",
}
} else {
scene.action()
};
let st = state.clone();
let size_state = state.clone();
let cb = self.on_action;
super::surface(cx)
.id(self.id.clone())
.role(Role::Region)
.aria_label("Empty states")
.relative()
.on_prepaint(move |bounds, window, cx| {
let width = f32::from(bounds.size.width);
if (size_state.read(cx).container_width - width).abs() > 0.5 {
size_state.update(cx, |s, _| s.container_width = width);
window.refresh();
}
})
.test_support()
.py(px((container_width * 0.05).clamp(16.0, 48.0)))
.px(px((container_width * 0.04).clamp(16.0, 40.0)))
.gap(px((container_width * 0.04).clamp(20.0, 32.0)))
.items_center()
.child(tabs)
.child(
div()
.flex()
.flex_col()
.items_center()
.gap(Spacing::S5)
.w_full()
.max_w(px(480.0))
.child(artwork(
&self.id,
scene,
phase,
container_width - 2.0 * (container_width * 0.04).clamp(16.0, 40.0) - 2.0,
w,
cx,
))
.child(
div()
.flex()
.flex_col()
.items_center()
.w_full()
.gap(Spacing::S4)
.child(
div()
.flex()
.flex_col()
.items_center()
.id(child_id(&self.id, "copy"))
.test_support()
.gap(px(6.0))
.w_full()
.px(Spacing::S2)
.text_center()
.child(
div()
.id(child_id(&self.id, "status"))
.test_support()
.role(Role::Status)
.aria_label(title)
.text_size(if container_width >= 560.0 {
Typography::TEXT_XL
} else {
Typography::TEXT_LG
})
.font_medium()
.text_color(colors.foreground)
.relative()
.top(px(title_rise.value))
.opacity(rise_opacity(title_rise.value))
.child(title),
)
.child(
text(line, cx)
.text_size(Typography::TEXT_SM)
.max_w(px(360.0))
.relative()
.top(px(line_rise.value))
.opacity(rise_opacity(line_rise.value)),
),
)
.child(
div().w_full().flex().justify_center().child(
Button::new(child_id(&self.id, "action"))
.label(action_label)
.loading(phase == Phase::Loading)
.disabled(phase == Phase::Loading)
.size(ButtonSize::Sm)
.on_click(move |_, w, cx| {
let wait = BlockTokens::EMPTY_WAITS_MS[scene.index()];
let generation = st.update(cx, |s, _| {
s.generation += 1;
s.from = phase;
s.phase = if phase == Phase::Done
&& scene != EmptyScene::Inbox
{
Phase::Idle
} else if wait == 0 {
Phase::Done
} else {
Phase::Loading
};
s.generation
});
if st.read(cx).phase == Phase::Loading {
let weak = st.downgrade();
w.spawn(cx, async move |cx| {
cx.background_executor()
.timer(Duration::from_millis(wait))
.await;
let _ = cx.update(|w, cx| {
let _ = weak.update(cx, |s, _| {
if s.generation == generation {
s.phase = Phase::Done;
}
});
w.refresh();
});
})
.detach();
}
if let Some(cb) = &cb {
cb(scene, w, cx);
}
w.refresh();
}),
),
),
),
)
.rounded(px(20.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scenes_have_distinct_actions_and_completion_copy() {
for scene in [
EmptyScene::Search,
EmptyScene::Offline,
EmptyScene::Inbox,
EmptyScene::NotFound,
] {
assert!(!scene.action().is_empty());
assert_ne!(scene.title(), scene.done_title());
}
}
}