all lists on lists.proxmox.com
 help / color / mirror / Atom feed
* [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press
@ 2025-05-02 13:30 Dominik Csapak
  2025-05-02 13:30 ` [yew-devel] [PATCH yew-comp 2/2] wizard: allow enter to be used for switching to next page Dominik Csapak
  2025-05-05 11:06 ` [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press Shannon Sterz
  0 siblings, 2 replies; 3+ messages in thread
From: Dominik Csapak @ 2025-05-02 13:30 UTC (permalink / raw)
  To: yew-devel

this adds 2 new methods to the WizardPageRenderInfo
* on_next: sets a callback for the current page that will be called if
  the wizards wants to change to a later page (e.g. by clicking 'next')
  this callback can also prevent the switching by returning false

* go_to_next_page: switches to the next page. In case a page intercepts
  the switching, it must make sure to switch to the next page when
  the action it wanted to do finished.

for this to work properly, we have to not set the state when the
selection changes already, since we need the old page to check for a
such a callback.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
 src/wizard.rs | 82 ++++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 72 insertions(+), 10 deletions(-)

diff --git a/src/wizard.rs b/src/wizard.rs
index 1ff7b6a..5f49563 100644
--- a/src/wizard.rs
+++ b/src/wizard.rs
@@ -82,6 +82,39 @@ impl WizardPageRenderInfo {
             }
         }
     }
+
+    /// Sets a callback that will be called when a later page wants to be selected
+    /// (e.g. by the next button)
+    ///
+    /// The callback should return true when that's allowed, false otherwise.
+    /// When the callback returns false, the page should handle navigating
+    /// to the next page by itself.
+    ///
+    /// This is useful for panels in a wizard that act like a form that
+    /// has to be submitted before navigating to the next page.
+    pub fn on_next(&self, callback: impl Into<Callback<(), bool>>) {
+        let mut controller = self.controller.write();
+        controller
+            .submit_callbacks
+            .insert(self.key.clone(), callback.into());
+    }
+
+    /// Navigates the wizard to the next page (if possible)
+    ///
+    /// Note that callbacks setup with [`on_next`] will not be called,
+    /// otherwise it could lead to an infinite loop easily.
+    pub fn go_to_next_page(&self) {
+        let controller = self.controller.write();
+        let Some(current_idx) = controller.page_list.iter().position(|p| *p == self.key) else {
+            return;
+        };
+        let Some(next_page) = controller.page_list.get(current_idx + 1) else {
+            return;
+        };
+        controller
+            .link
+            .send_message(Msg::SelectPage(next_page.clone(), false));
+    }
 }
 
 #[derive(Clone, PartialEq)]
