1use next_rust_view::{Attr, attrs::raw_attr};
4
5#[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 pub fn action(url: impl Into<String>) -> Self {
39 Press { kind: Kind::Action(url.into()), input: None, refresh: true }
40 }
41
42 pub fn navigate(href: impl Into<String>) -> Self {
44 Press { kind: Kind::Navigate(href.into()), input: None, refresh: true }
45 }
46
47 pub fn emit(name: impl Into<String>) -> Self {
50 Press { kind: Kind::Emit(name.into()), input: None, refresh: true }
51 }
52
53 pub fn open_modal(id: impl Into<String>) -> Self {
56 Press { kind: Kind::OpenModal(id.into()), input: None, refresh: true }
57 }
58
59 pub fn close_modal() -> Self {
61 Press { kind: Kind::CloseModal, input: None, refresh: true }
62 }
63
64 pub fn script(js: impl Into<String>) -> Self {
67 Press { kind: Kind::Script(js.into()), input: None, refresh: true }
68 }
69
70 pub fn input(mut self, value: &impl serde::Serialize) -> Self {
72 self.input = serde_json::to_string(value).ok();
73 self
74 }
75
76 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}