datastar/
lib.rs

1//! Datastar is a Rust implementation of the [Datastar](https://data-star.dev) SDK specification.
2
3#![forbid(missing_docs)]
4#![forbid(missing_debug_implementations)]
5
6#[cfg(feature = "axum")]
7pub mod axum;
8#[cfg(feature = "rocket")]
9pub mod rocket;
10
11pub mod execute_script;
12pub mod patch_elements;
13pub mod patch_signals;
14
15#[doc = include_str!("../README.md")]
16#[cfg(doctest)]
17#[expect(unused)]
18struct ReadmeDoctests;
19
20pub mod consts;
21
22/// The prelude for the `datastar` crate
23pub mod prelude {
24    pub use crate::{
25        DatastarEvent, consts::ElementPatchMode, execute_script::ExecuteScript,
26        patch_elements::PatchElements, patch_signals::PatchSignals,
27    };
28}
29
30use core::{fmt::Display, time::Duration};
31
32/// [`DatastarEvent`] is a struct that represents a generic Datastar event.
33/// All Datastar events implement `Into<DatastarEvent>`.
34#[derive(Debug)]
35pub struct DatastarEvent {
36    /// `event` is the type of event.
37    pub event: consts::EventType,
38    /// `id` is can be used by the backend to replay events.
39    /// This is part of the SSE spec and is used to tell the browser how to handle the event.
40    /// For more details see <https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#id>
41    pub id: Option<String>,
42    /// `retry` is part of the SSE spec and is used to tell the browser how long to wait before reconnecting if the connection is lost.
43    /// For more details see <https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#retry>
44    pub retry: Duration,
45    /// `data` is the data that is sent with the event.
46    pub data: Vec<String>,
47}
48
49impl Display for DatastarEvent {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "event: {}", self.event.as_str())?;
52
53        if let Some(id) = &self.id {
54            write!(f, "\nid: {id}")?;
55        }
56
57        let millis = self.retry.as_millis();
58        if millis != consts::DEFAULT_SSE_RETRY_DURATION as u128 {
59            write!(f, "\nretry: {millis}")?;
60        }
61
62        for line in &self.data {
63            write!(f, "\ndata: {line}")?;
64        }
65
66        write!(f, "\n\n")?;
67
68        Ok(())
69    }
70}