1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//! Declarative live-broadcast trait for repository auto-broadcasting.
//!
//! Implement [`LiveFragment`] on any `#[model]` type to opt in to
//! `hx-swap-oob` broadcasts whenever the repository mutates that model.
//! Then add `broadcasts = true` (and optionally `topic = "tasks"`) to your
//! `#[repository]` attribute and the generated `save`/`update`/`delete_by_id`
//! methods will automatically publish the rendered HTML fragment to the
//! named channel.
//!
//! # Example
//!
//! ```rust,no_run
//! use autumn_web::live::LiveFragment;
//! use maud::{Markup, html};
//!
//! // Given a model:
//! // pub struct Task { pub id: i64, pub title: String }
//!
//! # struct Task { pub id: i64, pub title: String }
//! impl LiveFragment for Task {
//! fn dom_id_for(id: i64) -> String {
//! format!("task-{id}")
//! }
//!
//! fn dom_id(&self) -> String {
//! Self::dom_id_for(self.id)
//! }
//!
//! fn render_fragment(&self) -> Markup {
//! html! {
//! li id=(self.dom_id()) { (self.title) }
//! }
//! }
//! }
//! // Then declare:
//! // #[autumn_web::repository(Task, broadcasts = true, topic = "tasks")]
//! // pub trait TaskRepository {}
//! ```
//!
//! # Swap strategies
//!
//! | Mutation | Default swap |
//! |----------|-------------|
//! | `save` | `insert_swap()` — default `OobSwap::True` (replace element) |
//! | `update` | `OobSwap::True` (replace element by matching id) |
//! | `delete` | `OobSwap::Delete` (remove element from DOM) |
//!
//! Override `insert_swap()` to append new items to a list container.
//! **Always target a container** — `OobSwap::True` tries to replace an element
//! with the new record's id, which does not exist yet on remote clients and is
//! silently dropped. Use `OobSwap::Target` with the list container's id instead:
//!
//! ```rust,no_run
//! # use autumn_web::htmx::{OobMethod, OobSwap};
//! # struct Task;
//! # impl autumn_web::live::LiveFragment for Task {
//! # fn dom_id_for(_: i64) -> String { String::new() }
//! # fn dom_id(&self) -> String { String::new() }
//! # fn render_fragment(&self) -> maud::Markup { maud::html!{} }
//! fn insert_swap() -> OobSwap {
//! OobSwap::Target(OobMethod::BeforeEnd, "#tasks-list".to_string())
//! }
//! # }
//! ```
//!
//! Wire the matching container in your index template:
//! ```html
//! <ul id="tasks-list" hx-ext="sse" sse-connect="/tasks/stream"
//! sse-swap="message" hx-swap="none"></ul>
//! ```
//!
//! # Note on `commit_hooks`
//!
//! Broadcasts fire inline after the mutation in the same async task. They are
//! **not** wired through the durable `after_*_commit` queue, which has no
//! channel handle. If the channel has no active subscribers the publish
//! silently succeeds with zero receivers.
/// Trait that connects a model to its live-broadcast HTML fragment.
///
/// Implement this on your model type and declare `broadcasts = true` (plus an
/// optional `topic = "..."`) on the `#[repository]` attribute to enable
/// automatic OOB broadcasts after each mutation.
///
/// Requires the `ws`, `maud`, and `htmx` features of `autumn-web`.
#[cfg(all(feature = "htmx", feature = "maud"))]
pub trait LiveFragment {
/// Compute the DOM id for a primary key value.
///
/// Used for delete broadcasts where only the `id` is available (the
/// record has already been removed from the database).
fn dom_id_for(id: i64) -> String;
/// Compute the DOM id for this model instance.
///
/// The root element of [`render_fragment`](Self::render_fragment) **must**
/// carry `id = self.dom_id()` so htmx can match it for OOB swaps.
fn dom_id(&self) -> String;
/// Render the single-item HTML fragment for this record.
///
/// The root element must have `id = self.dom_id()`.
fn render_fragment(&self) -> maud::Markup;
/// Htmx swap strategy to use when a new record is inserted into the list.
///
/// The target container is controlled by the `broadcast_container`
/// repository attribute (defaults to `{table}-list`). This method only
/// controls the *strategy* — how the fragment lands in that container.
///
/// Defaults to [`crate::htmx::OobSwap::BeforeEnd`] (append). Override to
/// [`crate::htmx::OobSwap::AfterBegin`] to prepend instead:
///
/// ```rust,ignore
/// fn insert_swap() -> OobSwap {
/// OobSwap::AfterBegin
/// }
/// ```
#[must_use]
fn insert_swap() -> crate::htmx::OobSwap {
crate::htmx::OobSwap::BeforeEnd
}
}
#[cfg(test)]
#[cfg(all(feature = "htmx", feature = "maud"))]
mod tests {
use super::*;
struct Thing {
id: i64,
label: String,
}
impl LiveFragment for Thing {
fn dom_id_for(id: i64) -> String {
format!("thing-{id}")
}
fn dom_id(&self) -> String {
Self::dom_id_for(self.id)
}
fn render_fragment(&self) -> maud::Markup {
maud::html! {
li id=(self.dom_id()) { (self.label) }
}
}
}
#[test]
fn dom_id_for_formats_correctly() {
assert_eq!(Thing::dom_id_for(42), "thing-42");
}
#[test]
fn dom_id_matches_dom_id_for() {
let t = Thing {
id: 7,
label: "x".into(),
};
assert_eq!(t.dom_id(), Thing::dom_id_for(7));
}
#[test]
fn render_fragment_contains_id() {
let t = Thing {
id: 5,
label: "hello".into(),
};
let html = t.render_fragment().into_string();
assert!(
html.contains("thing-5"),
"fragment must embed dom_id: {html}"
);
assert!(
html.contains("hello"),
"fragment must embed content: {html}"
);
}
#[test]
fn insert_swap_defaults_to_before_end() {
assert!(matches!(
Thing::insert_swap(),
crate::htmx::OobSwap::BeforeEnd
));
}
}