anathema_widgets/widget/
factory.rs1use std::collections::HashMap;
2
3use anathema_value_resolver::Attributes;
4
5use super::{AnyWidget, Widget};
6use crate::error::{ErrorKind, Result};
7
8pub struct Factory(HashMap<Box<str>, Box<dyn Fn(&Attributes<'_>) -> Box<dyn AnyWidget>>>);
9
10impl Factory {
11 pub fn new() -> Self {
12 Self(HashMap::new())
13 }
14
15 pub(crate) fn make(&self, ident: &str, attribs: &Attributes<'_>) -> Result<Box<dyn AnyWidget>, ErrorKind> {
16 let f = self.0.get(ident).ok_or(ErrorKind::InvalidElement(ident.to_string()))?;
17 Ok((f)(attribs))
18 }
19
20 pub fn register_widget(&mut self, ident: &str, factory: impl Fn(&Attributes<'_>) -> Box<dyn AnyWidget> + 'static) {
21 self.0.insert(ident.into(), Box::new(factory));
22 }
23
24 pub fn register_default<W: 'static + Widget + Default>(&mut self, ident: &str) {
25 self.0.insert(ident.into(), Box::new(|_| Box::<W>::default()));
26 }
27}