#![allow(
unused_imports,
dead_code,
non_camel_case_types,
unused_variables,
unexpected_cfgs,
clippy::all
)]
use super::context::{LoadContext, SaveContext};
use super::inline::Inline;
use super::table_row::TableRow;
#[derive(Debug, Clone, PartialEq)]
pub enum BlockKind {
Heading { level: i32, content: Vec<Inline> },
Paragraph { content: Vec<Inline> },
Code {
language: Option<String>,
code: String,
},
Quote { blocks: Vec<Block> },
Alert {
alert_type: String,
title: Option<String>,
blocks: Vec<Block>,
},
ListItem {
blocks: Vec<Block>,
task: Option<bool>,
},
List {
ordered: bool,
start: i32,
items: Vec<Block>,
},
Table {
align: Vec<String>,
head: TableRow,
rows: Vec<TableRow>,
},
ThematicBreak,
Unknown {
kind_name: String,
raw: serde_json::Map<String, serde_json::Value>,
},
}
impl Default for BlockKind {
fn default() -> Self {
BlockKind::Unknown {
kind_name: String::new(),
raw: serde_json::Map::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Block {
pub kind: BlockKind,
}
impl Block {
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 {
"heading" => BlockKind::Heading {
level: value.get("level").and_then(|v| v.as_i64()).unwrap_or(0) as i32,
content: value
.get("content")
.map(|v| Self::load_content(v, ctx))
.unwrap_or_default(),
},
"paragraph" => BlockKind::Paragraph {
content: value
.get("content")
.map(|v| Self::load_content(v, ctx))
.unwrap_or_default(),
},
"code_block" => BlockKind::Code {
language: value
.get("language")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
code: value
.get("code")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
},
"block_quote" => BlockKind::Quote {
blocks: value
.get("blocks")
.map(|v| Self::load_blocks(v, ctx))
.unwrap_or_default(),
},
"alert" => BlockKind::Alert {
alert_type: value
.get("alert_type")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
title: value
.get("title")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
blocks: value
.get("blocks")
.map(|v| Self::load_blocks(v, ctx))
.unwrap_or_default(),
},
"list_item" => BlockKind::ListItem {
blocks: value
.get("blocks")
.map(|v| Self::load_blocks(v, ctx))
.unwrap_or_default(),
task: value.get("task").and_then(|v| v.as_bool()),
},
"list" => BlockKind::List {
ordered: value
.get("ordered")
.and_then(|v| v.as_bool())
.unwrap_or(false),
start: value.get("start").and_then(|v| v.as_i64()).unwrap_or(0) as i32,
items: value
.get("items")
.map(|v| Self::load_items(v, ctx))
.unwrap_or_default(),
},
"table" => BlockKind::Table {
align: value
.get("align")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default(),
head: value
.get("head")
.filter(|v| v.is_object() || v.is_array() || v.is_string())
.map(|v| TableRow::load_from_value(v, ctx))
.unwrap_or_default(),
rows: value
.get("rows")
.map(|v| Self::load_rows(v, ctx))
.unwrap_or_default(),
},
"thematic_break" => BlockKind::ThematicBreak,
_ => BlockKind::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 Block discriminator property: 'kind'".to_string())?;
let discriminator = match discriminator {
serde_json::Value::String(value) if !value.is_empty() => value.as_str(),
_ => {
return Err(
"Invalid Block discriminator field 'kind': expected non-blank string"
.to_string(),
)
}
};
match discriminator {
"heading" => {
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)?;
}
}
}
"paragraph" => {
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)?;
}
}
}
"code_block" => {}
"block_quote" => {
if let Some(entries) = value
.get("blocks")
.and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"blocks".to_string()
} else {
format!("{}.blocks", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Block::validate_input_at(entry, &entry_path)?;
}
}
}
"alert" => {
if let Some(entries) = value
.get("blocks")
.and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"blocks".to_string()
} else {
format!("{}.blocks", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Block::validate_input_at(entry, &entry_path)?;
}
}
}
"list_item" => {
if let Some(entries) = value
.get("blocks")
.and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"blocks".to_string()
} else {
format!("{}.blocks", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Block::validate_input_at(entry, &entry_path)?;
}
}
}
"list" => {
if let Some(entries) = value
.get("items")
.and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"items".to_string()
} else {
format!("{}.items", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
Block::validate_input_at(entry, &entry_path)?;
}
}
}
"table" => {
let child_path = if path.is_empty() {
"head".to_string()
} else {
format!("{}.head", path)
};
let child = value
.get("head")
.filter(|candidate| !candidate.is_null())
.ok_or_else(|| format!("{}: missing required field", child_path))?;
TableRow::validate_input_at(child, &child_path)?;
if let Some(entries) = value.get("rows").and_then(|candidate| candidate.as_array())
{
let collection_path = if path.is_empty() {
"rows".to_string()
} else {
format!("{}.rows", path)
};
for (index, entry) in entries.iter().enumerate() {
let entry_path = format!("{}[{}]", collection_path, index);
TableRow::validate_input_at(entry, &entry_path)?;
}
}
}
"thematic_break" => {}
_ => {}
}
Ok(())
}
pub fn kind_str(&self) -> &str {
match &self.kind {
BlockKind::Heading { .. } => "heading",
BlockKind::Paragraph { .. } => "paragraph",
BlockKind::Code { .. } => "code_block",
BlockKind::Quote { .. } => "block_quote",
BlockKind::Alert { .. } => "alert",
BlockKind::ListItem { .. } => "list_item",
BlockKind::List { .. } => "list",
BlockKind::Table { .. } => "table",
BlockKind::ThematicBreak => "thematic_break",
BlockKind::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 {
BlockKind::Heading { level, content, .. } => {
result.insert(
"level".to_string(),
serde_json::Value::Number(serde_json::Number::from(*level)),
);
result.insert(
"content".to_string(),
serde_json::Value::Array(
content.iter().map(|item| item.to_value(ctx)).collect(),
),
);
}
BlockKind::Paragraph { content, .. } => {
result.insert(
"content".to_string(),
serde_json::Value::Array(
content.iter().map(|item| item.to_value(ctx)).collect(),
),
);
}
BlockKind::Code { language, code, .. } => {
if let Some(val) = language {
result.insert(
"language".to_string(),
serde_json::Value::String(val.clone()),
);
}
result.insert("code".to_string(), serde_json::Value::String(code.clone()));
}
BlockKind::Quote { blocks, .. } => {
result.insert(
"blocks".to_string(),
serde_json::Value::Array(
blocks.iter().map(|item| item.to_value(ctx)).collect(),
),
);
}
BlockKind::Alert {
alert_type,
title,
blocks,
..
} => {
result.insert(
"alert_type".to_string(),
serde_json::Value::String(alert_type.clone()),
);
if let Some(val) = title {
result.insert("title".to_string(), serde_json::Value::String(val.clone()));
}
result.insert(
"blocks".to_string(),
serde_json::Value::Array(
blocks.iter().map(|item| item.to_value(ctx)).collect(),
),
);
}
BlockKind::ListItem { blocks, task, .. } => {
result.insert(
"blocks".to_string(),
serde_json::Value::Array(
blocks.iter().map(|item| item.to_value(ctx)).collect(),
),
);
if let Some(val) = task {
result.insert("task".to_string(), serde_json::Value::Bool(*val));
}
}
BlockKind::List {
ordered,
start,
items,
..
} => {
result.insert("ordered".to_string(), serde_json::Value::Bool(*ordered));
result.insert(
"start".to_string(),
serde_json::Value::Number(serde_json::Number::from(*start)),
);
result.insert(
"items".to_string(),
serde_json::Value::Array(items.iter().map(|item| item.to_value(ctx)).collect()),
);
}
BlockKind::Table {
align, head, rows, ..
} => {
result.insert(
"align".to_string(),
serde_json::to_value(align).unwrap_or(serde_json::Value::Null),
);
{
let nested = head.to_value(ctx);
result.insert("head".to_string(), nested);
}
result.insert(
"rows".to_string(),
serde_json::Value::Array(rows.iter().map(|item| item.to_value(ctx)).collect()),
);
}
BlockKind::ThematicBreak => {}
BlockKind::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_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<_>>(),
)
}
fn load_blocks(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Block> {
match data {
serde_json::Value::Array(arr) => {
arr.iter().map(|v| Block::load_from_value(v, ctx)).collect()
}
_ => Vec::new(),
}
}
fn save_blocks(items: &[Block], ctx: &SaveContext) -> serde_json::Value {
serde_json::Value::Array(
items
.iter()
.map(|item| item.to_value(ctx))
.collect::<Vec<_>>(),
)
}
fn load_items(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Block> {
match data {
serde_json::Value::Array(arr) => {
arr.iter().map(|v| Block::load_from_value(v, ctx)).collect()
}
_ => Vec::new(),
}
}
fn save_items(items: &[Block], ctx: &SaveContext) -> serde_json::Value {
serde_json::Value::Array(
items
.iter()
.map(|item| item.to_value(ctx))
.collect::<Vec<_>>(),
)
}
fn load_rows(data: &serde_json::Value, ctx: &LoadContext) -> Vec<TableRow> {
match data {
serde_json::Value::Array(arr) => arr
.iter()
.map(|v| TableRow::load_from_value(v, ctx))
.collect(),
_ => Vec::new(),
}
}
fn save_rows(items: &[TableRow], 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 Block {
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 Block {
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 BlockKind {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let parent = Block {
kind: self.clone(),
..Default::default()
};
serde::Serialize::serialize(&parent.to_value(&SaveContext::default()), serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for BlockKind {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
Block::validate_input_at(&value, "").map_err(serde::de::Error::custom)?;
Ok(Block::load_from_value(&value, &LoadContext::default()).kind)
}
}