use next_rust_view::{Attr, attrs::raw_attr};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Press {
kind: Kind,
input: Option<String>,
refresh: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
Action(String),
Navigate(String),
Emit(String),
Script(String),
OpenModal(String),
CloseModal,
}
impl Press {
pub fn action(url: impl Into<String>) -> Self {
Press { kind: Kind::Action(url.into()), input: None, refresh: true }
}
pub fn navigate(href: impl Into<String>) -> Self {
Press { kind: Kind::Navigate(href.into()), input: None, refresh: true }
}
pub fn emit(name: impl Into<String>) -> Self {
Press { kind: Kind::Emit(name.into()), input: None, refresh: true }
}
pub fn open_modal(id: impl Into<String>) -> Self {
Press { kind: Kind::OpenModal(id.into()), input: None, refresh: true }
}
pub fn close_modal() -> Self {
Press { kind: Kind::CloseModal, input: None, refresh: true }
}
pub fn script(js: impl Into<String>) -> Self {
Press { kind: Kind::Script(js.into()), input: None, refresh: true }
}
pub fn input(mut self, value: &impl serde::Serialize) -> Self {
self.input = serde_json::to_string(value).ok();
self
}
pub fn no_refresh(mut self) -> Self {
self.refresh = false;
self
}
pub(crate) fn is_action(&self) -> bool {
matches!(self.kind, Kind::Action(_))
}
pub(crate) fn attrs(&self) -> Vec<Attr> {
let (kind, target) = match &self.kind {
Kind::Script(js) => return vec![raw_attr("onclick", js.clone())],
Kind::Action(url) => ("action", url),
Kind::Navigate(href) => ("navigate", href),
Kind::Emit(name) => ("emit", name),
Kind::OpenModal(id) => ("modal", id),
Kind::CloseModal => {
return vec![Attr::new("data-nr-ui", "press"), Attr::new("data-nr-press", "close-modal")];
}
};
let mut attrs = vec![
Attr::new("data-nr-ui", "press"),
Attr::new("data-nr-press", kind),
Attr::new("data-nr-press-target", target.clone()),
];
if let Some(input) = &self.input {
attrs.push(Attr::new("data-nr-press-input", input.clone()));
}
if !self.refresh {
attrs.push(Attr::new("data-nr-press-refresh", "false"));
}
attrs
}
}