diff --git a/crates/tinyclient/src/gui/sidebar.rs b/crates/tinyclient/src/gui/sidebar.rs index cbc73947..4861d1ae 100644 --- a/crates/tinyclient/src/gui/sidebar.rs +++ b/crates/tinyclient/src/gui/sidebar.rs @@ -39,7 +39,7 @@ use gpui::{ use history::History; use pages::Pages; use protocol::{ - AccountKey, Badge, CallSupport, Conversation, ConversationKind, InboxCounts, InboxFilter, Key, Link, Network, + AccountKey, Badge, CallSupport, Conversation, ConversationKind, GroupKind, InboxCounts, InboxFilter, Key, Link, Network, Occupants, Request, Response, PAGE_LIMIT, }; use std::collections::{HashMap, HashSet}; @@ -53,6 +53,19 @@ const WATCH: &str = "sidebar"; /// Drafts remembered ahead of their rows being read again. const DRAFTS_HELD: usize = 256; +#[derive(Clone, PartialEq, Eq, Debug)] +struct MovedSlackSection { + space: Key, + id: String, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct MovedMattermostGroup { + space: Key, + id: String, + name: String, +} + /// The id to ask before on the next mention page. `None` when this page is the last. /// A page that was filtered down to nothing still moves on, using the raw page's last id. fn mention_cursor(items: &[protocol::MentionHit], more: bool, cursor: Option) -> Option { @@ -187,6 +200,8 @@ pub struct State { /// Groups the user opened or closed against how they start, and what they revealed. opened: HashSet, closed: HashSet, + /// Mattermost's displayed team groups have no server-side reorder API. + mattermost_group_order: HashMap>, quiet_shown: HashSet, threads_shown: HashSet, muted_shown: HashSet, @@ -505,6 +520,7 @@ impl State { spaces_loaded: false, opened: HashSet::new(), closed: HashSet::new(), + mattermost_group_order: HashMap::new(), quiet_shown: HashSet::new(), threads_shown: HashSet::new(), muted_shown: HashSet::new(), @@ -963,7 +979,23 @@ impl Shell { threads_shown: Some(&state.threads_shown), unread: state.home_unread && matches!(space.network, Network::Slack | Network::Mattermost), }; - tree::flatten(space, &tree.groups, &tree.conversations, self.open.as_ref(), depth, &rules) + if space.network == Network::Mattermost { + let mut groups = tree.groups.clone(); + if let Some(order) = state.mattermost_group_order.get(space) { + groups.sort_by_key(|group| { + ( + order.iter().position(|id| id == &group.id).unwrap_or(usize::MAX), + group.position, + ) + }); + for (position, group) in groups.iter_mut().enumerate() { + group.position = position as i32; + } + } + tree::flatten(space, &groups, &tree.conversations, self.open.as_ref(), depth, &rules) + } else { + tree::flatten(space, &tree.groups, &tree.conversations, self.open.as_ref(), depth, &rules) + } } None => vec![Row::Loading { depth }; 6], }; @@ -2117,7 +2149,7 @@ impl Shell { .when(can_moderate && channel.rights.voice_move && !phone, |row| row .on_drag(drag, |drag, _, _, cx| cx.new(|_| VoiceMovePreview(drag.name.clone().into())))) } - Row::Group { space, id, name, collapsed, muted, rollup, depth, .. } => { + Row::Group { space, id, name, kind, collapsed, muted, rollup, depth, .. } => { let lit = *collapsed && (rollup.attention > 0 || rollup.unread); let dot = rollup_badge(rollup.attention, rollup.unread).filter(|_| *collapsed); let chevron = if *collapsed { "icons/chevron-right.svg" } else { "icons/chevron-down.svg" }; @@ -2128,8 +2160,20 @@ impl Shell { let menu_id = id.clone(); let menu_name = name.clone(); let menu_muted = *muted; - let discord = space.network == Network::Discord; let phone = super::phone::active(); + let discord = space.network == Network::Discord; + let slack = !phone + && space.network == Network::Slack + && *kind == GroupKind::Section + && id != tree::APPS_GROUP + && id != protocol::STARS_SECTION; + let moved_section = MovedSlackSection { space: space.clone(), id: id.clone() }; + let mattermost = !phone && space.network == Network::Mattermost; + let moved_mattermost_group = MovedMattermostGroup { space: space.clone(), id: id.clone(), name: name.clone() }; + let drop_space = space.clone(); + let drop_id = id.clone(); + let mattermost_drop_space = space.clone(); + let mattermost_drop_id = id.clone(); let add_btn = can_create.then(|| { div() .id((gpui::ElementId::from("group-add"), id.clone())) @@ -2185,6 +2229,22 @@ impl Shell { }), ) }) + .when(slack, |row| row + .on_drag(moved_section, |dragged, _, _, cx| cx.new(|_| home_view::MoveGhost(SharedString::from(dragged.id.clone())))) + .drag_over::(|style, _, _, _| style.bg(theme::accent_soft())) + .on_drop(cx.listener(move |this, dragged: &MovedSlackSection, _, cx| { + if dragged.space == drop_space { + this.move_slack_section(drop_space.clone(), dragged.id.clone(), drop_id.clone(), cx); + } + }))) + .when(mattermost, |row| row + .on_drag(moved_mattermost_group, |dragged, _, _, cx| cx.new(|_| home_view::MoveGhost(SharedString::from(dragged.name.clone())))) + .drag_over::(|style, _, _, _| style.bg(theme::accent_soft())) + .on_drop(cx.listener(move |this, dragged: &MovedMattermostGroup, _, cx| { + if dragged.space == mattermost_drop_space { + this.move_mattermost_group(mattermost_drop_space.clone(), dragged.id.clone(), mattermost_drop_id.clone(), cx); + } + }))) } Row::Conversation { conversation: c, depth } => self.place_row(c, *depth, focused, cx), } @@ -3145,6 +3205,70 @@ impl Shell { ); } + /// Reorders Slack's custom sidebar sections (`Request::SectionReorder`). + fn move_slack_section(&mut self, space: Key, moved: String, target: String, cx: &mut Context) { + if moved == target { + return; + } + let Some(tree) = self.trees.get(&space) else { + return; + }; + let mut groups: Vec<_> = tree.groups.iter().filter(|group| group.kind == GroupKind::Section).collect(); + groups.sort_by_key(|group| group.position); + let stars_present = groups.iter().any(|group| group.id == protocol::STARS_SECTION); + let mut section_ids: Vec = groups + .into_iter() + .filter(|group| group.id != protocol::STARS_SECTION) + .map(|group| group.id.clone()) + .collect(); + if stars_present { + section_ids.insert(0, protocol::STARS_SECTION.to_owned()); + } + let (Some(from), Some(to)) = ( + section_ids.iter().position(|id| id == &moved), + section_ids.iter().position(|id| id == &target), + ) else { + return; + }; + section_ids.swap(from, to); + let request = Request::SectionReorder { space, section_ids }; + self.off_thread( + cx, + move || crate::client::ask(&request), + |this, answer, cx| { + if let Some(why) = refused(&answer) { + this.toast(None, why, cx); + } + }, + ); + } + + /// Reorders the synthetic team groups in Mattermost's workspace locally. + fn move_mattermost_group(&mut self, space: Key, moved: String, target: String, cx: &mut Context) { + if moved == target { + return; + } + let Some(tree) = self.trees.get(&space) else { + return; + }; + let mut order = self.sidebar_state.mattermost_group_order.get(&space).cloned().unwrap_or_else(|| { + let mut groups: Vec<_> = tree.groups.iter().collect(); + groups.sort_by_key(|group| group.position); + groups.into_iter().map(|group| group.id.clone()).collect() + }); + for group in &tree.groups { + if !order.contains(&group.id) { + order.push(group.id.clone()); + } + } + let (Some(from), Some(to)) = (order.iter().position(|id| id == &moved), order.iter().position(|id| id == &target)) else { + return; + }; + order.swap(from, to); + self.sidebar_state.mattermost_group_order.insert(space, order); + self.rebuild_rows(cx); + } + /// The Slack or Mattermost header's menu on a phone: the same rows as a bottom sheet over the screen. pub(in crate::gui) fn phone_slack_sheet(&self, window: &Window, cx: &mut Context) -> Option
{ let body = self.slack_menu_body(cx).or_else(|| self.mattermost_menu_body(cx))?; diff --git a/crates/tinyclient/src/gui/sidebar/home.rs b/crates/tinyclient/src/gui/sidebar/home.rs index 77b2b879..eb1e9a17 100644 --- a/crates/tinyclient/src/gui/sidebar/home.rs +++ b/crates/tinyclient/src/gui/sidebar/home.rs @@ -65,6 +65,24 @@ pub enum Act { JoinFound(String), } +/// A section of the Discord home the user can fold and move. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Section { + Voice, + Dms, + Servers, +} + +impl Section { + pub fn label(self) -> &'static str { + match self { + Section::Voice => "In voice", + Section::Dms => "Direct messages", + Section::Servers => "Servers", + } + } +} + /// Consecutive calls with the same person collapsed into one row with a count. #[derive(Clone, PartialEq, Eq, Debug)] pub struct CollapsedCall { @@ -99,6 +117,8 @@ pub fn collapse_call_entries(entries: &[protocol::CallLogEntry]) -> Vec), /// A voice channel or DM call with friends in it. Voice(Rc), @@ -126,6 +146,8 @@ impl Item { match self { Item::Header { first: true, .. } => crate::gui::theme::SECTION_FIRST, Item::Header { first: false, .. } => crate::gui::theme::SECTION, + Item::Section { first: true, .. } => crate::gui::theme::SECTION_FIRST, + Item::Section { first: false, .. } => crate::gui::theme::SECTION, Item::UnreadGroupHeader(_) => crate::gui::theme::row_height(32.), Item::UnreadMessage { .. } => crate::gui::theme::row_height(44.), Item::Chat(_) | Item::Voice(_) | Item::Call(_) | Item::Meeting(_) => { @@ -153,6 +175,7 @@ impl Item { Item::Meeting(event) => Some(format!("m/{}", event.id)), Item::Folder { key, .. } => Some(format!("f/{}", key.id)), Item::Header { label, .. } => Some(format!("h/{label}")), + Item::Section { which, .. } => Some(format!("h/{}", which.label())), _ => None, } } @@ -197,6 +220,12 @@ pub struct Home { // The user's folds, for this session. pub dms_all: bool, pub voice_all: bool, + /// The user folded a section of the Discord home away. + pub voice_folded: bool, + pub servers_folded: bool, + pub dms_folded: bool, + /// The order of the Discord home sections, for this session. + pub section_order: Vec
, pub chats_all: bool, pub meetings_open: bool, pub opened: HashSet, @@ -233,7 +262,30 @@ impl Home { } pub fn for_network(network: Network) -> Home { - Home { network: Some(network), ..Home::default() } + let section_order = if network == Network::Discord { + vec![Section::Voice, Section::Servers, Section::Dms] + } else { + Vec::new() + }; + Home { network: Some(network), section_order, ..Home::default() } + } + + /// Move a Discord home section into the other section's place. + pub fn move_section(&mut self, moved: Section, target: Section) { + if moved == target { + return; + } + for section in [Section::Voice, Section::Servers, Section::Dms] { + if !self.section_order.contains(§ion) { + self.section_order.push(section); + } + } + if let (Some(from), Some(to)) = ( + self.section_order.iter().position(|section| *section == moved), + self.section_order.iter().position(|section| *section == target), + ) { + self.section_order.swap(from, to); + } } } @@ -245,9 +297,9 @@ fn header(out: &mut Vec, label: &'static str) { out.push(Item::Header { label, first: out.is_empty() }); } -/// The Discord home, top to bottom: Friends, Message requests, In voice, DMs, servers by the -/// user's order with folders. `open_space`: the Space of the open conversation. `unread`: the -/// Unread segment, which keeps only what has news. +/// The Discord home: Friends and Message requests, then In voice, DMs and servers in the user's +/// section order. `open_space`: the Space of the open conversation. `unread`: the Unread segment, +/// which keeps only what has news. pub fn discord(home: &Home, spaces: &[Space], open_space: Option<&str>, unread: bool) -> Vec { // Spaces arrive separately. Showing them before chats inserts DMs above visible rows. if !home.loaded_once { @@ -264,26 +316,57 @@ pub fn discord(home: &Home, spaces: &[Space], open_space: Option<&str>, unread: if home.requests > 0 && !unread { out.push(Item::Action { act: Act::Requests, icon: "icons/mail.svg", words: "Message requests".into(), after: home.requests.to_string(), dot: None }); } + let mut voice_rows = Vec::new(); if !home.in_voice.is_empty() && !unread { - header(&mut out, "In voice"); - let shown = if home.voice_all { home.in_voice.len() } else { VOICE_SHOWN.min(home.in_voice.len()) }; - out.extend(home.in_voice.iter().take(shown).cloned().map(Item::Voice)); - if home.in_voice.len() > shown { - out.push(Item::Action { act: Act::MoreVoice, icon: "icons/chevron-down.svg", words: format!("{} more", home.in_voice.len() - shown), after: String::new(), dot: None }); + let open = !home.voice_folded; + voice_rows.push(Item::Section { which: Section::Voice, open, first: false }); + if open { + let shown = if home.voice_all { home.in_voice.len() } else { VOICE_SHOWN.min(home.in_voice.len()) }; + voice_rows.extend(home.in_voice.iter().take(shown).cloned().map(Item::Voice)); + if home.in_voice.len() > shown { + voice_rows.push(Item::Action { act: Act::MoreVoice, icon: "icons/chevron-down.svg", words: format!("{} more", home.in_voice.len() - shown), after: String::new(), dot: None }); + } } } + let mut dm_rows = Vec::new(); let dms = shown_dms(&home.chats, home.dms_all, unread); if !dms.0.is_empty() { - header(&mut out, "Direct messages"); - out.extend(dms.0.into_iter().map(Item::Chat)); - if dms.1 > 0 { - out.push(Item::Action { act: Act::MoreDms, icon: "icons/chevron-down.svg", words: format!("Show {} more", dms.1), after: String::new(), dot: None }); + let open = !home.dms_folded || unread; + dm_rows.push(Item::Section { which: Section::Dms, open, first: false }); + if open { + dm_rows.extend(dms.0.into_iter().map(Item::Chat)); + if dms.1 > 0 { + dm_rows.push(Item::Action { act: Act::MoreDms, icon: "icons/chevron-down.svg", words: format!("Show {} more", dms.1), after: String::new(), dot: None }); + } } } + let mut server_rows = Vec::new(); let servers = servers(spaces, &home.folders, &home.opened, open_space, unread); if !servers.is_empty() { - header(&mut out, "Servers"); - out.extend(servers); + let open = !home.servers_folded || unread; + server_rows.push(Item::Section { which: Section::Servers, open, first: false }); + if open { + server_rows.extend(servers); + } + } + let mut order = home.section_order.clone(); + for section in [Section::Voice, Section::Servers, Section::Dms] { + if !order.contains(§ion) { + order.push(section); + } + } + for section in order { + let rows = match section { + Section::Voice => &voice_rows, + Section::Servers => &server_rows, + Section::Dms => &dm_rows, + }; + for mut item in rows.iter().cloned() { + if let Item::Section { first, .. } = &mut item { + *first = out.is_empty(); + } + out.push(item); + } } out } @@ -531,6 +614,7 @@ mod tests { .iter() .map(|item| match item { Item::Header { label, .. } => format!("[{label}]"), + Item::Section { which, open, .. } => format!("[{}{}]", which.label(), if *open { "" } else { "+" }), Item::Chat(c) | Item::Voice(c) | Item::Channel(c) => c.key.id.clone(), Item::Action { words, .. } => format!("<{words}>"), Item::Space { index, child, .. } => format!("{}{}", if child.is_some() { "." } else { "" }, spaces[*index].name), @@ -630,7 +714,7 @@ mod tests { ..Home::for_network(Network::Discord) }; let got = shape(&discord(&home, &spaces, None, false), &spaces); - assert_eq!(got, ["", "", "", "[In voice]", "v0", "v1", "v2", "<2 more>", "[Direct messages]", "ines", "kofi", "[Servers]", "moss"]); + assert_eq!(got, ["", "", "", "[In voice]", "v0", "v1", "v2", "<2 more>", "[Servers]", "moss", "[Direct messages]", "ines", "kofi"]); assert_eq!(shape(&discord(&home, &spaces, None, true), &spaces), ["[Direct messages]", "ines"]); } @@ -645,13 +729,59 @@ mod tests { home.loaded = true; home.loaded_once = true; let ready = shape(&discord(&home, &spaces, None, false), &spaces); - assert_eq!(ready, ["", "", "[Direct messages]", "ines", "[Servers]", "moss"]); + assert_eq!(ready, ["", "", "[Servers]", "moss", "[Direct messages]", "ines"]); // Refreshes and sublist loading keep the cached home ready. home.epoch += 1; home.loaded = false; assert_eq!(shape(&discord(&home, &spaces, None, false), &spaces), ready); } + #[test] + fn the_servers_fold_away_and_say_how_many_they_hold() { + let spaces = [space("moss", None, 0, false), space("fern", None, 0, false)]; + let mut home = Home { loaded: true, loaded_once: true, ..Home::for_network(Network::Discord) }; + assert_eq!(shape(&discord(&home, &spaces, None, false), &spaces), ["", "", "[Servers]", "moss", "fern"]); + home.servers_folded = true; + assert_eq!(shape(&discord(&home, &spaces, None, false), &spaces), ["", "", "[Servers+]"]); + // The Unread segment lists only what has news, folded or not. + let news = [space("moss", None, 3, false)]; + assert_eq!(shape(&discord(&home, &news, None, true), &news), ["[Servers]", "moss"]); + } + + #[test] + fn dms_fold_and_can_go_above_the_servers() { + let spaces = [space("moss", None, 0, false)]; + let mut home = Home { chats: vec![chat("ines", 1)], loaded: true, loaded_once: true, ..Home::for_network(Network::Discord) }; + let at = |home: &Home| shape(&discord(home, &spaces, None, false), &spaces); + home.dms_folded = true; + assert_eq!(at(&home), ["", "", "[Servers]", "moss", "[Direct messages+]"]); + home.move_section(Section::Dms, Section::Servers); + assert_eq!(at(&home), ["", "", "[Direct messages+]", "[Servers]", "moss"]); + } + + #[test] + fn discord_voice_folds_and_swaps_with_the_other_home_sections() { + let spaces = [space("moss", None, 0, false)]; + let mut home = Home { + chats: vec![chat("ines", 1)], + in_voice: (0..4).map(|n| chat(&format!("v{n}"), 0)).collect(), + loaded: true, + loaded_once: true, + ..Home::for_network(Network::Discord) + }; + let at = |home: &Home| shape(&discord(home, &spaces, None, false), &spaces); + assert_eq!(at(&home), ["", "", "[In voice]", "v0", "v1", "v2", "<1 more>", "[Servers]", "moss", "[Direct messages]", "ines"]); + + home.voice_folded = true; + assert_eq!(at(&home), ["", "", "[In voice+]", "[Servers]", "moss", "[Direct messages]", "ines"]); + + home.voice_folded = false; + home.move_section(Section::Voice, Section::Dms); + assert_eq!(at(&home), ["", "", "[Direct messages]", "ines", "[Servers]", "moss", "[In voice]", "v0", "v1", "v2", "<1 more>"]); + home.move_section(Section::Voice, Section::Servers); + assert_eq!(at(&home), ["", "", "[Direct messages]", "ines", "[In voice]", "v0", "v1", "v2", "<1 more>", "[Servers]", "moss"]); + } + #[test] fn discord_shows_servers_after_a_completed_empty_chat_read() { let spaces = [space("moss", None, 0, false)]; @@ -660,8 +790,9 @@ mod tests { } #[test] - fn discord_servers_arriving_after_chats_append_below_them() { - let home = Home { loaded: true, loaded_once: true, chats: vec![chat("ines", 0)], ..Home::for_network(Network::Discord) }; + fn discord_servers_arriving_after_chats_append_below_them_when_dms_come_first() { + let mut home = Home { loaded: true, loaded_once: true, chats: vec![chat("ines", 0)], ..Home::for_network(Network::Discord) }; + home.move_section(Section::Dms, Section::Servers); let chats = shape(&discord(&home, &[], None, false), &[]); let spaces = [space("moss", None, 0, false)]; let complete = shape(&discord(&home, &spaces, None, false), &spaces); diff --git a/crates/tinyclient/src/gui/sidebar/home_view.rs b/crates/tinyclient/src/gui/sidebar/home_view.rs index f6df7a1b..a4324534 100644 --- a/crates/tinyclient/src/gui/sidebar/home_view.rs +++ b/crates/tinyclient/src/gui/sidebar/home_view.rs @@ -1,7 +1,7 @@ //! Reading and drawing the network homes and the lists they drill into. use super::chat::Look; -use super::home::{self, Act, Drill, Item}; +use super::home::{self, Act, Drill, Item, Section}; use super::super::layout::Menu; use super::{joins_from_list, on_screen, respliced, Mode}; use crate::client::ask; @@ -21,7 +21,11 @@ pub(super) struct MovedSpace { pub(super) name: String, } -struct MoveGhost(SharedString); +/// A Discord home section being dragged above or below the other. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct MovedSection(Section); + +pub(super) struct MoveGhost(pub(super) SharedString); impl Render for MoveGhost { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { @@ -650,6 +654,13 @@ impl Shell { return; } Item::Header { .. } => return, + Item::Section { which, .. } => { + match which { + Section::Voice => home.voice_folded = !home.voice_folded, + Section::Dms => home.dms_folded = !home.dms_folded, + Section::Servers => home.servers_folded = !home.servers_folded, + } + } Item::Action { act, .. } => match act { Act::Friends => { self.go(Mode::People, cx); @@ -910,6 +921,41 @@ impl Shell { } row.into_any_element() } + Item::Section { which, open, first } => { + let chevron = if open { "icons/chevron-down.svg" } else { "icons/chevron-right.svg" }; + let mut row = section_header(which.label(), first) + .id(("home-section", ix)) + .pr(px(theme::PANE_PAD)) + .cursor_pointer() + .child(glyph(chevron, 12., theme::text_faint())) + .child(div().flex_1()); + if which == Section::Dms && network == Some(Network::Discord) { + let can_group = self.snapshot.as_ref().is_some_and(|s| { + s.accounts + .iter() + .any(|a| a.key.network == Network::Discord && a.link == protocol::Link::Connected && a.can.groups > 0) + }); + if can_group { + row = row.child( + icon_button("discord-new-group", "icons/plus.svg", false) + .size(px(20.)) + .tooltip(tip("New group DM", None)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(|this, _, window, cx| this.open_switcher("@", window, cx))), + ); + } + } + let row = row + .on_drag(MovedSection(which), |dragged, _, _, cx| cx.new(|_| MoveGhost(SharedString::from(dragged.0.label())))) + .drag_over::(|style, _, _, _| style.bg(theme::accent_soft())) + .on_drop(cx.listener(move |this, dragged: &MovedSection, _, cx| { + if dragged.0 != which { + this.sidebar_state.home.move_section(dragged.0, which); + this.rebuild_home(cx); + } + })); + click(row, cx).into_any_element() + } Item::Chat(c) => { let look = match network { Some(Network::Discord) if self.sidebar_state.drill.is_none() => Look { status: true, ..Look::default() }, diff --git a/crates/tinyclient/src/gui/sidebar/tree.rs b/crates/tinyclient/src/gui/sidebar/tree.rs index c34ad570..60405140 100644 --- a/crates/tinyclient/src/gui/sidebar/tree.rs +++ b/crates/tinyclient/src/gui/sidebar/tree.rs @@ -69,7 +69,7 @@ pub enum Row { Threads { space: Key, count: u32, mention: bool }, /// A Slack workspace's Drafts: conversations with unsent drafts. Drafts { space: Key, count: u32 }, - Group { space: Key, id: String, name: String, collapsed: bool, muted: bool, rollup: Rollup, depth: u8 }, + Group { space: Key, id: String, name: String, kind: GroupKind, collapsed: bool, muted: bool, rollup: Rollup, depth: u8 }, Conversation { conversation: Rc, depth: u8 }, Occupant { channel: Rc, occupant: Occupant, depth: u8 }, /// `+4` under a voice channel. @@ -256,6 +256,7 @@ pub fn flatten(space: &Key, groups: &[Group], conversations: &[Rc] space: space.clone(), id: group.id.clone(), name: display_name, + kind: group.kind, collapsed, muted: group.muted, rollup: if collapsed { rollup } else { Rollup::default() }, @@ -274,7 +275,7 @@ pub fn flatten(space: &Key, groups: &[Group], conversations: &[Rc] apps.sort_by_key(|app| std::cmp::Reverse(app.updated)); let opened = rules.opened.is_some_and(|opened| opened.contains(APPS_GROUP)); let rollup = Rollup::of(apps.iter().map(|c| &***c)); - rows.push(Row::Group { space: space.clone(), id: APPS_GROUP.into(), name: "Apps".into(), collapsed: !opened, muted: false, rollup: if opened { Rollup::default() } else { rollup }, depth }); + rows.push(Row::Group { space: space.clone(), id: APPS_GROUP.into(), name: "Apps".into(), kind: GroupKind::Section, collapsed: !opened, muted: false, rollup: if opened { Rollup::default() } else { rollup }, depth }); // Folded apps stay folded unless one names me: their plain unread is the header's dot. if !opened { apps.retain(|app| app.mentions > 0 || open == Some(&app.key)); diff --git a/e2e/scenarios/network-home-sections/drive.linux.sh b/e2e/scenarios/network-home-sections/drive.linux.sh new file mode 100644 index 00000000..63dc78a7 --- /dev/null +++ b/e2e/scenarios/network-home-sections/drive.linux.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +python3 "$(dirname "$0")/drive.py" linux diff --git a/e2e/scenarios/network-home-sections/drive.macos.sh b/e2e/scenarios/network-home-sections/drive.macos.sh new file mode 100644 index 00000000..ff2e3e54 --- /dev/null +++ b/e2e/scenarios/network-home-sections/drive.macos.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +python3 "$(dirname "$0")/drive.py" macos diff --git a/e2e/scenarios/network-home-sections/drive.py b/e2e/scenarios/network-home-sections/drive.py new file mode 100644 index 00000000..03cff1d4 --- /dev/null +++ b/e2e/scenarios/network-home-sections/drive.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Drive the real desktop app to fold and reorder Discord home sections. + +The lab supplies a desktop build and records the display. chatd seeds invented demo data in a +scratch profile; PyAutoGUI sends mouse input and Tesseract checks the visible result. +""" + +import csv +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +import pyautogui +from PIL import Image, ImageChops + +OUT = Path(os.environ["E2E_OUT"]) +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP_DIR = Path(os.environ["E2E_APP_DIR"]) +PLATFORM = sys.argv[1] + + +def binary(name): + folder = APP_DIR / "Contents" / "MacOS" if PLATFORM == "macos" and APP_DIR.suffix == ".app" else APP_DIR + return folder / (name + (".exe" if PLATFORM == "windows" else "")) + + +def screen(name): + path = OUT / (name + ".png") + image = pyautogui.screenshot() + image.save(path) + width, height = pyautogui.size() + text = subprocess.run(["tesseract", str(path), "stdout", "tsv"], check=True, + capture_output=True, text=True, encoding="utf-8").stdout + lines = {} + for word in csv.DictReader(io.StringIO(text), delimiter="\t"): + value = word["text"].strip(" .,·…:").lower() + if not value: + continue + key = (word["block_num"], word["par_num"], word["line_num"]) + x = (int(word["left"]) + int(word["width"]) / 2) * width / image.width + y = (int(word["top"]) + int(word["height"]) / 2) * height / image.height + lines.setdefault(key, []).append((value, round(x), round(y))) + return path, list(lines.values()) + + +def locate(lines, phrase): + wanted = phrase.lower().split() + for line in lines: + for index in range(len(line) - len(wanted) + 1): + run = line[index:index + len(wanted)] + if [word[0] for word in run] == wanted: + return (round(sum(word[1] for word in run) / len(run)), run[0][2]) + return None + + +def step(name, ok, shot): + with (OUT / "steps.jsonl").open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"t": round(time.time() - T0, 2), "step": name, + "ok": bool(ok), "shot": shot.name}) + "\n") + print(("[ok] " if ok else "[FAILED] ") + name, flush=True) + if not ok: + raise RuntimeError(name) + + +def wait_for(name, phrase, present=True, timeout=12): + deadline = time.monotonic() + timeout + while True: + shot, lines = screen(name) + found = bool(locate(lines, phrase)) + if found == present or time.monotonic() >= deadline: + step(name, found == present, shot) + return lines + time.sleep(0.35) + + +def click_phrase(name, phrase): + shot, lines = screen(name) + point = locate(lines, phrase) + step(name, point is not None, shot) + if point is None: + raise RuntimeError("could not locate " + phrase) + pyautogui.click(*point) + time.sleep(0.8) + + +def toggle_section(name, phrase): + before, lines = screen(name + "-before") + point = locate(lines, phrase) + step(name + " header is visible", point is not None, before) + if point is None: + raise RuntimeError("could not locate " + phrase) + width, height = pyautogui.size() + away = (round(width * 0.9), round(height * 0.9)) + pyautogui.moveTo(*away) + time.sleep(0.2) + before, _ = screen(name + "-before-clean") + pyautogui.click(*point) + time.sleep(0.8) + pyautogui.moveTo(*away) + after, lines = screen(name + "-after") + with Image.open(before) as original, Image.open(after) as changed: + y = point[1] + box = (0, max(0, y - 16), min(500, original.width), min(original.height, y + 16)) + visually_changed = ImageChops.difference(original.crop(box), changed.crop(box)).getbbox() is not None + step(name + " toggles the section", visually_changed, after) + return lines + + +def main(): + OUT.mkdir(parents=True, exist_ok=True) + (OUT / "steps.jsonl").write_text("", encoding="utf-8") + for name in ("chatd", "tinyclient"): + if not binary(name).is_file(): + raise RuntimeError(name + " is missing from E2E_APP_DIR") + + with tempfile.TemporaryDirectory(prefix="network-home-sections-") as data: + env = dict(os.environ, TINYCLIENT_DIR=data, TINYCLIENT_LOG_LEVEL="info") + with (OUT / "chatd.log").open("w", encoding="utf-8") as log: + chatd = subprocess.Popen([str(binary("chatd")), "--seed-demo=live"], cwd=data, + env=env, stdout=log, stderr=subprocess.STDOUT, + creationflags=0x08000000 if PLATFORM == "windows" else 0) + app = None + try: + time.sleep(2) + with (OUT / "tinyclient.log").open("w", encoding="utf-8") as log: + app = subprocess.Popen([str(binary("tinyclient"))], cwd=data, env=env, + stdout=log, stderr=subprocess.STDOUT, + creationflags=0x08000000 if PLATFORM == "windows" else 0) + time.sleep(3) + pyautogui.hotkey("command" if PLATFORM == "macos" else "ctrl", "3") + deadline = time.monotonic() + 60 + initial = None + shot = OUT / "01-discord-home.png" + while time.monotonic() < deadline and app.poll() is None: + shot, lines = screen("01-discord-home") + voice = locate(lines, "In voice") + servers = locate(lines, "Servers") + dms = locate(lines, "Direct messages") + if voice and servers and dms: + initial = (shot, lines, voice, servers, dms) + break + time.sleep(0.5) + step("Discord home shows In voice, Servers, then Direct messages", + initial is not None and initial[2][1] < initial[3][1] < initial[4][1], + initial[0] if initial else shot) + if initial is None: + raise RuntimeError("Discord home sections did not appear") + + toggle_section("02-fold-in-voice", "In voice") + toggle_section("03-reopen-in-voice", "In voice") + click_phrase("04-fold-direct-messages", "Direct messages") + wait_for("05-direct-messages-folded", "Ines Marchetti", present=False) + wait_for("06-servers-remain-visible", "Moss & Lichen") + click_phrase("07-reopen-direct-messages", "Direct messages") + lines = wait_for("08-direct-messages-reopened", "Ines Marchetti") + source = locate(lines, "Direct messages") + target = locate(lines, "Servers") + step("both section headers are visible for reordering", source is not None and target is not None, + screen("09-before-reorder")[0]) + pyautogui.moveTo(*source) + pyautogui.mouseDown() + time.sleep(0.6) + pyautogui.moveTo(*target, duration=0.8) + time.sleep(0.4) + pyautogui.mouseUp() + time.sleep(1.2) + shot, lines = screen("10-reordered-dms") + servers = locate(lines, "Servers") + dms = locate(lines, "Direct messages") + step("Direct messages now appears above Servers", + servers is not None and dms is not None and dms[1] < servers[1], shot) + + source = locate(lines, "In voice") + target = locate(lines, "Direct messages") + step("In voice and Direct messages are visible for reordering", + source is not None and target is not None, + screen("11-before-reorder-voice")[0]) + pyautogui.moveTo(*source) + pyautogui.mouseDown() + time.sleep(0.6) + pyautogui.moveTo(*target, duration=0.8) + time.sleep(0.4) + pyautogui.mouseUp() + time.sleep(1.2) + shot, lines = screen("12-reordered-voice") + dms = locate(lines, "Direct messages") + voice = locate(lines, "In voice") + servers = locate(lines, "Servers") + step("In voice now appears between Direct messages and Servers", + dms is not None and voice is not None and servers is not None + and dms[1] < voice[1] < servers[1], shot) + + click_phrase("13-fold-servers", "Servers") + wait_for("14-servers-folded", "Moss & Lichen", present=False) + wait_for("15-direct-messages-remain-visible", "Ines Marchetti") + finally: + if app is not None and app.poll() is None: + app.terminate() + try: + app.wait(timeout=8) + except subprocess.TimeoutExpired: + app.kill() + app.wait(timeout=5) + if chatd.poll() is None: + chatd.terminate() + try: + chatd.wait(timeout=5) + except subprocess.TimeoutExpired: + chatd.kill() + chatd.wait(timeout=5) + + +if __name__ == "__main__": + main() diff --git a/e2e/scenarios/network-home-sections/drive.windows.ps1 b/e2e/scenarios/network-home-sections/drive.windows.ps1 new file mode 100644 index 00000000..d2a77f1a --- /dev/null +++ b/e2e/scenarios/network-home-sections/drive.windows.ps1 @@ -0,0 +1,16 @@ +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive windows + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive windows + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive windows + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/network-home-sections/scenario.json b/e2e/scenarios/network-home-sections/scenario.json new file mode 100644 index 00000000..e16c1d77 --- /dev/null +++ b/e2e/scenarios/network-home-sections/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "network-home-sections", + "title": "A Discord member folds and reorders the In voice, Servers, and Direct messages sections", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The Android home does not render the desktop Discord sidebar sections or support dragging them.", + "ios": "The iOS home does not render the desktop Discord sidebar sections or support dragging them." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}