use std::fmt;
use gpui::{div, prelude::*, AnyElement, App, Window};
use super::QueryError;
use crate::{theme::ActiveTheme, Cx};
#[derive(Clone, Debug)]
pub enum Suspend {
Pending,
Failed(QueryError),
}
impl From<QueryError> for Suspend {
fn from(error: QueryError) -> Self {
Self::Failed(error)
}
}
impl<E: std::error::Error + Send + Sync + 'static> From<E> for Suspend {
fn from(error: E) -> Self {
Self::Failed(error.into())
}
}
type Content = Box<dyn FnOnce(&mut Cx) -> Result<AnyElement, Suspend>>;
type ErrorView = Box<dyn FnOnce(&QueryError, &mut Cx) -> AnyElement>;
#[must_use = "components do nothing unless rendered as a child"]
pub struct Suspense {
content: Content,
fallback: Option<AnyElement>,
error: Option<ErrorView>,
}
impl Suspense {
pub fn new<E: IntoElement>(
content: impl FnOnce(&mut Cx) -> Result<E, Suspend> + 'static,
) -> Self {
Self {
content: Box::new(move |cx| content(cx).map(IntoElement::into_any_element)),
fallback: None,
error: None,
}
}
pub fn fallback(mut self, fallback: impl IntoElement) -> Self {
self.fallback = Some(fallback.into_any_element());
self
}
pub fn error<E: IntoElement>(
mut self,
view: impl FnOnce(&QueryError, &mut Cx) -> E + 'static,
) -> Self {
self.error = Some(Box::new(move |error, cx| {
view(error, cx).into_any_element()
}));
self
}
}
impl RenderOnce for Suspense {
fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement {
let mut cx = Cx::new(window, app);
match (self.content)(&mut cx) {
Ok(content) => content,
Err(Suspend::Pending) => self.fallback.unwrap_or_else(|| div().into_any_element()),
Err(Suspend::Failed(error)) => match self.error {
Some(view) => view(&error, &mut cx),
None => default_error_view(&error, &cx),
},
}
}
}
impl IntoElement for Suspense {
type Element = gpui::Component<Self>;
fn into_element(self) -> Self::Element {
gpui::Component::new(self)
}
}
fn default_error_view(error: &dyn fmt::Display, cx: &App) -> AnyElement {
div()
.text_color(cx.theme().colors.destructive)
.child(crate::components::BidiText::new(error.to_string()))
.into_any_element()
}
type Boundary = Box<dyn FnOnce(&mut Cx) -> AnyElement>;
#[must_use = "components do nothing unless rendered as a child"]
pub struct ErrorBoundary {
render: Boundary,
}
impl ErrorBoundary {
pub fn new<V, F, E>(
content: impl FnOnce(&mut Cx) -> Result<V, E> + 'static,
fallback: impl FnOnce(E, &mut Cx) -> F + 'static,
) -> Self
where
V: IntoElement,
F: IntoElement,
{
Self {
render: Box::new(move |cx| match content(cx) {
Ok(view) => view.into_any_element(),
Err(error) => fallback(error, cx).into_any_element(),
}),
}
}
}
impl RenderOnce for ErrorBoundary {
fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement {
(self.render)(&mut Cx::new(window, app))
}
}
impl IntoElement for ErrorBoundary {
type Element = gpui::Component<Self>;
fn into_element(self) -> Self::Element {
gpui::Component::new(self)
}
}