use std::rc::Rc;
use crate::{JsJson, dev::JsJsonListDecoder, struct_mut::ValueMut};
#[derive(Clone, Debug, Default)]
pub struct ClickEvent {
pub alt_key: bool,
pub ctrl_key: bool,
pub shift_key: bool,
pub meta_key: bool,
pub position: Option<ClickPosition>,
inner: Rc<ValueMut<ClickEventInner>>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ClickPosition {
pub x: f64,
pub y: f64,
pub element_width: f64,
pub element_height: f64,
}
#[derive(Clone, Debug, Default)]
pub struct ClickEventInner {
stop_propagation: bool,
prevent_default: bool,
}
impl ClickEvent {
pub fn stop_propagation(&self) {
self.inner.change(|inner| inner.stop_propagation = true);
}
pub fn prevent_default(&self) {
self.inner.change(|inner| inner.prevent_default = true);
}
pub(crate) fn from_driver(data: JsJson) -> Self {
let decoded = data.map_list(|mut params: JsJsonListDecoder| {
let alt_key = params.get_bool("altKey")?;
let ctrl_key = params.get_bool("ctrlKey")?;
let shift_key = params.get_bool("shiftKey")?;
let meta_key = params.get_bool("metaKey")?;
let position = match params.get_any("position")? {
JsJson::Null => None,
position => Some(position.map_list(|mut params: JsJsonListDecoder| {
let position = ClickPosition {
x: params.get_f64("pointerX")?,
y: params.get_f64("pointerY")?,
element_width: params.get_f64("elementWidth")?,
element_height: params.get_f64("elementHeight")?,
};
params.expect_no_more()?;
Ok(position)
})?),
};
params.expect_no_more()?;
Ok(Self {
alt_key,
ctrl_key,
shift_key,
meta_key,
position,
inner: Rc::default(),
})
});
decoded.unwrap_or_default()
}
}
impl From<ClickEvent> for JsJson {
fn from(val: ClickEvent) -> JsJson {
let inner = val.inner.get();
JsJson::Object(
[
(
"stop_propagation".to_string(),
JsJson::from(inner.stop_propagation),
),
(
"prevent_default".to_string(),
JsJson::from(inner.prevent_default),
),
]
.into_iter()
.collect(),
)
}
}