matrix_sdk_ui/timeline/
util.rsuse 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,
pub internal_id: &'a TimelineUniqueId,
}
impl EventTimelineItemWithId<'_> {
pub fn with_inner_kind(&self, kind: impl Into<EventTimelineItemKind>) -> Arc<TimelineItem> {
TimelineItem::new(self.inner.with_kind(kind), self.internal_id.clone())
}
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))
}
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))
}
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))
}
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),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RelativePosition {
After,
Same,
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
}
}
pub(super) fn timestamp_to_date(ts: MilliSecondsSinceUnixEpoch) -> Date {
let datetime = Local
.timestamp_millis_opt(ts.0.into())
.single()
.unwrap_or_else(Local::now);
Date { year: datetime.year(), month: datetime.month(), day: datetime.day() }
}