use crossterm::{cursor::{MoveToNextLine, MoveToPreviousLine},
terminal::{Clear, ClearType}};
use crate::{queue_commands,
throws,
ChUnit,
OutputDevice,
ResizeHint,
Size,
DEVELOPMENT_MODE};
pub trait CalculateResizeHint {
fn set_size(&mut self, new_size: Size);
fn get_resize_hint(&self) -> Option<ResizeHint>;
fn set_resize_hint(&mut self, new_size: Size);
fn clear_resize_hint(&mut self);
}
pub trait FunctionComponent<S: CalculateResizeHint> {
fn get_output_device(&mut self) -> OutputDevice;
fn calculate_header_viewport_height(&self, state: &mut S) -> ChUnit;
fn calculate_items_viewport_height(&self, state: &mut S) -> ChUnit;
fn render(&mut self, state: &mut S) -> miette::Result<()>;
fn allocate_viewport_height_space(&mut self, state: &mut S) -> miette::Result<()> {
throws!({
let viewport_height =
self.calculate_items_viewport_height(state) +
self.calculate_header_viewport_height(state);
for _ in 0..*viewport_height {
println!();
}
queue_commands! {
self.get_output_device(),
MoveToPreviousLine(*viewport_height),
};
});
}
fn clear_viewport_for_resize(&mut self, state: &mut S) -> miette::Result<()> {
throws!({
DEVELOPMENT_MODE.then(|| {
tracing::debug!(
message = "🥑🥑🥑 clear viewport for resize",
resize_hint = ?state.get_resize_hint()
);
});
let viewport_height = match state.get_resize_hint() {
Some(ResizeHint::GotBigger)
| Some(ResizeHint::NoChange)
| Some(ResizeHint::GotSmaller) => {
self.calculate_items_viewport_height(state) +
self.calculate_header_viewport_height(state)
}
None => return Ok(()),
};
for _ in 0..*viewport_height {
queue_commands! {
self.get_output_device(),
Clear(ClearType::FromCursorDown),
MoveToNextLine(1),
};
}
queue_commands! {
self.get_output_device(),
MoveToPreviousLine(*viewport_height),
};
state.clear_resize_hint();
});
}
fn clear_viewport(&mut self, state: &mut S) -> miette::Result<()> {
throws!({
let viewport_height =
self.calculate_items_viewport_height(state) +
self.calculate_header_viewport_height(state);
for _ in 0..*viewport_height {
queue_commands! {
self.get_output_device(),
Clear(ClearType::CurrentLine),
MoveToNextLine(1),
};
}
queue_commands! {
self.get_output_device(),
MoveToPreviousLine(*viewport_height),
};
});
}
}