src/windows/room/space.rs
242 lines · 7260 bytes
1//! Window for Matrix spaces
2use std::ops::{Deref, DerefMut};
3use std::time::{Duration, Instant};
4
5use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
6use matrix_sdk::ruma::events::StateEventType;
7use matrix_sdk::{
8 room::Room as MatrixRoom,
9 ruma::{OwnedRoomId, RoomId},
10};
11
12use modalkit::prelude::{EditInfo, InfoMessage};
13use ratatui::{
14 buffer::Buffer,
15 layout::Rect,
16 style::{Color, Style},
17 text::{Line, Span, Text},
18 widgets::StatefulWidget,
19};
20
21use modalkit_ratatui::{
22 list::{List, ListState},
23 TermOffset,
24 TerminalCursor,
25 WindowOps,
26};
27
28use crate::base::{
29 IambBufferId,
30 IambError,
31 IambInfo,
32 IambResult,
33 ProgramContext,
34 ProgramStore,
35 RoomFocus,
36 SpaceAction,
37};
38
39use crate::windows::{room_fields_cmp, RoomItem, RoomLikeItem};
40
41const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
42
43/// State needed for rendering [Space].
44pub struct SpaceState {
45 room_id: OwnedRoomId,
46 room: MatrixRoom,
47 list: ListState<RoomItem, IambInfo>,
48 last_fetch: Option<Instant>,
49}
50
51impl SpaceState {
52 pub fn new(room: MatrixRoom) -> Self {
53 let room_id = room.room_id().to_owned();
54 let content = IambBufferId::Room(room_id.clone(), None, RoomFocus::Scrollback);
55 let list = ListState::new(content, vec![]);
56 let last_fetch = None;
57
58 SpaceState { room_id, room, list, last_fetch }
59 }
60
61 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
62 if let Some(room) = store.application.worker.client.get_room(self.id()) {
63 self.room = room;
64 }
65 }
66
67 pub fn room(&self) -> &MatrixRoom {
68 &self.room
69 }
70
71 pub fn id(&self) -> &RoomId {
72 &self.room_id
73 }
74
75 pub fn dup(&self, store: &mut ProgramStore) -> Self {
76 SpaceState {
77 room_id: self.room_id.clone(),
78 room: self.room.clone(),
79 list: self.list.dup(store),
80 last_fetch: self.last_fetch,
81 }
82 }
83
84 pub async fn space_command(
85 &mut self,
86 act: SpaceAction,
87 _: ProgramContext,
88 store: &mut ProgramStore,
89 ) -> IambResult<EditInfo> {
90 match act {
91 SpaceAction::SetChild(child_id, order, suggested) => {
92 if !self
93 .room
94 .can_user_send_state(
95 &store.application.settings.profile.user_id,
96 StateEventType::SpaceChild,
97 )
98 .await
99 .map_err(IambError::from)?
100 {
101 return Err(IambError::InsufficientPermission.into());
102 }
103
104 let via = self.room.route().await.map_err(IambError::from)?;
105 let mut ev = SpaceChildEventContent::new(via);
106 ev.order = order;
107 ev.suggested = suggested;
108 let _ = self
109 .room
110 .send_state_event_for_key(&child_id, ev)
111 .await
112 .map_err(IambError::from)?;
113
114 Ok(InfoMessage::from("Space updated").into())
115 },
116 SpaceAction::RemoveChild => {
117 let space = self.list.get().ok_or(IambError::NoSelectedRoomOrSpaceItem)?;
118 if !self
119 .room
120 .can_user_send_state(
121 &store.application.settings.profile.user_id,
122 StateEventType::SpaceChild,
123 )
124 .await
125 .map_err(IambError::from)?
126 {
127 return Err(IambError::InsufficientPermission.into());
128 }
129
130 let ev = SpaceChildEventContent::new(vec![]);
131 let event_id = self
132 .room
133 .send_state_event_for_key(&space.room_id().to_owned(), ev)
134 .await
135 .map_err(IambError::from)?;
136
137 // Fix for element (see https://github.com/element-hq/element-web/issues/29606)
138 let _ = self
139 .room
140 .redact(&event_id.event_id, Some("workaround for element bug"), None)
141 .await
142 .map_err(IambError::from)?;
143
144 Ok(InfoMessage::from("Room removed").into())
145 },
146 }
147 }
148}
149
150impl TerminalCursor for SpaceState {
151 fn get_term_cursor(&self) -> Option<TermOffset> {
152 self.list.get_term_cursor()
153 }
154}
155
156impl Deref for SpaceState {
157 type Target = ListState<RoomItem, IambInfo>;
158
159 fn deref(&self) -> &Self::Target {
160 &self.list
161 }
162}
163
164impl DerefMut for SpaceState {
165 fn deref_mut(&mut self) -> &mut Self::Target {
166 &mut self.list
167 }
168}
169
170/// [StatefulWidget] for Matrix spaces.
171pub struct Space<'a> {
172 focused: bool,
173 store: &'a mut ProgramStore,
174}
175
176impl<'a> Space<'a> {
177 pub fn new(store: &'a mut ProgramStore) -> Self {
178 Space { focused: false, store }
179 }
180
181 pub fn focus(mut self, focused: bool) -> Self {
182 self.focused = focused;
183 self
184 }
185}
186
187impl StatefulWidget for Space<'_> {
188 type State = SpaceState;
189
190 fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
191 let mut empty_message = None;
192 let need_fetch = match state.last_fetch {
193 Some(i) => i.elapsed() >= SPACE_HIERARCHY_DEBOUNCE,
194 None => true,
195 };
196
197 if need_fetch {
198 let res = self.store.application.worker.space_members(state.room_id.clone());
199
200 match res {
201 Ok(members) => {
202 let mut items = members
203 .into_iter()
204 .filter_map(|id| {
205 let (room, _, tags) =
206 self.store.application.worker.get_room(id.clone()).ok()?;
207 let room_info = std::sync::Arc::new((room, tags));
208
209 if id != state.room_id {
210 Some(RoomItem::new(room_info, self.store))
211 } else {
212 None
213 }
214 })
215 .collect::<Vec<_>>();
216 let fields = &self.store.application.settings.tunables.sort.rooms;
217 let collator = &mut self.store.application.collator;
218 items.sort_by(|a, b| room_fields_cmp(a, b, fields, collator));
219
220 state.list.set(items);
221 state.last_fetch = Some(Instant::now());
222 },
223 Err(e) => {
224 let lines = vec![
225 Line::from("Unable to fetch space room hierarchy:"),
226 Span::styled(e.to_string(), Style::default().fg(Color::Red)).into(),
227 ];
228
229 empty_message = Text::from(lines).into();
230 },
231 }
232 }
233
234 let mut list = List::new(self.store).focus(self.focused);
235
236 if let Some(text) = empty_message {
237 list = list.empty_message(text);
238 }
239
240 list.render(area, buffer, &mut state.list)
241 }
242}