1use std::path::Path;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use bytes::Bytes;
6use http_body::{Body, Frame};
7use tokio::sync::mpsc::UnboundedReceiver;
8
9use crate::error::StaticError;
10use crate::watcher::ChangeEvent;
11
12pub const LIVE_RELOAD_PATH: &str = "/__mini_static_reload";
15
16#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum ChangeType {
22 Css,
24 Script,
26 Html,
28 Other,
30}
31
32impl ChangeType {
33 pub fn from_path(path: &Path) -> Self {
35 match path.extension().and_then(|e| e.to_str()) {
36 Some("css") => ChangeType::Css,
37 Some("js" | "mjs") => ChangeType::Script,
38 Some("html" | "htm") => ChangeType::Html,
39 _ => ChangeType::Other,
40 }
41 }
42
43 pub fn as_str(&self) -> &'static str {
45 match self {
46 ChangeType::Css => "css",
47 ChangeType::Script => "script",
48 ChangeType::Html => "html",
49 ChangeType::Other => "other",
50 }
51 }
52}
53
54pub fn reload_event_frame(change_type: &ChangeType) -> Bytes {
72 let name = change_type.as_str();
73 Bytes::from(format!("event: {name}\ndata: {{\"type\":\"{name}\"}}\n\n"))
74}
75
76pub struct SseBody {
80 rx: UnboundedReceiver<ChangeEvent>,
81}
82
83impl SseBody {
84 pub(crate) fn new(rx: UnboundedReceiver<ChangeEvent>) -> Self {
85 SseBody { rx }
86 }
87}
88
89impl Body for SseBody {
90 type Data = Bytes;
91 type Error = StaticError;
92
93 fn poll_frame(
94 mut self: Pin<&mut Self>,
95 cx: &mut Context<'_>,
96 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
97 match self.rx.poll_recv(cx) {
98 Poll::Ready(Some(event)) => Poll::Ready(Some(Ok(Frame::data(reload_event_frame(
99 &event.change_type,
100 ))))),
101 Poll::Ready(None) => Poll::Ready(None),
102 Poll::Pending => Poll::Pending,
103 }
104 }
105}
106
107fn reload_script_tag() -> String {
119 format!(
120 "<script>(function(){{\
121 var es=new EventSource(\"{LIVE_RELOAD_PATH}\");\
122 function reload(){{location.reload();}}\
123 es.addEventListener(\"css\",function(){{\
124 document.querySelectorAll('link[rel=\"stylesheet\"]').forEach(function(l){{\
125 var u=new URL(l.href);u.searchParams.set(\"_mr\",Date.now());l.href=u.toString();\
126 }});\
127 }});\
128 es.addEventListener(\"script\",reload);\
129 es.addEventListener(\"html\",reload);\
130 es.addEventListener(\"other\",reload);\
131 }})();</script>"
132 )
133}
134
135pub(crate) fn inject_reload_script(html: &mut Vec<u8>) {
142 let script = reload_script_tag();
143
144 let pos = find_subsequence(html, b"</body>").or_else(|| find_subsequence(html, b"</BODY>"));
145
146 match pos {
147 Some(pos) => {
148 html.splice(pos..pos, script.into_bytes());
149 }
150 None => html.extend_from_slice(script.as_bytes()),
151 }
152}
153
154fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
155 haystack.windows(needle.len()).position(|w| w == needle)
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn reload_event_frame_formats_css_correctly() {
164 let frame = reload_event_frame(&ChangeType::Css);
165 let s = String::from_utf8(frame.to_vec()).unwrap();
166 assert_eq!(s, "event: css\ndata: {\"type\":\"css\"}\n\n");
167 }
168
169 #[test]
170 fn reload_event_frame_formats_script_correctly() {
171 let frame = reload_event_frame(&ChangeType::Script);
172 let s = String::from_utf8(frame.to_vec()).unwrap();
173 assert_eq!(s, "event: script\ndata: {\"type\":\"script\"}\n\n");
174 }
175
176 #[test]
177 fn reload_event_frame_formats_html_correctly() {
178 let frame = reload_event_frame(&ChangeType::Html);
179 let s = String::from_utf8(frame.to_vec()).unwrap();
180 assert_eq!(s, "event: html\ndata: {\"type\":\"html\"}\n\n");
181 }
182
183 #[test]
184 fn reload_event_frame_formats_other_correctly() {
185 let frame = reload_event_frame(&ChangeType::Other);
186 let s = String::from_utf8(frame.to_vec()).unwrap();
187 assert_eq!(s, "event: other\ndata: {\"type\":\"other\"}\n\n");
188 }
189
190 #[test]
191 fn change_type_from_path_css() {
192 assert_eq!(
193 ChangeType::from_path(Path::new("style.css")),
194 ChangeType::Css
195 );
196 assert_eq!(
197 ChangeType::from_path(Path::new("dir/main.css")),
198 ChangeType::Css
199 );
200 }
201
202 #[test]
203 fn change_type_from_path_script() {
204 assert_eq!(
205 ChangeType::from_path(Path::new("app.js")),
206 ChangeType::Script
207 );
208 assert_eq!(
209 ChangeType::from_path(Path::new("mod.mjs")),
210 ChangeType::Script
211 );
212 assert_eq!(
213 ChangeType::from_path(Path::new("dir/lib.js")),
214 ChangeType::Script
215 );
216 }
217
218 #[test]
219 fn change_type_from_path_html() {
220 assert_eq!(
221 ChangeType::from_path(Path::new("index.html")),
222 ChangeType::Html
223 );
224 assert_eq!(
225 ChangeType::from_path(Path::new("page.htm")),
226 ChangeType::Html
227 );
228 assert_eq!(
229 ChangeType::from_path(Path::new("dir/file.html")),
230 ChangeType::Html
231 );
232 }
233
234 #[test]
235 fn change_type_from_path_other() {
236 assert_eq!(
237 ChangeType::from_path(Path::new("image.png")),
238 ChangeType::Other
239 );
240 assert_eq!(
241 ChangeType::from_path(Path::new("data.json")),
242 ChangeType::Other
243 );
244 assert_eq!(
245 ChangeType::from_path(Path::new("README")),
246 ChangeType::Other
247 );
248 }
249
250 #[test]
251 fn reload_script_tag_embeds_the_live_reload_path() {
252 assert!(reload_script_tag().contains(LIVE_RELOAD_PATH));
256 }
257
258 #[test]
259 fn inject_reload_script_inserts_before_closing_body_tag() {
260 let mut html = b"<html><body><h1>hi</h1></body></html>".to_vec();
261 inject_reload_script(&mut html);
262 let s = String::from_utf8(html).unwrap();
263
264 assert!(s.starts_with("<html><body><h1>hi</h1>"));
265 assert!(s.ends_with("</body></html>"));
266 assert!(s.contains(LIVE_RELOAD_PATH));
267 assert!(s.find("<script>").unwrap() < s.find("</body>").unwrap());
269 }
270
271 #[test]
272 fn inject_reload_script_handles_uppercase_closing_tag() {
273 let mut html = b"<HTML><BODY>hi</BODY></HTML>".to_vec();
274 inject_reload_script(&mut html);
275 let s = String::from_utf8(html).unwrap();
276
277 assert!(s.find("<script>").unwrap() < s.find("</BODY>").unwrap());
278 }
279
280 #[test]
281 fn inject_reload_script_appends_when_no_body_tag_present() {
282 let mut html = b"<h1>fragment, no body tag</h1>".to_vec();
283 inject_reload_script(&mut html);
284 let s = String::from_utf8(html).unwrap();
285
286 assert!(s.starts_with("<h1>fragment, no body tag</h1>"));
287 assert!(s.ends_with("</script>"));
288 }
289
290 #[tokio::test]
291 async fn sse_body_yields_a_frame_per_broadcast_event() {
292 use crate::watcher::Broadcaster;
293 use http_body_util::BodyExt;
294 use std::path::PathBuf;
295
296 let broadcaster = Broadcaster::new();
297 let rx = broadcaster.subscribe();
298 let mut body = SseBody::new(rx);
299
300 broadcaster.broadcast(ChangeEvent {
301 path: PathBuf::from("style.css"),
302 change_type: ChangeType::Css,
303 });
304
305 let frame = body
306 .frame()
307 .await
308 .expect("stream ended early")
309 .expect("frame error");
310 let data = frame.into_data().unwrap();
311 assert_eq!(&data[..], b"event: css\ndata: {\"type\":\"css\"}\n\n");
312 }
313}