use std::{cell::RefCell, rc::Rc};
use futures::{channel::mpsc, StreamExt as _};
use gpui::{prelude::*, AnyElement, App, ElementId, Task, Window};
use rok_ui_bloc::{Observable, Subscription};
use crate::{hooks::use_keyed_state, scope::single};
type Build<S> = Box<dyn FnOnce(&S, &mut Window, &mut App) -> AnyElement>;
type When<S> = Rc<dyn Fn(&S, &S) -> bool>;
#[derive(IntoElement)]
pub struct BlocBuilder<O: Observable> {
source: O,
build: Build<O::State>,
build_when: Option<When<O::State>>,
key: ElementId,
}
impl<O: Observable> BlocBuilder<O> {
#[track_caller]
#[must_use]
pub fn new<E: IntoElement>(
source: &O,
build: impl FnOnce(&O::State, &mut Window, &mut App) -> E + 'static,
) -> Self {
Self {
source: source.clone(),
build: Box::new(move |state, window, cx| build(state, window, cx).into_any_element()),
build_when: None,
key: ElementId::CodeLocation(*std::panic::Location::caller()),
}
}
#[must_use]
pub fn build_when(mut self, when: impl Fn(&O::State, &O::State) -> bool + 'static) -> Self {
self.build_when = Some(Rc::new(when));
self
}
#[must_use]
pub fn key(mut self, key: impl Into<ElementId>) -> Self {
self.key = key.into();
self
}
}
impl<O: Observable> RenderOnce for BlocBuilder<O> {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let current = self.source.state();
let shown = match self.build_when {
None => current,
Some(when) => {
let shown = use_keyed_state(self.key, window, cx, || current.clone());
let previous = shown.read(cx).clone();
if previous != current && when(&previous, ¤t) {
shown.update(cx, |shown| *shown = current.clone());
}
shown.read(cx).clone()
}
};
(self.build)(&shown, window, cx)
}
}
#[derive(IntoElement)]
pub struct BlocSelector<O: Observable> {
build: Build<O::State>,
source: O,
}
impl<O: Observable> BlocSelector<O> {
#[must_use]
pub fn new<T: 'static, E: IntoElement>(
source: &O,
select: impl Fn(&O::State) -> T + 'static,
build: impl FnOnce(&T, &mut Window, &mut App) -> E + 'static,
) -> Self {
Self {
build: Box::new(move |state, window, cx| {
build(&select(state), window, cx).into_any_element()
}),
source: source.clone(),
}
}
}
impl<O: Observable> RenderOnce for BlocSelector<O> {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
(self.build)(&self.source.state(), window, cx)
}
}
type Listen<S> = Rc<dyn Fn(&S, &mut Window, &mut App)>;
struct Callbacks<S> {
listen: Listen<S>,
when: Option<When<S>>,
}
struct Listening<S> {
callbacks: Rc<RefCell<Callbacks<S>>>,
_subscription: Subscription,
_task: Task<()>,
}
#[derive(IntoElement)]
pub struct BlocListener<O: Observable> {
source: O,
listen: Listen<O::State>,
when: Option<When<O::State>>,
key: ElementId,
children: Vec<AnyElement>,
}
impl<O: Observable> BlocListener<O> {
#[track_caller]
#[must_use]
pub fn new(source: &O, listen: impl Fn(&O::State, &mut Window, &mut App) + 'static) -> Self {
Self {
source: source.clone(),
listen: Rc::new(listen),
when: None,
key: ElementId::CodeLocation(*std::panic::Location::caller()),
children: Vec::new(),
}
}
#[must_use]
pub fn listen_when(mut self, when: impl Fn(&O::State, &O::State) -> bool + 'static) -> Self {
self.when = Some(Rc::new(when));
self
}
#[must_use]
pub fn key(mut self, key: impl Into<ElementId>) -> Self {
self.key = key.into();
self
}
}
impl<O: Observable> ParentElement for BlocListener<O> {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl<O: Observable> RenderOnce for BlocListener<O> {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let callbacks = Callbacks {
listen: self.listen,
when: self.when,
};
let source = self.source;
let state = use_keyed_state(self.key, window, cx, || None::<Listening<O::State>>);
let existing = state
.read(cx)
.as_ref()
.map(|listening| listening.callbacks.clone());
if let Some(existing) = existing {
*existing.borrow_mut() = callbacks;
} else {
let callbacks = Rc::new(RefCell::new(callbacks));
let (sender, mut states) = mpsc::unbounded::<O::State>();
let subscription = source.subscribe(move |state| {
sender.unbounded_send(state.clone()).ok();
});
let mut previous = source.state();
let delivered = callbacks.clone();
let task = window.spawn(cx, async move |cx| {
while let Some(current) = states.next().await {
let callbacks = delivered.clone();
let accepted = callbacks
.borrow()
.when
.as_ref()
.is_none_or(|when| when(&previous, ¤t));
if accepted {
let listen = callbacks.borrow().listen.clone();
if cx
.update(|window, cx| listen(¤t, window, cx))
.is_err()
{
return;
}
}
previous = current;
}
});
state.update(cx, |slot| {
*slot = Some(Listening {
callbacks,
_subscription: subscription,
_task: task,
});
});
}
single(self.children)
}
}
#[derive(IntoElement)]
pub struct BlocConsumer<O: Observable> {
listener: BlocListener<O>,
builder: BlocBuilder<O>,
}
impl<O: Observable> BlocConsumer<O> {
#[track_caller]
#[must_use]
pub fn new<E: IntoElement>(
source: &O,
listen: impl Fn(&O::State, &mut Window, &mut App) + 'static,
build: impl FnOnce(&O::State, &mut Window, &mut App) -> E + 'static,
) -> Self {
let location = *std::panic::Location::caller();
let mut listener = BlocListener::new(source, listen);
listener.key = ElementId::NamedChild(
Box::new(ElementId::CodeLocation(location)),
"listener".into(),
);
let mut builder = BlocBuilder::new(source, build);
builder.key = ElementId::NamedChild(
Box::new(ElementId::CodeLocation(location)),
"builder".into(),
);
Self { listener, builder }
}
#[must_use]
pub fn listen_when(mut self, when: impl Fn(&O::State, &O::State) -> bool + 'static) -> Self {
self.listener = self.listener.listen_when(when);
self
}
#[must_use]
pub fn build_when(mut self, when: impl Fn(&O::State, &O::State) -> bool + 'static) -> Self {
self.builder = self.builder.build_when(when);
self
}
}
impl<O: Observable> RenderOnce for BlocConsumer<O> {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
self.listener.child(self.builder)
}
}