fractal/session/model/room/event/
reaction_group.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use gtk::{gio, glib, prelude::*, subclass::prelude::*};
use indexmap::IndexMap;
use matrix_sdk_ui::timeline::ReactionInfo;
use ruma::{MilliSecondsSinceUnixEpoch, OwnedUserId};

use crate::{prelude::*, session::model::User};

/// A map of user ID to reaction info.
type ReactionsMap = IndexMap<OwnedUserId, ReactionInfo>;

/// Data of a reaction in a reaction group.
#[derive(Clone, Debug)]
pub struct ReactionData {
    /// The sender of the reaction.
    pub sender_id: OwnedUserId,
    /// The timestamp of the reaction.
    pub timestamp: MilliSecondsSinceUnixEpoch,
}

mod imp {
    use std::{
        cell::{OnceCell, RefCell},
        marker::PhantomData,
    };

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::ReactionGroup)]
    pub struct ReactionGroup {
        /// The user of the parent session.
        #[property(get, construct_only)]
        user: OnceCell<User>,
        /// The key of the group.
        #[property(get, construct_only)]
        key: OnceCell<String>,
        /// The reactions in the group.
        reactions: RefCell<Option<ReactionsMap>>,
        /// The number of reactions in this group.
        #[property(get = Self::count)]
        count: PhantomData<u32>,
        /// Whether this group has a reaction from our own user.
        #[property(get = Self::has_own_user)]
        has_own_user: PhantomData<bool>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for ReactionGroup {
        const NAME: &'static str = "ReactionGroup";
        type Type = super::ReactionGroup;
        type Interfaces = (gio::ListModel,);
    }

    #[glib::derived_properties]
    impl ObjectImpl for ReactionGroup {}

    impl ListModelImpl for ReactionGroup {
        fn item_type(&self) -> glib::Type {
            glib::BoxedAnyObject::static_type()
        }

        fn n_items(&self) -> u32 {
            self.reactions
                .borrow()
                .as_ref()
                .map(IndexMap::len)
                .unwrap_or_default() as u32
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            self.reactions
                .borrow()
                .as_ref()
                .and_then(|reactions| reactions.get_index(position as usize))
                .map(|(user_id, info)| {
                    glib::BoxedAnyObject::new(ReactionData {
                        sender_id: user_id.clone(),
                        timestamp: info.timestamp,
                    })
                    .upcast()
                })
        }
    }

    impl ReactionGroup {
        /// The number of reactions in this group.
        fn count(&self) -> u32 {
            self.n_items()
        }

        /// Whether this group has a reaction from our own user.
        fn has_own_user(&self) -> bool {
            let user_id = self.user.get().expect("user is initialized").user_id();
            self.reactions
                .borrow()
                .as_ref()
                .is_some_and(|reactions| reactions.contains_key(user_id))
        }

        /// Update this group with the given reactions.
        pub(super) fn update(&self, new_reactions: &ReactionsMap) {
            let prev_has_own_user = self.has_own_user();
            let prev_count = self.count();
            let new_count = new_reactions.len() as u32;

            let same_reactions = match self.reactions.borrow().as_ref() {
                Some(old_reactions) => {
                    prev_count == new_count
                        && new_reactions.iter().zip(old_reactions.iter()).all(
                            |((old_sender_id, old_info), (new_sender_id, new_info))| {
                                old_sender_id == new_sender_id
                                    && old_info.timestamp == new_info.timestamp
                            },
                        )
                }
                // There were no reactions before, now there are, so it is definitely not the same.
                None => false,
            };
            if same_reactions {
                return;
            }

            *self.reactions.borrow_mut() = Some(new_reactions.clone());

            let obj = self.obj();
            obj.items_changed(0, prev_count, new_count);

            if self.count() != prev_count {
                obj.notify_count();
            }

            if self.has_own_user() != prev_has_own_user {
                obj.notify_has_own_user();
            }
        }
    }
}

glib::wrapper! {
    /// Reactions grouped by a given key.
    ///
    /// Implements `GListModel`.
    pub struct ReactionGroup(ObjectSubclass<imp::ReactionGroup>)
        @implements gio::ListModel;
}

impl ReactionGroup {
    pub fn new(key: &str, user: &User) -> Self {
        glib::Object::builder()
            .property("key", key)
            .property("user", user)
            .build()
    }

    /// Update this group with the given reactions.
    pub(crate) fn update(&self, new_reactions: &ReactionsMap) {
        self.imp().update(new_reactions);
    }
}