use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use super::form::{self, Answer, Form, FormRecord};
use super::State;
pub const MAX_FEED: usize = 300;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FeedItem {
pub seq: u64,
pub at: u64,
pub kind: ItemKind,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ItemKind {
Message {
id: String,
blocks: Vec<Block>,
#[serde(default)]
edited: bool,
#[serde(default)]
withdrawn: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
form: Option<FormRecord>,
},
Reply { text: String, client: String },
Submission { message: String, form: String, answers: BTreeMap<String, Answer>, client: String },
Action { action: String, label: String, client: String },
Marker(Marker),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Block {
Markdown { text: String },
Fields { items: Vec<Field> },
Form(Form),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
pub label: String,
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "marker", rename_all = "lowercase")]
pub enum Marker {
Done { client: String },
Reopen { client: String },
State { from: State, to: State },
Status { from: Option<String>, to: Option<String> },
}
impl FeedItem {
#[cfg(test)]
pub fn markdown(seq: u64, at: u64, id: &str, text: &str) -> FeedItem {
let blocks = vec![Block::Markdown { text: text.to_string() }];
let kind = ItemKind::Message { id: id.to_string(), blocks, edited: false, withdrawn: false, form: None };
FeedItem { seq, at, kind }
}
fn is_marker(&self) -> bool {
matches!(self.kind, ItemKind::Marker(_))
}
fn is_message(&self) -> bool {
matches!(self.kind, ItemKind::Message { .. })
}
fn has_open_form(&self) -> bool {
matches!(&self.kind, ItemKind::Message { form: Some(r), .. } if r.is_open())
}
}
pub fn form_of<'a>(feed: &'a [FeedItem], id: &str) -> Option<(&'a Form, &'a FormRecord)> {
feed.iter().find_map(|i| match &i.kind {
ItemKind::Message { id: have, blocks, form: Some(record), .. } if have == id => {
form::form_in(blocks).map(|f| (f, record))
}
_ => None,
})
}
pub fn form_record_mut<'a>(feed: &'a mut [FeedItem], id: &str) -> Option<&'a mut FormRecord> {
feed.iter_mut().find_map(|i| match &mut i.kind {
ItemKind::Message { id: have, form: Some(record), .. } if have == id => Some(record),
_ => None,
})
}
pub fn markdown_of(blocks: &[Block]) -> String {
blocks
.iter()
.filter_map(|b| match b {
Block::Markdown { text } => Some(text.as_str()),
Block::Fields { .. } | Block::Form(_) => None,
})
.collect::<Vec<_>>()
.join("\n\n")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sent {
Unchanged,
Edited { form_opened: bool },
Inserted,
}
pub fn send(feed: &mut Vec<FeedItem>, id: &str, blocks: Vec<Block>, seq: impl FnOnce() -> u64, at: u64) -> Sent {
let existing = feed.iter_mut().find_map(|i| match &mut i.kind {
ItemKind::Message { id: have, blocks, edited, withdrawn, form } if have == id => {
Some((blocks, edited, withdrawn, form))
}
_ => None,
});
match existing {
Some((have, edited, withdrawn, record)) => {
let resent = form::resend(have, record.as_ref(), blocks);
if resent.blocks == *have && resent.record == *record && !*withdrawn {
return Sent::Unchanged;
}
*have = resent.blocks;
*record = resent.record;
*edited = true;
*withdrawn = false;
Sent::Edited { form_opened: resent.opened }
}
None => {
let form = form::form_in(&blocks).map(|f| FormRecord::open(&f.id));
let kind = ItemKind::Message { id: id.to_string(), blocks, edited: false, withdrawn: false, form };
push(feed, FeedItem { seq: seq(), at, kind });
Sent::Inserted
}
}
}
pub fn withdraw(feed: &mut [FeedItem], id: &str) -> bool {
feed.iter_mut().any(|i| match &mut i.kind {
ItemKind::Message { id: have, withdrawn, form, .. } if have == id && !*withdrawn => {
*withdrawn = true;
if let Some(record) = form {
record.withdraw();
}
true
}
_ => false,
})
}
pub fn push(feed: &mut Vec<FeedItem>, item: FeedItem) {
let back_to_start = match (&item.kind, feed.last().map(|l| &l.kind)) {
(ItemKind::Marker(Marker::Status { to, .. }), Some(ItemKind::Marker(Marker::Status { from, .. }))) => from == to,
_ => {
feed.push(item);
return;
}
};
if back_to_start {
feed.pop();
return;
}
let (Some(last), ItemKind::Marker(Marker::Status { to, .. })) = (feed.last_mut(), item.kind) else { return };
if let ItemKind::Marker(Marker::Status { to: prev_to, .. }) = &mut last.kind {
*prev_to = to;
}
last.at = item.at;
}
pub fn cap(feed: &mut Vec<FeedItem>, max: usize) {
while feed.len() > max {
let pos = feed
.iter()
.position(FeedItem::is_marker)
.or_else(|| feed.iter().position(|i| i.is_message() && !i.has_open_form()))
.or_else(|| feed.iter().position(|i| !i.has_open_form()));
let Some(pos) = pos else { return };
feed.remove(pos);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn status(seq: u64, from: Option<&str>, to: Option<&str>) -> FeedItem {
let (from, to) = (from.map(str::to_string), to.map(str::to_string));
FeedItem { seq, at: seq * 10, kind: ItemKind::Marker(Marker::Status { from, to }) }
}
fn state(seq: u64, from: State, to: State) -> FeedItem {
FeedItem { seq, at: seq * 10, kind: ItemKind::Marker(Marker::State { from, to }) }
}
fn reply(seq: u64) -> FeedItem {
FeedItem { seq, at: seq * 10, kind: ItemKind::Reply { text: format!("r{seq}"), client: "tui".into() } }
}
fn statuses(feed: &[FeedItem]) -> Vec<(u64, u64, Option<&str>, Option<&str>)> {
feed.iter()
.filter_map(|i| match &i.kind {
ItemKind::Marker(Marker::Status { from, to }) => Some((i.seq, i.at, from.as_deref(), to.as_deref())),
_ => None,
})
.collect()
}
#[test]
fn consecutive_status_markers_merge() {
let mut feed = Vec::new();
push(&mut feed, status(1, None, Some("a")));
push(&mut feed, status(2, Some("a"), Some("b")));
push(&mut feed, status(3, Some("b"), Some("c")));
assert_eq!(feed.len(), 1);
assert_eq!(statuses(&feed), [(1, 30, None, Some("c"))]);
}
#[test]
fn a_merge_back_to_the_start_leaves_nothing() {
let mut feed = vec![reply(1)];
push(&mut feed, status(2, Some("a"), Some("b")));
push(&mut feed, status(3, Some("b"), Some("a")));
assert_eq!(feed, [reply(1)]);
push(&mut feed, status(4, None, Some("x")));
push(&mut feed, status(5, Some("x"), None));
assert_eq!(feed, [reply(1)]);
}
#[test]
fn anything_in_between_stops_the_merge() {
for between in [reply(2), state(2, State::Active, State::NeedsYou), FeedItem::markdown(2, 20, "m", "hi")] {
let mut feed = Vec::new();
push(&mut feed, status(1, Some("a"), Some("b")));
push(&mut feed, between.clone());
push(&mut feed, status(3, Some("b"), Some("c")));
assert_eq!(feed.len(), 3, "{between:?}");
assert_eq!(statuses(&feed), [(1, 10, Some("a"), Some("b")), (3, 30, Some("b"), Some("c"))]);
}
}
#[test]
fn state_markers_never_merge() {
let mut feed = Vec::new();
push(&mut feed, state(1, State::Active, State::NeedsYou));
push(&mut feed, state(2, State::NeedsYou, State::Active));
assert_eq!(feed.len(), 2);
push(&mut feed, status(3, None, Some("x")));
assert_eq!(feed.len(), 3);
}
#[test]
fn cap_drops_markers_then_messages_then_user_items() {
let mut feed = vec![
reply(1),
FeedItem::markdown(2, 20, "m1", "one"),
state(3, State::Active, State::NeedsYou),
FeedItem::markdown(4, 40, "m2", "two"),
status(5, None, Some("s")),
reply(6),
];
let seqs = |feed: &[FeedItem]| feed.iter().map(|i| i.seq).collect::<Vec<_>>();
cap(&mut feed, 6);
assert_eq!(seqs(&feed), [1, 2, 3, 4, 5, 6], "within the cap: untouched");
cap(&mut feed, 4);
assert_eq!(seqs(&feed), [1, 2, 4, 6], "markers first, oldest first");
cap(&mut feed, 3);
assert_eq!(seqs(&feed), [1, 4, 6], "then the oldest message");
cap(&mut feed, 1);
assert_eq!(seqs(&feed), [6], "then the oldest replies");
}
fn md(text: &str) -> Vec<Block> {
vec![Block::Markdown { text: text.into() }]
}
fn message(feed: &[FeedItem], id: &str) -> (u64, u64, Vec<Block>, bool, bool) {
feed.iter()
.find_map(|i| match &i.kind {
ItemKind::Message { id: have, blocks, edited, withdrawn, .. } if have == id => {
Some((i.seq, i.at, blocks.clone(), *edited, *withdrawn))
}
_ => None,
})
.unwrap()
}
#[test]
fn send_inserts_edits_in_place_and_ignores_repeats() {
let mut feed = vec![reply(1)];
assert_eq!(send(&mut feed, "a", md("one"), || 2, 20), Sent::Inserted);
assert_eq!(send(&mut feed, "b", md("two"), || 3, 30), Sent::Inserted);
assert_eq!(send(&mut feed, "a", md("one"), || panic!("minted"), 40), Sent::Unchanged);
assert_eq!(send(&mut feed, "a", md("uno"), || panic!("minted"), 50), Sent::Edited { form_opened: false });
assert_eq!(message(&feed, "a"), (2, 20, md("uno"), true, false));
assert_eq!(feed.iter().map(|i| i.seq).collect::<Vec<_>>(), [1, 2, 3]);
assert_eq!(send(&mut feed, "a", md("uno"), || panic!("minted"), 60), Sent::Unchanged);
}
#[test]
fn withdraw_keeps_the_message_and_a_resend_brings_it_back() {
let mut feed = Vec::new();
send(&mut feed, "a", md("one"), || 1, 10);
assert!(!withdraw(&mut feed, "nope"), "an unknown id is a no-op");
assert!(withdraw(&mut feed, "a"));
assert!(!withdraw(&mut feed, "a"), "already withdrawn");
assert_eq!(message(&feed, "a"), (1, 10, md("one"), false, true));
assert_eq!(send(&mut feed, "a", md("one"), || panic!("minted"), 20), Sent::Edited { form_opened: false });
assert_eq!(message(&feed, "a"), (1, 10, md("one"), true, false));
assert_eq!(feed.len(), 1);
}
fn with_form(text: &str) -> Vec<Block> {
vec![Block::Markdown { text: text.into() }, Block::Form(form::tests::mixed())]
}
fn record(feed: &[FeedItem], id: &str) -> Option<FormRecord> {
feed.iter().find_map(|i| match &i.kind {
ItemKind::Message { id: have, form, .. } if have == id => Some(form.clone()),
_ => None,
})?
}
#[test]
fn a_form_opens_with_its_message_and_withdraws_with_it() {
let mut feed = Vec::new();
assert_eq!(send(&mut feed, "a", with_form("one"), || 1, 10), Sent::Inserted);
assert_eq!(record(&feed, "a"), Some(FormRecord::open("f")));
assert_eq!(form_of(&feed, "a").map(|(f, _)| f.id.as_str()), Some("f"));
assert!(form_of(&feed, "nope").is_none());
assert_eq!(send(&mut feed, "a", with_form("one"), || panic!(), 11), Sent::Unchanged);
assert_eq!(send(&mut feed, "a", with_form("uno"), || panic!(), 12), Sent::Edited { form_opened: false });
assert!(withdraw(&mut feed, "a"));
assert_eq!(record(&feed, "a").unwrap().state, form::FormState::Withdrawn);
assert_eq!(send(&mut feed, "a", with_form("uno"), || panic!(), 13), Sent::Edited { form_opened: true });
assert_eq!(record(&feed, "a"), Some(FormRecord::open("f")));
send(&mut feed, "b", md("two"), || 2, 20);
assert_eq!(record(&feed, "b"), None);
assert_eq!(send(&mut feed, "b", with_form("two"), || panic!(), 21), Sent::Edited { form_opened: true });
assert_eq!(send(&mut feed, "b", md("two"), || panic!(), 22), Sent::Edited { form_opened: false });
assert_eq!(record(&feed, "b").unwrap().state, form::FormState::Withdrawn);
assert!(form_of(&feed, "b").is_none(), "no form block left");
assert_eq!(send(&mut feed, "b", md("two"), || panic!(), 23), Sent::Unchanged);
}
#[test]
fn a_submitted_form_survives_resends_and_withdrawal() {
let mut feed = Vec::new();
send(&mut feed, "a", with_form("one"), || 1, 10);
let answers: BTreeMap<String, Answer> = [("note".to_string(), Answer::Text("hi".into()))].into();
let submitted = form::FormState::Submitted { at: 11, answers, client: "tui".into() };
form_record_mut(&mut feed, "a").unwrap().state = submitted.clone();
assert_eq!(send(&mut feed, "a", with_form("one"), || panic!(), 12), Sent::Unchanged);
let other = vec![Block::Markdown { text: "uno".into() }, Block::Form(form::tests::example())];
assert_eq!(send(&mut feed, "a", other.clone(), || panic!(), 13), Sent::Edited { form_opened: false });
assert_eq!(message(&feed, "a").2, with_form("uno"));
assert_eq!(record(&feed, "a").unwrap().state, submitted);
assert_eq!(send(&mut feed, "a", other, || panic!(), 14), Sent::Unchanged, "frozen re-sends settle");
withdraw(&mut feed, "a");
assert_eq!(record(&feed, "a").unwrap().state, submitted);
}
#[test]
fn cap_never_drops_an_open_form() {
let open = |seq: u64, id: &str| {
let mut feed = Vec::new();
send(&mut feed, id, with_form("q"), || seq, seq * 10);
feed.pop().unwrap()
};
let mut done = open(3, "m3");
if let ItemKind::Message { form: Some(r), .. } = &mut done.kind {
r.withdraw();
}
let mut feed = vec![open(1, "m1"), reply(2), done, FeedItem::markdown(4, 40, "m4", "x"), status(5, None, Some("s"))];
let seqs = |feed: &[FeedItem]| feed.iter().map(|i| i.seq).collect::<Vec<_>>();
cap(&mut feed, 4);
assert_eq!(seqs(&feed), [1, 2, 3, 4], "markers first");
cap(&mut feed, 2);
assert_eq!(seqs(&feed), [1, 2], "then messages, skipping the open form; a withdrawn one goes");
cap(&mut feed, 1);
assert_eq!(seqs(&feed), [1], "then user items, still skipping it");
cap(&mut feed, 0);
assert_eq!(seqs(&feed), [1], "only open forms left: the cap goes soft");
}
#[test]
fn markdown_of_skips_fields() {
let blocks = vec![
Block::Markdown { text: "a".into() },
Block::Fields { items: vec![Field { label: "Head".into(), value: "36b1".into() }] },
Block::Markdown { text: "b".into() },
];
assert_eq!(markdown_of(&blocks), "a\n\nb");
}
#[test]
fn store_shape_round_trips() {
let fields = vec![Block::Fields { items: vec![Field { label: "Head".into(), value: "36b1".into() }] }];
let feed = vec![
FeedItem { seq: 8, at: 80, kind: ItemKind::Message { id: "f".into(), blocks: fields, edited: true, withdrawn: false, form: None } },
FeedItem {
seq: 9,
at: 90,
kind: ItemKind::Message {
id: "q".into(),
blocks: vec![Block::Form(form::tests::mixed())],
edited: false,
withdrawn: false,
form: Some(FormRecord { draft: [("note".to_string(), Answer::Text("n".into()))].into(), ..FormRecord::open("f") }),
},
},
FeedItem {
seq: 10,
at: 100,
kind: ItemKind::Submission {
message: "q".into(),
form: "f".into(),
answers: [("sure".to_string(), Answer::Confirm(true))].into(),
client: "tui".into(),
},
},
FeedItem::markdown(1, 10, "m", "hi"),
reply(2),
FeedItem { seq: 3, at: 30, kind: ItemKind::Action { action: "go".into(), label: "Go".into(), client: "api:x".into() } },
FeedItem { seq: 4, at: 40, kind: ItemKind::Marker(Marker::Done { client: "cli".into() }) },
FeedItem { seq: 5, at: 50, kind: ItemKind::Marker(Marker::Reopen { client: "tui".into() }) },
state(6, State::Done, State::Active),
status(7, None, Some("s")),
];
let json = serde_json::to_string(&feed).unwrap();
assert!(json.contains(r#""kind":{"type":"marker","marker":"done","client":"cli"}"#), "{json}");
assert!(json.contains(r#""blocks":[{"type":"fields","items":[{"label":"Head","value":"36b1"}]}]"#), "{json}");
assert_eq!(serde_json::from_str::<Vec<FeedItem>>(&json).unwrap(), feed);
}
}