Skip to main content

leptos_use_event_source/
options.rs

1use crate::{ReconnectLimit, UseEventSourceOnEventReturn};
2use default_struct_builder::DefaultBuilder;
3use std::marker::PhantomData;
4use std::sync::Arc;
5
6/// Options for [`use_event_source_with_options`](crate::use_event_source_with_options).
7#[derive(DefaultBuilder)]
8pub struct UseEventSourceOptions<T>
9where
10    T: 'static,
11{
12    /// Retry times. Defaults to `ReconnectLimit::Limited(3)`. Use `ReconnectLimit::Infinite` for
13    /// infinite retries.
14    pub(crate) reconnect_limit: ReconnectLimit,
15
16    /// Retry interval in ms. Defaults to 3000.
17    pub(crate) reconnect_interval: u64,
18
19    /// On maximum retry times reached.
20    pub(crate) on_failed: Arc<dyn Fn() + Send + Sync>,
21
22    /// If `true` the `EventSource` connection will immediately be opened when calling this function.
23    /// If `false` you have to manually call the `open` function.
24    /// Defaults to `true`.
25    pub(crate) immediate: bool,
26
27    /// List of named events to listen for on the `EventSource`.
28    #[builder(into)]
29    pub(crate) named_events: Vec<String>,
30
31    /// The `on_event` is called before processing any event inside of [`use_event_source`](crate::use_event_source).
32    /// Return `UseEventSourceOnEventReturn::Ignore` to ignore further processing of the respective event
33    /// in [`use_event_source`](crate::use_event_source), or `UseEventSourceOnEventReturn::Use` to process the event as usual.
34    ///
35    /// Beware that ignoring processing the `open` and `error` events may yield unexpected results.
36    ///
37    /// You may want to use [`UseEventSourceMessage::try_from()`](crate::UseEventSourceMessage::try_from) to access the event data.
38    ///
39    /// Default handler returns `UseEventSourceOnEventReturn::Use`.
40    pub(crate) on_event: Arc<dyn Fn(&web_sys::Event) -> UseEventSourceOnEventReturn + Send + Sync>,
41
42    /// If CORS should be set to `include` credentials. Defaults to `false`.
43    pub(crate) with_credentials: bool,
44
45    pub(crate) _marker: PhantomData<T>,
46}
47
48impl<T> Default for UseEventSourceOptions<T> {
49    fn default() -> Self {
50        Self {
51            reconnect_limit: ReconnectLimit::default(),
52            reconnect_interval: 3000,
53            on_failed: Arc::new(|| {}),
54            immediate: true,
55            named_events: vec![],
56            on_event: Arc::new(|_| UseEventSourceOnEventReturn::ProcessMessage),
57            with_credentials: false,
58            _marker: PhantomData,
59        }
60    }
61}