1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! Defines the `Component` trait and related types.

pub mod layout;
pub(crate) mod template;

pub use self::layout::Layout;

use smallvec::SmallVec;
use std::{
    any::TypeId, cmp::Ordering, collections::hash_map::HashMap, marker::PhantomData, rc::Rc,
};
use tokio::sync::mpsc::UnboundedSender;

use self::template::{ComponentId, DynamicMessage};
use crate::terminal::{Key, Rect};

/// Components are the building blocks of the UI in Zi.
///
/// The trait describes stateful components and their lifecycle. This is the
/// main trait that users of the library will implement to describe their UI.
/// All components are owned directly by an [`App`](../struct.App.html) which
/// manages their lifecycle. An `App` instance will create new components,
/// update them in reaction to user input or to messages from other components
/// and eventually drop them when a component gone off screen.
///
/// Anyone familiar with Yew, Elm or React + Redux should be familiar with all
/// the high-level concepts. Moreover, the names of some types and functions are
/// the same as in `Yew`.
///
/// A component has to describe how:
///   - how to create a fresh instance from `Component::Properties` received from their parent (`create` fn)
///   - how to render it (`view` fn)
///   - how to update its inter
///
pub trait Component: Sized + 'static {
    /// Messages are used to make components dynamic and interactive. For simple
    /// components, this will be `()`. Complex ones will typically use
    /// an enum to declare multiple Message types.
    type Message: Send + 'static;

    /// Properties are the inputs to a Component.
    type Properties: Clone;

    /// Components are created with three pieces of data:
    ///   - their Properties
    ///   - the current position and size on the screen
    ///   - a `ComponentLink` which can be used to send messages and create callbacks for triggering updates
    ///
    /// Conceptually, there's an "update" method for each one of these:
    ///   - `change` when the Properties change
    ///   - `resize` when their current position and size on the screen changes
    ///   - `update` when the a message was sent to the component
    fn create(properties: Self::Properties, frame: Rect, link: ComponentLink<Self>) -> Self;

    /// Returns the current visual layout of the component.
    fn view(&self) -> Layout;

    /// When the parent of a Component is re-rendered, it will either be re-created or
    /// receive new properties in the `change` lifecycle method. Component's can choose
    /// to re-render if the new properties are different than the previously
    /// received properties.
    ///
    /// Root components don't have a parent and subsequently, their `change`
    /// method will never be called. Components which don't have properties
    /// should always return false.
    fn change(&mut self, _properties: Self::Properties) -> ShouldRender {
        ShouldRender::No
    }

    /// This method is called when a component's position and size on the screen changes.
    fn resize(&mut self, _frame: Rect) -> ShouldRender {
        ShouldRender::No
    }

    /// Components handle messages in their `update` method and commonly use this method
    /// to update their state and (optionally) re-render themselves.
    fn update(&mut self, _message: Self::Message) -> ShouldRender {
        ShouldRender::No
    }

    /// Whether the component is currently focused.
    fn has_focus(&self) -> bool {
        false
    }

    /// If the component is currently focused (see `has_focus`), `input_binding`
    /// will be called on every keyboard events.
    fn input_binding(&self, _pressed: &[Key]) -> BindingMatch<Self::Message> {
        BindingMatch {
            transition: BindingTransition::Clear,
            message: None,
        }
    }

    fn tick(&self) -> Option<Self::Message> {
        None
    }
}

/// Callback wrapper. Useful for passing callbacks in child components
/// `Properties`. An `Rc` wrapper is used to make it cloneable.
pub struct Callback<InputT, OutputT = ()>(pub Rc<dyn Fn(InputT) -> OutputT>);

impl<InputT, OutputT> Clone for Callback<InputT, OutputT> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<InputT, OutputT> PartialEq for Callback<InputT, OutputT> {
    fn eq(&self, _other: &Self) -> bool {
        false
        // Rc::ptr_eq(&self.0, &other.0)
    }
}

impl<InputT, OutputT> Callback<InputT, OutputT> {
    pub fn emit(&self, value: InputT) -> OutputT {
        (self.0)(value)
    }
}

impl<InputT, OutputT, FnT> From<FnT> for Callback<InputT, OutputT>
where
    FnT: Fn(InputT) -> OutputT + 'static,
{
    fn from(function: FnT) -> Self {
        Self(Rc::new(function))
    }
}

/// A context for sending messages to a component or the runtime.
///
/// It can be used in a multi-threaded environment (implements `Sync` and
/// `Send`). Additionally, it can send messages to the runtime, in particular
/// it's used to gracefully stop a running [`App`](struct.App.html).
#[derive(Debug)]
pub struct ComponentLink<ComponentT> {
    sender: UnboundedSender<LinkMessage>,
    component_id: ComponentId,
    _component: PhantomData<fn() -> ComponentT>,
}

