1use serde::Serialize;
4use zaun_community_protocol::event::TypingSignal;
5use zaun_community_protocol::ids::{ChannelId, MemberId};
6use zaun_community_protocol::model::TypingMode;
7
8use crate::cache::CommunityData;
9
10pub const TYPING_SHOWN_MS: u64 = 6_000;
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
16#[serde(tag = "kind", rename_all = "snake_case")]
17pub enum TypingNow {
18 Named {
20 member_ids: Vec<MemberId>,
22 },
23 Anonymous {
25 count: u32,
27 },
28}
29
30impl TypingNow {
31 #[must_use]
33 pub fn from_signal(s: &TypingSignal) -> Option<Self> {
34 match (s.count, s.member_ids.is_empty()) {
35 (Some(count), _) if count > 0 => Some(Self::Anonymous { count }),
36 (_, false) => Some(Self::Named {
37 member_ids: s.member_ids.clone(),
38 }),
39 _ => None,
40 }
41 }
42
43 #[must_use]
45 pub fn count(&self) -> usize {
46 match self {
47 Self::Named { member_ids } => member_ids.len(),
48 Self::Anonymous { count } => usize::try_from(*count).unwrap_or(usize::MAX),
49 }
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
55pub struct TypingSeen {
56 pub now: TypingNow,
58 pub until_ms: u64,
60}
61
62impl CommunityData {
63 #[must_use]
65 pub fn typing_in(&self, channel: &ChannelId, now_ms: u64) -> Option<&TypingNow> {
66 self.typing
67 .get(channel)
68 .filter(|t| t.until_ms > now_ms)
69 .map(|t| &t.now)
70 }
71
72 #[must_use]
74 pub fn typing_mode(&self, channel: &ChannelId) -> TypingMode {
75 self.channels
76 .get(channel)
77 .map_or(TypingMode::Named, |c| c.typing)
78 }
79
80 pub(crate) fn saw_typing(&mut self, s: &TypingSignal, now_ms: u64) {
82 match TypingNow::from_signal(s) {
83 Some(now) => {
84 let until_ms = now_ms.saturating_add(TYPING_SHOWN_MS);
85 self.typing
86 .insert(s.channel_id, TypingSeen { now, until_ms });
87 }
88 None => {
89 self.typing.remove(&s.channel_id);
90 }
91 }
92 }
93}