crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Notebook documents: text, queries, plots, and code cells in one file.
//!
//! ```
//! use crisol_core::state::Notebook;
//! let _ = Notebook::new("analysis");
//! ```

#[cfg(feature = "threads")]
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::storage::StorageError;

/// One cell of a notebook.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::NotebookCell;
/// let cell = NotebookCell::Text { source: "hi".to_owned() };
/// ```
pub enum NotebookCell {
    /// Markdown text.
    Text {
        /// Source.
        source: String,
    },
    /// A query against a named dataset.
    Query {
        /// Dataset name.
        dataset: String,
        /// Query source.
        query: String,
    },
    /// A declarative plot spec.
    Plot {
        /// PlotSpec JSON.
        spec: serde_json::Value,
    },
    /// Code in a host language.
    Code {
        /// Language name.
        language: String,
        /// Source.
        source: String,
    },
}

/// A notebook document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::{Notebook, NotebookCell};
///
/// let mut notebook = Notebook::new("analysis");
/// notebook.push(NotebookCell::Text { source: "# Results".to_owned() });
/// assert_eq!(notebook.cells.len(), 1);
/// ```
pub struct Notebook {
    /// File format version.
    pub version: u32,
    /// Notebook title.
    pub title: String,
    /// Cells in order.
    #[serde(default)]
    pub cells: Vec<NotebookCell>,
}

impl Notebook {
    /// The current version.
    pub const VERSION: u32 = 1;

    /// An empty notebook.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            version: Self::VERSION,
            title: title.into(),
            cells: Vec::new(),
        }
    }

    /// Append a cell.
    pub fn push(&mut self, cell: NotebookCell) {
        self.cells.push(cell);
    }

    /// Save atomically as JSON.
    ///
    /// # Errors
    /// When serialization or the atomic write fails.
    #[cfg(feature = "threads")]
    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), NotebookError> {
        let text = serde_json::to_vec_pretty(self).map_err(NotebookError::Json)?;
        crate::storage::atomic_write(path.as_ref(), &text).map_err(NotebookError::Storage)
    }

    /// Load a notebook from JSON.
    ///
    /// # Errors
    /// When the file cannot be read, is invalid JSON, or has a newer version.
    #[cfg(feature = "threads")]
    pub fn load(path: impl AsRef<Path>) -> Result<Self, NotebookError> {
        let text = crate::storage::read_to_string(path).map_err(NotebookError::Storage)?;
        let notebook: Self = serde_json::from_str(&text).map_err(NotebookError::Json)?;
        if notebook.version > Self::VERSION {
            return Err(NotebookError::Version(notebook.version));
        }
        Ok(notebook)
    }
}

/// Why a notebook could not be saved or loaded.
///
/// # Example
///
/// ```
/// use crisol_core::state::NotebookError;
/// let error = NotebookError::Version(9);
/// assert!(error.to_string().contains("9"));
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum NotebookError {
    /// Serialization failed.
    #[error("notebook JSON: {0}")]
    Json(serde_json::Error),
    /// The file could not be read or written.
    #[error("{0}")]
    Storage(StorageError),
    /// The file was written by a newer version.
    #[error("notebook version {0} is newer than 1")]
    Version(u32),
}

#[cfg(all(test, feature = "threads", not(target_family = "wasm")))]
mod tests {
    use super::*;

    #[test]
    fn a_notebook_round_trips_every_cell() {
        let mut notebook = Notebook::new("study");
        notebook.push(NotebookCell::Text {
            source: "# Title".to_owned(),
        });
        notebook.push(NotebookCell::Query {
            dataset: "signal".to_owned(),
            query: "v > 0".to_owned(),
        });
        notebook.push(NotebookCell::Plot {
            spec: serde_json::json!({"series": []}),
        });
        notebook.push(NotebookCell::Code {
            language: "python".to_owned(),
            source: "print(1)".to_owned(),
        });
        let directory = std::env::temp_dir().join(format!("crisol-notebook-{}", std::process::id()));
        std::fs::create_dir_all(&directory).expect("directory");
        let path = directory.join("study.ipynb.crisol");
        notebook.save(&path).expect("save");
        assert_eq!(Notebook::load(&path).expect("load"), notebook);
        let _ = std::fs::remove_dir_all(directory);
    }
}