#![allow(
unused_imports,
dead_code,
non_camel_case_types,
unused_variables,
unexpected_cfgs,
clippy::all
)]
use super::context::{LoadContext, SaveContext};
#[derive(Debug, Clone, PartialEq)]
pub enum InlineKind {
Text { data: String },
Strong { data: Vec<Inline> },
Emphasis { data: Vec<Inline> },
Strikethrough { data: Vec<Inline> },
Subscript { data: Vec<Inline> },
Code { data: String },
Link { href: String, content: Vec<Inline> },
Math { latex: String, display: bool },
Image {
src: String,
alt: String,
title: String,
},
FootnoteReference { label: String },
SoftBreak,
HardBreak,
Unknown {
kind_name: String,
raw: serde_json::Map<String, serde_json::Value>,
},
}
impl Default for InlineKind {
fn default() -> Self {
InlineKind::Unknown {
kind_name: String::new(),
raw: serde_json::Map::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Inline {
pub kind: InlineKind,
}
impl Inline {
pub fn new() -> Self {
Self::default()
}
pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
let value: serde_json::Value = serde_json::from_str(json)?;
Self::validate_input_at(&value, "")
.map_err(|message| <serde_json::Error as serde::de::Error>::custom(message))?;
Ok(Self::load_from_value(&value, ctx))
}
pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
let value: serde_json::Value = serde_yaml::from_str(yaml)?;
Self::validate_input_at(&value, "")
.map_err(|message| <serde_yaml::Error as serde::de::Error>::custom(message))?;
Ok(Self::load_from_value(&value, ctx))
}
pub fn try_load_from_value(
value: &serde_json::Value,
ctx: &LoadContext,
) -> Result<Self, serde_json::Error> {
Self::validate_input_at(value, "")
.map_err(|message| <serde_json::Error as serde::de::Error>::custom(message))?;
Ok(Self::load_from_value(value, ctx))
}
pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
let value = ctx.process_input(value.clone());
if let Err(message) = Self::validate_input_at(&value, "") {
panic!("{}", message);
}
let kind_str = value.get("kind").and_then(|v| v.as_str()).unwrap_or("");
let kind = match kind_str {
"text" => InlineKind::Text {
data: value
.get("data")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
},
"strong" => InlineKind::Strong {
data: value
.get("data")
.map(|v| Self::load_data(v, ctx))
.unwrap_or_default(),
},
"emphasis" => InlineKind::Emphasis {
data: value
.get("data")
.map(|v| Self::load_data(v, ctx))
.unwrap_or_default(),
},
"strikethrough" => InlineKind::Strikethrough {
data: value
.get("data")
.map(|v| Self::load_data(v, ctx))
.unwrap_or_default(),
},
"subscript" => InlineKind::Subscript {
data: value
.get("data")
.map(|v| Self::load_data(v, ctx))
.unwrap_or_default(),
},
"code" => InlineKind::Code {
data: value
.get("data")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
},
"link" => InlineKind::Link {
href: value
.get("href")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
content: value
.get("content")
.map(|v| Self::load_content(v, ctx))
.unwrap_or_default(),
},
"math" => InlineKind::Math {
latex: value
.get("latex")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
display: value
.get("display")
.and_then(|v| v.as_bool())
.unwrap_or(false),
},
"image" => InlineKind::Image {
src: value
.get("src")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
alt: value
.get("alt")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
title: value
.get("title")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
},
"footnote_reference" => InlineKind::FootnoteReference {
label: value
.get("label")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
},
"soft_break" => InlineKind::SoftBreak,
"hard_break" => InlineKind::HardBreak,
_ => InlineKind::Unknown {
kind_name: kind_str.to_string(),
raw: {
let mut raw = value.as_object().cloned().unwrap_or_default();
raw.remove("kind");
raw
},
},
};
Self { kind: kind }
}
pub(crate) fn validate_input_at(value: &serde_json::Value, path: &str) -> Result<(), String> {
let discriminator = value
.get("kind")
.ok_or_else(|| "Missing Inline discriminator property: 'kind'".to_string())?;
let discriminator = match discriminator {
serde_json::Value::String(value) if !value.is_empty() => value.as_str(),
_ => {
return Err(
"Invalid Inline discriminator field 'kind': expected non-blank string"
.to_string(),
)
}
};
match discriminator {
"text" => {}
"strong" => {
if let Some(entries) = value.get("data").and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"data".to_string()
} else {
format!("{}.data", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Inline::validate_input_at(entry, &entry_path)?;
}
}
}
"emphasis" => {
if let Some(entries) = value.get("data").and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"data".to_string()
} else {
format!("{}.data", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Inline::validate_input_at(entry, &entry_path)?;
}
}
}
"strikethrough" => {
if let Some(entries) = value.get("data").and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"data".to_string()
} else {
format!("{}.data", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Inline::validate_input_at(entry, &entry_path)?;
}
}
}
"subscript" => {
if let Some(entries) = value.get("data").and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"data".to_string()
} else {
format!("{}.data", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Inline::validate_input_at(entry, &entry_path)?;
}
}
}
"code" => {}
"link" => {
if let Some(entries) = value
.get("content")
.and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"content".to_string()
} else {
format!("{}.content", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Inline::validate_input_at(entry, &entry_path)?;
}
}
}
"math" => {}
"image" => {}
"footnote_reference" => {}
"soft_break" => {}
"hard_break" => {}
_ => {}
}
Ok(())
}
pub fn kind_str(&self) -> &str {
match &self.kind {
InlineKind::Text { .. } => "text",
InlineKind::Strong { .. } => "strong",
InlineKind::Emphasis { .. } => "emphasis",
InlineKind::Strikethrough { .. } => "strikethrough",
InlineKind::Subscript { .. } => "subscript",
InlineKind::Code { .. } => "code",
InlineKind::Link { .. } => "link",
InlineKind::Math { .. } => "math",
InlineKind::Image { .. } => "image",
InlineKind::FootnoteReference { .. } => "footnote_reference",
InlineKind::SoftBreak => "soft_break",
InlineKind::HardBreak => "hard_break",
InlineKind::Unknown { kind_name, .. } => kind_name.as_str(),
}
}
pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
let mut result = serde_json::Map::new();
result.insert(
"kind".to_string(),
serde_json::Value::String(self.kind_str().to_string()),
);
match &self.kind {
InlineKind::Text { data, .. } => {
result.insert("data".to_string(), serde_json::Value::String(data.clone()));
}
InlineKind::Strong { data, .. } => {
result.insert(
"data".to_string(),
serde_json::Value::Array(data.iter().map(|item| item.to_value(ctx)).collect()),
);
}
InlineKind::Emphasis { data, .. } => {
result.insert(
"data".to_string(),
serde_json::Value::Array(data.iter().map(|item| item.to_value(ctx)).collect()),
);
}
InlineKind::Strikethrough { data, .. } => {
result.insert(
"data".to_string(),
serde_json::Value::Array(data.iter().map(|item| item.to_value(ctx)).collect()),
);
}
InlineKind::Subscript { data, .. } => {
result.insert(
"data".to_string(),
serde_json::Value::Array(data.iter().map(|item| item.to_value(ctx)).collect()),
);
}
InlineKind::Code { data, .. } => {
result.insert("data".to_string(), serde_json::Value::String(data.clone()));
}
InlineKind::Link { href, content, .. } => {
result.insert("href".to_string(), serde_json::Value::String(href.clone()));
result.insert(
"content".to_string(),
serde_json::Value::Array(
content.iter().map(|item| item.to_value(ctx)).collect(),
),
);
}
InlineKind::Math { latex, display, .. } => {
result.insert(
"latex".to_string(),
serde_json::Value::String(latex.clone()),
);
result.insert("display".to_string(), serde_json::Value::Bool(*display));
}
InlineKind::Image {
src, alt, title, ..
} => {
result.insert("src".to_string(), serde_json::Value::String(src.clone()));
result.insert("alt".to_string(), serde_json::Value::String(alt.clone()));
result.insert(
"title".to_string(),
serde_json::Value::String(title.clone()),
);
}
InlineKind::FootnoteReference { label, .. } => {
result.insert(
"label".to_string(),
serde_json::Value::String(label.clone()),
);
}
InlineKind::SoftBreak => {}
InlineKind::HardBreak => {}
InlineKind::Unknown { raw, .. } => {
for (key, value) in raw {
if matches!(key.as_str(), "kind") {
continue;
}
result.insert(key.clone(), value.clone());
}
}
}
ctx.process_dict(serde_json::Value::Object(result))
}
pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(&self.to_value(ctx))
}
pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
serde_yaml::to_string(&self.to_value(ctx))
}
fn load_data(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Inline> {
match data {
serde_json::Value::Array(arr) => arr
.iter()
.map(|v| Inline::load_from_value(v, ctx))
.collect(),
_ => Vec::new(),
}
}
fn save_data(items: &[Inline], ctx: &SaveContext) -> serde_json::Value {
serde_json::Value::Array(
items
.iter()
.map(|item| item.to_value(ctx))
.collect::<Vec<_>>(),
)
}
fn load_content(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Inline> {
match data {
serde_json::Value::Array(arr) => arr
.iter()
.map(|v| Inline::load_from_value(v, ctx))
.collect(),
_ => Vec::new(),
}
}
fn save_content(items: &[Inline], ctx: &SaveContext) -> serde_json::Value {
serde_json::Value::Array(
items
.iter()
.map(|item| item.to_value(ctx))
.collect::<Vec<_>>(),
)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Inline {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(&self.to_value(&SaveContext::default()), serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Inline {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
Self::validate_input_at(&value, "").map_err(serde::de::Error::custom)?;
Ok(Self::load_from_value(&value, &LoadContext::default()))
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for InlineKind {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let parent = Inline {
kind: self.clone(),
..Default::default()
};
serde::Serialize::serialize(&parent.to_value(&SaveContext::default()), serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for InlineKind {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
Inline::validate_input_at(&value, "").map_err(serde::de::Error::custom)?;
Ok(Inline::load_from_value(&value, &LoadContext::default()).kind)
}
}