diff --git a/bin/commands/inbox/select.rs b/bin/commands/inbox/select.rs index d80b4a17..7878e8d8 100644 --- a/bin/commands/inbox/select.rs +++ b/bin/commands/inbox/select.rs @@ -19,7 +19,7 @@ use tui::store; use tui::store::StateValue; use tui::ui::items::{Filter, NotificationItem, NotificationItemFilter}; use tui::ui::widget::window::{Window, WindowProps}; -use tui::ui::widget::{Properties, Widget}; +use tui::ui::widget::{Properties, View}; use tui::Channel; use tui::Exit; diff --git a/bin/commands/inbox/select/ui.rs b/bin/commands/inbox/select/ui.rs index f10f09f6..1c20f000 100644 --- a/bin/commands/inbox/select/ui.rs +++ b/bin/commands/inbox/select/ui.rs @@ -22,7 +22,7 @@ use tui::ui::widget::input::{TextField, TextFieldProps}; use tui::ui::widget::list::{Table, TableProps, TableUtils}; use tui::ui::widget::text::{Paragraph, ParagraphProps}; use tui::ui::widget::window::{Shortcuts, ShortcutsProps}; -use tui::ui::widget::{BoxedAny, Properties, RenderProps, Widget, WidgetBase}; +use tui::ui::widget::{BoxedAny, Properties, RenderProps, View, WidgetBase}; use tui::Selection; @@ -122,7 +122,7 @@ pub struct Browser<'a> { search: BoxedWidget, } -impl<'a: 'static> Widget for Browser<'a> { +impl<'a: 'static> View for Browser<'a> { type Message = Message; type State = State; @@ -315,7 +315,7 @@ pub struct BrowserPage<'a> { shortcuts: BoxedWidget, } -impl<'a: 'static> Widget for BrowserPage<'a> { +impl<'a: 'static> View for BrowserPage<'a> { type Message = Message; type State = State; @@ -410,7 +410,7 @@ pub struct Search { input: BoxedWidget, } -impl Widget for Search { +impl View for Search { type Message = Message; type State = State; @@ -513,7 +513,7 @@ pub struct HelpPage<'a> { shortcuts: BoxedWidget, } -impl<'a: 'static> Widget for HelpPage<'a> { +impl<'a: 'static> View for HelpPage<'a> { type Message = Message; type State = State; diff --git a/bin/commands/issue/select.rs b/bin/commands/issue/select.rs index d3960753..5874bf36 100644 --- a/bin/commands/issue/select.rs +++ b/bin/commands/issue/select.rs @@ -15,7 +15,7 @@ use tui::cob::issue; use tui::store::StateValue; use tui::ui::items::{Filter, IssueItem, IssueItemFilter}; use tui::ui::widget::window::{Window, WindowProps}; -use tui::ui::widget::{Properties, Widget}; +use tui::ui::widget::{Properties, View}; use tui::Channel; use tui::Exit; diff --git a/bin/commands/issue/select/ui.rs b/bin/commands/issue/select/ui.rs index fd16f781..58564992 100644 --- a/bin/commands/issue/select/ui.rs +++ b/bin/commands/issue/select/ui.rs @@ -24,7 +24,7 @@ use tui::ui::widget::input::{TextField, TextFieldProps}; use tui::ui::widget::list::{Table, TableProps, TableUtils}; use tui::ui::widget::text::{Paragraph, ParagraphProps}; use tui::ui::widget::window::{Shortcuts, ShortcutsProps}; -use tui::ui::widget::{BoxedAny, Properties, RenderProps, Widget, WidgetBase}; +use tui::ui::widget::{BoxedAny, Properties, RenderProps, View, WidgetBase}; use tui::Selection; @@ -142,7 +142,7 @@ pub struct Browser<'a> { search: BoxedWidget, } -impl<'a: 'static> Widget for Browser<'a> { +impl<'a: 'static> View for Browser<'a> { type Message = Message; type State = State; @@ -275,7 +275,7 @@ impl<'a: 'static> Widget for Browser<'a> { self.search .render(frame, RenderProps::from(search_area).focus(props.focus)); } else { - self.issues.render(frame, props); + self.issues.render(frame, frame, props); } } @@ -334,7 +334,7 @@ pub struct BrowserPage<'a> { shortcuts: BoxedWidget, } -impl<'a: 'static> Widget for BrowserPage<'a> { +impl<'a: 'static> View for BrowserPage<'a> { type Message = Message; type State = State; @@ -429,7 +429,7 @@ pub struct Search { input: BoxedWidget, } -impl Widget for Search { +impl View for Search { type Message = Message; type State = State; @@ -529,7 +529,7 @@ pub struct HelpPage<'a> { shortcuts: BoxedWidget, } -impl<'a: 'static> Widget for HelpPage<'a> { +impl<'a: 'static> View for HelpPage<'a> { type Message = Message; type State = State; diff --git a/bin/commands/patch/select.rs b/bin/commands/patch/select.rs index 9e0f8366..56386e81 100644 --- a/bin/commands/patch/select.rs +++ b/bin/commands/patch/select.rs @@ -15,7 +15,7 @@ use tui::cob::patch; use tui::store; use tui::ui::items::{Filter, PatchItem, PatchItemFilter}; use tui::ui::widget::window::{Window, WindowProps}; -use tui::ui::widget::{Properties, Widget}; +use tui::ui::widget::{Properties, View}; use tui::Channel; use tui::Exit; diff --git a/bin/commands/patch/select/ui.rs b/bin/commands/patch/select/ui.rs index c4643a13..9ab63643 100644 --- a/bin/commands/patch/select/ui.rs +++ b/bin/commands/patch/select/ui.rs @@ -25,7 +25,7 @@ use tui::ui::widget::input::{TextField, TextFieldProps}; use tui::ui::widget::list::{Table, TableProps, TableUtils}; use tui::ui::widget::text::{Paragraph, ParagraphProps}; use tui::ui::widget::window::{Shortcuts, ShortcutsProps}; -use tui::ui::widget::{BoxedAny, Properties, RenderProps, Widget, WidgetBase}; +use tui::ui::widget::{BoxedAny, Properties, RenderProps, View, WidgetBase}; use tui::Selection; @@ -142,7 +142,7 @@ pub struct Browser<'a> { search: BoxedWidget, } -impl<'a: 'static> Widget for Browser<'a> { +impl<'a: 'static> View for Browser<'a> { type Message = Message; type State = State; @@ -357,7 +357,7 @@ pub struct BrowserPage<'a> { shortcuts: BoxedWidget, } -impl<'a: 'static> Widget for BrowserPage<'a> { +impl<'a: 'static> View for BrowserPage<'a> { type Message = Message; type State = State; @@ -452,7 +452,7 @@ pub struct Search { input: BoxedWidget, } -impl Widget for Search { +impl View for Search { type Message = Message; type State = State; @@ -552,7 +552,7 @@ pub struct HelpPage<'a> { shortcuts: BoxedWidget, } -impl<'a: 'static> Widget for HelpPage<'a> { +impl<'a: 'static> View for HelpPage<'a> { type Message = Message; type State = State; diff --git a/examples/hello.rs b/examples/hello.rs index 0bb89379..8f132281 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -5,8 +5,8 @@ use radicle_tui as tui; use termion::event::Key; use tui::store; use tui::ui::widget::text::{Paragraph, ParagraphProps}; -use tui::ui::widget::{Properties, Widget}; -use tui::{Channel, Exit}; +use tui::ui::widget::ToWidget; +use tui::{BoxedAny, Channel, Exit}; #[derive(Clone, Debug)] struct State { @@ -41,22 +41,19 @@ pub async fn main() -> Result<()> { welcome: "Hello TUI".to_string(), }; - let welcome = Paragraph::new(&state, channel.tx.clone()) - .on_update(|state| { + let welcome = Paragraph::default() + .to_widget(channel.tx.clone()) + .on_update(|state: &State| { ParagraphProps::default() .text(&state.welcome.clone().into()) - .to_boxed() + .to_boxed_any() + .into() }) - .on_event(|paragraph, key| { - paragraph - .downcast_mut::>() - .and_then(|paragraph| match key { - Key::Char('r') => paragraph.send(Message::ReverseWelcome).ok(), - Key::Char('q') => paragraph.send(Message::Quit).ok(), - _ => None, - }); - }) - .to_boxed(); + .on_event(|_, key| match key { + Key::Char('r') => Some(Message::ReverseWelcome), + Key::Char('q') => Some(Message::Quit), + _ => None, + }); tui::run(channel, state, welcome).await?; diff --git a/src/lib.rs b/src/lib.rs index cfac989e..a6f0cc94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,15 +8,19 @@ pub mod task; pub mod terminal; pub mod ui; +use std::any::Any; use std::fmt::Debug; +use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; + +use serde::ser::{Serialize, SerializeStruct, Serializer}; + use anyhow::Result; -use serde::ser::{Serialize, SerializeStruct, Serializer}; use store::State; use task::Interrupted; -use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; -use ui::{widget::Widget, Frontend}; +use ui::widget::Widget; +use ui::Frontend; /// An optional return value. #[derive(Clone, Debug)] @@ -74,6 +78,36 @@ where } } +/// Provide implementations for conversions to and from `Box`. +pub trait BoxedAny { + fn from_boxed_any(any: Box) -> Option + where + Self: Sized + Clone + 'static; + + fn to_boxed_any(self) -> Box + where + Self: Sized + Clone + 'static; +} + +impl BoxedAny for T +where + T: Sized + Clone + 'static, +{ + fn from_boxed_any(any: Box) -> Option + where + Self: Sized + Clone + 'static, + { + any.downcast::().ok().map(|b| *b) + } + + fn to_boxed_any(self) -> Box + where + Self: Sized + Clone + 'static, + { + Box::new(self) + } +} + /// A 'PageStack' for applications. Page identifier can be pushed to and /// popped from the stack. #[derive(Clone, Default, Debug)] @@ -120,20 +154,20 @@ impl Default for Channel { /// Initialize a `Store` with the `State` given and a `Frontend` with the `Widget` given, /// and run their main loops concurrently. Connect them to the `Channel` and also to /// an interrupt broadcast channel also initialized in this function. -pub async fn run(channel: Channel, state: S, root: Box) -> Result> +pub async fn run(channel: Channel, state: S, root: Widget) -> Result> where S: State + Clone + Debug + Send + Sync + 'static, - W: Widget, + M: 'static, P: Clone + Debug + Send + Sync + 'static, { let (terminator, mut interrupt_rx) = task::create_termination(); let (store, state_rx) = store::Store::::new(); - let frontend = Frontend::::new(channel.tx.clone()); + let frontend = Frontend::default(); tokio::try_join!( store.main_loop(state, terminator, channel.rx, interrupt_rx.resubscribe()), - frontend.main_loop(Some(*root), state_rx, interrupt_rx.resubscribe()), + frontend.main_loop(root, state_rx, interrupt_rx.resubscribe()), )?; if let Ok(reason) = interrupt_rx.recv().await { diff --git a/src/ui.rs b/src/ui.rs index 843eae30..2e0909bd 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -10,16 +10,16 @@ use std::fmt::Debug; use std::time::Duration; use tokio::sync::broadcast; -use tokio::sync::mpsc; use tokio::sync::mpsc::UnboundedReceiver; use crate::ui::widget::RenderProps; +use self::widget::Widget; + use super::event::Event; use super::store::State; use super::task::Interrupted; use super::terminal; -use super::ui::widget::Widget; const RENDERING_TICK_RATE: Duration = Duration::from_millis(250); const INLINE_HEIGHT: usize = 20; @@ -29,16 +29,10 @@ const INLINE_HEIGHT: usize = 20; /// /// Once created and run with `main_loop`, the `Frontend` will wait for new messages /// being sent on either the terminal event, the state or the interrupt message channel. -pub struct Frontend { - tx: mpsc::UnboundedSender, -} - -impl Frontend { - /// Create a new `Frontend` storing the sending end of a message channel. - pub fn new(tx: mpsc::UnboundedSender) -> Self { - Self { tx: tx.clone() } - } +#[derive(Default)] +pub struct Frontend {} +impl Frontend { /// By calling `main_loop`, the `Frontend` will wait for new messages being sent /// on either the terminal event, the state or the interrupt message channel. /// After all, it will draw the (potentially) updated root widget. @@ -53,15 +47,15 @@ impl Frontend { /// /// Interrupt messages are being sent to broadcast channel for retrieving the /// application kill signal. - pub async fn main_loop( + pub async fn main_loop( self, - root: Option, + mut root: Widget, mut state_rx: UnboundedReceiver, mut interrupt_rx: broadcast::Receiver>, ) -> anyhow::Result> where - S: State

, - W: Widget, + S: State

+ 'static, + M: 'static, P: Clone + Send + Sync + Debug, { let mut ticker = tokio::time::interval(RENDERING_TICK_RATE); @@ -72,13 +66,8 @@ impl Frontend { let mut root = { let state = state_rx.recv().await.unwrap(); - match root { - Some(mut root) => { - root.update(&state); - root - } - None => W::new(&state, self.tx.clone()), - } + root.update(&state); + root }; let result: anyhow::Result> = loop { diff --git a/src/ui/items.rs b/src/ui/items.rs index 5b90ba6a..95c396fe 100644 --- a/src/ui/items.rs +++ b/src/ui/items.rs @@ -22,9 +22,13 @@ use ratatui::widgets::Cell; use super::super::git; use super::theme::style; -use super::widget::ToRow; use super::{format, span}; +/// Needs to be implemented for items that are supposed to be rendered in tables. +pub trait ToRow { + fn to_row(&self) -> [Cell; W]; +} + pub trait Filter { fn matches(&self, item: &T) -> bool; } diff --git a/src/ui/widget.rs b/src/ui/widget.rs index 05e2eda4..6e3918b6 100644 --- a/src/ui/widget.rs +++ b/src/ui/widget.rs @@ -6,48 +6,70 @@ pub mod window; use std::any::Any; -use tokio::sync::mpsc::error::SendError; use tokio::sync::mpsc::UnboundedSender; use termion::event::Key; use ratatui::prelude::*; -use ratatui::widgets::Cell; -pub type BoxedWidget = Box>; +pub type BoxedView = Box>; +pub type UpdateCallback = fn(&S) -> ViewProps; +pub type EventCallback = fn(Option<&ViewState>, Key) -> Option; -pub type UpdateCallback = fn(&S) -> Box; -pub type EventCallback = fn(&mut dyn Any, Key); - -/// A `WidgetBase` provides common functionality to a `Widget`. It's used to store -/// event and update callbacks as well sending messages to the UI's message channel. -pub struct WidgetBase { - /// Message sender - pub tx: UnboundedSender, - /// Custom update handler - pub on_update: Option>, - /// Additional custom event handler - pub on_event: Option, +/// `ViewProps` are properties of a `View`. They define a `View`s data, configuration etc. +/// Since the framework itself does not know the concrete type of `View`, it also does not +/// know the concrete type of a `View`s properties. +/// Hence, view properties are stored inside a `Box` and downcasted to the concrete +/// type when needed. +pub struct ViewProps { + inner: Box, } -impl WidgetBase { - /// Create a new `WidgetBase` with no callbacks set. - pub fn new(tx: UnboundedSender) -> Self { +impl ViewProps { + pub fn new(inner: &'static dyn Any) -> Self { Self { - tx: tx.clone(), - on_update: None, - on_event: None, + inner: Box::new(inner), } } - /// Send a message to the internal channel. - pub fn send(&self, message: M) -> Result<(), SendError> { - self.tx.send(message) + pub fn inner(self) -> Option + where + T: Clone + 'static, + { + self.inner.downcast::().ok().map(|inner| *inner) } } -/// General properties that specify how a `Widget` is rendered. -/// They can be passed to a widgets' `render` function. +impl From> for ViewProps { + fn from(props: Box) -> Self { + ViewProps { inner: props } + } +} + +/// A `ViewState` is the representation of a `View`s internal state. e.g. current +/// table selection or contents of a text field. +pub enum ViewState { + USize(usize), + String(String), +} + +impl ViewState { + pub fn unwrap_usize(&self) -> Option { + match self { + ViewState::USize(value) => Some(*value), + _ => None, + } + } + + pub fn unwrap_string(&self) -> Option { + match self { + ViewState::String(value) => Some(value.clone()), + _ => None, + } + } +} + +/// General properties that specify how a `View` is rendered. #[derive(Clone, Default)] pub struct RenderProps { /// Area of the render props. @@ -82,27 +104,67 @@ impl From for RenderProps { } } -/// Main trait defining a `Widget` behaviour. -/// -/// This is the trait that you should implement to define a custom `Widget`. -pub trait Widget { +/// Main trait defining a `View` behaviour, which needs be implemented in order to +/// build a custom widget. A `View` operates on an application state and can emit +/// application messages. It's usually is accompanied by a definition of view-specific +/// properties, which are being built from the application state by the framework. +pub trait View { type State; type Message; - /// Should return a new view with props build from state (if type is known) and a - /// message sender set. - fn new(state: &Self::State, tx: UnboundedSender) -> Self - where - Self: Sized; - /// Should handle key events and call `handle_event` on all children. - /// - /// After key events have been handled, the custom event handler `on_event` should - /// be called - fn handle_event(&mut self, key: Key); + fn handle_event(&mut self, key: Key) -> Option; /// Should update the internal props of this and all children. - /// + fn update(&mut self, state: &Self::State, props: Option); + + /// Should render the view using the given `RenderProps`. + fn render(&self, frame: &mut Frame, props: RenderProps); + + /// Should return the internal state. + fn view_state(&self) -> Option { + None + } +} + +/// A `View` needs to wrapped into a `Widget` before being able to use with the +/// framework. A `Widget` enhances a `View` with event and update callbacks and takes +/// care of calling them before / after calling into the `View`. +pub struct Widget { + view: BoxedView, + sender: UnboundedSender, + on_update: Option>, + on_event: Option>, +} + +impl Widget { + pub fn new(view: V, sender: UnboundedSender) -> Self + where + Self: Sized, + V: View + 'static, + { + Self { + view: Box::new(view), + sender: sender.clone(), + on_update: None, + on_event: None, + } + } + + /// Calls `handle_event` on the wrapped view as well as the `on_event` callback. + /// Sends any message returned by either the view or the callback. + pub fn handle_event(&mut self, key: Key) { + if let Some(message) = self.view.handle_event(key) { + let _ = self.sender.send(message); + } + + if let Some(on_event) = self.on_event { + if let Some(message) = (on_event)(self.view.view_state().as_ref(), key) { + let _ = self.sender.send(message); + } + } + } + /// Applications are usually defined by app-specific widgets that do know /// the type of `state`. These can use widgets from the library that do not know the /// type of `state`. @@ -111,88 +173,58 @@ pub trait Widget { /// construct and update the internal props. If it is not set, app widgets can construct /// props directly via their state converters, whereas library widgets can just fallback /// to their current props. - fn update(&mut self, state: &Self::State); - - /// Renders a widget to the given frame in the given area. - /// - /// Optional render props can be given. - fn render(&self, frame: &mut Frame, props: RenderProps); - - /// Return a reference to this widgets' base. - fn base(&self) -> &WidgetBase; - - /// Return a mutable reference to this widgets' base. - fn base_mut(&mut self) -> &mut WidgetBase; - - /// Send a message to the widgets' base channel. - fn send(&self, message: Self::Message) -> Result<(), SendError> { - self.base().send(message) + pub fn update(&mut self, state: &S) { + let props = self.on_update.map(|on_update| (on_update)(state)); + self.view.update(state, props); } - /// Should set the optional custom event handler. - fn on_event(mut self, callback: EventCallback) -> Self + /// Renders the wrapped view. + pub fn render(&self, frame: &mut Frame, props: RenderProps) { + self.view.render(frame, props); + } + + /// Sets the optional custom event handler. + pub fn on_event(mut self, callback: EventCallback) -> Self where Self: Sized, { - self.base_mut().on_event = Some(callback); + self.on_event = Some(callback); self } - /// Should set the optional update handler. - fn on_update(mut self, callback: UpdateCallback) -> Self + /// Sets the optional update handler. + pub fn on_update(mut self, callback: UpdateCallback) -> Self where Self: Sized, { - self.base_mut().on_update = Some(callback); + self.on_update = Some(callback); self } - /// Returns a boxed `Widget` - fn to_boxed(self) -> Box - where - Self: Sized, - { - Box::new(self) + /// Sends a message to the widgets' message channel. + pub fn send(&self, message: M) { + let _ = self.sender.send(message); } } -/// Needs to be implemented for items that are supposed to be rendered in tables. -pub trait ToRow { - fn to_row(&self) -> [Cell; W]; +/// A `View` needs to be wrapped into a `Widget` in order to be used with the framework. +/// `ToWidget` provides a blanket implementation for all `View`s. +pub trait ToWidget { + fn to_widget(self, tx: UnboundedSender) -> Widget + where + Self: Sized + 'static; } -/// Common trait for widget properties. -pub trait Properties { - fn to_boxed(self) -> Box +impl ToWidget for T +where + T: View, + S: 'static, + M: 'static, +{ + fn to_widget(self, tx: UnboundedSender) -> Widget where - Self: Sized, + Self: Sized + 'static, { - Box::new(self) - } - - fn from_callback(callback: Option>, state: &S) -> Option - where - Self: Sized + Clone + 'static + BoxedAny, - { - callback - .map(|callback| (callback)(state)) - .and_then(|props| Self::from_boxed_any(props)) - } -} - -/// Provide default implementations for conversions to and from `Box`. -pub trait BoxedAny { - fn from_boxed_any(any: Box) -> Option - where - Self: Sized + Clone + 'static, - { - any.downcast_ref::().cloned() - } - - fn to_boxed_any(self) -> Box - where - Self: Sized + Clone + 'static, - { - Box::new(self) + Widget::new(self, tx) } } diff --git a/src/ui/widget/container.rs b/src/ui/widget/container.rs index c98bf55e..e624996e 100644 --- a/src/ui/widget/container.rs +++ b/src/ui/widget/container.rs @@ -1,6 +1,5 @@ use std::fmt::Debug; - -use tokio::sync::mpsc::UnboundedSender; +use std::marker::PhantomData; use termion::event::Key; @@ -10,7 +9,7 @@ use ratatui::widgets::{Block, BorderType, Borders, Row}; use crate::ui::ext::{FooterBlock, FooterBlockType, HeaderBlock}; use crate::ui::theme::style; -use super::{BoxedAny, BoxedWidget, Properties, RenderProps, Widget, WidgetBase}; +use super::{RenderProps, View, ViewProps, Widget}; #[derive(Clone, Debug)] pub struct Column<'a> { @@ -64,14 +63,20 @@ impl<'a> Default for HeaderProps<'a> { } } -impl<'a: 'static> Properties for HeaderProps<'a> {} -impl<'a: 'static> BoxedAny for HeaderProps<'a> {} - pub struct Header<'a: 'static, S, M> { /// Internal props props: HeaderProps<'a>, - /// Internal base - base: WidgetBase, + /// Phantom + phantom: PhantomData<(S, M)>, +} + +impl<'a, S, M> Default for Header<'a, S, M> { + fn default() -> Self { + Self { + props: HeaderProps::default(), + phantom: PhantomData, + } + } } impl<'a, S, A> Header<'a, S, A> { @@ -87,25 +92,18 @@ impl<'a, S, A> Header<'a, S, A> { } } -impl<'a: 'static, S, M> Widget for Header<'a, S, M> { +impl<'a: 'static, S, M> View for Header<'a, S, M> { type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self { - Self { - base: WidgetBase::new(tx.clone()), - props: HeaderProps::default(), - } + fn handle_event(&mut self, _key: Key) -> Option { + None } - fn handle_event(&mut self, _key: Key) {} - - fn update(&mut self, state: &S) { - self.props = self - .base - .on_update - .and_then(|on_update| HeaderProps::from_boxed_any((on_update)(state))) - .unwrap_or(self.props.clone()); + fn update(&mut self, _state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; + } } fn render(&self, frame: &mut ratatui::Frame, props: RenderProps) { @@ -165,14 +163,6 @@ impl<'a: 'static, S, M> Widget for Header<'a, S, M> { frame.render_widget(block, props.area); frame.render_widget(header, header_layout[0]); } - - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base - } } #[derive(Clone, Debug)] @@ -205,14 +195,20 @@ impl<'a> Default for FooterProps<'a> { } } -impl<'a: 'static> Properties for FooterProps<'a> {} -impl<'a: 'static> BoxedAny for FooterProps<'a> {} - pub struct Footer<'a, S, M> { /// Internal props props: FooterProps<'a>, - /// Internal base - base: WidgetBase, + /// Phantom + phantom: PhantomData<(S, M)>, +} + +impl<'a, S, M> Default for Footer<'a, S, M> { + fn default() -> Self { + Self { + props: FooterProps::default(), + phantom: PhantomData, + } + } } impl<'a, S, M> Footer<'a, S, M> { @@ -250,25 +246,18 @@ impl<'a, S, M> Footer<'a, S, M> { } } -impl<'a: 'static, S, M> Widget for Footer<'a, S, M> { +impl<'a: 'static, S, M> View for Footer<'a, S, M> { type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self { - Self { - base: WidgetBase::new(tx.clone()), - props: FooterProps::default(), - } + fn handle_event(&mut self, _key: Key) -> Option { + None } - fn handle_event(&mut self, _key: Key) {} - - fn update(&mut self, state: &S) { - self.props = self - .base - .on_update - .and_then(|on_update| FooterProps::from_boxed_any((on_update)(state))) - .unwrap_or(self.props.clone()); + fn update(&mut self, _state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; + } } fn render(&self, frame: &mut ratatui::Frame, props: RenderProps) { @@ -304,14 +293,6 @@ impl<'a: 'static, S, M> Widget for Footer<'a, S, M> { self.render_cell(frame, *area, block_type, cell.clone(), props.focus); } } - - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base - } } #[derive(Clone, Default)] @@ -326,65 +307,65 @@ impl ContainerProps { } } -impl Properties for ContainerProps {} -impl BoxedAny for ContainerProps {} - pub struct Container { - /// Internal base - base: WidgetBase, /// Internal props props: ContainerProps, /// Container header - header: Option>, + header: Option>, /// Content widget - content: Option>, + content: Option>, /// Container footer - footer: Option>, + footer: Option>, } -impl Container { - pub fn header(mut self, header: BoxedWidget) -> Self { - self.header = Some(header); - self - } - - pub fn content(mut self, content: BoxedWidget) -> Self { - self.content = Some(content); - self - } - - pub fn footer(mut self, footer: BoxedWidget) -> Self { - self.footer = Some(footer); - self - } -} - -impl Widget for Container { - type Message = M; - type State = S; - - fn new(_state: &S, tx: UnboundedSender) -> Self - where - Self: Sized, - { +impl Default for Container { + fn default() -> Self { Self { - base: WidgetBase::new(tx.clone()), props: ContainerProps::default(), header: None, content: None, footer: None, } } +} - fn handle_event(&mut self, key: termion::event::Key) { +impl Container { + pub fn header(mut self, header: Widget) -> Self { + self.header = Some(header); + self + } + + pub fn content(mut self, content: Widget) -> Self { + self.content = Some(content); + self + } + + pub fn footer(mut self, footer: Widget) -> Self { + self.footer = Some(footer); + self + } +} + +impl View for Container +where + S: 'static, + M: 'static, +{ + type Message = M; + type State = S; + + fn handle_event(&mut self, key: termion::event::Key) -> Option { if let Some(content) = &mut self.content { content.handle_event(key); } + + None } - fn update(&mut self, state: &S) { - self.props = - ContainerProps::from_callback(self.base.on_update, state).unwrap_or(self.props.clone()); + fn update(&mut self, state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; + } if let Some(header) = &mut self.header { header.update(state); @@ -445,14 +426,6 @@ impl Widget for Container { footer.render(frame, RenderProps::from(footer_area).focus(props.focus)); } } - - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base - } } #[derive(Clone)] @@ -461,8 +434,6 @@ pub struct SectionGroupState { focus: Option, } -impl BoxedAny for SectionGroupState {} - #[derive(Clone, Default)] pub struct SectionGroupProps { /// If this pages' keys should be handled. @@ -476,22 +447,27 @@ impl SectionGroupProps { } } -impl Properties for SectionGroupProps {} -impl BoxedAny for SectionGroupProps {} - pub struct SectionGroup { - /// Internal base - base: WidgetBase, /// Internal table properties props: SectionGroupProps, /// All sections - sections: Vec>, + sections: Vec>, /// Internal selection and offset state state: SectionGroupState, } +impl Default for SectionGroup { + fn default() -> Self { + Self { + props: SectionGroupProps::default(), + sections: vec![], + state: SectionGroupState { focus: Some(0) }, + } + } +} + impl SectionGroup { - pub fn section(mut self, section: BoxedWidget) -> Self { + pub fn section(mut self, section: Widget) -> Self { self.sections.push(section); self } @@ -515,7 +491,7 @@ impl SectionGroup { } } -impl Widget for SectionGroup +impl View for SectionGroup where S: 'static, M: 'static, @@ -523,16 +499,7 @@ where type State = S; type Message = M; - fn new(_state: &S, tx: UnboundedSender) -> Self { - Self { - base: WidgetBase::new(tx.clone()), - props: SectionGroupProps::default(), - sections: vec![], - state: SectionGroupState { focus: Some(0) }, - } - } - - fn handle_event(&mut self, key: Key) { + fn handle_event(&mut self, key: Key) -> Option { if let Some(section) = self .state .focus @@ -553,14 +520,13 @@ where } } - if let Some(on_event) = self.base.on_event { - (on_event)(self, key); - } + None } - fn update(&mut self, state: &S) { - self.props = SectionGroupProps::from_callback(self.base.on_update, state) - .unwrap_or(self.props.clone()); + fn update(&mut self, state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; + } for section in &mut self.sections { section.update(state); @@ -582,12 +548,4 @@ where } } } - - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base - } } diff --git a/src/ui/widget/input.rs b/src/ui/widget/input.rs index 52660662..6e934826 100644 --- a/src/ui/widget/input.rs +++ b/src/ui/widget/input.rs @@ -1,12 +1,12 @@ -use termion::event::Key; +use std::marker::PhantomData; -use tokio::sync::mpsc::UnboundedSender; +use termion::event::Key; use ratatui::layout::{Constraint, Layout}; use ratatui::style::Stylize; use ratatui::text::{Line, Span}; -use super::{BoxedAny, Properties, RenderProps, Widget, WidgetBase}; +use super::{RenderProps, View, ViewProps, ViewState}; #[derive(Clone)] pub struct TextFieldProps { @@ -46,30 +46,35 @@ impl Default for TextFieldProps { } } -impl Properties for TextFieldProps {} - #[derive(Clone)] struct TextFieldState { pub text: Option, pub cursor_position: usize, } -impl BoxedAny for TextFieldState {} - pub struct TextField { - /// Internal base - base: WidgetBase, /// Internal props props: TextFieldProps, /// Internal state state: TextFieldState, + /// Phantom + phantom: PhantomData<(S, M)>, +} + +impl Default for TextField { + fn default() -> Self { + Self { + props: TextFieldProps::default(), + state: TextFieldState { + text: None, + cursor_position: 0, + }, + phantom: PhantomData, + } + } } impl TextField { - pub fn text(&self) -> Option<&String> { - self.state.text.as_ref() - } - fn move_cursor_left(&mut self) { let cursor_moved_left = self.state.cursor_position.saturating_sub(1); self.state.cursor_position = self.clamp_cursor(cursor_moved_left); @@ -131,7 +136,7 @@ impl TextField { } } -impl Widget for TextField +impl View for TextField where S: 'static, M: 'static, @@ -139,18 +144,7 @@ where type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self { - Self { - base: WidgetBase::new(tx.clone()), - props: TextFieldProps::default(), - state: TextFieldState { - text: None, - cursor_position: 0, - }, - } - } - - fn handle_event(&mut self, key: Key) { + fn handle_event(&mut self, key: Key) -> Option { match key { Key::Char(to_insert) if (key != Key::Alt('\n')) @@ -171,21 +165,17 @@ where _ => {} } - if let Some(on_event) = self.base.on_event { - (on_event)(self, key); - } + None } - fn update(&mut self, state: &S) { - if let Some(on_update) = self.base.on_update { - if let Some(props) = (on_update)(state).downcast_ref::() { - self.props = props.clone(); + fn update(&mut self, _state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; - if self.state.text.is_none() { - self.state.cursor_position = props.text.len().saturating_sub(1); - } - self.state.text = Some(props.text.clone()); + if self.state.text.is_none() { + self.state.cursor_position = self.props.text.len().saturating_sub(1); } + self.state.text = Some(self.props.text.clone()); } } @@ -238,13 +228,10 @@ where } } - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base + fn view_state(&self) -> Option { + self.state + .text + .as_ref() + .map(|text| ViewState::String(text.to_string())) } } - -impl BoxedAny for TextField {} diff --git a/src/ui/widget/list.rs b/src/ui/widget/list.rs index 9c8254d2..00defda7 100644 --- a/src/ui/widget/list.rs +++ b/src/ui/widget/list.rs @@ -1,8 +1,7 @@ use std::cmp; +use std::marker::PhantomData; use ratatui::widgets::Row; -use tokio::sync::mpsc::UnboundedSender; - use termion::event::Key; use ratatui::layout::Constraint; @@ -10,11 +9,12 @@ use ratatui::style::Stylize; use ratatui::text::Text; use ratatui::widgets::TableState; +use crate::ui::items::ToRow; use crate::ui::theme::style; use crate::ui::{layout, span}; -use super::BoxedAny; -use super::{container::Column, Properties, RenderProps, ToRow, Widget, WidgetBase}; +use super::{container::Column, RenderProps, View}; +use super::{ViewProps, ViewState}; #[derive(Clone, Debug)] pub struct TableProps<'a, R, const W: usize> @@ -83,31 +83,35 @@ where } } -impl<'a: 'static, R, const W: usize> Properties for TableProps<'a, R, W> where R: ToRow + 'static {} -impl<'a: 'static, R, const W: usize> BoxedAny for TableProps<'a, R, W> where R: ToRow + 'static {} - -impl BoxedAny for TableState {} - pub struct Table<'a, S, M, R, const W: usize> where R: ToRow, { - /// Internal base - base: WidgetBase, /// Internal table properties props: TableProps<'a, R, W>, /// Internal selection and offset state state: TableState, + /// Phantom + phantom: PhantomData<(S, M)>, +} + +impl<'a, S, M, R, const W: usize> Default for Table<'a, S, M, R, W> +where + R: ToRow, +{ + fn default() -> Self { + Self { + props: TableProps::default(), + state: TableState::default().with_selected(Some(0)), + phantom: PhantomData, + } + } } impl<'a, S, M, R, const W: usize> Table<'a, S, M, R, W> where R: ToRow, { - pub fn selected(&self) -> Option { - self.state.selected() - } - fn prev(&mut self) -> Option { let selected = self .state @@ -159,22 +163,14 @@ where } } -impl<'a: 'static, S: 'a, M: 'a, R, const W: usize> Widget for Table<'a, S, M, R, W> +impl<'a: 'static, S: 'a, M: 'a, R, const W: usize> View for Table<'a, S, M, R, W> where R: ToRow + Clone + 'static, { type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self { - Self { - base: WidgetBase::new(tx.clone()), - props: TableProps::default(), - state: TableState::default().with_selected(Some(0)), - } - } - - fn handle_event(&mut self, key: Key) { + fn handle_event(&mut self, key: Key) -> Option { match key { Key::Up | Key::Char('k') => { self.prev(); @@ -197,18 +193,17 @@ where _ => {} } - if let Some(on_event) = self.base.on_event { - (on_event)(self, key); - } + None } - fn update(&mut self, state: &S) { - self.props = - TableProps::from_callback(self.base.on_update, state).unwrap_or(self.props.clone()); - - if self.props.selected != self.state.selected() { - self.state.select(self.props.selected); + fn update(&mut self, _state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::>()) { + self.props = props; } + + // if self.props.selected != self.state.selected() { + // self.state.select(self.props.selected); + // } } fn render(&self, frame: &mut ratatui::Frame, props: RenderProps) { @@ -268,12 +263,8 @@ where } } - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base + fn view_state(&self) -> Option { + self.state.selected().map(ViewState::USize) } } diff --git a/src/ui/widget/text.rs b/src/ui/widget/text.rs index 1e00cdff..333dd4a6 100644 --- a/src/ui/widget/text.rs +++ b/src/ui/widget/text.rs @@ -1,11 +1,11 @@ -use tokio::sync::mpsc::UnboundedSender; +use std::marker::PhantomData; use termion::event::Key; use ratatui::layout::{Constraint, Layout}; use ratatui::text::Text; -use super::{BoxedAny, Properties, RenderProps, Widget, WidgetBase}; +use super::{RenderProps, View, ViewProps, ViewState}; #[derive(Clone)] pub struct ParagraphProps<'a> { @@ -40,9 +40,6 @@ impl<'a> Default for ParagraphProps<'a> { } } -impl<'a: 'static> Properties for ParagraphProps<'a> {} -impl<'a: 'static> BoxedAny for ParagraphProps<'a> {} - #[derive(Clone)] struct ParagraphState { /// Internal offset @@ -51,15 +48,26 @@ struct ParagraphState { pub progress: usize, } -impl BoxedAny for ParagraphState {} - pub struct Paragraph<'a, S, M> { - /// Internal base - base: WidgetBase, /// Internal props props: ParagraphProps<'a>, /// Internal state state: ParagraphState, + /// Phantom + phantom: PhantomData<(S, M)>, +} + +impl<'a, S, M> Default for Paragraph<'a, S, M> { + fn default() -> Self { + Self { + props: ParagraphProps::default(), + state: ParagraphState { + offset: 0, + progress: 0, + }, + phantom: PhantomData, + } + } } impl<'a, S, M> Paragraph<'a, S, M> { @@ -118,10 +126,6 @@ impl<'a, S, M> Paragraph<'a, S, M> { self.scroll() } - pub fn progress(&self) -> usize { - self.state.progress - } - fn scroll_percent(offset: usize, len: usize, height: usize) -> usize { if height >= len { 100 @@ -136,7 +140,7 @@ impl<'a, S, M> Paragraph<'a, S, M> { } } -impl<'a, S, M> Widget for Paragraph<'a, S, M> +impl<'a, S, M> View for Paragraph<'a, S, M> where 'a: 'static, S: 'static, @@ -145,21 +149,7 @@ where type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self - where - Self: Sized, - { - Self { - base: WidgetBase::new(tx.clone()), - props: ParagraphProps::default(), - state: ParagraphState { - offset: 0, - progress: 0, - }, - } - } - - fn handle_event(&mut self, key: Key) { + fn handle_event(&mut self, key: Key) -> Option { let len = self.props.content.lines.len() + 1; let page_size = self.props.page_size; @@ -185,14 +175,13 @@ where _ => {} } - if let Some(on_event) = self.base.on_event { - (on_event)(self, key); - } + None } - fn update(&mut self, state: &S) { - self.props = - ParagraphProps::from_callback(self.base.on_update, state).unwrap_or(self.props.clone()); + fn update(&mut self, _state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; + } } fn render(&self, frame: &mut ratatui::Frame, props: RenderProps) { @@ -205,11 +194,7 @@ where frame.render_widget(content, content_area); } - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base + fn view_state(&self) -> Option { + Some(ViewState::USize(self.state.progress)) } } diff --git a/src/ui/widget/window.rs b/src/ui/widget/window.rs index a0dd7b76..7e7e627c 100644 --- a/src/ui/widget/window.rs +++ b/src/ui/widget/window.rs @@ -1,7 +1,5 @@ -use std::collections::HashMap; use std::hash::Hash; - -use tokio::sync::mpsc::UnboundedSender; +use std::{collections::HashMap, marker::PhantomData}; use termion::event::Key; @@ -12,7 +10,7 @@ use ratatui::widgets::Row; use crate::ui::theme::style; -use super::{BoxedAny, BoxedWidget, Properties, RenderProps, Widget, WidgetBase}; +use super::{RenderProps, View, ViewProps, Widget}; #[derive(Clone)] pub struct WindowProps { @@ -32,29 +30,33 @@ impl Default for WindowProps { } } -impl Properties for WindowProps {} -impl BoxedAny for WindowProps {} - pub struct Window { - /// Internal base - base: WidgetBase, /// Internal properties props: WindowProps, /// All pages known - pages: HashMap>, + pages: HashMap>, +} + +impl Default for Window { + fn default() -> Self { + Self { + props: WindowProps::default(), + pages: HashMap::new(), + } + } } impl Window where Id: Clone + Hash + Eq + PartialEq, { - pub fn page(mut self, id: Id, page: BoxedWidget) -> Self { + pub fn page(mut self, id: Id, page: Widget) -> Self { self.pages.insert(id, page); self } } -impl<'a, S, M, Id> Widget for Window +impl<'a, S, M, Id> View for Window where 'a: 'static, S: 'static, @@ -64,18 +66,7 @@ where type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self - where - Self: Sized, - { - Self { - base: WidgetBase::new(tx.clone()), - props: WindowProps::default(), - pages: HashMap::new(), - } - } - - fn handle_event(&mut self, key: termion::event::Key) { + fn handle_event(&mut self, key: termion::event::Key) -> Option { let page = self .props .current_page @@ -86,14 +77,13 @@ where page.handle_event(key); } - if let Some(on_event) = self.base.on_event { - (on_event)(self, key); - } + None } - fn update(&mut self, state: &S) { - self.props = - WindowProps::from_callback(self.base.on_update, state).unwrap_or(self.props.clone()); + fn update(&mut self, state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::>()) { + self.props = props; + } let page = self .props @@ -119,14 +109,6 @@ where page.render(frame, RenderProps::from(area).focus(true)); } } - - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base - } } #[derive(Clone)] @@ -159,14 +141,11 @@ impl Default for ShortcutsProps { } } -impl Properties for ShortcutsProps {} -impl BoxedAny for ShortcutsProps {} - pub struct Shortcuts { - /// Internal properties + /// Internal props props: ShortcutsProps, - /// Internal base - base: WidgetBase, + /// Phantom + phantom: PhantomData<(S, M)>, } impl Shortcuts { @@ -186,22 +165,27 @@ impl Shortcuts { } } -impl Widget for Shortcuts { +impl Default for Shortcuts { + fn default() -> Self { + Self { + props: ShortcutsProps::default(), + phantom: PhantomData, + } + } +} + +impl View for Shortcuts { type Message = M; type State = S; - fn new(_state: &S, tx: UnboundedSender) -> Self { - Self { - base: WidgetBase::new(tx.clone()), - props: ShortcutsProps::default(), - } + fn handle_event(&mut self, _key: Key) -> Option { + None } - fn handle_event(&mut self, _key: Key) {} - - fn update(&mut self, state: &S) { - self.props = - ShortcutsProps::from_callback(self.base.on_update, state).unwrap_or(self.props.clone()); + fn update(&mut self, _state: &Self::State, props: Option) { + if let Some(props) = props.and_then(|props| props.inner::()) { + self.props = props; + } } fn render(&self, frame: &mut ratatui::Frame, props: RenderProps) { @@ -241,12 +225,4 @@ impl Widget for Shortcuts { let table = Table::new([Row::new(row)], widths).column_spacing(0); frame.render_widget(table, props.area); } - - fn base(&self) -> &WidgetBase { - &self.base - } - - fn base_mut(&mut self) -> &mut WidgetBase { - &mut self.base - } }