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
use std::fmt::Debug;

use std::marker::PhantomData;
use std::rc::Rc;

use respo_state_derive::RespoState;
use serde::{Deserialize, Serialize};

use crate::ui::dialog::{css_backdrop, css_drawer_card};
use crate::ui::{column, ui_center, ui_fullscreen, ui_global};

use crate::node::css::{CssLineHeight, CssPosition, RespoStyle};
use crate::node::{DispatchFn, RespoAction, RespoEvent, RespoNode};
use crate::{div, space, span, RespoComponent};

use crate::states_tree::{RespoState, RespoStatesTree};

use crate::ui::dialog::effect_drawer_fade;

use super::comp_esc_listener;

/// The options for custom drawer.
#[derive(Debug, Clone, Default)]
pub struct DrawerOptions<T>
where
  T: Debug + Clone,
{
  /// inline style for backdrop
  pub backdrop_style: RespoStyle,
  /// inline style for card
  pub card_style: RespoStyle,
  /// title of the drawer, defaults to `drawer`
  pub title: Option<String>,
  /// render body
  pub render: DrawerRenderer<T>,
}

type DrawerRendererFn<T> = dyn Fn(Rc<dyn Fn(DispatchFn<T>) -> Result<(), String>>) -> Result<RespoNode<T>, String>;

/// wraps render function
#[derive(Clone)]
pub struct DrawerRenderer<T>(Rc<DrawerRendererFn<T>>)
where
  T: Debug + Clone;

impl<T> Debug for DrawerRenderer<T>
where
  T: Debug + Clone,
{
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "(&DrawerRenderer ..)")
  }
}

impl<T> Default for DrawerRenderer<T>
where
  T: Debug + Clone,
{
  fn default() -> Self {
    Self(Rc::new(|_close: _| Ok(div().to_node())))
  }
}

impl<T> DrawerRenderer<T>
where
  T: Debug + Clone,
{
  pub fn new<V>(renderer: V) -> Self
  where
    V: Fn(Rc<dyn Fn(DispatchFn<T>) -> Result<(), String>>) -> Result<RespoNode<T>, String> + 'static,
  {
    Self(Rc::new(renderer))
  }

  pub fn run<V>(&self, close: V) -> Result<RespoNode<T>, String>
  where
    V: Fn(DispatchFn<T>) -> Result<(), String> + 'static,
  {
    (self.0)(Rc::new(close))
  }
}

fn comp_drawer<T, U>(options: DrawerOptions<T>, show: bool, on_close: U) -> Result<RespoNode<T>, String>
where
  U: Fn(DispatchFn<T>) -> Result<(), String> + 'static,
  T: Clone + Debug,
{
  let close = Rc::new(on_close);

  Ok(
    RespoComponent::named(
      "drawer",
      div()
        .style(RespoStyle::default().position(CssPosition::Absolute))
        .elements([if show {
          div()
            .class_list(&[ui_fullscreen(), ui_center(), css_backdrop()])
            .style(options.backdrop_style)
            .on_click({
              let close = close.to_owned();
              move |e, dispatch| -> Result<(), String> {
                if let RespoEvent::Click { original_event, .. } = e {
                  // stop propagation to prevent closing the drawer
                  original_event.stop_propagation();
                }
                close(dispatch)?;
                Ok(())
              }
            })
            .children([
              div()
                .class_list(&[column(), ui_global(), css_drawer_card()])
                .style(RespoStyle::default().padding(0.0).line_height(CssLineHeight::Px(32.0)))
                .style(options.card_style)
                .on_click(move |e, _dispatch| -> Result<(), String> {
                  // nothing to do
                  if let RespoEvent::Click { original_event, .. } = e {
                    // stop propagation to prevent closing the drawer
                    original_event.stop_propagation();
                  }
                  Ok(())
                })
                .elements([div().class(column()).children([
                  div()
                    .class(ui_center())
                    .children([span().inner_text(options.title.unwrap_or_else(|| "Drawer".to_owned())).to_node()])
                    .to_node(),
                  space(None, Some(8)).to_node(),
                  options.render.run({
                    let close = close.to_owned();
                    move |dispatch| -> Result<(), String> {
                      close(dispatch)?;
                      Ok(())
                    }
                  })?,
                ])])
                .to_node(),
              comp_esc_listener(show, close)?,
            ])
        } else {
          span().attribute("data-name", "placeholder")
        }]),
    )
    // .effect(&[show], effect_focus)
    .effect(&[show], effect_drawer_fade)
    .to_node()
    .rc(),
  )
}

/// provides the interfaces to component of custom drawer dialog
pub trait DrawerPluginInterface<T>
where
  T: Debug + Clone + RespoAction,
{
  /// renders UI
  fn render(&self) -> Result<RespoNode<T>, String>
  where
    T: Clone + Debug;
  /// to show drawer
  fn show(&self, dispatch: DispatchFn<T>) -> Result<(), String>;
  /// to close drawer
  fn close(&self, dispatch: DispatchFn<T>) -> Result<(), String>;

  fn new(states: RespoStatesTree, options: DrawerOptions<T>) -> Result<Self, String>
  where
    Self: std::marker::Sized;

  /// share it with `Rc`
  fn share_with_ref(&self) -> Rc<Self>;
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, RespoState)]
struct DrawerPluginState {
  show: bool,
}

/// a drawer that you can render you down card body
#[derive(Debug, Clone)]
pub struct DrawerPlugin<T>
where
  T: Clone + Debug,
{
  state: Rc<DrawerPluginState>,
  options: DrawerOptions<T>,
  /// tracking content to display
  cursor: Vec<Rc<str>>,
  phantom: PhantomData<T>,
}

impl<T> DrawerPluginInterface<T> for DrawerPlugin<T>
where
  T: Clone + Debug + RespoAction,
{
  fn render(&self) -> Result<RespoNode<T>, String> {
    let cursor = self.cursor.to_owned();

    comp_drawer(self.options.to_owned(), self.state.show, move |dispatch: DispatchFn<_>| {
      let s = DrawerPluginState { show: false };
      dispatch.run_state(&cursor, s)?;
      Ok(())
    })
  }
  fn show(&self, dispatch: DispatchFn<T>) -> Result<(), String> {
    let s = DrawerPluginState { show: true };
    dispatch.run_state(&self.cursor, s)?;
    Ok(())
  }
  fn close(&self, dispatch: DispatchFn<T>) -> Result<(), String> {
    let s = DrawerPluginState { show: false };
    dispatch.run_state(&self.cursor, s)?;
    Ok(())
  }

  fn new(states: RespoStatesTree, options: DrawerOptions<T>) -> Result<Self, String> {
    let cursor = states.path();
    let state = states.cast_branch::<DrawerPluginState>()?;

    let instance = Self {
      state,
      options,
      cursor,
      phantom: PhantomData,
    };

    Ok(instance)
  }

  fn share_with_ref(&self) -> Rc<Self> {
    Rc::new(self.to_owned())
  }
}