use rdom_core::NodeId;
use super::dropdown::{close, is_dropdown, is_open, open};
use super::model::{closest_option, closest_select, enclosing_select, is_multi, option_disabled};
use super::state::{
extend_selection_to, fire_input_and_change, select_single, set_highlight, toggle_option,
};
use crate::{TuiDom, TuiEventCtx};
pub(super) fn on_click(ctx: &mut TuiEventCtx<'_>) {
if ctx.event.default_prevented() {
return;
}
let Some(target) = ctx.event.target else {
return;
};
let option = closest_option(ctx.dom, target);
let select = match option {
Some(o) => enclosing_select(ctx.dom, o),
None => closest_select(ctx.dom, target),
};
let Some(select) = select else {
return;
};
if ctx.dom.is_actually_disabled(select) {
return;
}
let shift = ctx
.event
.detail
.as_mouse()
.map(|m| m.modifiers.shift)
.unwrap_or(false);
match option {
Some(opt) if !option_disabled(ctx.dom, opt) => {
click_option(ctx.dom, select, opt, shift);
if is_dropdown(ctx.dom, select) {
close(ctx.dom, select);
}
}
Some(_) => {
}
None => {
if is_dropdown(ctx.dom, select) {
if is_open(ctx.dom, select) {
close(ctx.dom, select);
} else {
open(ctx.dom, select);
}
}
}
}
}
fn click_option(dom: &mut TuiDom, select: NodeId, option: NodeId, shift: bool) {
let multi = is_multi(dom, select);
if multi {
if shift {
extend_selection_to(dom, select, option);
} else {
toggle_option(dom, select, option);
}
set_highlight(dom, select, Some(option));
} else {
select_single(dom, select, option);
set_highlight(dom, select, Some(option));
}
fire_input_and_change(dom, select);
}