use std::sync::Arc;
use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::dump::session::PayloadReaders;
use crate::lang::{Flm, PresPayload};
use crate::stdlib::backends::pres::payload::{bad, entries, field, map, string, text};
use super::markup::Markup;
pub const TAG: &str = "flm.pres.html.tag";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TagBody {
#[default]
Children,
Markup(Markup),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HtmlTagPayload {
pub tag: String,
pub attributes: Vec<(String, String)>,
pub body: TagBody,
pub block: bool,
}
impl HtmlTagPayload {
pub fn new(tag: impl Into<String>) -> HtmlTagPayload {
HtmlTagPayload {
tag: tag.into(),
attributes: Vec::new(),
body: TagBody::Children,
block: false,
}
}
pub fn attributes<N, V>(mut self, attributes: impl IntoIterator<Item = (N, V)>) -> Self
where
N: Into<String>,
V: Into<String>,
{
self.attributes =
attributes.into_iter().map(|(name, value)| (name.into(), value.into())).collect();
self
}
pub fn markup(mut self, markup: Markup) -> Self {
self.body = TagBody::Markup(markup);
self
}
pub fn block(mut self) -> Self {
self.block = true;
self
}
pub fn from_projection(value: &SerialValue) -> Result<HtmlTagPayload, DeserializeError> {
let e = entries(TAG, value)?;
let tag = string(TAG, e, "tag")?;
let attributes = match field(e, "attributes") {
None | Some(SerialValue::Null) => Vec::new(),
Some(SerialValue::List(items)) => items
.iter()
.map(|item| match item {
SerialValue::List(pair) => match pair.as_slice() {
[SerialValue::Str(name), SerialValue::Str(value)] => {
Ok((name.clone(), value.clone()))
}
other => Err(bad(
TAG,
format!("`attributes` holds {other:?}, not a name and a value"),
)),
},
other => {
Err(bad(TAG, format!("`attributes` holds a non-list {other:?}")))
}
})
.collect::<Result<Vec<_>, _>>()?,
Some(other) => {
return Err(bad(TAG, format!("`attributes` must be a list, found {other:?}")));
}
};
let body = match field(e, "markup") {
None | Some(SerialValue::Null) => TagBody::Children,
Some(SerialValue::Str(html)) => TagBody::Markup(Markup::from_library(html.clone())),
Some(other) => {
return Err(bad(TAG, format!("`markup` must be a string, found {other:?}")));
}
};
let block = match field(e, "block") {
None | Some(SerialValue::Null) => false,
Some(SerialValue::Bool(block)) => *block,
Some(other) => {
return Err(bad(TAG, format!("`block` must be a boolean, found {other:?}")));
}
};
Ok(HtmlTagPayload { tag, attributes, body, block })
}
}
impl PresPayload for HtmlTagPayload {
fn project(&self) -> SerialValue {
let mut fields = vec![("tag", text(&self.tag))];
if !self.attributes.is_empty() {
fields.push((
"attributes",
SerialValue::List(
self.attributes
.iter()
.map(|(name, value)| {
SerialValue::List(vec![text(name.as_str()), text(value.as_str())])
})
.collect(),
),
));
}
if let TagBody::Markup(markup) = &self.body {
fields.push(("markup", text(markup.as_str())));
}
if self.block {
fields.push(("block", SerialValue::Bool(true)));
}
map(fields)
}
}
pub fn payload_readers() -> PayloadReaders {
let mut readers = PayloadReaders::new();
readers.register(TAG, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
HtmlTagPayload::from_projection(value)
.map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
});
readers
}
pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.presentation_element::<HtmlTagPayload>(
TAG,
"one HTML tag: its name, its attributes, and either children or one piece of markup",
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_projection_holds_the_keys_that_have_a_value() {
let plain = HtmlTagPayload::new("span");
assert_eq!(plain.project(), map(vec![("tag", text("span"))]));
let full = HtmlTagPayload::new("div")
.attributes([("class", "mine"), ("data-x", "1")])
.markup(Markup::trusted("<svg></svg>"))
.block();
assert_eq!(
full.project(),
map(vec![
("tag", text("div")),
(
"attributes",
SerialValue::List(vec![
SerialValue::List(vec![text("class"), text("mine")]),
SerialValue::List(vec![text("data-x"), text("1")]),
])
),
("markup", text("<svg></svg>")),
("block", SerialValue::Bool(true)),
])
);
}
#[test]
fn a_projection_reads_back_as_the_payload_it_came_from() {
for payload in [
HtmlTagPayload::new("span"),
HtmlTagPayload::new("div").block(),
HtmlTagPayload::new("tex-html")
.attributes([("id", "eq-1")])
.markup(Markup::trusted("<span></span>")),
] {
let read = HtmlTagPayload::from_projection(&payload.project()).expect("reads back");
assert_eq!(read, payload);
}
}
#[test]
fn a_projection_that_is_not_one_is_refused() {
let cases = [
map(vec![]),
map(vec![("tag", SerialValue::Int(3))]),
map(vec![("tag", text("p")), ("block", text("yes"))]),
map(vec![("tag", text("p")), ("markup", SerialValue::Bool(true))]),
map(vec![("tag", text("p")), ("attributes", text("class"))]),
];
for projection in &cases {
assert!(HtmlTagPayload::from_projection(projection).is_err(), "{projection:?}");
}
}
#[test]
fn an_attributes_list_of_the_wrong_shape_is_refused() {
let projection = map(vec![
("tag", text("p")),
(
"attributes",
SerialValue::List(vec![SerialValue::List(vec![text("only-a-name")])]),
),
]);
assert!(HtmlTagPayload::from_projection(&projection).is_err());
}
}