use std::fmt;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use hyve::Scope;
use serge_style::{Style, StyleProp, Theme};
use crate::paint::{PaintCtx, Rect};
#[must_use = "an Element does nothing until it is mounted"]
#[derive(Clone)]
pub struct Element(pub Node);
impl Element {
pub fn empty() -> Element {
Element(Node::Empty)
}
pub fn fragment(children: Vec<Element>) -> Element {
Element(Node::Fragment(children.into_iter().map(|e| e.0).collect()))
}
pub fn scoped(scope: Scope, inner: Element) -> Element {
Element(Node::Scoped(scope, Box::new(inner.0)))
}
}
impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Clone)]
pub enum Node {
Empty,
Widget(Box<Widget>),
Fragment(Vec<Node>),
Region(Rc<dyn Fn() -> Element>),
Keyed(Rc<Keyed>),
Scoped(Scope, Box<Node>),
}
impl fmt::Debug for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Node::Empty => f.write_str("Empty"),
Node::Widget(w) => f
.debug_struct("Widget")
.field("kind", &w.kind)
.field("children", &w.children)
.finish_non_exhaustive(),
Node::Fragment(c) => f.debug_tuple("Fragment").field(c).finish(),
Node::Region(_) => f.write_str("Region(..)"),
Node::Keyed(_) => f.write_str("Keyed(..)"),
Node::Scoped(_, n) => f.debug_tuple("Scoped").field(n).finish(),
}
}
}
pub struct KeyedItem {
pub key: u64,
pub value: Rc<dyn std::any::Any>,
pub same: fn(&dyn std::any::Any, &dyn std::any::Any) -> bool,
pub build: Box<dyn FnOnce() -> Element>,
}
pub struct Keyed {
pub items: Box<dyn Fn() -> Vec<KeyedItem>>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Kind {
View,
Stack,
Card,
Text,
Button,
Slider,
Input,
Checkbox,
Canvas,
ProgressBar,
Link,
}
impl Kind {
pub fn html(self) -> (&'static str, &'static str) {
match self {
Kind::View => ("div", "serge-view"),
Kind::Stack => ("div", "serge-stack"),
Kind::Card => ("div", "serge-card"),
Kind::Text => ("div", "serge-text"),
Kind::Button => ("button", "serge-button"),
Kind::Slider => ("input", "serge-slider"),
Kind::Input => ("input", "serge-input"),
Kind::Checkbox => ("label", "serge-checkbox"),
Kind::Canvas => ("div", "serge-canvas"),
Kind::ProgressBar => ("div", "serge-progress"),
Kind::Link => ("a", "serge-link"),
}
}
pub fn base_style(self, theme: &Theme) -> Style {
use serge_style::{Align, Length::Px};
let mut s = Style {
color: theme.text,
..Style::default()
};
match self {
Kind::View | Kind::Text => {}
Kind::Stack => s.gap = Px(8.0),
Kind::Card => {
s.padding_x = Px(16.0);
s.padding_y = Px(16.0);
s.gap = Px(8.0);
s.background = theme.surface;
s.radius = Px(12.0);
s.border_width = Px(1.0);
s.border_color = theme.border;
}
Kind::Button => {
s.padding_x = Px(14.0);
s.padding_y = Px(8.0);
s.radius = Px(8.0);
s.background = theme.primary;
s.color = theme.on_primary;
s.font_weight = 600;
s.align = Align::Center;
s.justify = Align::Center;
}
Kind::Slider => {
s.height = Px(24.0);
s.min_width = Px(120.0);
}
Kind::Input => {
s.padding_x = Px(10.0);
s.padding_y = Px(6.0);
s.radius = Px(6.0);
s.border_width = Px(1.0);
s.border_color = theme.border;
s.background = theme.surface;
s.min_width = Px(160.0);
}
Kind::Checkbox => {
s.layout = serge_style::Layout::Row;
s.gap = Px(8.0);
s.align = Align::Center;
}
Kind::Canvas => s.height = Px(120.0),
Kind::ProgressBar => {
s.height = Px(8.0);
s.radius = Px(4.0);
s.background = theme.border;
}
Kind::Link => s.color = theme.primary,
}
s
}
}
pub enum Prop<T> {
Static(T),
Const(T),
Dynamic(Rc<dyn Fn() -> T>),
}
impl<T: Clone + 'static> Prop<T> {
pub fn get(&self) -> T {
match self {
Prop::Static(v) | Prop::Const(v) => v.clone(),
Prop::Dynamic(f) => f(),
}
}
pub fn map<U: 'static>(self, f: impl Fn(T) -> U + 'static) -> Prop<U> {
match self {
Prop::Static(v) => Prop::Static(f(v)),
Prop::Const(v) => Prop::Const(f(v)),
Prop::Dynamic(g) => Prop::Dynamic(Rc::new(move || f(g()))),
}
}
pub fn is_dynamic(&self) -> bool {
matches!(self, Prop::Dynamic(_))
}
pub fn is_const(&self) -> bool {
matches!(self, Prop::Const(_))
}
}
impl<T: Clone> Clone for Prop<T> {
fn clone(&self) -> Self {
match self {
Prop::Static(v) => Prop::Static(v.clone()),
Prop::Const(v) => Prop::Const(v.clone()),
Prop::Dynamic(f) => Prop::Dynamic(f.clone()),
}
}
}
#[derive(Debug)]
pub struct Site {
pub parent: Option<&'static Site>,
}
impl Site {
pub const fn new(parent: Option<&'static Site>) -> Site {
Site { parent }
}
pub fn is_child_of(&self, parent: &Site) -> bool {
self.parent.is_some_and(|p| std::ptr::eq(p, parent))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Attr {
Text,
Value,
Min,
Max,
Step,
Checked,
InputText,
Placeholder,
Href,
Disabled,
}
#[derive(Clone, PartialEq, Debug)]
pub enum AttrValue {
Str(String),
Num(f32),
Bool(bool),
}
impl AttrValue {
pub fn as_str(&self) -> &str {
match self {
AttrValue::Str(s) => s,
_ => "",
}
}
pub fn as_num(&self) -> f32 {
match self {
AttrValue::Num(n) => *n,
_ => 0.0,
}
}
pub fn as_bool(&self) -> bool {
matches!(self, AttrValue::Bool(true))
}
}
pub type PaintFn = Rc<dyn Fn(Rect, &mut PaintCtx)>;
#[derive(Clone)]
pub enum Handler {
Clicked(Rc<dyn Fn()>),
ChangedNum(Rc<dyn Fn(f32)>),
ChangedText(Rc<dyn Fn(String)>),
ChangedBool(Rc<dyn Fn(bool)>),
Submitted(Rc<dyn Fn()>),
Paint(PaintFn),
Viewport(crate::viewport::Viewport),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Cursor {
#[default]
Default,
Pointer,
Text,
}
#[derive(Clone)]
pub struct Widget {
pub kind: Kind,
pub style: Vec<Prop<StyleProp>>,
pub attrs: Vec<(Attr, Prop<AttrValue>)>,
pub handlers: Vec<Handler>,
pub web: Vec<(&'static str, Prop<String>)>,
pub cursor: Option<Cursor>,
pub children: Vec<Node>,
pub site: Option<&'static Site>,
}
impl Widget {
pub fn new(kind: Kind) -> Widget {
Widget {
kind,
style: Vec::new(),
attrs: Vec::new(),
handlers: Vec::new(),
web: Vec::new(),
cursor: None,
children: Vec::new(),
site: None,
}
}
pub fn attr(&self, a: Attr) -> Option<&Prop<AttrValue>> {
self.attrs
.iter()
.rev()
.find(|(k, _)| *k == a)
.map(|(_, v)| v)
}
pub fn resolve_style(kind: Kind, theme: &Theme, props: &[Prop<StyleProp>]) -> Style {
let mut s = kind.base_style(theme);
for p in props {
s.apply(&p.get());
}
s
}
}
pub struct Callback<A = ()>(Rc<dyn Fn(A)>);
impl<A> Callback<A> {
pub fn new(f: impl Fn(A) + 'static) -> Self {
Callback(Rc::new(f))
}
pub fn call(&self, args: A) {
(self.0)(args)
}
}
impl<A> Clone for Callback<A> {
fn clone(&self) -> Self {
Callback(self.0.clone())
}
}
impl<A> fmt::Debug for Callback<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Callback(..)")
}
}
pub trait IntoElement {
fn into_element(self) -> Element;
}
impl IntoElement for Element {
fn into_element(self) -> Element {
self
}
}
impl IntoElement for () {
fn into_element(self) -> Element {
Element::empty()
}
}
impl<E: IntoElement> IntoElement for Option<E> {
fn into_element(self) -> Element {
self.map_or_else(Element::empty, IntoElement::into_element)
}
}
impl<E: IntoElement> IntoElement for Vec<E> {
fn into_element(self) -> Element {
Element::fragment(self.into_iter().map(IntoElement::into_element).collect())
}
}
pub fn key_hash<K: Hash>(key: &K) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut h);
h.finish()
}