@@ -224,6 +257,19 @@ struct WizardState {
     page: Option<Key>,
     page_data: HashMap<Key, FormContext>,
     page_list: Vec<Key>,
+    submit_callbacks: HashMap<Key, Callback<(), bool>>,
+}
+
+impl WizardState {
+    /// Returns the index of the page from the given [`Key`] if that exists
+    pub fn get_index(&self, key: Option<&Key>) -> Option<usize> {
+        key.and_then(|key| self.page_list.iter().position(|page_key| *page_key == *key))
+    }
+
+    /// Returns the callback of the page from the given [`Key`] if that exists
+    pub fn get_callback(&self, key: Option<&Key>) -> Option<Callback<(), bool>> {
+        key.and_then(|key| self.submit_callbacks.get(key).cloned())
+    }
 }
 
 impl WizardController {
@@ -233,6 +279,7 @@ impl WizardController {
             page: None,
             page_data: HashMap::new(),
             page_list: Vec::new(),
+            submit_callbacks: HashMap::new(),
         };
         Self {
             state: Rc::new(RefCell::new(state)),
@@ -273,8 +320,8 @@ pub struct PwtWizard {
 }
 
 pub enum Msg {
-    PageLock(Key, bool), // disable/enable next button
-    SelectPage(Key),
+    PageLock(Key, bool),   // disable/enable next button
+    SelectPage(Key, bool), // call optional callback
     ChangeValid(Key, bool),
     SelectionChange(Selection),
     CloseDialog,
@@ -314,8 +361,27 @@ impl Component for PwtWizard {
     fn update(&mut self, ctx: &yew::Context<Self>, msg: Self::Message) -> bool {
         let props = ctx.props();
         match msg {
-            Msg::SelectPage(page) => {
+            Msg::SelectPage(page, use_callback) => {
                 let mut state = self.controller.write();
+
+                if use_callback {
+                    let cur_idx = state.get_index(state.page.as_ref());
+                    let target_idx = state.get_index(Some(&page));
+
+                    match (cur_idx, target_idx) {
+                        (Some(cur), Some(target)) if target > cur => {
+                            // we selected a later page
+                            if let Some(callback) = state.get_callback(state.page.as_ref()) {
+                                if !callback.emit(()) {
+                                    self.selection.select(state.page.clone().unwrap());
+                                    return true;
+                                }
+                            }
+                        }
+                        _ => {}
+                    }
+                }
+
                 self.selection.select(page.clone());
                 state.page = Some(page.clone());
 
@@ -334,14 +400,10 @@ impl Component for PwtWizard {
             }
             Msg::SelectionChange(selection) => {
                 if let Some(selected_key) = selection.selected_key() {
-                    {
-                        let mut state = self.controller.write();
-                        state.page = Some(selected_key.clone());
-                    }
                     return <Self as yew::Component>::update(
                         self,
                         ctx,
-                        Msg::SelectPage(selected_key),
+                        Msg::SelectPage(selected_key, true),
                     );
                 }
             }
@@ -569,7 +631,7 @@ impl PwtWizard {
                     let prev_page = prev_page.clone();
                     move |_| {
                         if let Some(prev_page) = &prev_page {
-                            link.send_message(Msg::SelectPage(prev_page.clone()));
+                            link.send_message(Msg::SelectPage(prev_page.clone(), false));
                         }
                     }
                 })
@@ -583,7 +645,7 @@ impl PwtWizard {
                         let next_page = next_page.clone();
                         move |_| {
                             if let Some(next_page) = &next_page {
-                                link.send_message(Msg::SelectPage(next_page.clone()));
+                                link.send_message(Msg::SelectPage(next_page.clone(), true));
                             } else {
                                 link.send_message(Msg::Submit);
                             }
-- 
2.39.5



_______________________________________________
yew-devel mailing list
yew-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/yew-devel


^ permalink raw reply	[flat|nested] 3+ messages in thread

* [yew-devel] [PATCH yew-comp 2/2] wizard: allow enter to be used for switching to next page
  2025-05-02 13:30 [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press Dominik Csapak
@ 2025-05-02 13:30 ` Dominik Csapak
  2025-05-05 11:06 ` [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press Shannon Sterz
  1 sibling, 0 replies; 3+ messages in thread
From: Dominik Csapak @ 2025-05-02 13:30 UTC (permalink / raw)
  To: yew-devel

by intercepting the `onsubmit` event of the form for each page, which is
triggered when pressing enter in an input field.

For it to work on all forms, we have to inject an invisible input
'submit' element, since pressing enter only submits the form if such an
element is present (or if the form contains a single field; which we
cannot check here).

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
 src/wizard.rs | 27 +++++++++++++++++++++++----
 1 file changed, 23 insertions(+), 4 deletions(-)

diff --git a/src/wizard.rs b/src/wizard.rs
index 5f49563..cb7ec9d 100644
--- a/src/wizard.rs
+++ b/src/wizard.rs
@@ -17,8 +17,8 @@ use pwt::props::{AsCssStylesMut, ContainerBuilder, CssStyles};
 use pwt::state::Selection;
 use pwt::widget::form::{Form, FormContext};
 use pwt::widget::{
-    AlertDialog, Button, Container, Dialog, Mask, MiniScrollMode, Row, TabBarItem, TabBarStyle,
-    TabPanel,
+    AlertDialog, Button, Container, Dialog, Input, Mask, MiniScrollMode, Row, TabBarItem,
+    TabBarStyle, TabPanel,
 };
 
 use yew::html::{IntoEventCallback, IntoPropValue};
@@ -462,7 +462,7 @@ impl Component for PwtWizard {
         let state = self.controller.read();
 
         let mut disabled = false;
-        for (key, page) in props.pages.iter() {
+        for (page_num, (key, page)) in props.pages.iter().enumerate() {
             let active = Some(key) == state.page.as_ref();
             let form_ctx = state.page_data.get(key).unwrap();
 
@@ -474,11 +474,30 @@ impl Component for PwtWizard {
                 controller: self.controller.clone(),
             });
 
+            let next_page = props
+                .pages
+                .get_index(page_num + 1)
+                .map(|(key, _)| key.clone());
+
             let page_content = Form::new()
                 .class(Overflow::Auto)
                 .class(Flex::Fill)
                 .form_context(form_ctx.clone())
-                .with_child(page_content);
+                .onsubmit(ctx.link().batch_callback({
+                    let form_ctx = form_ctx.clone();
+                    move |_| {
+                        if !form_ctx.read().is_valid() {
+                            return None;
+                        }
+                        if let Some(page) = next_page.clone() {
+                            Some(Msg::SelectPage(page, true))
+                        } else {
+                            Some(Msg::Submit)
+                        }
+                    }
+                }))
+                .with_child(page_content)
+                .with_child(Input::new().attribute("type", "submit").class("pwt-d-none"));
 
             let tab_bar_item = page.tab_bar_item.clone().disabled(disabled);
 
-- 
2.39.5



_______________________________________________
yew-devel mailing list
yew-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/yew-devel


^ permalink raw reply	[flat|nested] 3+ messages in thread

* Re: [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press
  2025-05-02 13:30 [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press Dominik Csapak
  2025-05-02 13:30 ` [yew-devel] [PATCH yew-comp 2/2] wizard: allow enter to be used for switching to next page Dominik Csapak
@ 2025-05-05 11:06 ` Shannon Sterz
  1 sibling, 0 replies; 3+ messages in thread
From: Shannon Sterz @ 2025-05-05 11:06 UTC (permalink / raw)
  To: Yew framework devel list at Proxmox, Dominik Csapak

On Fri May 2, 2025 at 3:30 PM CEST, Dominik Csapak wrote:
> this adds 2 new methods to the WizardPageRenderInfo
> * on_next: sets a callback for the current page that will be called if
>   the wizards wants to change to a later page (e.g. by clicking 'next')
>   this callback can also prevent the switching by returning false
>
> * go_to_next_page: switches to the next page. In case a page intercepts
>   the switching, it must make sure to switch to the next page when
>   the action it wanted to do finished.
>
> for this to work properly, we have to not set the state when the
> selection changes already, since we need the old page to check for a
> such a callback.
>
> Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
> ---
>  src/wizard.rs | 82 ++++++++++++++++++++++++++++++++++++++++++++-------
>  1 file changed, 72 insertions(+), 10 deletions(-)
>
> diff --git a/src/wizard.rs b/src/wizard.rs
> index 1ff7b6a..5f49563 100644
> --- a/src/wizard.rs
> +++ b/src/wizard.rs
> @@ -82,6 +82,39 @@ impl WizardPageRenderInfo {
>              }
>          }
>      }
> +
> +    /// Sets a callback that will be called when a later page wants to be selected
> +    /// (e.g. by the next button)
> +    ///
> +    /// The callback should return true when that's allowed, false otherwise.
> +    /// When the callback returns false, the page should handle navigating
> +    /// to the next page by itself.
> +    ///
> +    /// This is useful for panels in a wizard that act like a form that
> +    /// has to be submitted before navigating to the next page.
> +    pub fn on_next(&self, callback: impl Into<Callback<(), bool>>) {
> +        let mut controller = self.controller.write();
> +        controller
> +            .submit_callbacks
> +            .insert(self.key.clone(), callback.into());
> +    }
> +
> +    /// Navigates the wizard to the next page (if possible)
> +    ///
> +    /// Note that callbacks setup with [`on_next`] will not be called,
> +    /// otherwise it could lead to an infinite loop easily.
> +    pub fn go_to_next_page(&self) {
> +        let controller = self.controller.write();
> +        let Some(current_idx) = controller.page_list.iter().position(|p| *p == self.key) else {
> +            return;
> +        };
> +        let Some(next_page) = controller.page_list.get(current_idx + 1) else {
> +            return;
> +        };
> +        controller
> +            .link
> +            .send_message(Msg::SelectPage(next_page.clone(), false));
> +    }
>  }
>
>  #[derive(Clone, PartialEq)]
> @@ -224,6 +257,19 @@ struct WizardState {
>      page: Option<Key>,
>      page_data: HashMap<Key, FormContext>,
>      page_list: Vec<Key>,
> +    submit_callbacks: HashMap<Key, Callback<(), bool>>,
> +}
> +
> +impl WizardState {
> +    /// Returns the index of the page from the given [`Key`] if that exists
> +    pub fn get_index(&self, key: Option<&Key>) -> Option<usize> {
> +        key.and_then(|key| self.page_list.iter().position(|page_key| *page_key == *key))
> +    }

i feel like this shouldn't take an `Option<&Key>`, this mostly seems to
be done out of convenience so you can directly pass `WizardState::page`
here, but imo `page.and_then(|k| state.get_index(k))` would be just as
elegant there and it would remove the somewhat obvious "passing `None`
to this, will return `None`" tautology. same for the helper below. as
this is a `pub fn` it might get re-used in context in which wrapping the
`Key` in an `Option` is just superfluous.

it might also make sense to create a `get_current_index()` helper as
well that re-uses this function. for example:

```rs
pub fn get_current_index(&self) -> Option<usize> {
    self.page.and_then(|k| self.get_current_index(k))
}
```

also is there any reason you manually access the `page_list` again in
the above `go_to_next_page` function, instead of simply using this
helper?

> +
> +    /// Returns the callback of the page from the given [`Key`] if that exists
> +    pub fn get_callback(&self, key: Option<&Key>) -> Option<Callback<(), bool>> {
> +        key.and_then(|key| self.submit_callbacks.get(key).cloned())
> +    }
>  }
>
>  impl WizardController {
> @@ -233,6 +279,7 @@ impl WizardController {
>              page: None,
>              page_data: HashMap::new(),
>              page_list: Vec::new(),
> +            submit_callbacks: HashMap::new(),
>          };
>          Self {
>              state: Rc::new(RefCell::new(state)),
> @@ -273,8 +320,8 @@ pub struct PwtWizard {
>  }
>
>  pub enum Msg {
> -    PageLock(Key, bool), // disable/enable next button
> -    SelectPage(Key),
> +    PageLock(Key, bool),   // disable/enable next button
> +    SelectPage(Key, bool), // call optional callback
>      ChangeValid(Key, bool),
>      SelectionChange(Selection),
>      CloseDialog,
> @@ -314,8 +361,27 @@ impl Component for PwtWizard {
>      fn update(&mut self, ctx: &yew::Context<Self>, msg: Self::Message) -> bool {
>          let props = ctx.props();
>          match msg {
> -            Msg::SelectPage(page) => {
> +            Msg::SelectPage(page, use_callback) => {
>                  let mut state = self.controller.write();
> +
> +                if use_callback {
> +                    let cur_idx = state.get_index(state.page.as_ref());
> +                    let target_idx = state.get_index(Some(&page));
> +
> +                    match (cur_idx, target_idx) {
> +                        (Some(cur), Some(target)) if target > cur => {
> +                            // we selected a later page
> +                            if let Some(callback) = state.get_callback(state.page.as_ref()) {
> +                                if !callback.emit(()) {
> +                                    self.selection.select(state.page.clone().unwrap());
> +                                    return true;
> +                                }
> +                            }
> +                        }
> +                        _ => {}
> +                    }
> +                }
> +
>                  self.selection.select(page.clone());
>                  state.page = Some(page.clone());
>
> @@ -334,14 +400,10 @@ impl Component for PwtWizard {
>              }
>              Msg::SelectionChange(selection) => {
>                  if let Some(selected_key) = selection.selected_key() {
> -                    {
> -                        let mut state = self.controller.write();
> -                        state.page = Some(selected_key.clone());
> -                    }
>                      return <Self as yew::Component>::update(
>                          self,
>                          ctx,
> -                        Msg::SelectPage(selected_key),
> +                        Msg::SelectPage(selected_key, true),
>                      );
>                  }
>              }
> @@ -569,7 +631,7 @@ impl PwtWizard {
>                      let prev_page = prev_page.clone();
>                      move |_| {
>                          if let Some(prev_page) = &prev_page {
> -                            link.send_message(Msg::SelectPage(prev_page.clone()));
> +                            link.send_message(Msg::SelectPage(prev_page.clone(), false));
>                          }
>                      }
>                  })
> @@ -583,7 +645,7 @@ impl PwtWizard {
>                          let next_page = next_page.clone();
>                          move |_| {
>                              if let Some(next_page) = &next_page {
> -                                link.send_message(Msg::SelectPage(next_page.clone()));
> +                                link.send_message(Msg::SelectPage(next_page.clone(), true));
>                              } else {
>                                  link.send_message(Msg::Submit);
>                              }



_______________________________________________
yew-devel mailing list
yew-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/yew-devel


^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2025-05-05 11:06 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2025-05-02 13:30 [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press Dominik Csapak
2025-05-02 13:30 ` [yew-devel] [PATCH yew-comp 2/2] wizard: allow enter to be used for switching to next page Dominik Csapak
2025-05-05 11:06 ` [yew-devel] [PATCH yew-comp 1/2] wizard: add possibility to intercept the 'next' button press Shannon Sterz

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal