Commit 8943909f06

8943909f06654261c948327f26519e44d7c0f0d7

parent: 443ad241b4

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-10-21 02:32 UTC
committer: <noreply@github.com>

Support custom sorting for room and user lists (#170)

Layout: unified · split

README.md +1 −1
@@ -1,6 +1,6 @@
1# iamb 1# iamb
2 2
3[![Build Status](https://github.com/ulyssa/iamb/workflows/CI/badge.svg)](https://github.com/ulyssa/iamb/actions?query=workflow%3ACI+) 3[![Build Status](https://github.com/ulyssa/iamb/actions/workflows/ci.yml/badge.svg)](https://github.com/ulyssa/iamb/actions?query=workflow%3ACI+)
4[![License: Apache 2.0](https://img.shields.io/crates/l/iamb.svg?logo=apache)](https://crates.io/crates/iamb) 4[![License: Apache 2.0](https://img.shields.io/crates/l/iamb.svg?logo=apache)](https://crates.io/crates/iamb)
5[![#iamb:0x.badd.cafe](https://img.shields.io/badge/matrix-%23iamb:0x.badd.cafe-blue)](https://matrix.to/#/#iamb:0x.badd.cafe) 5[![#iamb:0x.badd.cafe](https://img.shields.io/badge/matrix-%23iamb:0x.badd.cafe-blue)](https://matrix.to/#/#iamb:0x.badd.cafe)
6[![Latest Version](https://img.shields.io/crates/v/iamb.svg?logo=rust)](https://crates.io/crates/iamb) 6[![Latest Version](https://img.shields.io/crates/v/iamb.svg?logo=rust)](https://crates.io/crates/iamb)
src/base.rs +130 −1
@@ -202,6 +202,135 @@ bitflags::bitflags! {
202 } 202 }
203} 203}
204 204
205/// Fields that rooms and spaces can be sorted by.
206#[derive(Clone, Debug, Eq, PartialEq)]
207pub enum SortFieldRoom {
208 Favorite,
209 LowPriority,
210 Name,
211 Alias,
212 RoomId,
213}
214
215/// Fields that users can be sorted by.
216#[derive(Clone, Debug, Eq, PartialEq)]
217pub enum SortFieldUser {
218 PowerLevel,
219 UserId,
220 LocalPart,
221 Server,
222}
223
224/// Whether to use the default sort direction for a field, or to reverse it.
225#[derive(Clone, Debug, Eq, PartialEq)]
226pub enum SortOrder {
227 Ascending,
228 Descending,
229}
230
231/// One of the columns to sort on.
232#[derive(Clone, Debug, Eq, PartialEq)]
233pub struct SortColumn<T>(pub T, pub SortOrder);
234
235impl<'de> Deserialize<'de> for SortColumn<SortFieldRoom> {
236 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
237 where
238 D: Deserializer<'de>,
239 {
240 deserializer.deserialize_str(SortRoomVisitor)
241 }
242}
243
244/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
245struct SortRoomVisitor;
246
247impl<'de> Visitor<'de> for SortRoomVisitor {
248 type Value = SortColumn<SortFieldRoom>;
249
250 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
251 formatter.write_str("a valid field for sorting rooms")
252 }
253
254 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
255 where
256 E: SerdeError,
257 {
258 if value.is_empty() {
259 return Err(E::custom("Invalid sort field"));
260 }
261
262 let order = if value.starts_with('~') {
263 value = &value[1..];
264 SortOrder::Descending
265 } else {
266 SortOrder::Ascending
267 };
268
269 let field = match value {
270 "favorite" => SortFieldRoom::Favorite,
271 "lowpriority" => SortFieldRoom::LowPriority,
272 "name" => SortFieldRoom::Name,
273 "alias" => SortFieldRoom::Alias,
274 "id" => SortFieldRoom::RoomId,
275 _ => {
276 let msg = format!("Unknown sort field: {value:?}");
277 return Err(E::custom(msg));
278 },
279 };
280
281 Ok(SortColumn(field, order))
282 }
283}
284
285impl<'de> Deserialize<'de> for SortColumn<SortFieldUser> {
286 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
287 where
288 D: Deserializer<'de>,
289 {
290 deserializer.deserialize_str(SortUserVisitor)
291 }
292}
293
294/// [serde] visitor for deserializing [SortColumn] for users.
295struct SortUserVisitor;
296
297impl<'de> Visitor<'de> for SortUserVisitor {
298 type Value = SortColumn<SortFieldUser>;
299
300 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
301 formatter.write_str("a valid field for sorting rooms")
302 }
303
304 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
305 where
306 E: SerdeError,
307 {
308 if value.is_empty() {
309 return Err(E::custom("Invalid field for sorting users"));
310 }
311
312 let order = if value.starts_with('~') {
313 value = &value[1..];
314 SortOrder::Descending
315 } else {
316 SortOrder::Ascending
317 };
318
319 let field = match value {
320 "id" => SortFieldUser::UserId,
321 "localpart" => SortFieldUser::LocalPart,
322 "server" => SortFieldUser::Server,
323 "power" => SortFieldUser::PowerLevel,
324 _ => {
325 let msg = format!("Unknown sort field: {value:?}");
326 return Err(E::custom(msg));
327 },
328 };
329
330 Ok(SortColumn(field, order))
331 }
332}
333
205/// A room property. 334/// A room property.
206#[derive(Clone, Debug, Eq, PartialEq)] 335#[derive(Clone, Debug, Eq, PartialEq)]
207pub enum RoomField { 336pub enum RoomField {
@@ -811,7 +940,7 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
811#[derive(Default)] 940#[derive(Default)]
812pub struct SyncInfo { 941pub struct SyncInfo {
813 /// Spaces that the user is a member of. 942 /// Spaces that the user is a member of.
814 pub spaces: Vec<MatrixRoom>, 943 pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
815 944
816 /// Rooms that the user is a member of. 945 /// Rooms that the user is a member of.
817 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>, 946 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
src/config.rs +90 −1
@@ -20,7 +20,7 @@ use modalkit::tui::{
20 text::Span, 20 text::Span,
21}; 21};
22 22
23use super::base::{IambId, RoomInfo}; 23use super::base::{IambId, RoomInfo, SortColumn, SortFieldRoom, SortFieldUser, SortOrder};
24 24
25macro_rules! usage { 25macro_rules! usage {
26 ( $($args: tt)* ) => { 26 ( $($args: tt)* ) => {
@@ -29,6 +29,17 @@ macro_rules! usage {
29 } 29 }
30} 30}
31 31
32const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 2] = [
33 SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending),
34 SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
35];
36
37const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 3] = [
38 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
39 SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
40 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
41];
42
32const DEFAULT_REQ_TIMEOUT: u64 = 120; 43const DEFAULT_REQ_TIMEOUT: u64 = 120;
33 44
34const COLORS: [Color; 13] = [ 45const COLORS: [Color; 13] = [
@@ -213,6 +224,15 @@ pub struct UserDisplayTunables {
213 224
214pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>; 225pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
215 226
227fn merge_sorts(a: SortOverrides, b: SortOverrides) -> SortOverrides {
228 SortOverrides {
229 dms: b.dms.or(a.dms),
230 rooms: b.rooms.or(a.rooms),
231 spaces: b.spaces.or(a.spaces),
232 members: b.members.or(a.members),
233 }
234}
235
216fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> { 236fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
217 match (a, b) { 237 match (a, b) {
218 (Some(a), None) => Some(a), 238 (Some(a), None) => Some(a),
@@ -246,6 +266,33 @@ pub enum UserDisplayStyle {
246 DisplayName, 266 DisplayName,
247} 267}
248 268
269#[derive(Clone)]
270pub struct SortValues {
271 pub dms: Vec<SortColumn<SortFieldRoom>>,
272 pub rooms: Vec<SortColumn<SortFieldRoom>>,
273 pub spaces: Vec<SortColumn<SortFieldRoom>>,
274 pub members: Vec<SortColumn<SortFieldUser>>,
275}
276
277#[derive(Clone, Default, Deserialize)]
278pub struct SortOverrides {
279 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
280 pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
281 pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
282 pub members: Option<Vec<SortColumn<SortFieldUser>>>,
283}
284
285impl SortOverrides {
286 pub fn values(self) -> SortValues {
287 let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
288 let dms = self.dms.unwrap_or_else(|| rooms.clone());
289 let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
290 let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
291
292 SortValues { rooms, members, dms, spaces }
293 }
294}
295
249#[derive(Clone)] 296#[derive(Clone)]
250pub struct TunableValues { 297pub struct TunableValues {
251 pub log_level: Level, 298 pub log_level: Level,
@@ -254,6 +301,7 @@ pub struct TunableValues {
254 pub read_receipt_send: bool, 301 pub read_receipt_send: bool,
255 pub read_receipt_display: bool, 302 pub read_receipt_display: bool,
256 pub request_timeout: u64, 303 pub request_timeout: u64,
304 pub sort: SortValues,
257 pub typing_notice_send: bool, 305 pub typing_notice_send: bool,
258 pub typing_notice_display: bool, 306 pub typing_notice_display: bool,
259 pub users: UserOverrides, 307 pub users: UserOverrides,
@@ -270,6 +318,8 @@ pub struct Tunables {
270 pub read_receipt_send: Option<bool>, 318 pub read_receipt_send: Option<bool>,
271 pub read_receipt_display: Option<bool>, 319 pub read_receipt_display: Option<bool>,
272 pub request_timeout: Option<u64>, 320 pub request_timeout: Option<u64>,
321 #[serde(default)]
322 pub sort: SortOverrides,
273 pub typing_notice_send: Option<bool>, 323 pub typing_notice_send: Option<bool>,
274 pub typing_notice_display: Option<bool>, 324 pub typing_notice_display: Option<bool>,
275 pub users: Option<UserOverrides>, 325 pub users: Option<UserOverrides>,
@@ -289,6 +339,7 @@ impl Tunables {
289 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send), 339 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
290 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display), 340 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
291 request_timeout: self.request_timeout.or(other.request_timeout), 341 request_timeout: self.request_timeout.or(other.request_timeout),
342 sort: merge_sorts(self.sort, other.sort),
292 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send), 343 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
293 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display), 344 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
294 users: merge_users(self.users, other.users), 345 users: merge_users(self.users, other.users),
@@ -306,6 +357,7 @@ impl Tunables {
306 read_receipt_send: self.read_receipt_send.unwrap_or(true), 357 read_receipt_send: self.read_receipt_send.unwrap_or(true),
307 read_receipt_display: self.read_receipt_display.unwrap_or(true), 358 read_receipt_display: self.read_receipt_display.unwrap_or(true),
308 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT), 359 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
360 sort: self.sort.values(),
309 typing_notice_send: self.typing_notice_send.unwrap_or(true), 361 typing_notice_send: self.typing_notice_send.unwrap_or(true),
310 typing_notice_display: self.typing_notice_display.unwrap_or(true), 362 typing_notice_display: self.typing_notice_display.unwrap_or(true),
311 users: self.users.unwrap_or_default(), 363 users: self.users.unwrap_or_default(),
@@ -701,6 +753,43 @@ mod tests {
701 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName)); 753 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
702 } 754 }
703 755
756 #[test]
757 fn test_parse_tunables_sort() {
758 let res: Tunables = serde_json::from_str(
759 r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
760 )
761 .unwrap();
762 assert_eq!(
763 res.sort.members,
764 Some(vec![
765 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
766 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
767 ])
768 );
769 assert_eq!(
770 res.sort.spaces,
771 Some(vec![
772 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
773 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
774 ])
775 );
776 assert_eq!(res.sort.rooms, None);
777 assert_eq!(res.sort.dms, None);
778
779 // Check that we get the right default "rooms" and "dms" values.
780 let res = res.values();
781 assert_eq!(res.sort.members, vec![
782 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
783 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
784 ]);
785 assert_eq!(res.sort.spaces, vec![
786 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
787 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
788 ]);
789 assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
790 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
791 }
792
704 #[test] 793 #[test]
705 fn test_parse_layout() { 794 fn test_parse_layout() {
706 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned()); 795 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
src/tests.rs +2
@@ -28,6 +28,7 @@ use crate::{
28 ApplicationSettings, 28 ApplicationSettings,
29 DirectoryValues, 29 DirectoryValues,
30 ProfileConfig, 30 ProfileConfig,
31 SortOverrides,
31 TunableValues, 32 TunableValues,
32 UserColor, 33 UserColor,
33 UserDisplayStyle, 34 UserDisplayStyle,
@@ -183,6 +184,7 @@ pub fn mock_tunables() -> TunableValues {
183 read_receipt_send: true, 184 read_receipt_send: true,
184 read_receipt_display: true, 185 read_receipt_display: true,
185 request_timeout: 120, 186 request_timeout: 120,
187 sort: SortOverrides::default().values(),
186 typing_notice_send: true, 188 typing_notice_send: true,
187 typing_notice_display: true, 189 typing_notice_display: true,
188 users: vec![(TEST_USER5.clone(), UserDisplayTunables { 190 users: vec![(TEST_USER5.clone(), UserDisplayTunables {
src/windows/mod.rs +263 −100
@@ -17,7 +17,9 @@ use matrix_sdk::{
17 ruma::{ 17 ruma::{
18 events::room::member::MembershipState, 18 events::room::member::MembershipState,
19 events::tag::{TagName, Tags}, 19 events::tag::{TagName, Tags},
20 OwnedRoomAliasId,
20 OwnedRoomId, 21 OwnedRoomId,
22 RoomAliasId,
21 RoomId, 23 RoomId,
22 }, 24 },
23}; 25};
@@ -80,6 +82,10 @@ use crate::base::{
80 ProgramStore, 82 ProgramStore,
81 RoomAction, 83 RoomAction,
82 SendAction, 84 SendAction,
85 SortColumn,
86 SortFieldRoom,
87 SortFieldUser,
88 SortOrder,
83}; 89};
84 90
85use self::{room::RoomState, welcome::WelcomeState}; 91use self::{room::RoomState, welcome::WelcomeState};
@@ -125,42 +131,87 @@ fn selected_text(s: &str, selected: bool) -> Text {
125 Text::from(selected_span(s, selected)) 131 Text::from(selected_span(s, selected))
126} 132}
127 133
128fn room_cmp(a: &MatrixRoom, b: &MatrixRoom) -> Ordering { 134/// Sort `Some` to be less than `None` so that list items with values come before those without.
129 let ca1 = a.canonical_alias(); 135#[inline]
130 let ca2 = b.canonical_alias(); 136fn some_cmp<T: Ord>(a: Option<T>, b: Option<T>) -> Ordering {
131 137 match (a, b) {
132 let ord = match (ca1, ca2) { 138 (Some(a), Some(b)) => a.cmp(&b),
133 (None, None) => Ordering::Equal, 139 (None, None) => Ordering::Equal,
134 (None, Some(_)) => Ordering::Greater, 140 (None, Some(_)) => Ordering::Greater,
135 (Some(_), None) => Ordering::Less, 141 (Some(_), None) => Ordering::Less,
136 (Some(ca1), Some(ca2)) => ca1.cmp(&ca2), 142 }
137 }; 143}
144
145fn user_cmp(a: &MemberItem, b: &MemberItem, field: &SortFieldUser) -> Ordering {
146 let a_id = a.member.user_id();
147 let b_id = b.member.user_id();
138 148
139 ord.then_with(|| a.room_id().cmp(b.room_id())) 149 match field {
150 SortFieldUser::UserId => a_id.cmp(b_id),
151 SortFieldUser::LocalPart => a_id.localpart().cmp(b_id.localpart()),
152 SortFieldUser::Server => a_id.server_name().cmp(b_id.server_name()),
153 SortFieldUser::PowerLevel => {
154 // Sort higher power levels towards the top of the list.
155 b.member.power_level().cmp(&a.member.power_level())
156 },
157 }
140} 158}
141 159
142fn tag_cmp(a: &Option<Tags>, b: &Option<Tags>) -> Ordering { 160fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
143 let (fava, lowa) = a 161 match field {
144 .as_ref() 162 SortFieldRoom::Favorite => {
145 .map(|tags| { 163 let fava = a.has_tag(TagName::Favorite);
146 (tags.contains_key(&TagName::Favorite), tags.contains_key(&TagName::LowPriority)) 164 let favb = b.has_tag(TagName::Favorite);
147 })
148 .unwrap_or((false, false));
149 165
150 let (favb, lowb) = b 166 // If a has Favorite and b doesn't, it should sort earlier in room list.
151 .as_ref() 167 favb.cmp(&fava)
152 .map(|tags| { 168 },
153 (tags.contains_key(&TagName::Favorite), tags.contains_key(&TagName::LowPriority)) 169 SortFieldRoom::LowPriority => {
154 }) 170 let lowa = a.has_tag(TagName::LowPriority);
155 .unwrap_or((false, false)); 171 let lowb = b.has_tag(TagName::LowPriority);
156 172
157 // If a has Favorite and b doesn't, it should sort earlier in room list. 173 // If a has LowPriority and b doesn't, it should sort later in room list.
158 let cmpf = favb.cmp(&fava); 174 lowa.cmp(&lowb)
175 },
176 SortFieldRoom::Name => a.name().cmp(b.name()),
177 SortFieldRoom::Alias => some_cmp(a.alias(), b.alias()),
178 SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()),
179 }
180}
181
182/// Compare two rooms according the configured sort criteria.
183fn room_fields_cmp<T: RoomLikeItem>(
184 a: &T,
185 b: &T,
186 fields: &[SortColumn<SortFieldRoom>],
187) -> Ordering {
188 for SortColumn(field, order) in fields {
189 match (room_cmp(a, b, field), order) {
190 (Ordering::Equal, _) => continue,
191 (o, SortOrder::Ascending) => return o,
192 (o, SortOrder::Descending) => return o.reverse(),
193 }
194 }
159 195
160 // If a has LowPriority and b doesn't, it should sort later in room list. 196 // Break ties on ascending room id.
161 let cmpl = lowa.cmp(&lowb); 197 room_cmp(a, b, &SortFieldRoom::RoomId)
198}
162 199
163 cmpl.then(cmpf) 200fn user_fields_cmp(
201 a: &MemberItem,
202 b: &MemberItem,
203 fields: &[SortColumn<SortFieldUser>],
204) -> Ordering {
205 for SortColumn(field, order) in fields {
206 match (user_cmp(a, b, field), order) {
207 (Ordering::Equal, _) => continue,
208 (o, SortOrder::Ascending) => return o,
209 (o, SortOrder::Descending) => return o.reverse(),
210 }
211 }
212
213 // Break ties on ascending user id.
214 user_cmp(a, b, &SortFieldUser::UserId)
164} 215}
165 216
166fn append_tags<'a>(tags: &'a Tags, spans: &mut Vec<Span<'a>>, style: Style) { 217fn append_tags<'a>(tags: &'a Tags, spans: &mut Vec<Span<'a>>, style: Style) {
@@ -190,6 +241,13 @@ fn append_tags<'a>(tags: &'a Tags, spans: &mut Vec<Span<'a>>, style: Style) {
190 spans.push(Span::styled(")", style)); 241 spans.push(Span::styled(")", style));
191} 242}
192 243
244trait RoomLikeItem {
245 fn room_id(&self) -> &RoomId;
246 fn has_tag(&self, tag: TagName) -> bool;
247 fn alias(&self) -> Option<&RoomAliasId>;
248 fn name(&self) -> &str;
249}
250
193#[inline] 251#[inline]
194fn room_prompt( 252fn room_prompt(
195 room_id: &RoomId, 253 room_id: &RoomId,
@@ -399,7 +457,8 @@ impl WindowOps<IambInfo> for IambWindow {
399 .into_iter() 457 .into_iter()
400 .map(|room_info| DirectItem::new(room_info, store)) 458 .map(|room_info| DirectItem::new(room_info, store))
401 .collect::<Vec<_>>(); 459 .collect::<Vec<_>>();
402 items.sort(); 460 let fields = &store.application.settings.tunables.sort.dms;
461 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
403 462
404 state.set(items); 463 state.set(items);
405 464
@@ -417,8 +476,13 @@ impl WindowOps<IambInfo> for IambWindow {
417 476
418 if need_fetch { 477 if need_fetch {
419 if let Ok(mems) = store.application.worker.members(room_id.clone()) { 478 if let Ok(mems) = store.application.worker.members(room_id.clone()) {
420 let items = mems.into_iter().map(|m| MemberItem::new(m, room_id.clone())); 479 let mut items = mems
421 state.set(items.collect()); 480 .into_iter()
481 .map(|m| MemberItem::new(m, room_id.clone()))
482 .collect::<Vec<_>>();
483 let fields = &store.application.settings.tunables.sort.members;
484 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
485 state.set(items);
422 *last_fetch = Some(Instant::now()); 486 *last_fetch = Some(Instant::now());
423 } 487 }
424 } 488 }
@@ -438,7 +502,8 @@ impl WindowOps<IambInfo> for IambWindow {
438 .into_iter() 502 .into_iter()
439 .map(|room_info| RoomItem::new(room_info, store)) 503 .map(|room_info| RoomItem::new(room_info, store))
440 .collect::<Vec<_>>(); 504 .collect::<Vec<_>>();
441 items.sort(); 505 let fields = &store.application.settings.tunables.sort.rooms;
506 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
442 507
443 state.set(items); 508 state.set(items);
444 509
@@ -449,15 +514,18 @@ impl WindowOps<IambInfo> for IambWindow {
449 .render(area, buf, state); 514 .render(area, buf, state);
450 }, 515 },
451 IambWindow::SpaceList(state) => { 516 IambWindow::SpaceList(state) => {
452 let items = store 517 let mut items = store
453 .application 518 .application
454 .sync_info 519 .sync_info
455 .spaces 520 .spaces
456 .clone() 521 .clone()
457 .into_iter() 522 .into_iter()
458 .map(|room| SpaceItem::new(room, store)); 523 .map(|room| SpaceItem::new(room, store))
459 state.set(items.collect()); 524 .collect::<Vec<_>>();
460 state.draw(area, buf, focused, store); 525 let fields = &store.application.settings.tunables.sort.spaces;
526 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
527
528 state.set(items);
461 529
462 List::new(store) 530 List::new(store)
463 .empty_message("You haven't joined any spaces yet") 531 .empty_message("You haven't joined any spaces yet")
@@ -662,6 +730,7 @@ impl Window<IambInfo> for IambWindow {
662pub struct RoomItem { 730pub struct RoomItem {
663 room_info: MatrixRoomInfo, 731 room_info: MatrixRoomInfo,
664 name: String, 732 name: String,
733 alias: Option<OwnedRoomAliasId>,
665} 734}
666 735
667impl RoomItem { 736impl RoomItem {
@@ -671,13 +740,14 @@ impl RoomItem {
671 740
672 let info = store.application.get_room_info(room_id.to_owned()); 741 let info = store.application.get_room_info(room_id.to_owned());
673 let name = info.name.clone().unwrap_or_default(); 742 let name = info.name.clone().unwrap_or_default();
743 let alias = room.canonical_alias();
674 info.tags = room_info.deref().1.clone(); 744 info.tags = room_info.deref().1.clone();
675 745
676 if let Some(alias) = room.canonical_alias() { 746 if let Some(alias) = &alias {
677 store.application.names.insert(alias.to_string(), room_id.to_owned()); 747 store.application.names.insert(alias.to_string(), room_id.to_owned());
678 } 748 }
679 749
680 RoomItem { room_info, name } 750 RoomItem { room_info, name, alias }
681 } 751 }
682 752
683 #[inline] 753 #[inline]
@@ -685,34 +755,31 @@ impl RoomItem {
685 &self.room_info.deref().0 755 &self.room_info.deref().0
686 } 756 }
687 757
688 #[inline]
689 fn room_id(&self) -> &RoomId {
690 self.room().room_id()
691 }
692
693 #[inline] 758 #[inline]
694 fn tags(&self) -> &Option<Tags> { 759 fn tags(&self) -> &Option<Tags> {
695 &self.room_info.deref().1 760 &self.room_info.deref().1
696 } 761 }
697} 762}
698 763
699impl PartialEq for RoomItem { 764impl RoomLikeItem for RoomItem {
700 fn eq(&self, other: &Self) -> bool { 765 fn name(&self) -> &str {
701 self.room_id() == other.room_id() 766 self.name.as_str()
702 } 767 }
703}
704 768
705impl Eq for RoomItem {} 769 fn alias(&self) -> Option<&RoomAliasId> {
770 self.alias.as_deref()
771 }
706 772
707impl Ord for RoomItem { 773 fn room_id(&self) -> &RoomId {
708 fn cmp(&self, other: &Self) -> Ordering { 774 self.room().room_id()
709 tag_cmp(self.tags(), other.tags()).then_with(|| room_cmp(self.room(), other.room()))
710 } 775 }
711}
712 776
713impl PartialOrd for RoomItem { 777 fn has_tag(&self, tag: TagName) -> bool {
714 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 778 if let Some(tags) = &self.room_info.deref().1 {
715 self.cmp(other).into() 779 tags.contains_key(&tag)
780 } else {
781 false
782 }
716 } 783 }
717} 784}
718 785
@@ -756,14 +823,16 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
756pub struct DirectItem { 823pub struct DirectItem {
757 room_info: MatrixRoomInfo, 824 room_info: MatrixRoomInfo,
758 name: String, 825 name: String,
826 alias: Option<OwnedRoomAliasId>,
759} 827}
760 828
761impl DirectItem { 829impl DirectItem {
762 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self { 830 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
763 let room_id = room_info.deref().0.room_id().to_owned(); 831 let room_id = room_info.0.room_id().to_owned();
764 let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default(); 832 let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default();
833 let alias = room_info.0.canonical_alias();
765 834
766 DirectItem { room_info, name } 835 DirectItem { room_info, name, alias }
767 } 836 }
768 837
769 #[inline] 838 #[inline]
@@ -771,17 +840,34 @@ impl DirectItem {
771 &self.room_info.deref().0 840 &self.room_info.deref().0
772 } 841 }
773 842
774 #[inline]
775 fn room_id(&self) -> &RoomId {
776 self.room().room_id()
777 }
778
779 #[inline] 843 #[inline]
780 fn tags(&self) -> &Option<Tags> { 844 fn tags(&self) -> &Option<Tags> {
781 &self.room_info.deref().1 845 &self.room_info.deref().1
782 } 846 }
783} 847}
784 848
849impl RoomLikeItem for DirectItem {
850 fn name(&self) -> &str {
851 self.name.as_str()
852 }
853
854 fn alias(&self) -> Option<&RoomAliasId> {
855 self.alias.as_deref()
856 }
857
858 fn has_tag(&self, tag: TagName) -> bool {
859 if let Some(tags) = &self.room_info.deref().1 {
860 tags.contains_key(&tag)
861 } else {
862 false
863 }
864 }
865
866 fn room_id(&self) -> &RoomId {
867 self.room().room_id()
868 }
869}
870
785impl ToString for DirectItem { 871impl ToString for DirectItem {
786 fn to_string(&self) -> String { 872 fn to_string(&self) -> String {
787 return self.name.clone(); 873 return self.name.clone();
@@ -807,26 +893,6 @@ impl ListItem<IambInfo> for DirectItem {
807 } 893 }
808} 894}
809 895
810impl PartialEq for DirectItem {
811 fn eq(&self, other: &Self) -> bool {
812 self.room_id() == other.room_id()
813 }
814}
815
816impl Eq for DirectItem {}
817
818impl Ord for DirectItem {
819 fn cmp(&self, other: &Self) -> Ordering {
820 tag_cmp(self.tags(), other.tags()).then_with(|| room_cmp(self.room(), other.room()))
821 }
822}
823
824impl PartialOrd for DirectItem {
825 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
826 self.cmp(other).into()
827 }
828}
829
830impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem { 896impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
831 fn prompt( 897 fn prompt(
832 &mut self, 898 &mut self,
@@ -840,51 +906,58 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
840 906
841#[derive(Clone)] 907#[derive(Clone)]
842pub struct SpaceItem { 908pub struct SpaceItem {
843 room: MatrixRoom, 909 room_info: MatrixRoomInfo,
844 name: String, 910 name: String,
911 alias: Option<OwnedRoomAliasId>,
845} 912}
846 913
847impl SpaceItem { 914impl SpaceItem {
848 fn new(room: MatrixRoom, store: &mut ProgramStore) -> Self { 915 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
849 let room_id = room.room_id(); 916 let room_id = room_info.0.room_id();
850 let name = store 917 let name = store
851 .application 918 .application
852 .get_room_info(room_id.to_owned()) 919 .get_room_info(room_id.to_owned())
853 .name 920 .name
854 .clone() 921 .clone()
855 .unwrap_or_default(); 922 .unwrap_or_default();
923 let alias = room_info.0.canonical_alias();
856 924
857 if let Some(alias) = room.canonical_alias() { 925 if let Some(alias) = &alias {
858 store.application.names.insert(alias.to_string(), room_id.to_owned()); 926 store.application.names.insert(alias.to_string(), room_id.to_owned());
859 } 927 }
860 928
861 SpaceItem { room, name } 929 SpaceItem { room_info, name, alias }
862 } 930 }
863}
864 931
865impl PartialEq for SpaceItem { 932 #[inline]
866 fn eq(&self, other: &Self) -> bool { 933 fn room(&self) -> &MatrixRoom {
867 self.room.room_id() == other.room.room_id() 934 &self.room_info.deref().0
868 } 935 }
869} 936}
870 937
871impl Eq for SpaceItem {} 938impl RoomLikeItem for SpaceItem {
939 fn name(&self) -> &str {
940 self.name.as_str()
941 }
872 942
873impl Ord for SpaceItem { 943 fn room_id(&self) -> &RoomId {
874 fn cmp(&self, other: &Self) -> Ordering { 944 self.room().room_id()
875 room_cmp(&self.room, &other.room)
876 } 945 }
877}
878 946
879impl PartialOrd for SpaceItem { 947 fn alias(&self) -> Option<&RoomAliasId> {
880 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 948 self.alias.as_deref()
881 self.cmp(other).into() 949 }
950
951 fn has_tag(&self, _: TagName) -> bool {
952 // I think that spaces can technically have tags, but afaik no client
953 // exposes them, so we'll just always return false here for now.
954 false
882 } 955 }
883} 956}
884 957
885impl ToString for SpaceItem { 958impl ToString for SpaceItem {
886 fn to_string(&self) -> String { 959 fn to_string(&self) -> String {
887 return self.room.room_id().to_string(); 960 return self.room_id().to_string();
888 } 961 }
889} 962}
890 963
@@ -894,7 +967,7 @@ impl ListItem<IambInfo> for SpaceItem {
894 } 967 }
895 968
896 fn get_word(&self) -> Option<String> { 969 fn get_word(&self) -> Option<String> {
897 self.room.room_id().to_string().into() 970 self.room_id().to_string().into()
898 } 971 }
899} 972}
900 973
@@ -905,7 +978,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
905 ctx: &ProgramContext, 978 ctx: &ProgramContext,
906 _: &mut ProgramStore, 979 _: &mut ProgramStore,
907 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> { 980 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
908 room_prompt(self.room.room_id(), act, ctx) 981 room_prompt(self.room_id(), act, ctx)
909 } 982 }
910} 983}
911 984
@@ -1200,3 +1273,93 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1200 } 1273 }
1201 } 1274 }
1202} 1275}
1276
1277#[cfg(test)]
1278mod tests {
1279 use super::*;
1280 use matrix_sdk::ruma::{room_alias_id, server_name};
1281
1282 #[derive(Debug, Eq, PartialEq)]
1283 struct TestRoomItem {
1284 room_id: OwnedRoomId,
1285 tags: Vec<TagName>,
1286 alias: Option<OwnedRoomAliasId>,
1287 name: &'static str,
1288 }
1289
1290 impl RoomLikeItem for &TestRoomItem {
1291 fn room_id(&self) -> &RoomId {
1292 self.room_id.as_ref()
1293 }
1294
1295 fn has_tag(&self, tag: TagName) -> bool {
1296 self.tags.contains(&tag)
1297 }
1298
1299 fn alias(&self) -> Option<&RoomAliasId> {
1300 self.alias.as_deref()
1301 }
1302
1303 fn name(&self) -> &str {
1304 self.name
1305 }
1306 }
1307
1308 #[test]
1309 fn test_sort_rooms() {
1310 let server = server_name!("example.com");
1311
1312 let room1 = TestRoomItem {
1313 room_id: RoomId::new(server).to_owned(),
1314 tags: vec![TagName::Favorite],
1315 alias: Some(room_alias_id!("#room1:example.com").to_owned()),
1316 name: "Z",
1317 };
1318
1319 let room2 = TestRoomItem {
1320 room_id: RoomId::new(server).to_owned(),
1321 tags: vec![],
1322 alias: Some(room_alias_id!("#a:example.com").to_owned()),
1323 name: "Unnamed Room",
1324 };
1325
1326 let room3 = TestRoomItem {
1327 room_id: RoomId::new(server).to_owned(),
1328 tags: vec![],
1329 alias: None,
1330 name: "Cool Room",
1331 };
1332
1333 // Sort by Name ascending.
1334 let mut rooms = vec![&room1, &room2, &room3];
1335 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Ascending)];
1336 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1337 assert_eq!(rooms, vec![&room3, &room2, &room1]);
1338
1339 // Sort by Name descending.
1340 let mut rooms = vec![&room1, &room2, &room3];
1341 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Descending)];
1342 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1343 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1344
1345 // Sort by Favorite and Alias before Name to show order matters.
1346 let mut rooms = vec![&room1, &room2, &room3];
1347 let fields = &[
1348 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
1349 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1350 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1351 ];
1352 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1353 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1354
1355 // Now flip order of Favorite with Descending
1356 let mut rooms = vec![&room1, &room2, &room3];
1357 let fields = &[
1358 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1359 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1360 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1361 ];
1362 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1363 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1364 }
1365}
src/windows/room/space.rs +5 −3
@@ -22,7 +22,7 @@ use modalkit::{
22 22
23use crate::base::{IambBufferId, IambInfo, ProgramStore, RoomFocus}; 23use crate::base::{IambBufferId, IambInfo, ProgramStore, RoomFocus};
24 24
25use crate::windows::RoomItem; 25use crate::windows::{room_fields_cmp, RoomItem};
26 26
27const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5); 27const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
28 28
@@ -120,7 +120,7 @@ impl<'a> StatefulWidget for Space<'a> {
120 120
121 match res { 121 match res {
122 Ok(members) => { 122 Ok(members) => {
123 let items = members 123 let mut items = members
124 .into_iter() 124 .into_iter()
125 .filter_map(|id| { 125 .filter_map(|id| {
126 let (room, _, tags) = 126 let (room, _, tags) =
@@ -133,7 +133,9 @@ impl<'a> StatefulWidget for Space<'a> {
133 None 133 None
134 } 134 }
135 }) 135 })
136 .collect(); 136 .collect::<Vec<_>>();
137 let fields = &self.store.application.settings.tunables.sort.rooms;
138 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
137 139
138 state.list.set(items); 140 state.list.set(items);
139 state.last_fetch = Some(Instant::now()); 141 state.last_fetch = Some(Instant::now());
src/worker.rs +6 −10
@@ -330,34 +330,30 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore) {
330 330
331 for room in client.invited_rooms().into_iter() { 331 for room in client.invited_rooms().into_iter() {
332 let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string(); 332 let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string();
333 let tags = room.tags().await.unwrap_or_default();
334
333 names.push((room.room_id().to_owned(), name)); 335 names.push((room.room_id().to_owned(), name));
334 336
335 if room.is_direct() { 337 if room.is_direct() {
336 let tags = room.tags().await.unwrap_or_default();
337
338 dms.push(Arc::new((room.into(), tags))); 338 dms.push(Arc::new((room.into(), tags)));
339 } else if room.is_space() { 339 } else if room.is_space() {
340 spaces.push(room.into()); 340 spaces.push(Arc::new((room.into(), tags)));
341 } else { 341 } else {
342 let tags = room.tags().await.unwrap_or_default();
343
344 rooms.push(Arc::new((room.into(), tags))); 342 rooms.push(Arc::new((room.into(), tags)));
345 } 343 }
346 } 344 }
347 345
348 for room in client.joined_rooms().into_iter() { 346 for room in client.joined_rooms().into_iter() {
349 let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string(); 347 let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string();
348 let tags = room.tags().await.unwrap_or_default();
349
350 names.push((room.room_id().to_owned(), name)); 350 names.push((room.room_id().to_owned(), name));
351 351
352 if room.is_direct() { 352 if room.is_direct() {
353 let tags = room.tags().await.unwrap_or_default();
354
355 dms.push(Arc::new((room.into(), tags))); 353 dms.push(Arc::new((room.into(), tags)));
356 } else if room.is_space() { 354 } else if room.is_space() {
357 spaces.push(room.into()); 355 spaces.push(Arc::new((room.into(), tags)));
358 } else { 356 } else {
359 let tags = room.tags().await.unwrap_or_default();
360
361 rooms.push(Arc::new((room.into(), tags))); 357 rooms.push(Arc::new((room.into(), tags)));
362 } 358 }
363 } 359 }