use serde::{Deserialize, Serialize};
use super::split_source;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CellType {
Code,
Markdown,
Raw,
}
impl std::fmt::Display for CellType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Code => write!(f, "code"),
Self::Markdown => write!(f, "markdown"),
Self::Raw => write!(f, "raw"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cell {
pub cell_type: CellType,
pub source: Vec<String>,
pub outputs: Vec<CellOutput>,
pub execution_count: Option<u32>,
pub metadata: CellMetadata,
}
impl Cell {
pub fn code(source: impl Into<String>) -> Self {
Self {
cell_type: CellType::Code,
source: split_source(source.into()),
outputs: Vec::new(),
execution_count: None,
metadata: CellMetadata::default(),
}
}
pub fn markdown(source: impl Into<String>) -> Self {
Self {
cell_type: CellType::Markdown,
source: split_source(source.into()),
outputs: Vec::new(),
execution_count: None,
metadata: CellMetadata::default(),
}
}
pub fn raw(source: impl Into<String>) -> Self {
Self {
cell_type: CellType::Raw,
source: split_source(source.into()),
outputs: Vec::new(),
execution_count: None,
metadata: CellMetadata::default(),
}
}
pub fn with_output(mut self, output: CellOutput) -> Self {
self.outputs.push(output);
self
}
pub fn with_execution_count(mut self, count: u32) -> Self {
self.execution_count = Some(count);
self
}
pub fn source_text(&self) -> String {
self.source.join("")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CellOutput {
pub output_type: String,
pub data: Option<serde_json::Value>,
pub text: Option<Vec<String>>,
}
impl CellOutput {
pub fn stream(_name: &str, text: impl Into<String>) -> Self {
Self {
output_type: "stream".to_string(),
data: None,
text: Some(split_source(text.into())),
}
}
pub fn execute_result(data: serde_json::Value) -> Self {
Self { output_type: "execute_result".to_string(), data: Some(data), text: None }
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CellMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub collapsed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scrolled: Option<bool>,
}