Commit 3e45ca3d2c

3e45ca3d2cd7127a93647369027a33ea50b8c991

parent: 7dd09e32a8

Unregistered key

VAWVAW <94846592+VAWVAW@users.noreply.github.com> · 2025-05-15 03:26 UTC
committer: <noreply@github.com>

Support adding rooms to spaces (#407)

Layout: unified · split

docs/iamb.1 +10
@@ -159,6 +159,8 @@ Create and point the given alias to the room.
159159Delete the provided alias from the room's alternative alias list.
160160.It Sy ":room alias show"
161161Show alternative aliases to the room, if any are set.
162.It Sy ":room id show"
163Show the Matrix identifier for the room.
162164.It Sy ":room canon set [alias]"
163165Set the room's canonical alias to the one provided, and make the previous one an alternative alias.
164166.It Sy ":room canon unset [alias]"
@@ -173,6 +175,14 @@ Unban a user from this room with an optional reason.
173175Kick a user from this room with an optional reason.
174176.El
175177
178.Sh "SPACE COMMANDS"
179.Bl -tag -width Ds
180.It Sy ":space child set [room_id]"
181Add a room to the currently focused space.
182.It Sy ":space child remove"
183Remove the selected room from the currently focused space.
184.El
185
176186.Sh "WINDOW COMMANDS"
177187.Bl -tag -width Ds
178188.It Sy ":horizontal [cmd]"
src/base.rs +47
@@ -177,6 +177,19 @@ pub enum MessageAction {
177177 Unreact(Option<String>, bool),
178178}
179179
180/// An action taken in the currently selected space.
181#[derive(Clone, Debug, Eq, PartialEq)]
182pub enum SpaceAction {
183 /// Add a room or update metadata.
184 ///
185 /// The [`Option<String>`] argument is the order parameter.
186 /// The [`bool`] argument indicates whether the room is suggested.
187 SetChild(OwnedRoomId, Option<String>, bool),
188
189 /// Remove the selected room.
190 RemoveChild,
191}
192
180193/// The type of room being created.
181194#[derive(Clone, Debug, Eq, PartialEq)]
182195pub enum CreateRoomType {
@@ -379,6 +392,9 @@ pub enum RoomField {
379392 /// The room name.
380393 Name,
381394
395 /// The room id.
396 Id,
397
382398 /// A room tag.
383399 Tag(TagName),
384400
@@ -497,6 +513,9 @@ pub enum IambAction {
497513 /// Perform an action on the currently selected message.
498514 Message(MessageAction),
499515
516 /// Perform an action on the current space.
517 Space(SpaceAction),
518
500519 /// Open a URL.
501520 OpenLink(String),
502521
@@ -538,6 +557,12 @@ impl From<MessageAction> for IambAction {
538557 }
539558}
540559
560impl From<SpaceAction> for IambAction {
561 fn from(act: SpaceAction) -> Self {
562 IambAction::Space(act)
563 }
564}
565
541566impl From<RoomAction> for IambAction {
542567 fn from(act: RoomAction) -> Self {
543568 IambAction::Room(act)
@@ -557,6 +582,7 @@ impl ApplicationAction for IambAction {
557582 IambAction::Homeserver(..) => SequenceStatus::Break,
558583 IambAction::Keys(..) => SequenceStatus::Break,
559584 IambAction::Message(..) => SequenceStatus::Break,
585 IambAction::Space(..) => SequenceStatus::Break,
560586 IambAction::Room(..) => SequenceStatus::Break,
561587 IambAction::OpenLink(..) => SequenceStatus::Break,
562588 IambAction::Send(..) => SequenceStatus::Break,
@@ -572,6 +598,7 @@ impl ApplicationAction for IambAction {
572598 IambAction::Homeserver(..) => SequenceStatus::Atom,
573599 IambAction::Keys(..) => SequenceStatus::Atom,
574600 IambAction::Message(..) => SequenceStatus::Atom,
601 IambAction::Space(..) => SequenceStatus::Atom,
575602 IambAction::OpenLink(..) => SequenceStatus::Atom,
576603 IambAction::Room(..) => SequenceStatus::Atom,
577604 IambAction::Send(..) => SequenceStatus::Atom,
@@ -587,6 +614,7 @@ impl ApplicationAction for IambAction {
587614 IambAction::Homeserver(..) => SequenceStatus::Ignore,
588615 IambAction::Keys(..) => SequenceStatus::Ignore,
589616 IambAction::Message(..) => SequenceStatus::Ignore,
617 IambAction::Space(..) => SequenceStatus::Ignore,
590618 IambAction::Room(..) => SequenceStatus::Ignore,
591619 IambAction::OpenLink(..) => SequenceStatus::Ignore,
592620 IambAction::Send(..) => SequenceStatus::Ignore,
@@ -601,6 +629,7 @@ impl ApplicationAction for IambAction {
601629 IambAction::ClearUnreads => false,
602630 IambAction::Homeserver(..) => false,
603631 IambAction::Message(..) => false,
632 IambAction::Space(..) => false,
604633 IambAction::Room(..) => false,
605634 IambAction::Keys(..) => false,
606635 IambAction::Send(..) => false,
@@ -618,6 +647,12 @@ impl From<RoomAction> for ProgramAction {
618647 }
619648}
620649
650impl From<SpaceAction> for ProgramAction {
651 fn from(act: SpaceAction) -> Self {
652 IambAction::from(act).into()
653 }
654}
655
621656impl From<IambAction> for ProgramAction {
622657 fn from(act: IambAction) -> Self {
623658 Action::Application(act)
@@ -713,10 +748,22 @@ pub enum IambError {
713748 #[error("Current window is not a room or space")]
714749 NoSelectedRoomOrSpace,
715750
751 /// A failure due to not having a room or space item selected in a list.
752 #[error("No room or space currently selected in list")]
753 NoSelectedRoomOrSpaceItem,
754
716755 /// A failure due to not having a room selected.
717756 #[error("Current window is not a room")]
718757 NoSelectedRoom,
719758
759 /// A failure due to not having a space selected.
760 #[error("Current window is not a space")]
761 NoSelectedSpace,
762
763 /// A failure due to not having sufficient permission to perform an action in a room.
764 #[error("You do not have the permission to do that")]
765 InsufficientPermission,
766
720767 /// A failure due to not having an outstanding room invitation.
721768 #[error("You do not have a current invitation to this room")]
722769 NotInvited,
src/commands.rs +190 −3
@@ -2,9 +2,9 @@
22//!
33//! The command-bar commands are set up here, and iamb-specific commands are defined here. See
44//! [modalkit::env::vim::command] for additional Vim commands we pull in.
5use std::convert::TryFrom;
5use std::{convert::TryFrom, str::FromStr as _};
66
7use matrix_sdk::ruma::{events::tag::TagName, OwnedUserId};
7use matrix_sdk::ruma::{events::tag::TagName, OwnedRoomId, OwnedUserId};
88
99use modalkit::{
1010 commands::{CommandError, CommandResult, CommandStep},
@@ -27,6 +27,7 @@ use crate::base::{
2727 RoomAction,
2828 RoomField,
2929 SendAction,
30 SpaceAction,
3031 VerifyAction,
3132};
3233
@@ -535,6 +536,90 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
535536 return Result::Err(CommandError::InvalidArgument)
536537 },
537538
539 // :room id show
540 ("id", "show", None) => RoomAction::Show(RoomField::Id).into(),
541 ("id", "show", Some(_)) => return Result::Err(CommandError::InvalidArgument),
542
543 _ => return Result::Err(CommandError::InvalidArgument),
544 };
545
546 let step = CommandStep::Continue(act.into(), ctx.context.clone());
547
548 return Ok(step);
549}
550
551fn iamb_space(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
552 let mut args = desc.arg.options()?;
553
554 if args.len() < 2 {
555 return Err(CommandError::InvalidArgument);
556 }
557
558 let OptionType::Positional(field) = args.remove(0) else {
559 return Err(CommandError::InvalidArgument);
560 };
561 let OptionType::Positional(action) = args.remove(0) else {
562 return Err(CommandError::InvalidArgument);
563 };
564
565 let act: IambAction = match (field.as_str(), action.as_str()) {
566 ("child", "remove") => {
567 if !(args.is_empty()) {
568 return Err(CommandError::InvalidArgument);
569 }
570 SpaceAction::RemoveChild.into()
571 },
572 // :space child set
573 ("child", "set") => {
574 let mut order = None;
575 let mut suggested = false;
576 let mut raw_child = None;
577
578 for arg in args {
579 match arg {
580 OptionType::Flag(name, Some(arg)) => {
581 match name.as_str() {
582 "order" => {
583 if order.is_some() {
584 let msg = "Multiple ++order arguments are not allowed";
585 let err = CommandError::Error(msg.into());
586
587 return Err(err);
588 } else {
589 order = Some(arg);
590 }
591 },
592 _ => return Err(CommandError::InvalidArgument),
593 }
594 },
595 OptionType::Flag(name, None) => {
596 match name.as_str() {
597 "suggested" => suggested = true,
598 _ => return Err(CommandError::InvalidArgument),
599 }
600 },
601 OptionType::Positional(arg) => {
602 if raw_child.is_some() {
603 let msg = "Multiple room arguments are not allowed";
604 let err = CommandError::Error(msg.into());
605
606 return Err(err);
607 }
608 raw_child = Some(arg);
609 },
610 }
611 }
612
613 let child = if let Some(child) = raw_child {
614 OwnedRoomId::from_str(&child)
615 .map_err(|_| CommandError::Error("Invalid room id specified".into()))?
616 } else {
617 let msg = "Must specify a room to add";
618 return Err(CommandError::Error(msg.into()));
619 };
620
621 SpaceAction::SetChild(child, order, suggested).into()
622 },
538623 _ => return Result::Err(CommandError::InvalidArgument),
539624 };
540625
@@ -671,6 +756,11 @@ fn add_iamb_commands(cmds: &mut ProgramCommands) {
671756 f: iamb_rooms,
672757 });
673758 cmds.add_command(ProgramCommand { name: "room".into(), aliases: vec![], f: iamb_room });
759 cmds.add_command(ProgramCommand {
760 name: "space".into(),
761 aliases: vec![],
762 f: iamb_space,
763 });
674764 cmds.add_command(ProgramCommand {
675765 name: "spaces".into(),
676766 aliases: vec![],
@@ -725,7 +815,7 @@ pub fn setup_commands() -> ProgramCommands {
725815#[cfg(test)]
726816mod tests {
727817 use super::*;
728 use matrix_sdk::ruma::user_id;
818 use matrix_sdk::ruma::{room_id, user_id};
729819 use modalkit::actions::WindowAction;
730820 use modalkit::editing::context::EditContext;
731821
@@ -1067,6 +1157,103 @@ mod tests {
10671157 assert_eq!(res, vec![(act.into(), ctx.clone())]);
10681158 }
10691159
1160 #[test]
1161 fn test_cmd_room_id_show() {
1162 let mut cmds = setup_commands();
1163 let ctx = EditContext::default();
1164
1165 let res = cmds.input_cmd("room id show", ctx.clone()).unwrap();
1166 let act = RoomAction::Show(RoomField::Id);
1167 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1168
1169 let res = cmds.input_cmd("room id show foo", ctx.clone());
1170 assert_eq!(res, Err(CommandError::InvalidArgument));
1171 }
1172
1173 #[test]
1174 fn test_cmd_space_child() {
1175 let mut cmds = setup_commands();
1176 let ctx = EditContext::default();
1177
1178 let cmd = "space";
1179 let res = cmds.input_cmd(cmd, ctx.clone());
1180 assert_eq!(res, Err(CommandError::InvalidArgument));
1181
1182 let cmd = "space ++foo bar baz";
1183 let res = cmds.input_cmd(cmd, ctx.clone());
1184 assert_eq!(res, Err(CommandError::InvalidArgument));
1185
1186 let cmd = "space child foo";
1187 let res = cmds.input_cmd(cmd, ctx.clone());
1188 assert_eq!(res, Err(CommandError::InvalidArgument));
1189 }
1190
1191 #[test]
1192 fn test_cmd_space_child_set() {
1193 let mut cmds = setup_commands();
1194 let ctx = EditContext::default();
1195
1196 let cmd = "space child set !roomid:example.org";
1197 let res = cmds.input_cmd(cmd, ctx.clone()).unwrap();
1198 let act = SpaceAction::SetChild(room_id!("!roomid:example.org").to_owned(), None, false);
1199 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1200
1201 let cmd = "space child set ++order=abcd ++suggested !roomid:example.org";
1202 let res = cmds.input_cmd(cmd, ctx.clone()).unwrap();
1203 let act = SpaceAction::SetChild(
1204 room_id!("!roomid:example.org").to_owned(),
1205 Some("abcd".into()),
1206 true,
1207 );
1208 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1209
1210 let cmd = "space child set ++order=abcd ++order=1234 !roomid:example.org";
1211 let res = cmds.input_cmd(cmd, ctx.clone());
1212 assert_eq!(
1213 res,
1214 Err(CommandError::Error("Multiple ++order arguments are not allowed".into()))
1215 );
1216
1217 let cmd = "space child set !roomid:example.org !otherroom:example.org";
1218 let res = cmds.input_cmd(cmd, ctx.clone());
1219 assert_eq!(res, Err(CommandError::Error("Multiple room arguments are not allowed".into())));
1220
1221 let cmd = "space child set ++foo=abcd !roomid:example.org";
1222 let res = cmds.input_cmd(cmd, ctx.clone());
1223 assert_eq!(res, Err(CommandError::InvalidArgument));
1224
1225 let cmd = "space child set ++foo !roomid:example.org";
1226 let res = cmds.input_cmd(cmd, ctx.clone());
1227 assert_eq!(res, Err(CommandError::InvalidArgument));
1228
1229 let cmd = "space child ++order=abcd ++suggested set !roomid:example.org";
1230 let res = cmds.input_cmd(cmd, ctx.clone());
1231 assert_eq!(res, Err(CommandError::InvalidArgument));
1232
1233 let cmd = "space child set foo";
1234 let res = cmds.input_cmd(cmd, ctx.clone());
1235 assert_eq!(res, Err(CommandError::Error("Invalid room id specified".into())));
1236
1237 let cmd = "space child set";
1238 let res = cmds.input_cmd(cmd, ctx.clone());
1239 assert_eq!(res, Err(CommandError::Error("Must specify a room to add".into())));
1240 }
1241
1242 #[test]
1243 fn test_cmd_space_child_remove() {
1244 let mut cmds = setup_commands();
1245 let ctx = EditContext::default();
1246
1247 let cmd = "space child remove";
1248 let res = cmds.input_cmd(cmd, ctx.clone()).unwrap();
1249 let act = SpaceAction::RemoveChild;
1250 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1251
1252 let cmd = "space child remove foo";
1253 let res = cmds.input_cmd(cmd, ctx.clone());
1254 assert_eq!(res, Err(CommandError::InvalidArgument));
1255 }
1256
10701257 #[test]
10711258 fn test_cmd_invite() {
10721259 let mut cmds = setup_commands();
src/main.rs +3
@@ -557,6 +557,9 @@ impl Application {
557557 IambAction::Message(act) => {
558558 self.screen.current_window_mut()?.message_command(act, ctx, store).await?
559559 },
560 IambAction::Space(act) => {
561 self.screen.current_window_mut()?.space_command(act, ctx, store).await?
562 },
560563 IambAction::Room(act) => {
561564 let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
562565 self.action_prepend(acts);
src/windows/mod.rs +14
@@ -76,6 +76,7 @@ use crate::base::{
7676 SortFieldRoom,
7777 SortFieldUser,
7878 SortOrder,
79 SpaceAction,
7980 UnreadInfo,
8081};
8182
@@ -360,6 +361,19 @@ impl IambWindow {
360361 }
361362 }
362363
364 pub async fn space_command(
365 &mut self,
366 act: SpaceAction,
367 ctx: ProgramContext,
368 store: &mut ProgramStore,
369 ) -> IambResult<EditInfo> {
370 if let IambWindow::Room(w) = self {
371 w.space_command(act, ctx, store).await
372 } else {
373 return Err(IambError::NoSelectedRoom.into());
374 }
375 }
376
363377 pub async fn room_command(
364378 &mut self,
365379 act: RoomAction,
src/windows/room/mod.rs +23
@@ -66,6 +66,7 @@ use crate::base::{
6666 RoomAction,
6767 RoomField,
6868 SendAction,
69 SpaceAction,
6970};
7071
7172use self::chat::ChatState;
@@ -214,6 +215,18 @@ impl RoomState {
214215 }
215216 }
216217
218 pub async fn space_command(
219 &mut self,
220 act: SpaceAction,
221 ctx: ProgramContext,
222 store: &mut ProgramStore,
223 ) -> IambResult<EditInfo> {
224 match self {
225 RoomState::Space(space) => space.space_command(act, ctx, store).await,
226 RoomState::Chat(_) => Err(IambError::NoSelectedSpace.into()),
227 }
228 }
229
217230 pub async fn send_command(
218231 &mut self,
219232 act: SendAction,
@@ -464,6 +477,9 @@ impl RoomState {
464477 RoomField::Aliases => {
465478 // This never happens, aliases is only used for showing
466479 },
480 RoomField::Id => {
481 // This never happens, id is only used for showing
482 },
467483 }
468484
469485 Ok(vec![])
@@ -559,6 +575,9 @@ impl RoomState {
559575 RoomField::Aliases => {
560576 // This will not happen, you cannot unset all aliases
561577 },
578 RoomField::Id => {
579 // This never happens, id is only used for showing
580 },
562581 }
563582
564583 Ok(vec![])
@@ -574,6 +593,10 @@ impl RoomState {
574593 let visibility = room.history_visibility();
575594 format!("Room history visibility: {visibility}")
576595 },
596 RoomField::Id => {
597 let id = room.room_id();
598 format!("Room identifier: {id}")
599 },
577600 RoomField::Name => {
578601 match room.name() {
579602 None => "Room has no name".into(),
src/windows/room/space.rs +79 −2
@@ -2,11 +2,14 @@
22use std::ops::{Deref, DerefMut};
33use std::time::{Duration, Instant};
44
5use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
6use matrix_sdk::ruma::events::StateEventType;
57use matrix_sdk::{
68 room::Room as MatrixRoom,
79 ruma::{OwnedRoomId, RoomId},
810};
911
12use modalkit::prelude::{EditInfo, InfoMessage};
1013use ratatui::{
1114 buffer::Buffer,
1215 layout::Rect,
@@ -22,9 +25,18 @@ use modalkit_ratatui::{
2225 WindowOps,
2326};
2427
25use crate::base::{IambBufferId, IambInfo, ProgramStore, RoomFocus};
28use crate::base::{
29 IambBufferId,
30 IambError,
31 IambInfo,
32 IambResult,
33 ProgramContext,
34 ProgramStore,
35 RoomFocus,
36 SpaceAction,
37};
2638
27use crate::windows::{room_fields_cmp, RoomItem};
39use crate::windows::{room_fields_cmp, RoomItem, RoomLikeItem};
2840
2941const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
3042
@@ -68,6 +80,71 @@ impl SpaceState {
6880 last_fetch: self.last_fetch,
6981 }
7082 }
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 }
71148}
72149
73150impl TerminalCursor for SpaceState {