matrix_sdk_ui/timeline/
util.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
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{ops::Deref, sync::Arc};

use chrono::{Datelike, Local, TimeZone};
use imbl::Vector;
use ruma::{EventId, MilliSecondsSinceUnixEpoch};

#[cfg(doc)]
use super::controller::TimelineMetadata;
use super::{
    event_item::EventTimelineItemKind, item::TimelineUniqueId, EventTimelineItem,
    ReactionsByKeyBySender, TimelineEventItemId, TimelineItem,
};

pub(super) struct EventTimelineItemWithId<'a> {
    pub inner: &'a EventTimelineItem,
    /// Internal identifier generated by [`TimelineMetadata`].
    pub internal_id: &'a TimelineUniqueId,
}

impl EventTimelineItemWithId<'_> {
    /// Create a clone of the underlying [`TimelineItem`] with the given kind.
    pub fn with_inner_kind(&self, kind: impl Into<EventTimelineItemKind>) -> Arc<TimelineItem> {
        TimelineItem::new(self.inner.with_kind(kind), self.internal_id.clone())
    }

    /// Create a clone of the underlying [`TimelineItem`] with the given
    /// reactions.
    pub fn with_reactions(&self, reactions: ReactionsByKeyBySender) -> Arc<TimelineItem> {
        let event_item = self.inner.with_reactions(reactions);
        TimelineItem::new(event_item, self.internal_id.clone())
    }
}

impl Deref for EventTimelineItemWithId<'_> {
    type Target = EventTimelineItem;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}

#[inline(always)]
fn rfind_event_item_internal(
    items: &Vector<Arc<TimelineItem>>,
    mut f: impl FnMut(&EventTimelineItemWithId<'_>) -> bool,
) -> Option<(usize, EventTimelineItemWithId<'_>)> {
    items
        .iter()
        .enumerate()
        .filter_map(|(idx, item)| {
            Some((
                idx,
                EventTimelineItemWithId { inner: item.as_event()?, internal_id: &item.internal_id },
            ))
        })
        .rfind(|(_, it)| f(it))
}

/// Finds an item in the vector of `items` given a predicate `f`.
///
/// WARNING/FIXME: this does a linear scan of the items, so this can be slow if
/// there are many items in the timeline.
pub(super) fn rfind_event_item(
    items: &Vector<Arc<TimelineItem>>,
    mut f: impl FnMut(&EventTimelineItem) -> bool,
) -> Option<(usize, EventTimelineItemWithId<'_>)> {
    rfind_event_item_internal(items, |item_with_id| f(item_with_id.inner))
}

/// Find the timeline item that matches the given event id, if any.
///
/// WARNING: Linear scan of the items, see documentation of
/// [`rfind_event_item`].
pub(super) fn rfind_event_by_id<'a>(
    items: &'a Vector<Arc<TimelineItem>>,
    event_id: &EventId,
) -> Option<(usize, EventTimelineItemWithId<'a>)> {
    rfind_event_item(items, |it| it.event_id() == Some(event_id))
}

/// Find the timeline item that matches the given item (event or transaction)
/// id, if any.
///
/// WARNING: Linear scan of the items, see documentation of
/// [`rfind_event_item`].
pub(super) fn rfind_event_by_item_id<'a>(
    items: &'a Vector<Arc<TimelineItem>>,
    item_id: &TimelineEventItemId,
) -> Option<(usize, EventTimelineItemWithId<'a>)> {
    match item_id {
        TimelineEventItemId::TransactionId(txn_id) => {
            rfind_event_item(items, |item| match &item.kind {
                EventTimelineItemKind::Local(local) => local.transaction_id == *txn_id,
                EventTimelineItemKind::Remote(remote) => {
                    remote.transaction_id.as_deref() == Some(txn_id)
                }
            })
        }
        TimelineEventItemId::EventId(event_id) => rfind_event_by_id(items, event_id),
    }
}

/// Result of comparing events position in the timeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RelativePosition {
    /// Event B is after (more recent than) event A.
    After,
    /// They are the same event.
    Same,
    /// Event B is before (older than) event A.
    Before,
}

#[derive(Debug, PartialEq)]
pub(super) struct Date {
    year: i32,
    month: u32,
    day: u32,
}

impl Date {
    pub fn is_same_month_as(&self, date: Date) -> bool {
        self.year == date.year && self.month == date.month
    }
}

/// Converts a timestamp since Unix Epoch to a year, month and day.
pub(super) fn timestamp_to_date(ts: MilliSecondsSinceUnixEpoch) -> Date {
    let datetime = Local
        .timestamp_millis_opt(ts.0.into())
        // Only returns `None` if date is after Dec 31, 262143 BCE.
        .single()
        // Fallback to the current date to avoid issues with malicious
        // homeservers.
        .unwrap_or_else(Local::now);

    Date { year: datetime.year(), month: datetime.month(), day: datetime.day() }
}