1use crate::geom::{Bounds, Insets};
2use crate::{DrawFn, InputFn, LayoutFn};
3use alloc::boxed::Box;
4use alloc::string::String;
5use core::any::Any;
6use core::fmt::{Display, Formatter};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct ViewId(&'static str);
10impl ViewId {
11 pub const fn new(id: &'static str) -> Self {
12 ViewId(id)
13 }
14 pub const fn as_str(&self) -> &'static str {
15 self.0
16 }
17}
18impl Display for ViewId {
19 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
20 write!(f, "{}", self.0)
21 }
22}
23
24#[derive(PartialEq, Debug, Copy, Clone)]
25pub enum Flex {
26 Intrinsic,
27 Resize,
28}
29#[derive(Copy, Clone, PartialEq, Debug)]
30pub enum Align {
31 Start,
32 Center,
33 End,
34}
35
36#[derive(Debug)]
37pub struct View {
38 pub name: ViewId,
39 pub title: String,
40 pub bounds: Bounds,
41 pub padding: Insets,
42
43 pub v_flex: Flex,
44 pub h_flex: Flex,
45 pub h_align: Align,
46 pub v_align: Align,
47
48 pub visible: bool,
49 pub input: Option<InputFn>,
50 pub state: Option<Box<dyn Any>>,
51 pub layout: Option<LayoutFn>,
52 pub draw: Option<DrawFn>,
53}
54
55impl View {
56 pub fn position_at(mut self, x: i32, y: i32) -> View {
57 self.bounds.position.x = x;
58 self.bounds.position.y = y;
59 self
60 }
61 pub fn with_size(mut self, w: i32, h: i32) -> View {
62 self.bounds.size.w = w;
63 self.bounds.size.h = h;
64 self
65 }
66 pub fn hide(mut self) -> View {
67 self.visible = false;
68 self
69 }
70 pub fn get_state<T: 'static>(&mut self) -> Option<&mut T> {
71 if let Some(view) = &mut self.state {
72 return view.downcast_mut::<T>();
73 }
74 None
75 }
76}
77
78impl Default for View {
79 fn default() -> Self {
80 let id: ViewId = ViewId::new("noname");
81 View {
82 name: id,
83 title: id.as_str().into(),
84 bounds: Default::default(),
85 padding: Default::default(),
86
87 h_flex: Flex::Intrinsic,
88 v_flex: Flex::Intrinsic,
89 h_align: Align::Center,
90 v_align: Align::Center,
91
92 visible: true,
93 input: None,
94 state: None,
95 layout: None,
96 draw: None,
97 }
98 }
99}