Skip to main content

tilo_resource/
reactions.rs

1//! Reactions: people answering something with an emoji.
2//!
3//! Any item of any record, or a record itself, takes reactions by holding a
4//! [`Reactions`] field:
5//!
6//! ```
7//! use tilo_resource::{Collection, Model, Reactions};
8//!
9//! #[derive(Model, Default)]
10//! pub struct Page {
11//!     pub title: String,
12//!     pub reactions: Reactions,
13//! }
14//! ```
15//!
16//! Its edits are the framework's two field edits, [`EditOp::React`] and
17//! [`EditOp::Unreact`] (`Page::paths().reactions.react("👍")`). They store who
18//! invoked them ([`ActionCx::author`]), never an argument, so a reaction is
19//! always its author's own: a read-only item (a chat message) still takes
20//! them, and every API publishes, permissions, records in history, syncs
21//! and undoes them like any other field edit. A bot reacting for someone
22//! elsewhere (a Discord member, through the bridge) records the account it
23//! acts for and the name it shows ([`ActionCx::appearance`]), so each of
24//! them is a reaction of their own.
25//!
26//! An emoji is either a Unicode emoji (`👍`) or a workspace's own emoji
27//! written `:name:` ([`custom_emoji_name`]), which every view draws from the
28//! workspace's emoji and shows as its `:name:` text where the workspace has
29//! none of that name.
30
31use std::collections::BTreeSet;
32
33use automerge::transaction::Transactable as _;
34use automerge::{ObjId, ObjType, ReadDoc, Value};
35
36use tilo_action_policy::MemberId;
37
38use crate::action::{ActionCx, Refusal};
39use crate::delta::Delta;
40use crate::map::Map;
41use crate::model::{Atom, Doc, Model, ModelError, Slot};
42use crate::path::{EditOp, Segment};
43
44/// The most different emoji one thing holds reactions with.
45pub const MAX_EMOJI: usize = 20;
46/// The most reactions one thing holds, everyone's together.
47pub const MAX_REACTIONS: usize = 2000;
48/// The longest emoji, in bytes: a Unicode sequence (a family with skin
49/// tones) or a workspace emoji's `:name:`.
50pub const MAX_EMOJI_BYTES: usize = 64;
51pub use tilo_actions::reaction::{ReactionGroup, Reactor};
52pub use tilo_actions::{MAX_CUSTOM_NAME, custom_emoji_name, valid_custom_emoji_name};
53
54/// Separates the parts of a reaction's key: never part of an emoji or of a
55/// member id.
56const KEY_SEPARATOR: char = '\u{1f}';
57
58/// One reaction: who reacted with which emoji, and when.
59#[derive(crate::Model, Clone, Debug, PartialEq, Eq)]
60pub struct Reaction {
61    /// The emoji: Unicode, or a workspace emoji as `:name:`.
62    pub emoji: Atom,
63    /// The member who invoked it.
64    pub by: MemberId,
65    /// The outside account a bot reacted for (`discord/80351110224678912`).
66    pub persona: Option<Atom>,
67    /// The name the account shows, when a bot reacted for one.
68    pub name: Option<Atom>,
69    /// When, in milliseconds since the epoch.
70    pub at: i64,
71}
72
73impl Reaction {
74    /// Whether `member` made this reaction themselves: not a bot
75    /// reacting for someone elsewhere.
76    #[must_use]
77    pub fn is_own(&self, member: &MemberId) -> bool {
78        self.persona.is_none() && self.by == *member
79    }
80
81    fn key(&self) -> String {
82        key_of(
83            &self.emoji.0,
84            &self.by,
85            self.persona.as_ref().map(|p| p.0.as_str()),
86        )
87    }
88}
89
90fn key_of(emoji: &str, by: &MemberId, persona: Option<&str>) -> String {
91    let mut key = String::new();
92    key.push_str(emoji);
93    key.push(KEY_SEPARATOR);
94    key.push_str(persona.unwrap_or_default());
95    key.push(KEY_SEPARATOR);
96    key.push_str(&automerge::ActorId::from(by.actor_bytes()).to_hex_string());
97    key
98}
99
100/// The emoji part of a stored key.
101fn emoji_of_key(key: &str) -> &str {
102    key.split(KEY_SEPARATOR).next().unwrap_or(key)
103}
104
105/// The reactions to one thing. See the [module docs](self).
106#[derive(Clone, Debug, Default, PartialEq, Eq)]
107pub struct Reactions {
108    entries: Map<Reaction>,
109}
110
111impl Reactions {
112    #[must_use]
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    #[must_use]
118    pub fn is_empty(&self) -> bool {
119        self.entries.is_empty()
120    }
121
122    /// How many reactions, everyone's together.
123    #[must_use]
124    pub fn len(&self) -> usize {
125        self.entries.len()
126    }
127
128    /// Every reaction, by emoji.
129    pub fn iter(&self) -> impl Iterator<Item = &Reaction> {
130        self.entries.values()
131    }
132
133    /// The reactions grouped by emoji, the emoji reacted with first first:
134    /// what a reaction strip shows.
135    #[must_use]
136    pub fn groups(&self) -> Vec<ReactionGroup> {
137        let mut groups: Vec<ReactionGroup> = Vec::new();
138        let mut sorted: Vec<&Reaction> = self.entries.values().collect();
139        sorted.sort_by(|a, b| a.at.cmp(&b.at).then_with(|| a.key().cmp(&b.key())));
140        for reaction in sorted {
141            let reactor = Reactor {
142                by: reaction.by.clone(),
143                persona: reaction.persona.as_ref().map(|p| p.0.clone()),
144                name: reaction.name.as_ref().map(|n| n.0.clone()),
145            };
146            match groups.iter_mut().find(|g| g.emoji == reaction.emoji.0) {
147                Some(group) => group.reactors.push(reactor),
148                None => groups.push(ReactionGroup {
149                    emoji: reaction.emoji.0.clone(),
150                    reactors: vec![reactor],
151                    first_at: reaction.at,
152                }),
153            }
154        }
155        groups
156    }
157
158    /// Whether `member` reacted with `emoji` themselves.
159    #[must_use]
160    pub fn reacted(&self, emoji: &str, member: &MemberId) -> bool {
161        self.entries.contains_key(&key_of(emoji, member, None))
162    }
163
164    /// The edit that adds `member`'s reaction with `emoji`, or takes it
165    /// back when they already reacted with it: what a click on a pill or a
166    /// pick in the picker does.
167    #[must_use]
168    pub fn toggle(&self, emoji: &str, member: &MemberId) -> EditOp {
169        if self.reacted(emoji, member) {
170            EditOp::Unreact {
171                emoji: emoji.to_owned(),
172            }
173        } else {
174            EditOp::React {
175                emoji: emoji.to_owned(),
176            }
177        }
178    }
179
180    /// Add `reaction` (for fixtures and imports that hold a value, never a
181    /// verb: those react through [`EditOp::React`]).
182    pub fn insert(&mut self, reaction: Reaction) {
183        self.entries.insert(reaction.key(), reaction);
184    }
185}
186
187/// The [`Reactions`] field of `record`, a record of `table`'s type, and the
188/// key it is stored under, when the record holds one: the reactions to the
189/// record itself, which a window showing it offers in its bar. A record
190/// opts in by holding the field, nothing else; the first such field
191/// counts.
192///
193/// `table` is the record's own ([`Resource::RESOURCE_TABLE`](crate::Resource::RESOURCE_TABLE)),
194/// so code that does not know the record's type reads it.
195#[must_use]
196pub fn record_reactions<'a>(
197    table: &'static crate::table::ModelTable,
198    record: &'a dyn std::any::Any,
199) -> Option<(&'static str, &'a Reactions)> {
200    let desc = table.record()?;
201    let own = <Reactions as Model>::TABLE;
202    desc.fields
203        .iter()
204        .enumerate()
205        .filter(|(_, field)| std::ptr::eq(field.table, own))
206        .find_map(|(index, field)| {
207            (desc.field)(record, index)?
208                .downcast_ref::<Reactions>()
209                .map(|reactions| (field.key, reactions))
210        })
211}
212
213/// `text` as a reaction's emoji, trimmed: a workspace emoji's `:name:`, or
214/// one Unicode emoji (no letters, digits alone, spaces or control
215/// characters).
216///
217/// # Errors
218/// Why `text` is no emoji.
219pub fn reaction_emoji(text: &str) -> Result<&str, Refusal> {
220    let emoji = text.trim();
221    let unicode = || {
222        emoji.len() <= MAX_EMOJI_BYTES
223            && !emoji.is_ascii()
224            && !emoji
225                .chars()
226                .any(|c| c.is_whitespace() || c.is_control() || c.is_alphabetic() || c == ':')
227    };
228    if custom_emoji_name(emoji).is_some() || (!emoji.is_empty() && unicode()) {
229        Ok(emoji)
230    } else {
231        Err(Refusal::new("a reaction is one emoji"))
232    }
233}
234
235impl Model for Reactions {
236    crate::__own_table!(Reactions);
237    crate::model::leaf_paths!();
238
239    fn value_schema() -> serde_json::Value {
240        serde_json::json!({
241            "type": "array",
242            "description": "Reactions: changed only by the react and unreact field edits",
243            "items": {"type": "object"},
244        })
245    }
246    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
247        let _ = types;
248        crate::FieldType::Reactions
249    }
250
251    fn to_json(&self) -> serde_json::Value {
252        serde_json::Value::Array(self.entries.values().map(Model::to_json).collect())
253    }
254
255    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
256        let mut reactions = Self::new();
257        match value {
258            serde_json::Value::Array(values) => {
259                for value in values {
260                    reactions.insert(Reaction::from_json(value)?);
261                }
262            }
263            serde_json::Value::Null => {}
264            _ => return Err(ModelError::shape("a list of reactions")),
265        }
266        Ok(reactions)
267    }
268
269    /// An entry that reads as no reaction (written by something else under
270    /// this field's name) is passed over: the thing holding it still reads.
271    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
272        if !matches!(value, Value::Object(ObjType::Map)) {
273            return Ok(Self::new());
274        }
275        let entries = doc
276            .keys(id)
277            .filter_map(|key| {
278                let reaction = crate::model::read_key::<Reaction>(doc, id, &key).ok()?;
279                (reaction.key() == key).then_some((key, reaction))
280            })
281            .collect();
282        Ok(Self { entries })
283    }
284
285    fn missing() -> Result<Self, ModelError> {
286        Ok(Self::new())
287    }
288
289    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
290        self.entries.store(doc, slot)
291    }
292
293    fn stores_as(&self, before: &Self) -> bool {
294        self.entries.stores_as(&before.entries)
295    }
296
297    fn store_changed(
298        &self,
299        before: &Self,
300        doc: &mut Doc,
301        slot: Slot<'_>,
302        dirty: &Delta,
303    ) -> Result<(), ModelError> {
304        self.entries
305            .store_changed(&before.entries, doc, slot, dirty)
306    }
307
308    fn refresh(
309        &mut self,
310        doc: &Doc,
311        value: &Value<'_>,
312        id: &ObjId,
313        delta: &Delta,
314    ) -> Result<(), ModelError> {
315        // Read again whole, as `load` reads it: a thing's reactions are few.
316        let _ = delta;
317        *self = Self::load(doc, value, id)?;
318        Ok(())
319    }
320
321    /// Reactions change only by [`EditOp::React`] and [`EditOp::Unreact`],
322    /// which name their author themselves: a copy edited elsewhere says
323    /// nothing about who reacted, so it gives no edits.
324    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
325        let _ = (after, path, out);
326    }
327
328    fn edit(
329        doc: &mut Doc,
330        slot: Slot<'_>,
331        path: &[Segment],
332        op: &EditOp,
333        cx: &mut ActionCx,
334    ) -> Result<(), ModelError> {
335        if let Some(segment) = path.first() {
336            return Err(ModelError::invalid(format!(
337                "nothing inside reactions is called `{segment}`"
338            )));
339        }
340        let (emoji, adding) = match op {
341            EditOp::React { emoji } => (emoji, true),
342            EditOp::Unreact { emoji } => (emoji, false),
343            other => return Err(ModelError::unsupported(other)),
344        };
345        let emoji = reaction_emoji(emoji).map_err(ModelError::refused)?;
346        let by = cx
347            .author()
348            .ok_or_else(|| ModelError::Refused("a reaction is always someone's".into()))?
349            .clone();
350        let appearance = cx.appearance();
351        let persona = appearance
352            .as_ref()
353            .and_then(|appearance| appearance.persona.as_ref())
354            .map(|persona| format!("{}/{}", persona.service, persona.account));
355        let key = key_of(emoji, &by, persona.as_deref());
356        let map = slot.object(doc, ObjType::Map)?;
357        let present = doc.get(&map, key.as_str())?.is_some();
358        if !adding {
359            if present {
360                doc.delete(&map, key.as_str())?;
361            }
362            return Ok(());
363        }
364        if present {
365            return Ok(());
366        }
367        let keys: Vec<String> = doc.keys(&map).collect();
368        if keys.len() >= MAX_REACTIONS {
369            return Err(ModelError::Refused(
370                "this has as many reactions as it can hold".into(),
371            ));
372        }
373        let emoji_held: BTreeSet<&str> = keys.iter().map(|key| emoji_of_key(key)).collect();
374        if !emoji_held.contains(emoji) && emoji_held.len() >= MAX_EMOJI {
375            return Err(ModelError::Refused(format!(
376                "this already has reactions with {MAX_EMOJI} different emoji"
377            )));
378        }
379        let reaction = Reaction {
380            emoji: Atom(emoji.to_owned()),
381            by,
382            name: persona
383                .is_some()
384                .then(|| appearance.map(|appearance| Atom(appearance.name)))
385                .flatten(),
386            persona: persona.map(Atom),
387            at: cx.now_ms(),
388        };
389        crate::model::write_key(doc, &map, &key, &reaction)
390    }
391}
392
393#[cfg(test)]
394#[path = "reactions_tests.rs"]
395mod tests;