Skip to main content

next_rust_ui/
press.rs

1//! What happens when a component is pressed.
2
3use next_rust_view::{Attr, attrs::raw_attr};
4
5/// Behavior for `on_press`: call a server action, navigate, dispatch an
6/// event, or run a script.
7///
8/// ```ignore
9/// Button![on_press = action!(archive), "Archive"]                  // server action
10/// Button![on_press = Press::from(action!(like)).input(&id), "Like"]
11/// Button![on_press = Press::navigate("/settings"), "Settings"]
12/// Button![on_press = Press::emit("open-cart"), "Cart"]              // `nr:open-cart` event
13/// Button![on_press = Press::open_modal("confirm"), "Delete…"]       // opens `Modal![id = "confirm", ..]`
14/// ```
15///
16/// After a successful action the page refreshes (see [`Press::no_refresh`]);
17/// the element receives `nr:success` / `nr:error` events either way.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Press {
20    kind: Kind,
21    input: Option<String>,
22    refresh: bool,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26enum Kind {
27    Action(String),
28    Navigate(String),
29    Emit(String),
30    Script(String),
31    OpenModal(String),
32    CloseModal,
33}
34
35impl Press {
36    /// Call the server action at `url`. From a reference, use
37    /// `Press::from(action!(save))` (or simply `on_press = action!(save)`).
38    pub fn action(url: impl Into<String>) -> Self {
39        Press { kind: Kind::Action(url.into()), input: None, refresh: true }
40    }
41
42    /// Client-side navigation to `href`.
43    pub fn navigate(href: impl Into<String>) -> Self {
44        Press { kind: Kind::Navigate(href.into()), input: None, refresh: true }
45    }
46
47    /// Dispatch a bubbling `nr:<name>` event from the element, for your own
48    /// scripts: `addEventListener("nr:open-cart", …)`.
49    pub fn emit(name: impl Into<String>) -> Self {
50        Press { kind: Kind::Emit(name.into()), input: None, refresh: true }
51    }
52
53    /// Open the [`Modal`](struct@crate::Modal) with that `id` (as a modal dialog:
54    /// focus trapped, page behind inert).
55    pub fn open_modal(id: impl Into<String>) -> Self {
56        Press { kind: Kind::OpenModal(id.into()), input: None, refresh: true }
57    }
58
59    /// Close the modal the element is inside.
60    pub fn close_modal() -> Self {
61        Press { kind: Kind::CloseModal, input: None, refresh: true }
62    }
63
64    /// Run a script (an `onclick` attribute). Trusted code only: never pass
65    /// user input. Blocked by a strict Content Security Policy.
66    pub fn script(js: impl Into<String>) -> Self {
67        Press { kind: Kind::Script(js.into()), input: None, refresh: true }
68    }
69
70    /// The action's input, serialized as JSON.
71    pub fn input(mut self, value: &impl serde::Serialize) -> Self {
72        self.input = serde_json::to_string(value).ok();
73        self
74    }
75
76    /// Keep the page as it is after a successful action.
77    pub fn no_refresh(mut self) -> Self {
78        self.refresh = false;
79        self
80    }
81
82    pub(crate) fn is_action(&self) -> bool {
83        matches!(self.kind, Kind::Action(_))
84    }
85
86    pub(crate) fn attrs(&self) -> Vec<Attr> {
87        let (kind, target) = match &self.kind {
88            Kind::Script(js) => return vec![raw_attr("onclick", js.clone())],
89            Kind::Action(url) => ("action", url),
90            Kind::Navigate(href) => ("navigate", href),
91            Kind::Emit(name) => ("emit", name),
92            Kind::OpenModal(id) => ("modal", id),
93            Kind::CloseModal => {
94                return vec![Attr::new("data-nr-ui", "press"), Attr::new("data-nr-press", "close-modal")];
95            }
96        };
97        let mut attrs = vec![
98            Attr::new("data-nr-ui", "press"),
99            Attr::new("data-nr-press", kind),
100            Attr::new("data-nr-press-target", target.clone()),
101        ];
102        if let Some(input) = &self.input {
103            attrs.push(Attr::new("data-nr-press-input", input.clone()));
104        }
105        if !self.refresh {
106            attrs.push(Attr::new("data-nr-press-refresh", "false"));
107        }
108        attrs
109    }
110}