use std::{
any::{Any, TypeId},
cell::{OnceCell, RefCell},
collections::HashMap,
rc::Rc,
sync::Arc,
};
use serde::{Serialize, de::DeserializeOwned};
use crate::{
attributes::AttributeBag,
error::{Error, ErrorKind, Result},
library::fault,
shape::{Direction, Shape, TypeDesc, TypeRegistry},
value::{Arg, Object, Value, ValueMap},
};
use super::{decode, snake_case};
type Constructor =
for<'a> fn(ValueMap<'a>, &ComponentServices) -> Result<Option<Box<dyn ComponentInstance>>>;
#[derive(Clone, Copy)]
pub struct ComponentRegistration {
pub name: &'static str,
#[doc(hidden)]
pub fields: fn(&mut TypeRegistry) -> TypeDesc,
#[doc(hidden)]
pub construct: Constructor,
}
#[derive(Clone)]
pub(crate) struct RegisteredComponent {
pub(crate) registration: ComponentRegistration,
schema: Arc<ComponentSchema>,
}
struct ComponentSchema {
types: TypeRegistry,
shape: TypeDesc,
}
impl RegisteredComponent {
pub(crate) fn new(registration: ComponentRegistration) -> Self {
let mut types = TypeRegistry::default();
let shape = (registration.fields)(&mut types);
Self {
registration,
schema: Arc::new(ComponentSchema { types, shape }),
}
}
}
inventory::collect!(ComponentRegistration);
pub fn components() -> impl Iterator<Item = ComponentRegistration> {
inventory::iter::<ComponentRegistration>
.into_iter()
.copied()
}
#[derive(Default)]
pub struct ComponentServices(HashMap<TypeId, Arc<dyn Any + Send + Sync>>);
impl ComponentServices {
pub(crate) fn insert<T: Send + Sync + 'static>(&mut self, service: T) {
self.0.insert(TypeId::of::<T>(), Arc::new(service));
}
pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Result<T> {
self.0
.get(&TypeId::of::<T>())
.and_then(|value| value.downcast_ref::<T>())
.cloned()
.ok_or_else(|| {
fault(format!(
"no component service registered for `{}`",
std::any::type_name::<T>()
))
})
}
}
pub struct ComponentContext<'cx, 'a> {
attributes: &'cx AttributeBag,
data: &'cx ValueMap<'a>,
services: &'cx ComponentServices,
}
impl<'cx, 'a> ComponentContext<'cx, 'a> {
pub(super) fn new(
attributes: &'cx AttributeBag,
data: &'cx ValueMap<'a>,
services: &'cx ComponentServices,
) -> Self {
Self {
attributes,
data,
services,
}
}
pub fn attributes(&self) -> &AttributeBag {
self.attributes
}
pub fn data(&self) -> &ValueMap<'a> {
self.data
}
pub fn service<T: Clone + Send + Sync + 'static>(&self) -> Result<T> {
self.services.get()
}
pub fn slots(&self) -> Slots<'cx, 'a> {
Slots(self.data)
}
}
pub struct Slots<'cx, 'a>(&'cx ValueMap<'a>);
impl Slots<'_, '_> {
pub fn text(&self, name: &str) -> String {
self.0
.get(snake_case(name).as_ref())
.and_then(|value| value.display().ok())
.unwrap_or_default()
}
}
pub struct Output {
text: String,
limit: usize,
overflow: bool,
}
impl Output {
pub(super) fn new(limit: usize) -> Self {
Self {
text: String::new(),
limit,
overflow: false,
}
}
pub fn raw(&mut self, html: &str) -> Result<()> {
if html.len() > self.limit - self.text.len() {
self.overflow = true;
return Err(Self::limit_error());
}
self.text.push_str(html);
Ok(())
}
pub fn escaped(&mut self, text: &str) -> Result<()> {
self.raw(&crate::encode::e(text))
}
pub(super) fn finish(self) -> Result<String> {
if self.overflow {
Err(Self::limit_error())
} else {
Ok(self.text)
}
}
fn limit_error() -> Error {
Error::new(ErrorKind::Limit, "render output limit exceeded", None)
}
}
pub enum ComponentRender {
View(String),
Template(&'static str),
Direct,
}
#[doc(hidden)]
pub trait ClassComponent: DeserializeOwned + Shape + 'static {
fn inject(&mut self, _services: &ComponentServices) -> Result<()> {
Ok(())
}
fn enabled(&self) -> bool {
true
}
fn with_attributes(&mut self, _attributes: &mut AttributeBag) -> Result<()> {
Ok(())
}
fn fields<'a>(&self) -> Result<ValueMap<'a>>;
fn methods() -> &'static [&'static str] {
&[]
}
fn call<'a>(&self, name: &str, _args: &[Value<'a>]) -> Result<Value<'a>> {
Err(fault(format!("unknown component method `{name}`")))
}
fn view_data<'a>(&self, _cx: &ComponentContext<'_, '_>) -> Result<ValueMap<'a>> {
Ok(ValueMap::new())
}
fn render(&self, cx: &ComponentContext<'_, '_>, out: &mut Output) -> Result<ComponentRender>;
}
#[doc(hidden)]
pub trait ComponentInstance {
fn receiver<'a>(&self, fields: ValueMap<'a>) -> Value<'a>
where
Self: 'a;
fn data<'a>(&self) -> Result<ValueMap<'a>>
where
Self: 'a;
fn with_attributes(&mut self, attributes: &mut AttributeBag) -> Result<()>;
fn view_data<'a>(&self, cx: &ComponentContext<'_, '_>) -> Result<ValueMap<'a>>
where
Self: 'a;
fn render(&self, cx: &ComponentContext<'_, '_>, out: &mut Output) -> Result<ComponentRender>;
}
#[doc(hidden)]
pub fn construct<T: ClassComponent>(
input: ValueMap<'_>,
services: &ComponentServices,
) -> Result<Option<Box<dyn ComponentInstance>>> {
let mut instance: T = decode::from_value(&Value::Map(input))?;
instance.inject(services)?;
Ok(instance
.enabled()
.then(|| Box::new(Instance(Rc::new(instance))) as Box<_>))
}
struct Instance<T>(Rc<T>);
impl<T: ClassComponent> ComponentInstance for Instance<T> {
fn receiver<'a>(&self, fields: ValueMap<'a>) -> Value<'a>
where
Self: 'a,
{
Value::object(Receiver {
instance: Rc::clone(&self.0),
fields,
})
}
fn data<'a>(&self) -> Result<ValueMap<'a>>
where
Self: 'a,
{
let mut fields = self.0.fields()?;
for &name in T::methods() {
fields.insert(
name.into(),
Value::object(Exposed(Rc::clone(&self.0), name)),
);
}
Ok(fields)
}
fn with_attributes(&mut self, attributes: &mut AttributeBag) -> Result<()> {
Rc::get_mut(&mut self.0)
.ok_or_else(|| fault("component already shared"))?
.with_attributes(attributes)
}
fn view_data<'a>(&self, cx: &ComponentContext<'_, '_>) -> Result<ValueMap<'a>>
where
Self: 'a,
{
self.0.view_data(cx)
}
fn render(&self, cx: &ComponentContext<'_, '_>, out: &mut Output) -> Result<ComponentRender> {
self.0.render(cx, out)
}
}
struct Receiver<'a, T> {
instance: Rc<T>,
fields: ValueMap<'a>,
}
impl<T> std::fmt::Debug for Receiver<'_, T> {
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
out.write_str(std::any::type_name::<T>())
}
}
impl<'a, T: ClassComponent> Object<'a> for Receiver<'a, T> {
fn type_name(&self) -> &'static str {
std::any::type_name::<T>()
}
fn field(&self, name: &str) -> Option<Value<'a>> {
self.fields.get(name).cloned()
}
fn method(&self, name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
T::methods().contains(&name).then(|| {
let args = args
.into_iter()
.map(|arg| match arg {
Arg::Value(value) => Ok(value),
Arg::Closure(_) => Err(fault("component methods require value arguments")),
})
.collect::<Result<Vec<_>>>()?;
self.instance.call(name, &args)
})
}
}
struct Exposed<T>(Rc<T>, &'static str);
impl<T> std::fmt::Debug for Exposed<T> {
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
out.write_str(self.1)
}
}
impl<'a, T: ClassComponent> Object<'a> for Exposed<T> {
fn type_name(&self) -> &'static str {
"component method"
}
fn call(&self, args: &[Value<'a>]) -> Option<Result<Value<'a>>> {
Some(self.0.call(self.1, args))
}
}
#[doc(hidden)]
pub fn serialize_value<'a>(value: impl Serialize) -> Result<Value<'a>> {
decode::serialize_value(value)
}
#[doc(hidden)]
pub fn serialize_fields<'a>(value: impl Serialize) -> Result<ValueMap<'a>> {
let Value::Map(fields) = serialize_value(value)? else {
return Err(fault(
"component view() must return a model with named fields",
));
};
Ok(fields)
}
#[doc(hidden)]
pub fn argument<T: DeserializeOwned>(value: &Value<'_>) -> Result<T> {
decode::from_value(value)
}
#[doc(hidden)]
pub trait RenderOutput<'a, Kind> {
fn write(self, data: &ValueMap<'a>, out: &mut Output) -> Result<()>;
}
impl<'a> RenderOutput<'a, ()> for String {
fn write(self, _data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
out.raw(&self)
}
}
impl<'a> RenderOutput<'a, ()> for &str {
fn write(self, _data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
out.raw(self)
}
}
impl<'a> RenderOutput<'a, ()> for crate::shape::Html {
fn write(self, _data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
out.raw(self.as_str())
}
}
impl<'a, T: RenderOutput<'a, ()>> RenderOutput<'a, ()> for Result<T> {
fn write(self, data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
self?.write(data, out)
}
}
impl<'a, F, T> RenderOutput<'a, (T,)> for F
where
F: FnOnce(&ValueMap<'a>) -> T,
T: RenderOutput<'a, ()>,
{
fn write(self, data: &ValueMap<'a>, out: &mut Output) -> Result<()> {
self(data).write(data, out)
}
}
#[doc(hidden)]
pub fn render_output<'a, Kind>(
value: impl RenderOutput<'a, Kind>,
data: &ValueMap<'a>,
out: &mut Output,
) -> Result<ComponentRender> {
value.write(data, out)?;
Ok(ComponentRender::Direct)
}
#[derive(Clone, Copy)]
pub struct MethodRegistration {
pub type_name: fn() -> &'static str,
pub names: &'static [&'static str],
#[doc(hidden)]
pub invoke: for<'a> fn(&MethodCache<'a>, &Value<'a>, &str, &[Value<'a>]) -> Result<Value<'a>>,
#[doc(hidden)]
pub wrap: for<'a> fn(Value<'a>) -> Result<Value<'a>>,
}
inventory::collect!(MethodRegistration);
pub fn methods() -> impl Iterator<Item = MethodRegistration> {
inventory::iter::<MethodRegistration>.into_iter().copied()
}
#[doc(hidden)]
#[derive(Default)]
pub struct MethodCache<'a>(
RefCell<HashMap<(TypeId, *const serde_json::Value), CachedReceiver<'a>>>,
);
struct CachedReceiver<'a> {
_source: &'a serde_json::Value,
receiver: Rc<dyn Any>,
}
impl<'a> MethodCache<'a> {
fn receiver<T: DeserializeOwned + 'static>(&self, value: &Value<'a>) -> Result<Rc<T>> {
let Value::Json(value) = value else {
return decode::from_value(value).map(Rc::new);
};
let key = (TypeId::of::<T>(), std::ptr::from_ref(*value));
if let Some(entry) = self.0.borrow().get(&key) {
return entry
.receiver
.clone()
.downcast()
.map_err(|_| fault("incompatible cached method receiver"));
}
let receiver = Rc::new(decode::from_value::<T>(&Value::Json(value))?);
self.0.borrow_mut().insert(
key,
CachedReceiver {
_source: value,
receiver: receiver.clone(),
},
);
Ok(receiver)
}
}
#[doc(hidden)]
pub trait MethodReceiver: DeserializeOwned + 'static {
const METHODS: &'static [&'static str];
fn invoke<'a>(&self, name: &str, args: &[Value<'a>]) -> Result<Value<'a>>;
}
#[doc(hidden)]
pub fn call_method<'a, T: MethodReceiver>(
cache: &MethodCache<'a>,
value: &Value<'a>,
name: &str,
args: &[Value<'a>],
) -> Result<Value<'a>> {
cache.receiver::<T>(value)?.invoke(name, args)
}
#[doc(hidden)]
pub fn wrap_method_receiver<'a, T: MethodReceiver>(value: Value<'a>) -> Result<Value<'a>> {
Ok(Value::object(Typed::<T> {
value,
receiver: OnceCell::new(),
}))
}
struct Typed<'a, T> {
value: Value<'a>,
receiver: OnceCell<Result<T>>,
}
impl<T> std::fmt::Debug for Typed<'_, T> {
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.value.fmt(out)
}
}
impl<'a, T: MethodReceiver> Object<'a> for Typed<'a, T> {
fn type_name(&self) -> &'static str {
std::any::type_name::<T>()
}
fn field(&self, name: &str) -> Option<Value<'a>> {
self.value.field(name)
}
fn method(&self, name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
if !T::METHODS.contains(&name) {
return None;
}
let args = args
.into_iter()
.map(|arg| match arg {
Arg::Value(value) => Ok(value),
Arg::Closure(_) => Err(fault("registered methods require value arguments")),
})
.collect::<Result<Vec<_>>>();
Some(args.and_then(|args| {
let receiver = self
.receiver
.get_or_init(|| decode::from_value(&self.value));
receiver.as_ref().map_err(Clone::clone)?.invoke(name, &args)
}))
}
fn display(&self) -> Result<String> {
self.value.display()
}
fn entries(&self, limit: usize) -> Result<Vec<(Value<'a>, Value<'a>)>> {
self.value.entries(limit)
}
fn json_kind(&self) -> crate::encode::JsonKind<'_> {
crate::encode::JsonValue::json_kind(&self.value)
}
}
impl<'a> super::Markup<'a> {
pub(super) fn take_props(&mut self, class: &RegisteredComponent) -> ValueMap<'a> {
let mut output = ValueMap::new();
self.take_shape_props(&mut output, &class.schema.shape, &class.schema.types, 0);
output
}
fn take_shape_props(
&mut self,
output: &mut ValueMap<'a>,
shape: &TypeDesc,
registry: &TypeRegistry,
depth: usize,
) {
if depth >= 64 {
return;
}
match shape {
TypeDesc::Ref(name) => {
if let Some(ty) = registry.get(name, Direction::Deserialize) {
self.take_shape_props(output, &ty.ty, registry, depth + 1);
}
}
TypeDesc::Struct(fields) => {
for field in fields {
if field.flatten {
self.take_shape_props(output, &field.ty, registry, depth + 1);
continue;
}
let matched = self.supplied.keys().find(|supplied| {
std::iter::once(field.name)
.chain(field.aliases.iter().copied())
.any(|candidate| snake_case(candidate) == snake_case(supplied))
});
if let Some(name) = matched.cloned() {
self.bag.offset_unset(&name);
if let Some(value) = self.supplied.get(&name) {
let value = if self.literals.contains(&name) {
decode::coerce_shape(value.clone(), &field.ty)
} else {
value.clone()
};
output.insert(field.name.into(), value);
}
}
}
}
TypeDesc::Option(ty) | TypeDesc::Display { ty, .. } => {
self.take_shape_props(output, ty, registry, depth + 1);
}
_ => {}
}
}
}
pub(crate) fn annotate_methods<'a>(
data: &mut ValueMap<'a>,
shape: &TypeDesc,
types: &TypeRegistry,
registrations: &[MethodRegistration],
) -> Result<()> {
let dispatch = MethodShapes {
types,
registrations,
};
dispatch.fields(data, shape, 0)
}
struct MethodShapes<'a> {
types: &'a TypeRegistry,
registrations: &'a [MethodRegistration],
}
impl MethodShapes<'_> {
fn fields(&self, data: &mut ValueMap<'_>, shape: &TypeDesc, depth: usize) -> Result<()> {
if depth >= 64 {
return Ok(());
}
match shape {
TypeDesc::Ref(name) => {
if let Some(ty) = self.types.get(name, Direction::Serialize) {
self.fields(data, &ty.ty, depth + 1)?;
}
}
TypeDesc::Struct(fields) => {
for field in fields {
if field.flatten {
self.fields(data, &field.ty, depth + 1)?;
} else if let Some(value) = data.get_mut(field.name) {
*value = self.value(
std::mem::replace(value, Value::Null),
&field.ty,
depth + 1,
)?;
}
}
}
TypeDesc::Display { ty, .. } | TypeDesc::Option(ty) => {
self.fields(data, ty, depth + 1)?
}
_ => {}
}
Ok(())
}
fn value<'v>(&self, value: Value<'v>, ty: &TypeDesc, depth: usize) -> Result<Value<'v>> {
if depth >= 64 || value.is_null() || matches!(value, Value::Object(_)) {
return Ok(value);
}
Ok(match ty {
TypeDesc::Ref(name) => {
if let Some(method) = self
.registrations
.iter()
.find(|method| (method.type_name)() == *name)
{
return (method.wrap)(value);
}
if let Some(ty) = self.types.get(name, Direction::Serialize) {
return self.value(value, &ty.ty, depth + 1);
}
value
}
TypeDesc::Option(ty) | TypeDesc::Display { ty, .. } => {
self.value(value, ty, depth + 1)?
}
TypeDesc::List { element, .. } => match value {
Value::List(items) => Value::List(
items
.into_iter()
.map(|value| self.value(value, element, depth + 1))
.collect::<Result<_>>()?,
),
Value::Json(serde_json::Value::Array(items)) => Value::List(
items
.iter()
.map(|value| self.value(Value::Json(value), element, depth + 1))
.collect::<Result<_>>()?,
),
value => value,
},
TypeDesc::Tuple(types) => match value {
Value::List(items) => Value::List(
items
.into_iter()
.enumerate()
.map(|(index, value)| match types.get(index) {
Some(ty) => self.value(value, &ty.ty, depth + 1),
None => Ok(value),
})
.collect::<Result<_>>()?,
),
value => value,
},
TypeDesc::Struct(_) => match value {
Value::Map(mut fields) => {
self.fields(&mut fields, ty, depth + 1)?;
Value::Map(fields)
}
Value::Json(serde_json::Value::Object(fields)) => {
let mut fields = fields
.iter()
.map(|(name, value)| (name.clone(), Value::Json(value)))
.collect();
self.fields(&mut fields, ty, depth + 1)?;
Value::Map(fields)
}
value => value,
},
TypeDesc::Map { value: ty, .. } => match value {
Value::Map(fields) => Value::Map(
fields
.into_iter()
.map(|(name, value)| Ok((name, self.value(value, ty, depth + 1)?)))
.collect::<Result<_>>()?,
),
value => value,
},
_ => value,
})
}
}