Struct respo::StatesTree
source · pub struct StatesTree {
pub data: MaybeState,
pub cursor: Vec<String>,
pub branches: HashMap<String, Box<StatesTree>>,
}Expand description
Respo maintains states in a tree structure, where the keys are strings, each child component “picks” a key to attach its own state to the tree, and it dispatches events to global store to update the state.
Fields§
§data: MaybeStatelocal data
cursor: Vec<String>the path to the current state in the tree, use in updating
branches: HashMap<String, Box<StatesTree>>holding children states
Implementations§
source§impl StatesTree
impl StatesTree
sourcepub fn path(&self) -> Vec<String>
pub fn path(&self) -> Vec<String>
get cursor
Examples found in repository?
src/dialog/modal.rs (line 206)
205 206 207 208 209 210 211 212 213 214 215 216 217
fn new(states: StatesTree, options: ModalOptions<T>) -> Result<Self, String> {
let cursor = states.path();
let state: ModalPluginState = states.data.cast_or_default()?;
let instance = Self {
state,
options,
cursor,
phantom: PhantomData,
};
Ok(instance)
}More examples
src/dialog/drawer.rs (line 206)
205 206 207 208 209 210 211 212 213 214 215 216 217
fn new(states: StatesTree, options: DrawerOptions<T>) -> Result<Self, String> {
let cursor = states.path();
let state: DrawerPluginState = states.data.cast_or_default()?;
let instance = Self {
state,
options,
cursor,
phantom: PhantomData,
};
Ok(instance)
}src/dialog/alert.rs (line 204)
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
fn new(states: StatesTree, options: AlertOptions, on_read: U) -> Result<Self, String> {
let cursor = states.path();
let state: AlertPluginState = states.data.cast_or_default()?;
let instance = Self {
state,
options,
text: None,
cursor,
on_read,
phantom: PhantomData,
};
Ok(instance)
}src/dialog/confirm.rs (line 241)
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
fn new(states: StatesTree, options: ConfirmOptions, on_confirm: U) -> Result<Self, String> {
let cursor = states.path();
let state: ConfirmPluginState = states.data.cast_or_default()?;
let instance = Self {
state,
options,
text: None,
cursor,
on_confirm,
phantom: PhantomData,
};
Ok(instance)
}src/dialog/prompt.rs (line 85)
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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
fn comp_prompt_modal<T, U, V>(
states: StatesTree,
options: PromptOptions,
show: bool,
on_submit: U,
on_close: V,
) -> Result<RespoNode<T>, String>
where
U: Fn(String, DispatchFn<T>) -> Result<(), String> + 'static,
V: Fn(DispatchFn<T>) -> Result<(), String> + 'static,
T: Clone + Debug + RespoAction,
{
let cursor = states.path();
let cursor2 = cursor.clone();
let cursor3 = cursor.clone();
let mut state: InputState = states.data.cast_or_default()?;
if let Some(text) = &options.initial_value {
state.draft = text.to_owned();
}
// respo::util::log!("State: {:?}", state);
let state2 = state.clone();
let submit = Rc::new(on_submit);
let close = Rc::new(on_close);
let close2 = close.clone();
let on_text_input = move |e, dispatch: DispatchFn<_>| -> Result<(), String> {
if let RespoEvent::Input { value, .. } = e {
dispatch.run_state(&cursor, InputState { draft: value, error: None })?;
}
Ok(())
};
let check_submit = move |text: &str, dispatch: DispatchFn<_>| -> Result<(), String> {
let dispatch2 = dispatch.clone();
let dispatch3 = dispatch.clone();
let dispatch4 = dispatch.clone();
respo::util::log!("validator: {:?}", &options.validator);
if let Some(validator) = &options.validator {
// let validator = validator.borrow();
let result = validator.run(text);
match result {
Ok(()) => {
submit(text.to_owned(), dispatch)?;
close2(dispatch3)?;
dispatch4.run_empty_state(&cursor2)?;
}
Err(message) => {
// dispatch.run_state(&cursor2, InputState { draft: text.to_owned() })?;
dispatch4.run_state(
&cursor2,
InputState {
draft: text.to_owned(),
error: Some(message),
},
)?;
}
}
} else {
submit(text.to_owned(), dispatch)?;
close2(dispatch2)?;
dispatch4.run_empty_state(&cursor2)?;
}
Ok(())
};
let mut input_el = if options.multilines {
textarea().class(ui_textarea()).to_owned()
} else {
input().class(ui_input()).to_owned()
};
Ok(
RespoNode::new_component(
"prompt-modal",
div()
.style(RespoStyle::default().position(CssPosition::Absolute).to_owned())
.children([if show {
div()
.class_list(&[ui_fullscreen(), ui_center(), css_backdrop()])
.style(options.backdrop_style)
.on_click(move |e, dispatch| -> Result<(), String> {
if let RespoEvent::Click { original_event, .. } = e {
// stop propagation to prevent closing the modal
original_event.stop_propagation();
}
{
let dispatch = dispatch.clone();
close(dispatch)?;
}
dispatch.run_empty_state(&cursor3)?;
Ok(())
})
.children([div()
.class_list(&[ui_column(), ui_global(), css_modal_card()])
.style(RespoStyle::default().line_height(CssLineHeight::Px(32.0)).to_owned())
.style(options.card_style)
.style(options.input_style)
.on_click(move |e, _dispatch| -> Result<(), String> {
// nothing to do
if let RespoEvent::Click { original_event, .. } = e {
// stop propagation to prevent closing the modal
original_event.stop_propagation();
}
Ok(())
})
.children([div()
.children([
span()
.inner_text(options.text.unwrap_or_else(|| "Input your text:".to_owned()))
.to_owned(),
space(None, Some(8)),
div()
.children([input_el
.class_list(&[ui_input()])
.style(RespoStyle::default().width(CssSize::Percent(100.0)).to_owned())
.attribute("placeholder", "Content...")
.attribute("autoFocus", "autofocus")
.value(state.draft)
.on_input(on_text_input)
.to_owned()])
.to_owned(),
match &state.error {
Some(message) => div().class_list(&[css_error()]).inner_text(message).to_owned(),
None => span(),
},
space(None, Some(8)),
div()
.class(ui_row_parted())
.children([
span(),
button()
.class_list(&[ui_button(), css_button(), BUTTON_NAME.to_owned()])
.inner_text(options.button_text.unwrap_or_else(|| "Submit".to_owned()))
.on_click(move |_e, dispatch| -> Result<(), String> {
check_submit(&state2.draft, dispatch)?;
Ok(())
})
.to_owned(),
])
.to_owned(),
])
.to_owned()])
.to_owned()])
.to_owned()
} else {
span().attribute("data-name", "placeholder").to_owned()
}])
.to_owned(),
)
// .effect(&[show], effect_focus)
.effect(&[show], effect_modal_fade)
.share_with_ref(),
)
}
/// provides the interfaces to component of prompt dialog
pub trait PromptPluginInterface<T, U>
where
T: Debug + Clone + RespoAction,
U: Fn(String, DispatchFn<T>) -> Result<(), String>,
{
/// renders UI
fn render(&self) -> Result<RespoNode<T>, String>
where
T: Clone + Debug;
/// to show prompt dialog, second parameter is the callback task when the dialog is read,
/// the callback is stored in a dirty to provide syntax sugar
fn show<V>(&self, dispatch: DispatchFn<T>, next_task: V) -> Result<(), String>
where
V: Fn(String) -> Result<(), String> + 'static;
/// to close prompt dialog
fn close(&self, dispatch: DispatchFn<T>) -> Result<(), String>;
/// initialize the plugin, second parameter is the callback task when submitted,
fn new(states: StatesTree, options: PromptOptions, on_submit: U) -> Result<Self, String>
where
Self: std::marker::Sized;
/// shared it in `Rc`
fn share_with_ref(&self) -> Rc<Self>;
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct PromptPluginState {
show: bool,
text: Option<String>,
}
/// a dialog for prompt, request for some input, and submit
#[derive(Debug, Clone)]
pub struct PromptPlugin<T, U>
where
T: Clone + Debug,
U: Fn(String, DispatchFn<T>) -> Result<(), String> + 'static,
{
states: StatesTree,
state: PromptPluginState,
options: PromptOptions,
/// tracking content to display
text: Option<String>,
cursor: Vec<String>,
on_submit: U,
phantom: PhantomData<T>,
}
impl<T, U> PromptPluginInterface<T, U> for PromptPlugin<T, U>
where
T: Clone + Debug + RespoAction,
U: Fn(String, DispatchFn<T>) -> Result<(), String> + 'static + Copy,
{
fn render(&self) -> Result<RespoNode<T>, String> {
let on_submit = self.on_submit;
let cursor = self.cursor.clone();
let cursor2 = self.cursor.clone();
let state = self.state.to_owned();
let state2 = self.state.to_owned();
comp_prompt_modal(
self.states.pick("plugin"),
self.options.to_owned(),
self.state.show,
move |content, dispatch| {
let d2 = dispatch.clone();
on_submit(content.to_owned(), dispatch)?;
let window = web_sys::window().expect("window");
// TODO dirty global variable
let task = Reflect::get(&window, &JsValue::from_str(NEXT_TASK_NAME));
if let Ok(f) = task {
if f.is_function() {
let f = f.dyn_into::<Function>().unwrap();
let arr = Array::new();
arr.push(&JsValue::from_str(&content));
let _ = f.apply(&JsValue::NULL, &arr);
} else {
return Err("_NEXT_TASK is not a function".to_owned());
}
} else {
respo::util::log!("next task is None");
};
let s = PromptPluginState {
show: false,
text: state.text.to_owned(),
};
d2.run_state(&cursor, s)?;
// clean up leaked closure
let window = web_sys::window().expect("window");
let _ = Reflect::set(&window, &JsValue::from_str(NEXT_TASK_NAME), &JsValue::NULL);
Ok(())
},
move |dispatch| {
let s = PromptPluginState {
show: false,
text: state2.text.to_owned(),
};
dispatch.run_state(&cursor2, s)?;
// clean up leaked closure
let window = web_sys::window().expect("window");
let _ = Reflect::set(&window, &JsValue::from_str(NEXT_TASK_NAME), &JsValue::NULL);
Ok(())
},
)
}
fn show<V>(&self, dispatch: DispatchFn<T>, next_task: V) -> Result<(), String>
where
V: Fn(String) -> Result<(), String> + 'static,
{
let s = PromptPluginState {
show: true,
text: self.state.text.to_owned(),
};
let task = Closure::once(next_task);
let window = web_sys::window().unwrap();
// dirty global variable to store a shared callback
if let Err(e) = Reflect::set(&window, &JsValue::from_str(NEXT_TASK_NAME), task.as_ref()) {
respo::util::log!("failed to store next task {:?}", e);
}
task.forget();
dispatch.run_state(&self.cursor, s)?;
Ok(())
}
fn close(&self, dispatch: DispatchFn<T>) -> Result<(), String> {
let s = PromptPluginState {
show: false,
text: self.text.clone(),
};
dispatch.run_state(&self.cursor, s)?;
Ok(())
}
fn new(states: StatesTree, options: PromptOptions, on_submit: U) -> Result<Self, String> {
let cursor = states.path();
let state: PromptPluginState = states.data.cast_or_default()?;
let instance = Self {
states,
state,
options,
text: None,
cursor,
on_submit,
phantom: PhantomData,
};
Ok(instance)
}sourcepub fn pick(&self, name: &str) -> StatesTree
pub fn pick(&self, name: &str) -> StatesTree
pick a child branch as new cursor
Examples found in repository?
src/respo/states_tree.rs (line 57)
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
pub fn set_in_mut(&mut self, path: &[String], new_state: MaybeState) {
if path.is_empty() {
(*self).data = new_state;
} else {
let (p_head, p_rest) = path.split_at(1);
let p0 = p_head[0].to_owned();
if let Some(branch) = self.branches.get_mut(&p0) {
branch.set_in_mut(p_rest, new_state);
} else {
let mut branch = self.pick(&p0);
branch.set_in_mut(p_rest, new_state);
self.branches.insert(p0, Box::new(branch));
}
}
}More examples
src/dialog/prompt.rs (line 294)
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
fn render(&self) -> Result<RespoNode<T>, String> {
let on_submit = self.on_submit;
let cursor = self.cursor.clone();
let cursor2 = self.cursor.clone();
let state = self.state.to_owned();
let state2 = self.state.to_owned();
comp_prompt_modal(
self.states.pick("plugin"),
self.options.to_owned(),
self.state.show,
move |content, dispatch| {
let d2 = dispatch.clone();
on_submit(content.to_owned(), dispatch)?;
let window = web_sys::window().expect("window");
// TODO dirty global variable
let task = Reflect::get(&window, &JsValue::from_str(NEXT_TASK_NAME));
if let Ok(f) = task {
if f.is_function() {
let f = f.dyn_into::<Function>().unwrap();
let arr = Array::new();
arr.push(&JsValue::from_str(&content));
let _ = f.apply(&JsValue::NULL, &arr);
} else {
return Err("_NEXT_TASK is not a function".to_owned());
}
} else {
respo::util::log!("next task is None");
};
let s = PromptPluginState {
show: false,
text: state.text.to_owned(),
};
d2.run_state(&cursor, s)?;
// clean up leaked closure
let window = web_sys::window().expect("window");
let _ = Reflect::set(&window, &JsValue::from_str(NEXT_TASK_NAME), &JsValue::NULL);
Ok(())
},
move |dispatch| {
let s = PromptPluginState {
show: false,
text: state2.text.to_owned(),
};
dispatch.run_state(&cursor2, s)?;
// clean up leaked closure
let window = web_sys::window().expect("window");
let _ = Reflect::set(&window, &JsValue::from_str(NEXT_TASK_NAME), &JsValue::NULL);
Ok(())
},
)
}sourcepub fn set_in_mut(&mut self, path: &[String], new_state: MaybeState)
pub fn set_in_mut(&mut self, path: &[String], new_state: MaybeState)
in-place mutation of state tree
Examples found in repository?
src/respo/states_tree.rs (line 55)
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
pub fn set_in_mut(&mut self, path: &[String], new_state: MaybeState) {
if path.is_empty() {
(*self).data = new_state;
} else {
let (p_head, p_rest) = path.split_at(1);
let p0 = p_head[0].to_owned();
if let Some(branch) = self.branches.get_mut(&p0) {
branch.set_in_mut(p_rest, new_state);
} else {
let mut branch = self.pick(&p0);
branch.set_in_mut(p_rest, new_state);
self.branches.insert(p0, Box::new(branch));
}
}
}Trait Implementations§
source§impl Clone for StatesTree
impl Clone for StatesTree
source§fn clone(&self) -> StatesTree
fn clone(&self) -> StatesTree
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moresource§impl Debug for StatesTree
impl Debug for StatesTree
source§impl Default for StatesTree
impl Default for StatesTree
source§fn default() -> StatesTree
fn default() -> StatesTree
Returns the “default value” for a type. Read more
source§impl<'de> Deserialize<'de> for StatesTree
impl<'de> Deserialize<'de> for StatesTree
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl PartialEq<StatesTree> for StatesTree
impl PartialEq<StatesTree> for StatesTree
source§fn eq(&self, other: &StatesTree) -> bool
fn eq(&self, other: &StatesTree) -> bool
This method tests for
self and other values to be equal, and is used
by ==.