use minijinja::Value;
use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{self, DeserializeOwned},
forward_to_deserialize_any,
ser::SerializeMap,
};
use std::{collections::HashMap, fmt, sync::Arc};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentError {
message: String,
}
impl ComponentError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ComponentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ComponentError {}
pub trait Component: DeserializeOwned + Serialize + 'static {
const STRICT_ATTRIBUTES: bool = false;
fn prepare(self) -> Result<Self, ComponentError> {
Ok(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Html(String);
impl Html {
pub fn new(markup: impl Into<String>) -> Self {
Self(markup.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl From<String> for Html {
fn from(markup: String) -> Self {
Self(markup)
}
}
impl From<&str> for Html {
fn from(markup: &str) -> Self {
Self(markup.to_owned())
}
}
fn marker() -> &'static str {
static MARKER: std::sync::OnceLock<String> = std::sync::OnceLock::new();
MARKER.get_or_init(|| {
use std::hash::{BuildHasher, Hasher};
let token = std::collections::hash_map::RandomState::new()
.build_hasher()
.finish();
format!("__sword_html_{token:016x}")
})
}
impl Serialize for Html {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry(marker(), &self.0)?;
map.end()
}
}
impl<'de> Deserialize<'de> for Html {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer).map(Self)
}
}
pub(crate) fn to_value(json: serde_json::Value) -> Value {
match json {
serde_json::Value::Object(map) if map.len() == 1 && map.contains_key(marker()) => {
match map.into_iter().next() {
Some((_, serde_json::Value::String(markup))) => Value::from_safe_string(markup),
_ => Value::UNDEFINED,
}
}
serde_json::Value::Object(map) => {
Value::from_iter(map.into_iter().map(|(key, value)| (key, to_value(value))))
}
serde_json::Value::Array(items) => {
Value::from(items.into_iter().map(to_value).collect::<Vec<_>>())
}
serde_json::Value::Null => Value::from(()),
serde_json::Value::Bool(flag) => Value::from(flag),
serde_json::Value::String(text) => Value::from(text),
serde_json::Value::Number(number) => number
.as_i64()
.map(Value::from)
.or_else(|| number.as_u64().map(Value::from))
.or_else(|| number.as_f64().map(Value::from))
.unwrap_or(Value::UNDEFINED),
}
}
struct Probe<'a> {
fields: &'a mut Option<Vec<&'static str>>,
}
#[derive(Debug)]
struct Stop;
impl fmt::Display for Stop {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("probe stopped")
}
}
impl std::error::Error for Stop {}
impl de::Error for Stop {
fn custom<T: fmt::Display>(_: T) -> Self {
Stop
}
}
impl<'de> Deserializer<'de> for Probe<'_> {
type Error = Stop;
fn deserialize_any<V: de::Visitor<'de>>(self, _: V) -> Result<V::Value, Stop> {
Err(Stop)
}
fn deserialize_struct<V: de::Visitor<'de>>(
self,
_name: &'static str,
fields: &'static [&'static str],
_visitor: V,
) -> Result<V::Value, Stop> {
*self.fields = Some(fields.to_vec());
Err(Stop)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
option unit unit_struct newtype_struct seq tuple tuple_struct map enum identifier
ignored_any
}
}
fn fields_of<T: DeserializeOwned>(component: &str) -> Result<Vec<&'static str>, ComponentError> {
let mut fields = None;
let _ = T::deserialize(Probe {
fields: &mut fields,
});
let fields = fields.ok_or_else(|| {
ComponentError::new(format!(
"component `{component}` must be a struct with named fields and no #[serde(flatten)]"
))
})?;
for field in &fields {
let valid = field
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
&& !field.starts_with("__sword")
&& !matches!(*field, "slot" | "attributes" | "loop");
if !valid {
return Err(ComponentError::new(format!(
"component `{component}` has field `{field}`, which cannot be a template variable"
)));
}
}
Ok(fields)
}
type Build = dyn Fn(serde_json::Value) -> Result<Value, String> + Send + Sync;
#[derive(Clone)]
pub(crate) struct Typed {
pub fields: Vec<&'static str>,
pub strict: bool,
build: Arc<Build>,
}
#[derive(Clone, Default)]
pub(crate) struct Components(HashMap<String, Typed>);
impl fmt::Debug for Components {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.keys()).finish()
}
}
impl Components {
pub fn get(&self, name: &str) -> Option<&Typed> {
self.0.get(name)
}
pub fn register<T: Component>(&mut self, name: &str) -> Result<(), ComponentError> {
if !crate::valid_name(name) {
return Err(ComponentError::new(format!(
"invalid component name `{name}`"
)));
}
if self.0.contains_key(name) {
return Err(ComponentError::new(format!(
"component `{name}` is already registered"
)));
}
let fields = fields_of::<T>(name)?;
let build = |json: serde_json::Value| -> Result<Value, String> {
let component: T = serde_json::from_value(json).map_err(|error| {
let message = error.to_string();
if message.contains("invalid type: string") {
format!(
"{message} (a literal attribute is a string; write :name=\"...\" to pass a number or boolean)"
)
} else {
message
}
})?;
let component = component.prepare().map_err(|error| error.message)?;
let json = serde_json::to_value(&component).map_err(|error| error.to_string())?;
Ok(to_value(json))
};
self.0.insert(
name.to_owned(),
Typed {
fields,
strict: T::STRICT_ATTRIBUTES,
build: Arc::new(build),
},
);
Ok(())
}
pub fn build(&self, name: &str, given: Value) -> Result<Value, minijinja::Error> {
let fail = |message: String| {
minijinja::Error::new(
minijinja::ErrorKind::InvalidOperation,
format!("<x-{name}>: {message}"),
)
};
let typed = self
.get(name)
.ok_or_else(|| fail("is not a registered component".to_owned()))?;
let json = serde_json::to_value(&given).map_err(|error| fail(error.to_string()))?;
(typed.build)(json).map_err(fail)
}
}