1use ruma_macros::EventContent;
6use serde::{Deserialize, Serialize};
7
8use super::relation::Annotation;
9
10#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
14#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
15#[ruma_event(type = "m.reaction", kind = MessageLike)]
16pub struct ReactionEventContent {
17 #[serde(rename = "m.relates_to")]
19 pub relates_to: Annotation,
20}
21
22impl ReactionEventContent {
23 pub fn new(relates_to: Annotation) -> Self {
27 Self { relates_to }
28 }
29}
30
31impl From<Annotation> for ReactionEventContent {
32 fn from(relates_to: Annotation) -> Self {
33 Self::new(relates_to)
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use assert_matches2::assert_matches;
40 use ruma_common::{owned_event_id, serde::Raw};
41 use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
42
43 use super::ReactionEventContent;
44 use crate::relation::Annotation;
45
46 #[test]
47 fn deserialize() {
48 let json = json!({
49 "m.relates_to": {
50 "rel_type": "m.annotation",
51 "event_id": "$1598361704261elfgc:localhost",
52 "key": "🦛",
53 }
54 });
55
56 assert_matches!(
57 from_json_value::<ReactionEventContent>(json),
58 Ok(ReactionEventContent { relates_to })
59 );
60 assert_eq!(relates_to.event_id, "$1598361704261elfgc:localhost");
61 assert_eq!(relates_to.key, "🦛");
62 }
63
64 #[test]
65 fn serialize() {
66 let content = ReactionEventContent::new(Annotation::new(
67 owned_event_id!("$my_reaction"),
68 "🏠".to_owned(),
69 ));
70
71 assert_eq!(
72 to_json_value(&content).unwrap(),
73 json!({
74 "m.relates_to": {
75 "rel_type": "m.annotation",
76 "event_id": "$my_reaction",
77 "key": "🏠"
78 }
79 })
80 );
81 }
82
83 #[test]
84 fn serialization_roundtrip() {
85 let content = ReactionEventContent::new(Annotation::new(
86 owned_event_id!("$my_reaction"),
87 "🏠".to_owned(),
88 ));
89
90 let json_content = Raw::new(&content).unwrap();
91 let deser_content = json_content.deserialize().unwrap();
92
93 assert_eq!(deser_content.relates_to.event_id, content.relates_to.event_id);
94 assert_eq!(deser_content.relates_to.key, content.relates_to.key);
95 }
96}