use std::any::Any;
use std::collections::HashMap;
use super::{A11yNode, Dom};
use crate::input::KeyCode;
use crate::render::RenderContext;
use crate::types::Rect;
use crate::ui::style::Style;
#[derive(Clone, Debug, PartialEq)]
pub struct SlotPaint<'a> {
pub key: &'a str,
pub rect: Rect,
pub hover: Option<(f64, f64)>,
pub held: bool,
pub focused: bool,
pub style: Option<&'a Style>,
}
impl<'a> SlotPaint<'a> {
pub fn new(key: &'a str, rect: Rect) -> Self {
Self { key, rect, hover: None, held: false, focused: false, style: None }
}
pub fn var<'s>(&'s self, name: &str, fallback: &'s str) -> &'s str {
self.style.and_then(|s| s.custom(name)).unwrap_or(fallback)
}
pub fn color<'s>(&'s self, fallback: &'s str) -> &'s str {
self.style.and_then(|s| s.color.as_deref()).unwrap_or(fallback)
}
pub fn local(&self, x: f64, y: f64) -> (f64, f64) {
(x - self.rect.x, y - self.rect.y)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum SlotEvent {
Enter { x: f64, y: f64 },
Move { x: f64, y: f64 },
Leave,
Down { x: f64, y: f64 },
Drag { x: f64, y: f64, dx: f64, dy: f64 },
Up { x: f64, y: f64 },
Click { x: f64, y: f64 },
Wheel { x: f64, y: f64, dx: f64, dy: f64 },
Pan { x: f64, y: f64, dx: f64, dy: f64 },
PanEnd { x: f64, y: f64 },
Pinch { x: f64, y: f64, scale: f64 },
PinchPan { x: f64, y: f64, dx: f64, dy: f64 },
PinchEnd { scale: f64 },
LongPress { x: f64, y: f64 },
DoubleTap { x: f64, y: f64 },
Key { code: KeyCode, text: Option<String> },
Focus(bool),
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum SlotValue {
#[default]
None,
Num(f64),
Text(String),
Point(f64, f64),
}
#[derive(Clone, Debug, PartialEq)]
pub struct SlotAction {
pub slot: String,
pub name: String,
pub value: SlotValue,
}
impl SlotAction {
pub fn new(name: impl Into<String>) -> Self {
Self { slot: String::new(), name: name.into(), value: SlotValue::None }
}
pub fn num(mut self, v: f64) -> Self {
self.value = SlotValue::Num(v);
self
}
pub fn text(mut self, v: impl Into<String>) -> Self {
self.value = SlotValue::Text(v.into());
self
}
pub fn point(mut self, x: f64, y: f64) -> Self {
self.value = SlotValue::Point(x, y);
self
}
}
pub trait SlotPainter: Any {
fn paint(&mut self, ctx: &mut dyn RenderContext, f: &SlotPaint<'_>);
fn event(&mut self, ev: &SlotEvent, f: &SlotPaint<'_>) -> Option<SlotAction> {
let _ = (ev, f);
None
}
fn role(&self) -> &'static str {
"img"
}
fn name(&self) -> Option<String> {
None
}
fn focusable(&self) -> bool {
false
}
fn wants_frame(&self) -> bool {
false
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SlotInput {
pub pointer: Option<(f64, f64)>,
pub pressed: Option<(f64, f64)>,
pub clicked: bool,
pub wheel: (f64, f64),
pub focused: bool,
pub key: Option<(KeyCode, Option<String>)>,
pub events: Vec<SlotEvent>,
}
#[derive(Clone, Debug, PartialEq)]
enum Pat {
Exact(String),
Prefix(String),
}
impl Pat {
fn matches(&self, key: &str) -> bool {
match self {
Pat::Exact(k) => k == key,
Pat::Prefix(p) => key.starts_with(p.as_str()),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Seen {
hover: Option<(f64, f64)>,
held: Option<(f64, f64)>,
focused: bool,
}
#[derive(Default)]
pub struct SlotRegistry {
entries: Vec<(Pat, Box<dyn SlotPainter>)>,
seen: HashMap<String, Seen>,
}
impl std::fmt::Debug for SlotRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SlotRegistry").field("keys", &self.entries.iter().map(|(p, _)| p).collect::<Vec<_>>()).finish()
}
}
impl SlotRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, key: impl Into<String>, painter: impl SlotPainter) -> &mut Self {
self.put(Pat::Exact(key.into()), Box::new(painter));
self
}
pub fn register_prefix(&mut self, prefix: impl Into<String>, painter: impl SlotPainter) -> &mut Self {
self.put(Pat::Prefix(prefix.into()), Box::new(painter));
self
}
fn put(&mut self, pat: Pat, p: Box<dyn SlotPainter>) {
match self.entries.iter_mut().find(|(q, _)| *q == pat) {
Some(e) => e.1 = p,
None => self.entries.push((pat, p)),
}
}
pub fn remove(&mut self, key: &str) -> bool {
let n = self.entries.len();
self.entries.retain(|(p, _)| !matches!(p, Pat::Exact(k) | Pat::Prefix(k) if k == key));
self.seen.retain(|k, _| self.entries.iter().any(|(p, _)| p.matches(k)));
n != self.entries.len()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
fn index(&self, key: &str) -> Option<usize> {
let mut best: Option<(usize, usize)> = None;
for (i, (p, _)) in self.entries.iter().enumerate() {
if !p.matches(key) {
continue;
}
let rank = match p {
Pat::Exact(_) => usize::MAX,
Pat::Prefix(s) => s.len(),
};
if best.is_none_or(|(_, r)| rank > r) {
best = Some((i, rank));
}
}
best.map(|b| b.0)
}
pub fn contains(&self, key: &str) -> bool {
self.index(key).is_some()
}
pub fn painter(&self, key: &str) -> Option<&dyn SlotPainter> {
self.index(key).map(|i| &*self.entries[i].1)
}
pub fn painter_mut(&mut self, key: &str) -> Option<&mut dyn SlotPainter> {
let i = self.index(key)?;
Some(&mut *self.entries[i].1)
}
pub fn get<T: SlotPainter>(&self, key: &str) -> Option<&T> {
let p: &dyn Any = self.painter(key)?;
p.downcast_ref()
}
pub fn get_mut<T: SlotPainter>(&mut self, key: &str) -> Option<&mut T> {
let p: &mut dyn Any = self.painter_mut(key)?;
p.downcast_mut()
}
pub fn wants_frame(&self) -> bool {
self.entries.iter().any(|(_, p)| p.wants_frame())
}
fn frame<'k>(&self, key: &'k str, rect: Rect, style: Option<&'k Style>) -> SlotPaint<'k> {
let s = self.seen.get(key).copied().unwrap_or_default();
SlotPaint { key, rect, hover: s.hover, held: s.held.is_some(), focused: s.focused, style }
}
pub fn paint_slot(&mut self, ctx: &mut dyn RenderContext, key: &str, rect: Rect, style: Option<&Style>) -> bool {
let Some(i) = self.index(key) else { return false };
let f = self.frame(key, rect, style);
ctx.save();
ctx.begin_path();
ctx.rect(rect.x, rect.y, rect.width, rect.height);
ctx.clip();
self.entries[i].1.paint(ctx, &f);
ctx.restore();
true
}
pub fn paint(&mut self, ctx: &mut dyn RenderContext, dom: &Dom) {
super::paint_slots(ctx, dom, &mut |ctx, key, r| {
let style = dom.boxes.iter().find(|b| b.slot.as_deref() == Some(key)).map(|b| &b.style);
self.paint_slot(ctx, key, r, style);
});
}
pub fn send(&mut self, key: &str, rect: Rect, ev: &SlotEvent) -> Option<SlotAction> {
let i = self.index(key)?;
let f = self.frame(key, rect, None);
let mut a = self.entries[i].1.event(ev, &f)?;
a.slot = key.to_string();
Some(a)
}
pub fn input(&mut self, key: &str, rect: Rect, input: &SlotInput) -> Vec<SlotAction> {
if !self.contains(key) {
return Vec::new();
}
let loc = |(x, y): (f64, f64)| (x - rect.x, y - rect.y);
let was = self.seen.get(key).copied().unwrap_or_default();
let hover = input.pointer.map(loc);
let held = input.pressed.map(loc);
let mut evs = Vec::new();
if input.focused != was.focused {
evs.push(SlotEvent::Focus(input.focused));
}
match (was.hover, hover) {
(None, Some((x, y))) => evs.push(SlotEvent::Enter { x, y }),
(Some(a), Some((x, y))) if a != (x, y) => evs.push(SlotEvent::Move { x, y }),
(Some(_), None) if held.is_none() => evs.push(SlotEvent::Leave),
_ => {}
}
match (was.held, held) {
(None, Some((x, y))) => evs.push(SlotEvent::Down { x, y }),
(Some((ax, ay)), Some((x, y))) if (ax, ay) != (x, y) => evs.push(SlotEvent::Drag { x, y, dx: x - ax, dy: y - ay }),
(Some((x, y)), None) => evs.push(SlotEvent::Up { x, y }),
_ => {}
}
if input.clicked {
let (x, y) = hover.or(was.held).unwrap_or((0.0, 0.0));
evs.push(SlotEvent::Click { x, y });
}
if input.wheel != (0.0, 0.0) {
let (x, y) = hover.unwrap_or((0.0, 0.0));
evs.push(SlotEvent::Wheel { x, y, dx: input.wheel.0, dy: input.wheel.1 });
}
if input.focused {
if let Some((code, text)) = &input.key {
evs.push(SlotEvent::Key { code: *code, text: text.clone() });
}
}
evs.extend(input.events.iter().cloned());
self.seen.insert(key.to_string(), Seen { hover, held, focused: input.focused });
evs.iter().filter_map(|e| self.send(key, rect, e)).collect()
}
pub fn a11y(&self, dom: &Dom) -> Vec<A11yNode> {
let mut nodes = dom.a11y();
for n in &mut nodes {
let Some(b) = dom.get(&n.id) else { continue };
let Some(p) = b.slot.as_deref().and_then(|k| self.painter(k)) else { continue };
n.role = p.role();
if let Some(name) = p.name() {
n.name = name;
}
n.focusable |= p.focusable();
}
nodes
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::NullRenderContext;
use crate::ui::dom::{lay_out, El};
use crate::ui::style::{Sheet, State};
#[derive(Default)]
struct Probe {
events: Vec<SlotEvent>,
painted: Vec<(String, Rect)>,
}
impl SlotPainter for Probe {
fn paint(&mut self, _: &mut dyn RenderContext, f: &SlotPaint<'_>) {
self.painted.push((f.key.to_string(), f.rect));
}
fn event(&mut self, ev: &SlotEvent, _: &SlotPaint<'_>) -> Option<SlotAction> {
self.events.push(ev.clone());
match ev {
SlotEvent::Click { x, y } => Some(SlotAction::new("pick").point(*x, *y)),
_ => None,
}
}
fn role(&self) -> &'static str {
"figure"
}
fn name(&self) -> Option<String> {
Some("Выручка".into())
}
fn focusable(&self) -> bool {
true
}
}
#[test]
fn exact_beats_prefix_and_longest_prefix_wins() {
let mut r = SlotRegistry::new();
r.register_prefix("@c", Probe::default()).register_prefix("@crit:", Probe::default()).register("@crit:7", Probe::default());
assert_eq!(r.index("@crit:7"), Some(2));
assert_eq!(r.index("@crit:1"), Some(1));
assert_eq!(r.index("@cx"), Some(0));
assert_eq!(r.index("other"), None);
assert!(r.remove("@crit:7"));
assert_eq!(r.index("@crit:7"), Some(1));
assert!(r.get_mut::<Probe>("@crit:7").is_some());
}
#[test]
fn input_becomes_local_events_and_actions() {
let mut r = SlotRegistry::new();
r.register("chart", Probe::default());
let rect = Rect::new(100.0, 50.0, 200.0, 100.0);
let a = r.input("chart", rect, &SlotInput { pointer: Some((110.0, 60.0)), ..Default::default() });
assert!(a.is_empty());
r.input("chart", rect, &SlotInput { pointer: Some((120.0, 60.0)), pressed: Some((120.0, 60.0)), ..Default::default() });
r.input("chart", rect, &SlotInput { pointer: Some((130.0, 65.0)), pressed: Some((130.0, 65.0)), ..Default::default() });
let a = r.input("chart", rect, &SlotInput { pointer: Some((130.0, 65.0)), clicked: true, wheel: (0.0, -3.0), ..Default::default() });
assert_eq!(a, vec![SlotAction { slot: "chart".into(), name: "pick".into(), value: SlotValue::Point(30.0, 15.0) }]);
r.input("chart", rect, &SlotInput { focused: true, key: Some((KeyCode::ArrowLeft, None)), ..Default::default() });
let p = r.get::<Probe>("chart").unwrap();
assert_eq!(
p.events,
vec![
SlotEvent::Enter { x: 10.0, y: 10.0 },
SlotEvent::Move { x: 20.0, y: 10.0 },
SlotEvent::Down { x: 20.0, y: 10.0 },
SlotEvent::Move { x: 30.0, y: 15.0 },
SlotEvent::Drag { x: 30.0, y: 15.0, dx: 10.0, dy: 5.0 },
SlotEvent::Up { x: 30.0, y: 15.0 },
SlotEvent::Click { x: 30.0, y: 15.0 },
SlotEvent::Wheel { x: 30.0, y: 15.0, dx: 0.0, dy: -3.0 },
SlotEvent::Focus(true),
SlotEvent::Leave,
SlotEvent::Key { code: KeyCode::ArrowLeft, text: None },
]
);
}
#[test]
fn paints_registered_slots_in_order_and_reports_their_role() {
let tree = El::new("div")
.css("width: 300px")
.child(El::new("div").paint_slot("a").css("height: 40px; padding: 5px"))
.child(El::new("div").paint_slot("free").css("height: 20px"))
.child(El::new("div").paint_slot("b").css("height: 30px"));
let mut ctx = NullRenderContext::default();
let d = lay_out(&mut ctx, &Sheet::default(), &tree, 0.0, 0.0, 300.0, &|_| State::NONE);
let mut r = SlotRegistry::new();
r.register("a", Probe::default()).register("b", Probe::default());
r.paint(&mut ctx, &d);
assert_eq!(r.get::<Probe>("a").unwrap().painted, vec![("a".to_string(), Rect::new(5.0, 5.0, 290.0, 30.0))]);
assert_eq!(r.get::<Probe>("b").unwrap().painted, vec![("b".to_string(), Rect::new(0.0, 60.0, 300.0, 30.0))]);
let a11y = r.a11y(&d);
let a = a11y.iter().find(|n| n.id == "a").unwrap();
assert_eq!((a.role, a.name.as_str(), a.focusable), ("figure", "Выручка", true));
assert_eq!(a11y.iter().find(|n| n.id == "free").unwrap().role, "generic");
}
}