livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The session access the server half needs synchronously, and the keys session-backed properties
//! persist under.

use laravel::session::Session;
use laravel_core::context::Context;
use laravel_http::session::SessionInternals as _;
use serde_json::Value;

/// The session of the request being handled, or `None` on a route without one.
///
/// Component templates read the CSRF token and session-backed properties synchronously, because
/// MiniJinja's rendering is synchronous.
#[must_use]
pub fn current() -> Option<Session> {
    Session::of(&Context::current()?)
}

/// The request's CSRF token, or `None` on a route without a session.
#[must_use]
pub fn csrf_token() -> Option<String> {
    current().map(|session| session.token())
}

/// Reads a value a session-backed property persisted, or `None` when the session has none.
#[must_use]
pub fn get(key: &str) -> Option<Value> {
    current()?.get::<Value>(key)
}

/// Writes a value a session-backed property persists.
///
/// Returns `false` when the route has no session, so the caller can skip the write instead of
/// panicking in the middle of a render.
pub fn put(key: &str, value: &Value) -> bool {
    match current() {
        Some(session) => {
            session.put(key, value);
            true
        }
        None => false,
    }
}

/// Forgets a value, such as one that no longer fits its property.
pub fn forget(key: &str) -> bool {
    match current() {
        Some(session) => {
            session.forget(key);
            true
        }
        None => false,
    }
}

/// Whether the session holds a value for the key.
#[must_use]
pub fn exists(key: &str) -> bool {
    current().is_some_and(|session| session.exists(key))
}

/// The key a session-backed property persists under.
///
/// A property with a configured key uses it, with `{path}` placeholders replaced from `lookup`.
/// A property without one uses `lw{crc32}`, so two components with a property of the same name do
/// not share a value.
#[must_use]
pub fn property_key(
    component: &str,
    property: &str,
    configured: Option<&str>,
    lookup: impl Fn(&str) -> Option<String>,
) -> String {
    match configured {
        Some(key) => replace_placeholders(key, lookup),
        None => {
            let mut name = String::with_capacity(component.len() + property.len());
            name.push_str(component);
            name.push_str(property);

            format!("lw{}", crc32(name.as_bytes()))
        }
    }
}

/// Replaces every `{path}` in a configured session key with the component value it names.
///
/// A placeholder that names nothing is left as it was, so a key never loses its identity.
fn replace_placeholders(key: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
    let mut out = String::with_capacity(key.len());
    let mut rest = key;

    while let Some(start) = rest.find('{') {
        let Some(end) = rest[start..].find('}').map(|end| start + end) else {
            break;
        };
        out.push_str(&rest[..start]);
        let path = &rest[start + 1..end];
        match lookup(path) {
            Some(value) => out.push_str(&value),
            None => out.push_str(&rest[start..=end]),
        }
        rest = &rest[end + 1..];
    }

    out.push_str(rest);
    out
}

/// The CRC-32 (IEEE 802.3) checksum of `bytes`, as PHP's `crc32()` and zlib compute it.
#[must_use]
pub fn crc32(bytes: &[u8]) -> u32 {
    let mut crc = 0xffff_ffffu32;

    for &byte in bytes {
        crc ^= u32::from(byte);
        for _ in 0..8 {
            let mask = (crc & 1).wrapping_neg();
            crc = (crc >> 1) ^ (0xedb8_8320 & mask);
        }
    }

    !crc
}

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

    #[test]
    fn crc32_matches_the_standard_check_value() {
        assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
        assert_eq!(crc32(b""), 0);
        assert_eq!(crc32(b"The quick brown fox jumps over the lazy dog"), 0x414f_a339);
    }

    #[test]
    fn a_property_without_a_key_is_scoped_to_its_component() {
        let counter = property_key("counter", "step", None, |_| None);
        let other = property_key("timer", "step", None, |_| None);

        assert!(counter.starts_with("lw"));
        assert_ne!(counter, other);
        // Stable across calls, so a value persisted last request is found again.
        assert_eq!(counter, property_key("counter", "step", None, |_| None));
    }

    #[test]
    fn a_configured_key_replaces_its_placeholders() {
        let key = property_key("counter", "step", Some("cart-{id}-{user.id}"), |path| match path {
            "id" => Some("7".to_owned()),
            "user.id" => Some("42".to_owned()),
            _ => None,
        });

        assert_eq!(key, "cart-7-42");
    }

    #[test]
    fn an_unknown_placeholder_keeps_its_text() {
        let key = property_key("counter", "step", Some("cart-{missing}"), |_| None);

        assert_eq!(key, "cart-{missing}");
    }

    #[test]
    fn a_configured_key_without_placeholders_is_used_as_it_is() {
        assert_eq!(
            property_key("counter", "step", Some("component-key"), |_| None),
            "component-key"
        );
    }
}