use futures::{
FutureExt,
future::{Either, select},
};
use std::io::{self};
use crate::{
ElementKey,
component::{ComponentHelperExt, InstantiatedComponent},
context::{ContextStack, SystemContext},
element::ElementRepr,
props::AnyProps,
terminal::{CrossTerminal, Terminal, TerminalImpl, UpdaterTerminal},
};
use super::ComponentDrawer;
struct RestoreGuard;
impl Drop for RestoreGuard {
fn drop(&mut self) {
ratatui::restore();
}
}
pub struct Tree<'a> {
root_component: InstantiatedComponent,
props: AnyProps<'a>,
system_context: SystemContext,
}
impl<'a> Tree<'a> {
pub(crate) fn new(mut props: AnyProps<'a>, helper: Box<dyn ComponentHelperExt>) -> Self {
Tree {
root_component: InstantiatedComponent::new(
ElementKey::user("_root_tree_"),
props.borrow(),
helper,
),
props,
system_context: SystemContext::new(),
}
}
pub(crate) fn update_once(&mut self, terminal: &mut dyn UpdaterTerminal) {
self.system_context.input.begin_frame();
let mut component_context_stack = ContextStack::root(&mut self.system_context);
self.root_component
.update(terminal, &mut component_context_stack, self.props.borrow());
}
pub(crate) fn draw_root(&mut self, drawer: &mut ComponentDrawer) {
self.root_component.draw(drawer);
}
fn render(&mut self, terminal: &mut Terminal) -> io::Result<()> {
self.update_once(terminal);
terminal.draw(|frame| {
let area = frame.area();
let mut drawer = ComponentDrawer::new(frame, area);
self.draw_root(&mut drawer);
})?;
Ok(())
}
async fn render_loop(&mut self, terminal: &mut Terminal) -> io::Result<()> {
loop {
self.render(terminal)?;
if self.system_context.should_exit() {
break;
}
match select(
self.root_component.wait().boxed_local(),
terminal.next_event().boxed_local(),
)
.await
{
Either::Left(((), _)) => continue,
Either::Right((Some(event), _)) => {
if CrossTerminal::received_ctrl_c(event.clone()) {
break;
}
self.system_context.input.dispatch(event);
continue;
}
Either::Right((None, _)) => break,
}
}
Ok(())
}
}
pub(crate) async fn render_loop<E: ElementRepr>(
mut element: E,
mut terminal: Terminal,
) -> io::Result<()> {
let helper = element.helper();
let mut tree = Tree::new(element.props_mut(), helper);
let _restore_guard = RestoreGuard;
tree.render_loop(&mut terminal).await
}