Skip to main content

devpage_core/
changes.rs

1//! What open pages hear: a change is typed — refresh the page, or fetch a
2//! page's comments again. Anything may publish through the [`Publish`]
3//! port: the file watcher, a comment store, the external-link checker. The
4//! bus that carries changes to open pages is the `devpage` binary's, and a
5//! bus serves one set of documents — a local devpage's served folder, or one
6//! published document in server mode — so every page on it hears every
7//! change on it.
8
9/// Something new for open pages to show.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum Change {
12    /// Fetch the page again.
13    Refresh,
14    /// The threads on the Markdown file at this address changed.
15    Comments(String),
16}
17
18impl Change {
19    /// The message the page script reads off its event stream.
20    pub fn message(&self) -> String {
21        match self {
22            Change::Refresh => "change".into(),
23            Change::Comments(page) => format!("comments {page}"),
24        }
25    }
26}
27
28/// Where a change goes: the bus open pages listen to.
29pub trait Publish: Send + Sync {
30    /// Tells every page listening on this bus about `change`. No one
31    /// listening is not an error.
32    fn publish(&self, change: Change);
33}
34
35/// A [`Publish`] that keeps what it was told, for tests.
36#[cfg(any(test, feature = "testing"))]
37#[derive(Default)]
38pub struct Recorder(std::sync::Mutex<Vec<Change>>);
39
40#[cfg(any(test, feature = "testing"))]
41impl Recorder {
42    /// The changes published so far, in order, forgotten once taken.
43    pub fn drain(&self) -> Vec<Change> {
44        std::mem::take(&mut *self.0.lock().unwrap())
45    }
46}
47
48#[cfg(any(test, feature = "testing"))]
49impl Publish for Recorder {
50    fn publish(&self, change: Change) {
51        self.0.lock().unwrap().push(change);
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn the_page_reads_the_same_messages_as_before() {
61        assert_eq!(Change::Refresh.message(), "change");
62        assert_eq!(
63            Change::Comments("/docs/a.md".into()).message(),
64            "comments /docs/a.md"
65        );
66    }
67}