livewire-rust 0.1.5

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The synthesizers that read and write a field whose wire form differs from its Rust form.
//!
//! Most fields cross the wire as plain JSON, and the derive's own per-field code reads and writes
//! them. A field needs a synthesizer when its JSON form cannot be read back without knowing what it
//! was: a model reference, a paginator, a form object, or a value that carries a type tag.
//!
//! A synthesized field crosses the wire as a two-element tuple, `[value, meta]`, where `meta.s` is
//! the synthesizer's key. The key comes from the checksum-verified snapshot, never from the update
//! the browser sent, and is resolved against the synthesizers the application registered — never
//! against a type named by the input.

use std::fmt;

use serde_json::{Map, Value};

/// Why a synthesizer could not read a value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SynthError {
    /// The value's shape does not match what the synthesizer reads.
    Corrupt(String),
    /// The value names a synthesizer the application did not register.
    UnknownKey(String),
}

impl SynthError {
    /// A corrupt value, with what was expected instead.
    pub fn corrupt(expected: impl Into<String>) -> Self {
        Self::Corrupt(expected.into())
    }
}

impl fmt::Display for SynthError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Corrupt(message) => formatter.write_str(message),
            Self::UnknownKey(key) => write!(formatter, "Unable to find synthesizer with key: [{key}]"),
        }
    }
}

impl std::error::Error for SynthError {}

/// The result of a synthesizer's read or write.
pub type Result<T, E = SynthError> = std::result::Result<T, E>;

/// A value whose wire form needs a type tag to be read back.
///
/// `#[livewire(synth(path::to::Synth))]` marks a field, and the derive calls the synthesizer before
/// it writes the field and after it reads it.
pub trait Synth: Sized + Send + Sync + 'static {
    /// The key the wire form carries, which the snapshot's metadata names.
    const KEY: &'static str;

    /// The field's wire value and metadata, or `None` when plain JSON reads back without help.
    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)>;

    /// Reads a field back from its wire value and the metadata the snapshot carried.
    ///
    /// # Errors
    ///
    /// Fails when the value cannot be read as this synthesizer's type.
    fn hydrate(value: &Value, meta: Option<&Map<String, Value>>) -> Result<Self>;
}

/// Splits a wire value into the value and the metadata of a synthesized field.
///
/// A value that is not a tuple is returned as it is, with no metadata, which is what a field the
/// snapshot has not seen looks like.
#[must_use]
pub fn split_tuple(value: &Value) -> (Value, Option<Map<String, Value>>) {
    let Value::Array(parts) = value else {
        return (value.clone(), None);
    };

    if parts.len() != 2 {
        return (value.clone(), None);
    }

    let meta = match &parts[1] {
        Value::Object(meta) if meta.contains_key(SYNTH_KEY) => Some(meta.clone()),
        _ => None,
    };

    match meta {
        Some(meta) => (parts[0].clone(), Some(meta)),
        None => (value.clone(), None),
    }
}

/// The metadata key that names the synthesizer.
pub const SYNTH_KEY: &str = "s";

/// A synthesizer that carries its key in the metadata it writes.
pub(crate) fn with_key(key: &'static str, mut meta: Map<String, Value>) -> Map<String, Value> {
    meta.insert(SYNTH_KEY.to_owned(), Value::from(key));
    meta
}

/// An array, which crosses the wire as an array.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Arr(pub Vec<Value>);

impl Synth for Arr {
    const KEY: &'static str = "arr";

    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
        Some((Value::Array(self.0.clone()), with_key(Self::KEY, Map::new())))
    }

    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
        match value {
            Value::Array(values) => Ok(Self(values.clone())),
            _ => Err(SynthError::corrupt("an array")),
        }
    }
}

/// An object, which crosses the wire as an object.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Std(pub Map<String, Value>);

impl Synth for Std {
    const KEY: &'static str = "std";

    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
        Some((Value::Object(self.0.clone()), with_key(Self::KEY, Map::new())))
    }

    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
        match value {
            Value::Object(map) => Ok(Self(map.clone())),
            _ => Err(SynthError::corrupt("an object")),
        }
    }
}

/// A string.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Str(pub String);

impl Synth for Str {
    const KEY: &'static str = "str";

    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
        None
    }

    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
        value
            .as_str()
            .map(|text| Self(text.to_owned()))
            .ok_or_else(|| SynthError::corrupt("a string"))
    }
}

/// An integer.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Int(pub i64);

impl Synth for Int {
    const KEY: &'static str = "int";

    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
        None
    }

    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
        value
            .as_i64()
            .map(Self)
            .ok_or_else(|| SynthError::corrupt("an integer"))
    }
}

/// A floating point number.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Float(pub f64);

impl Synth for Float {
    const KEY: &'static str = "float";

    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
        None
    }

    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
        value.as_f64().map(Self).ok_or_else(|| SynthError::corrupt("a number"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_synthesized_value_carries_its_key_in_the_metadata() {
        let (value, meta) = Arr(vec![Value::from(1)]).dehydrate().expect("a tuple");

        assert_eq!(value, serde_json::json!([1]));
        assert_eq!(meta[SYNTH_KEY], serde_json::json!("arr"));
    }

    #[test]
    fn a_plain_value_has_no_tuple() {
        assert_eq!(Str("hello".to_owned()).dehydrate(), None);
        assert_eq!(Int(3).dehydrate(), None);
    }

    #[test]
    fn only_a_tuple_with_a_key_is_split() {
        let tuple = serde_json::json!(["value", {"s": "arr"}]);
        let (value, meta) = split_tuple(&tuple);
        assert_eq!(value, serde_json::json!("value"));
        assert_eq!(meta.expect("metadata")[SYNTH_KEY], serde_json::json!("arr"));

        let plain = serde_json::json!(["a", "b"]);
        assert_eq!(split_tuple(&plain), (plain.clone(), None));

        let no_key = serde_json::json!([1, {"x": 1}]);
        assert_eq!(split_tuple(&no_key), (no_key.clone(), None));
    }

    #[test]
    fn a_mismatched_value_is_corrupt_not_a_panic() {
        assert_eq!(
            Arr::hydrate(&serde_json::json!("nope"), None),
            Err(SynthError::corrupt("an array"))
        );
        assert_eq!(
            Int::hydrate(&serde_json::json!(1.5), None),
            Err(SynthError::corrupt("an integer"))
        );
        assert!(Str::hydrate(&serde_json::json!(1), None).is_err());
    }

    #[test]
    fn a_value_round_trips_through_its_synthesizer() {
        let original = Std(Map::from_iter([("a".to_owned(), Value::from(1))]));
        let (value, meta) = original.dehydrate().expect("a tuple");

        assert_eq!(Std::hydrate(&value, Some(&meta)).expect("hydrates"), original);
    }
}