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 @@
11# iamb
22
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+)
44[![License: Apache 2.0](https://img.shields.io/crates/l/iamb.svg?logo=apache)](https://crates.io/crates/iamb)
55[![#iamb:0x.badd.cafe](https://img.shields.io/badge/matrix-%23iamb:0x.badd.cafe-blue)](https://matrix.to/#/#iamb:0x.badd.cafe)
66[![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! {
202202 }
203203}
204204
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
205334/// A room property.
206335#[derive(Clone, Debug, Eq, PartialEq)]
207336pub enum RoomField {
@@ -811,7 +940,7 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
811940#[derive(Default)]
812941pub struct SyncInfo {
813942 /// Spaces that the user is a member of.
814 pub spaces: Vec<MatrixRoom>,
943 pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
815944
816945 /// Rooms that the user is a member of.
817946 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
src/config.rs +90 −1
@@ -20,7 +20,7 @@ use modalkit::tui::{
2020 text::Span,
2121};
2222
23use super::base::{IambId, RoomInfo};
23use super::base::{IambId, RoomInfo, SortColumn, SortFieldRoom, SortFieldUser, SortOrder};
2424
2525macro_rules! usage {
2626 ( $($args: tt)* ) => {
@@ -29,6 +29,17 @@ macro_rules! usage {
2929 }
3030}
3131
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
3243const DEFAULT_REQ_TIMEOUT: u64 = 120;
3344
3445const COLORS: [Color; 13] = [
@@ -213,6 +224,15 @@ pub struct UserDisplayTunables {
213224
214225pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
215226
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
216236fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
217237 match (a, b) {
218238 (Some(a), None) => Some(a),
@@ -246,6 +266,33 @@ pub enum UserDisplayStyle {
246266 DisplayName,
247267}
248268
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
249296#[derive(Clone)]
250297pub struct TunableValues {
251298 pub log_level: Level,
@@ -254,6 +301,7 @@ pub struct TunableValues {
254301 pub read_receipt_send: bool,
255302 pub read_receipt_display: bool,
256303 pub request_timeout: u64,
304 pub sort: SortValues,
257305 pub typing_notice_send: bool,
258306 pub typing_notice_display: bool,
259307 pub users: UserOverrides,
@@ -270,6 +318,8 @@ pub struct Tunables {
270318 pub read_receipt_send: Option<bool>,
271319 pub read_receipt_display: Option<bool>,
272320 pub request_timeout: Option<u64>,
321 #[serde(default)]
322 pub sort: SortOverrides,
273323 pub typing_notice_send: Option<bool>,
274324 pub typing_notice_display: Option<bool>,
275325 pub users: Option<UserOverrides>,
@@ -289,6 +339,7 @@ impl Tunables {
289339 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
290340 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
291341 request_timeout: self.request_timeout.or(other.request_timeout),
342 sort: merge_sorts(self.sort, other.sort),
292343 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
293344 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
294345 users: merge_users(self.users, other.users),
@@ -306,6 +357,7 @@ impl Tunables {
306357 read_receipt_send: self.read_receipt_send.unwrap_or(true),
307358 read_receipt_display: self.read_receipt_display.unwrap_or(true),
308359 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
360 sort: self.sort.values(),
309361 typing_notice_send: self.typing_notice_send.unwrap_or(true),
310362 typing_notice_display: self.typing_notice_display.unwrap_or(true),
311363 users: self.users.unwrap_or_default(),
@@ -701,6 +753,43 @@ mod tests {
701753 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
702754 }
703755
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
704793 #[test]
705794 fn test_parse_layout() {
706795 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
src/tests.rs +2
@@ -28,6 +28,7 @@ use crate::{
2828 ApplicationSettings,
2929 DirectoryValues,
3030 ProfileConfig,
31 SortOverrides,
3132 TunableValues,
3233 UserColor,
3334 UserDisplayStyle,
@@ -183,6 +184,7 @@ pub fn mock_tunables() -> TunableValues {
183184 read_receipt_send: true,
184185 read_receipt_display: true,
185186 request_timeout: 120,
187 sort: SortOverrides::default().values(),
186188 typing_notice_send: true,
187189 typing_notice_display: true,
188190 users: vec![(TEST_USER5.clone(), UserDisplayTunables {
src/windows/mod.rs +263 −100
@@ -17,7 +17,9 @@ use matrix_sdk::{
1717 ruma::{
1818 events::room::member::MembershipState,
1919 events::tag::{TagName, Tags},
20 OwnedRoomAliasId,
2021 OwnedRoomId,
22 RoomAliasId,
2123 RoomId,
2224 },
2325};
@@ -80,6 +82,10 @@ use crate::base::{
8082 ProgramStore,
8183 RoomAction,
8284 SendAction,
85 SortColumn,
86 SortFieldRoom,
87 SortFieldUser,
88 SortOrder,
8389};
8490
8591use self::{room::RoomState, welcome::WelcomeState};
@@ -125,42 +131,87 @@ fn selected_text(s: &str, selected: bool) -> Text {
125131 Text::from(selected_span(s, selected))
126132}
127133
128fn room_cmp(a: &MatrixRoom, b: &MatrixRoom) -> Ordering {
129 let ca1 = a.canonical_alias();
130 let ca2 = b.canonical_alias();
131
132 let ord = match (ca1, ca2) {
134/// Sort `Some` to be less than `None` so that list items with values come before those without.
135#[inline]
136fn some_cmp<T: Ord>(a: Option<T>, b: Option<T>) -> Ordering {
137 match (a, b) {
138 (Some(a), Some(b)) => a.cmp(&b),
133139 (None, None) => Ordering::Equal,
134140 (None, Some(_)) => Ordering::Greater,
135141 (Some(_), None) => Ordering::Less,
136 (Some(ca1), Some(ca2)) => ca1.cmp(&ca2),
137 };
142 }
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();
138148
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 }
140158}
141159
142fn tag_cmp(a: &Option<Tags>, b: &Option<Tags>) -> Ordering {
143 let (fava, lowa) = a
144 .as_ref()
145 .map(|tags| {
146 (tags.contains_key(&TagName::Favorite), tags.contains_key(&TagName::LowPriority))
147 })
148 .unwrap_or((false, false));
160fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
161 match field {
162 SortFieldRoom::Favorite => {
163 let fava = a.has_tag(TagName::Favorite);
164 let favb = b.has_tag(TagName::Favorite);
149165
150 let (favb, lowb) = b
151 .as_ref()
152 .map(|tags| {
153 (tags.contains_key(&TagName::Favorite), tags.contains_key(&TagName::LowPriority))
154 })
155 .unwrap_or((false, false));
166 // If a has Favorite and b doesn't, it should sort earlier in room list.
167 favb.cmp(&fava)
168 },
169 SortFieldRoom::LowPriority => {
170 let lowa = a.has_tag(TagName::LowPriority);
171 let lowb = b.has_tag(TagName::LowPriority);
156172
157 // If a has Favorite and b doesn't, it should sort earlier in room list.
158 let cmpf = favb.cmp(&fava);
173 // If a has LowPriority and b doesn't, it should sort later in room list.
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 }
159195
160 // If a has LowPriority and b doesn't, it should sort later in room list.
161 let cmpl = lowa.cmp(&lowb);
196 // Break ties on ascending room id.
197 room_cmp(a, b, &SortFieldRoom::RoomId)
198}
162199
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)
164215}
165216
166217fn 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) {
190241 spans.push(Span::styled(")", style));
191242}
192243
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
193251#[inline]
194252fn room_prompt(
195253 room_id: &RoomId,
@@ -399,7 +457,8 @@ impl WindowOps<IambInfo> for IambWindow {
399457 .into_iter()
400458 .map(|room_info| DirectItem::new(room_info, store))
401459 .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));
403462
404463 state.set(items);
405464
@@ -417,8 +476,13 @@ impl WindowOps<IambInfo> for IambWindow {
417476
418477 if need_fetch {
419478 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()));
421 state.set(items.collect());
479 let mut items = mems
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);
422486 *last_fetch = Some(Instant::now());
423487 }
424488 }
@@ -438,7 +502,8 @@ impl WindowOps<IambInfo> for IambWindow {
438502 .into_iter()
439503 .map(|room_info| RoomItem::new(room_info, store))
440504 .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));
442507
443508 state.set(items);
444509
@@ -449,15 +514,18 @@ impl WindowOps<IambInfo> for IambWindow {
449514 .render(area, buf, state);
450515 },
451516 IambWindow::SpaceList(state) => {
452 let items = store
517 let mut items = store
453518 .application
454519 .sync_info
455520 .spaces
456521 .clone()
457522 .into_iter()
458 .map(|room| SpaceItem::new(room, store));
459 state.set(items.collect());
460 state.draw(area, buf, focused, store);
523 .map(|room| SpaceItem::new(room, store))
524 .collect::<Vec<_>>();
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);
461529
462530 List::new(store)
463531 .empty_message("You haven't joined any spaces yet")
@@ -662,6 +730,7 @@ impl Window<IambInfo> for IambWindow {
662730pub struct RoomItem {
663731 room_info: MatrixRoomInfo,
664732 name: String,
733 alias: Option<OwnedRoomAliasId>,
665734}
666735
667736impl RoomItem {
@@ -671,13 +740,14 @@ impl RoomItem {
671740
672741 let info = store.application.get_room_info(room_id.to_owned());
673742 let name = info.name.clone().unwrap_or_default();
743 let alias = room.canonical_alias();
674744 info.tags = room_info.deref().1.clone();
675745
676 if let Some(alias) = room.canonical_alias() {
746 if let Some(alias) = &alias {
677747 store.application.names.insert(alias.to_string(), room_id.to_owned());
678748 }
679749
680 RoomItem { room_info, name }
750 RoomItem { room_info, name, alias }
681751 }
682752
683753 #[inline]
@@ -685,34 +755,31 @@ impl RoomItem {
685755 &self.room_info.deref().0
686756 }
687757
688 #[inline]
689 fn room_id(&self) -> &RoomId {
690 self.room().room_id()
691 }
692
693758 #[inline]
694759 fn tags(&self) -> &Option<Tags> {
695760 &self.room_info.deref().1
696761 }
697762}
698763
699impl PartialEq for RoomItem {
700 fn eq(&self, other: &Self) -> bool {
701 self.room_id() == other.room_id()
764impl RoomLikeItem for RoomItem {
765 fn name(&self) -> &str {
766 self.name.as_str()
702767 }
703}
704768
705impl Eq for RoomItem {}
769 fn alias(&self) -> Option<&RoomAliasId> {
770 self.alias.as_deref()
771 }
706772
707impl Ord for RoomItem {
708 fn cmp(&self, other: &Self) -> Ordering {
709 tag_cmp(self.tags(), other.tags()).then_with(|| room_cmp(self.room(), other.room()))
773 fn room_id(&self) -> &RoomId {
774 self.room().room_id()
710775 }
711}
712776
713impl PartialOrd for RoomItem {
714 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
715 self.cmp(other).into()
777 fn has_tag(&self, tag: TagName) -> bool {
778 if let Some(tags) = &self.room_info.deref().1 {
779 tags.contains_key(&tag)
780 } else {
781 false
782 }
716783 }
717784}
718785
@@ -756,14 +823,16 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
756823pub struct DirectItem {
757824 room_info: MatrixRoomInfo,
758825 name: String,
826 alias: Option<OwnedRoomAliasId>,
759827}
760828
761829impl DirectItem {
762830 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();
764832 let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default();
833 let alias = room_info.0.canonical_alias();
765834
766 DirectItem { room_info, name }
835 DirectItem { room_info, name, alias }
767836 }
768837
769838 #[inline]
@@ -771,17 +840,34 @@ impl DirectItem {
771840 &self.room_info.deref().0
772841 }
773842
774 #[inline]
775 fn room_id(&self) -> &RoomId {
776 self.room().room_id()
777 }
778
779843 #[inline]
780844 fn tags(&self) -> &Option<Tags> {
781845 &self.room_info.deref().1
782846 }
783847}
784848
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
785871impl ToString for DirectItem {
786872 fn to_string(&self) -> String {
787873 return self.name.clone();
@@ -807,26 +893,6 @@ impl ListItem<IambInfo> for DirectItem {
807893 }
808894}
809895
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
830896impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
831897 fn prompt(
832898 &mut self,
@@ -840,51 +906,58 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
840906
841907#[derive(Clone)]
842908pub struct SpaceItem {
843 room: MatrixRoom,
909 room_info: MatrixRoomInfo,
844910 name: String,
911 alias: Option<OwnedRoomAliasId>,
845912}
846913
847914impl SpaceItem {
848 fn new(room: MatrixRoom, store: &mut ProgramStore) -> Self {
849 let room_id = room.room_id();
915 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
916 let room_id = room_info.0.room_id();
850917 let name = store
851918 .application
852919 .get_room_info(room_id.to_owned())
853920 .name
854921 .clone()
855922 .unwrap_or_default();
923 let alias = room_info.0.canonical_alias();
856924
857 if let Some(alias) = room.canonical_alias() {
925 if let Some(alias) = &alias {
858926 store.application.names.insert(alias.to_string(), room_id.to_owned());
859927 }
860928
861 SpaceItem { room, name }
929 SpaceItem { room_info, name, alias }
862930 }
863}
864931
865impl PartialEq for SpaceItem {
866 fn eq(&self, other: &Self) -> bool {
867 self.room.room_id() == other.room.room_id()
932 #[inline]
933 fn room(&self) -> &MatrixRoom {
934 &self.room_info.deref().0
868935 }
869936}
870937
871impl Eq for SpaceItem {}
938impl RoomLikeItem for SpaceItem {
939 fn name(&self) -> &str {
940 self.name.as_str()
941 }
872942
873impl Ord for SpaceItem {
874 fn cmp(&self, other: &Self) -> Ordering {
875 room_cmp(&self.room, &other.room)
943 fn room_id(&self) -> &RoomId {
944 self.room().room_id()
876945 }
877}
878946
879impl PartialOrd for SpaceItem {
880 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
881 self.cmp(other).into()
947 fn alias(&self) -> Option<&RoomAliasId> {
948 self.alias.as_deref()
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
882955 }
883956}
884957
885958impl ToString for SpaceItem {
886959 fn to_string(&self) -> String {
887 return self.room.room_id().to_string();
960 return self.room_id().to_string();
888961 }
889962}
890963
@@ -894,7 +967,7 @@ impl ListItem<IambInfo> for SpaceItem {
894967 }
895968
896969 fn get_word(&self) -> Option<String> {
897 self.room.room_id().to_string().into()
970 self.room_id().to_string().into()
898971 }
899972}
900973
@@ -905,7 +978,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
905978 ctx: &ProgramContext,
906979 _: &mut ProgramStore,
907980 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
908 room_prompt(self.room.room_id(), act, ctx)
981 room_prompt(self.room_id(), act, ctx)
909982 }
910983}
911984
@@ -1200,3 +1273,93 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
12001273 }
12011274 }
12021275}
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::{
2222
2323use crate::base::{IambBufferId, IambInfo, ProgramStore, RoomFocus};
2424
25use crate::windows::RoomItem;
25use crate::windows::{room_fields_cmp, RoomItem};
2626
2727const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
2828
@@ -120,7 +120,7 @@ impl<'a> StatefulWidget for Space<'a> {
120120
121121 match res {
122122 Ok(members) => {
123 let items = members
123 let mut items = members
124124 .into_iter()
125125 .filter_map(|id| {
126126 let (room, _, tags) =
@@ -133,7 +133,9 @@ impl<'a> StatefulWidget for Space<'a> {
133133 None
134134 }
135135 })
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));
137139
138140 state.list.set(items);
139141 state.last_fetch = Some(Instant::now());
src/worker.rs +6 −10
@@ -330,34 +330,30 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore) {
330330
331331 for room in client.invited_rooms().into_iter() {
332332 let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string();
333 let tags = room.tags().await.unwrap_or_default();
334
333335 names.push((room.room_id().to_owned(), name));
334336
335337 if room.is_direct() {
336 let tags = room.tags().await.unwrap_or_default();
337
338338 dms.push(Arc::new((room.into(), tags)));
339339 } else if room.is_space() {
340 spaces.push(room.into());
340 spaces.push(Arc::new((room.into(), tags)));
341341 } else {
342 let tags = room.tags().await.unwrap_or_default();
343
344342 rooms.push(Arc::new((room.into(), tags)));
345343 }
346344 }
347345
348346 for room in client.joined_rooms().into_iter() {
349347 let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string();
348 let tags = room.tags().await.unwrap_or_default();
349
350350 names.push((room.room_id().to_owned(), name));
351351
352352 if room.is_direct() {
353 let tags = room.tags().await.unwrap_or_default();
354
355353 dms.push(Arc::new((room.into(), tags)));
356354 } else if room.is_space() {
357 spaces.push(room.into());
355 spaces.push(Arc::new((room.into(), tags)));
358356 } else {
359 let tags = room.tags().await.unwrap_or_default();
360
361357 rooms.push(Arc::new((room.into(), tags)));
362358 }
363359 }