impl<ComponentT: Component> ComponentLink<ComponentT> {
    /// Sends a message to the component.
    pub fn send(&self, message: ComponentT::Message) {
        self.sender
            .send(LinkMessage::Component(
                self.component_id,
                DynamicMessage(Box::new(message)),
            ))
            .map_err(|_| ()) // tokio's SendError doesn't implement Debug
            .expect("App receiver needs to outlive senders for inter-component messages");
    }

    /// Creates a `Callback` which will send a message to the linked component's
    /// update method when invoked.
    pub fn callback<InputT>(
        &self,
        callback: impl Fn(InputT) -> ComponentT::Message + 'static,
    ) -> Callback<InputT> {
        let link = self.clone();
        Callback(Rc::new(move |input| link.send(callback(input))))
    }

    /// Sends a message to the `App` runtime requesting it to stop executing.
    ///
    /// This method only sends a message and returns immediately, the app will
    /// stop asynchronously and may deliver other pending messages before
    /// exiting.
    pub fn exit(&self) {
        self.sender
            .send(LinkMessage::Exit)
            .map_err(|_| ()) // tokio's SendError doesn't implement Debug
            .expect("App needs to outlive components");
    }

    /// Runs a closure that requires exclusive access to the backend (i.e.
    /// typically to stdin / stdout). For example spawning an external editor to
    /// collect some text.
    pub fn run_exclusive(
        &self,
        process: impl FnOnce() -> Option<ComponentT::Message> + Send + 'static,
    ) {
        let component_id = self.component_id;
        self.sender
            .send(LinkMessage::RunExclusive(Box::new(move || {
                process().map(|message| (component_id, DynamicMessage(Box::new(message))))
            })))
            .map_err(|_| ()) // tokio's SendError doesn't implement Debug
            .expect("App needs to outlive components");
    }

    pub(crate) fn new(sender: UnboundedSender<LinkMessage>, component_id: ComponentId) -> Self {
        assert_eq!(TypeId::of::<ComponentT>(), component_id.type_id());
        Self {
            sender,
            component_id,
            _component: PhantomData,
        }
    }
}

impl<ComponentT> Clone for ComponentLink<ComponentT> {
    fn clone(&self) -> Self {
        Self {
            sender: self.sender.clone(),
            component_id: self.component_id,
            _component: PhantomData,
        }
    }
}

/// Type to indicate whether a component should be rendered again.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShouldRender {
    Yes,
    No,
}

impl Into<bool> for ShouldRender {
    fn into(self) -> bool {
        self == ShouldRender::Yes
    }
}

impl From<bool> for ShouldRender {
    fn from(should_render: bool) -> Self {
        if should_render {
            ShouldRender::Yes
        } else {
            ShouldRender::No
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingTransition {
    Continue,
    Clear,
    ChangedFocus,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindingMatch<Message> {
    pub transition: BindingTransition,
    pub message: Option<Message>,
}

impl<Message> BindingMatch<Message> {
    pub fn clear(message: impl Into<Option<Message>>) -> Self {
        Self {
            transition: BindingTransition::Clear,
            message: message.into(),
        }
    }
}

pub(crate) enum LinkMessage {
    Component(ComponentId, DynamicMessage),
    Exit,
    RunExclusive(Box<dyn FnOnce() -> Option<(ComponentId, DynamicMessage)> + Send + 'static>),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct _HashBindings<Action>(HashMap<SmallVec<[Key; 2]>, Action>);

impl<Message> _HashBindings<Message> {
    pub fn _new(map: HashMap<SmallVec<[Key; 2]>, Message>) -> Self {
        Self(map)
    }
}

impl<Message: Clone> _HashBindings<Message> {
    pub fn _input_binding(&self, pressed: &[Key]) -> BindingMatch<Message> {
        for (binding, message) in self.0.iter() {
            let is_match = binding
                .iter()
                .zip(pressed.iter())
                .all(|(lhs, rhs)| *lhs == *rhs);
            if is_match {
                match pressed.len().cmp(&binding.len()) {
                    Ordering::Less => {
                        return BindingMatch {
                            transition: BindingTransition::Continue,
                            message: None,
                        };
                    }
                    Ordering::Equal => {
                        return BindingMatch {
                            transition: BindingTransition::Clear,
                            message: Some(message.clone()),
                        }
                    }
                    _ => {}
                }
            }
        }
        BindingMatch {
            transition: BindingTransition::Clear,
            message: None,
        }
    }
}