use std::path::Path;
use std::pin::Pin;
use std::task::{Context, Poll};
use bytes::Bytes;
use http_body::{Body, Frame};
use tokio::sync::mpsc::UnboundedReceiver;
use crate::error::StaticError;
use crate::watcher::ChangeEvent;
pub const LIVE_RELOAD_PATH: &str = "/__mini_static_reload";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChangeType {
Css,
Script,
Html,
Other,
}
impl ChangeType {
pub fn from_path(path: &Path) -> Self {
match path.extension().and_then(|e| e.to_str()) {
Some("css") => ChangeType::Css,
Some("js" | "mjs") => ChangeType::Script,
Some("html" | "htm") => ChangeType::Html,
_ => ChangeType::Other,
}
}
pub fn as_str(&self) -> &'static str {
match self {
ChangeType::Css => "css",
ChangeType::Script => "script",
ChangeType::Html => "html",
ChangeType::Other => "other",
}
}
}
pub fn reload_event_frame(change_type: &ChangeType) -> Bytes {
let name = change_type.as_str();
Bytes::from(format!("event: {name}\ndata: {{\"type\":\"{name}\"}}\n\n"))
}
pub struct SseBody {
rx: UnboundedReceiver<ChangeEvent>,
}
impl SseBody {
pub(crate) fn new(rx: UnboundedReceiver<ChangeEvent>) -> Self {
SseBody { rx }
}
}
impl Body for SseBody {
type Data = Bytes;
type Error = StaticError;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
match self.rx.poll_recv(cx) {
Poll::Ready(Some(event)) => Poll::Ready(Some(Ok(Frame::data(reload_event_frame(
&event.change_type,
))))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
fn reload_script_tag() -> String {
format!(
"<script>(function(){{\
var es=new EventSource(\"{LIVE_RELOAD_PATH}\");\
function reload(){{location.reload();}}\
es.addEventListener(\"css\",function(){{\
document.querySelectorAll('link[rel=\"stylesheet\"]').forEach(function(l){{\
var u=new URL(l.href);u.searchParams.set(\"_mr\",Date.now());l.href=u.toString();\
}});\
}});\
es.addEventListener(\"script\",reload);\
es.addEventListener(\"html\",reload);\
es.addEventListener(\"other\",reload);\
}})();</script>"
)
}
pub(crate) fn inject_reload_script(html: &mut Vec<u8>) {
let script = reload_script_tag();
let pos = find_subsequence(html, b"</body>").or_else(|| find_subsequence(html, b"</BODY>"));
match pos {
Some(pos) => {
html.splice(pos..pos, script.into_bytes());
}
None => html.extend_from_slice(script.as_bytes()),
}
}
pub(crate) fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
#[cfg(test)]
#[path = "../tests/unit/reload.rs"]
mod tests;