collab_panel.rs

   1mod channel_modal;
   2mod contact_finder;
   3
   4use self::channel_modal::ChannelModal;
   5use crate::{CollaborationPanelSettings, channel_view::ChannelView};
   6use anyhow::Context as _;
   7use call::ActiveCall;
   8use channel::{Channel, ChannelEvent, ChannelStore};
   9use client::{ChannelId, Client, Contact, User, UserStore};
  10use collections::{HashMap, HashSet};
  11use contact_finder::ContactFinder;
  12use db::kvp::KEY_VALUE_STORE;
  13use editor::{Editor, EditorElement, EditorStyle};
  14use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
  15use gpui::{
  16    AnyElement, App, AsyncWindowContext, Bounds, ClickEvent, ClipboardItem, Context, DismissEvent,
  17    Div, Entity, EventEmitter, FocusHandle, Focusable, FontStyle, InteractiveElement, IntoElement,
  18    KeyContext, ListOffset, ListState, MouseDownEvent, ParentElement, Pixels, Point, PromptLevel,
  19    Render, SharedString, Styled, Subscription, Task, TextStyle, WeakEntity, Window, actions,
  20    anchored, canvas, deferred, div, fill, list, point, prelude::*, px,
  21};
  22use menu::{Cancel, Confirm, SecondaryConfirm, SelectNext, SelectPrevious};
  23use project::{Fs, Project};
  24use rpc::{
  25    ErrorCode, ErrorExt,
  26    proto::{self, ChannelVisibility, PeerId},
  27};
  28use serde::{Deserialize, Serialize};
  29use settings::Settings;
  30use smallvec::SmallVec;
  31use std::{mem, sync::Arc};
  32use theme::{ActiveTheme, ThemeSettings};
  33use ui::{
  34    Avatar, AvatarAvailabilityIndicator, Button, Color, ContextMenu, Facepile, HighlightedLabel,
  35    Icon, IconButton, IconName, IconSize, Indicator, Label, ListHeader, ListItem, Tab, Tooltip,
  36    prelude::*, tooltip_container,
  37};
  38use util::{ResultExt, TryFutureExt, maybe};
  39use workspace::{
  40    CopyRoomId, Deafen, LeaveCall, Mute, OpenChannelNotes, ScreenShare, ShareProject, Workspace,
  41    dock::{DockPosition, Panel, PanelEvent},
  42    notifications::{DetachAndPromptErr, NotifyResultExt},
  43};
  44
  45actions!(
  46    collab_panel,
  47    [
  48        /// Toggles focus on the collaboration panel.
  49        ToggleFocus,
  50        /// Removes the selected channel or contact.
  51        Remove,
  52        /// Opens the context menu for the selected item.
  53        Secondary,
  54        /// Collapses the selected channel in the tree view.
  55        CollapseSelectedChannel,
  56        /// Expands the selected channel in the tree view.
  57        ExpandSelectedChannel,
  58        /// Opens the meeting notes for the selected channel in the panel.
  59        ///
  60        /// Use `collab::OpenChannelNotes` to open the channel notes for the current call.
  61        OpenSelectedChannelNotes,
  62        /// Starts moving a channel to a new location.
  63        StartMoveChannel,
  64        /// Moves the selected item to the current location.
  65        MoveSelected,
  66        /// Inserts a space character in the filter input.
  67        InsertSpace,
  68        /// Moves the selected channel up in the list.
  69        MoveChannelUp,
  70        /// Moves the selected channel down in the list.
  71        MoveChannelDown,
  72    ]
  73);
  74
  75#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  76struct ChannelMoveClipboard {
  77    channel_id: ChannelId,
  78}
  79
  80const COLLABORATION_PANEL_KEY: &str = "CollaborationPanel";
  81
  82pub fn init(cx: &mut App) {
  83    cx.observe_new(|workspace: &mut Workspace, _, _| {
  84        workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
  85            workspace.toggle_panel_focus::<CollabPanel>(window, cx);
  86            if let Some(collab_panel) = workspace.panel::<CollabPanel>(cx) {
  87                collab_panel.update(cx, |panel, cx| {
  88                    panel.filter_editor.update(cx, |editor, cx| {
  89                        if editor.snapshot(window, cx).is_focused() {
  90                            editor.select_all(&Default::default(), window, cx);
  91                        }
  92                    });
  93                })
  94            }
  95        });
  96        workspace.register_action(|_, _: &OpenChannelNotes, window, cx| {
  97            let channel_id = ActiveCall::global(cx)
  98                .read(cx)
  99                .room()
 100                .and_then(|room| room.read(cx).channel_id());
 101
 102            if let Some(channel_id) = channel_id {
 103                let workspace = cx.entity();
 104                window.defer(cx, move |window, cx| {
 105                    ChannelView::open(channel_id, None, workspace, window, cx)
 106                        .detach_and_log_err(cx)
 107                });
 108            }
 109        });
 110        // TODO: make it possible to bind this one to a held key for push to talk?
 111        // how to make "toggle_on_modifiers_press" contextual?
 112        workspace.register_action(|_, _: &Mute, window, cx| {
 113            let room = ActiveCall::global(cx).read(cx).room().cloned();
 114            if let Some(room) = room {
 115                window.defer(cx, move |_window, cx| {
 116                    room.update(cx, |room, cx| room.toggle_mute(cx))
 117                });
 118            }
 119        });
 120        workspace.register_action(|_, _: &Deafen, window, cx| {
 121            let room = ActiveCall::global(cx).read(cx).room().cloned();
 122            if let Some(room) = room {
 123                window.defer(cx, move |_window, cx| {
 124                    room.update(cx, |room, cx| room.toggle_deafen(cx))
 125                });
 126            }
 127        });
 128        workspace.register_action(|_, _: &LeaveCall, window, cx| {
 129            CollabPanel::leave_call(window, cx);
 130        });
 131        workspace.register_action(|workspace, _: &CopyRoomId, window, cx| {
 132            use workspace::notifications::{NotificationId, NotifyTaskExt as _};
 133
 134            struct RoomIdCopiedToast;
 135
 136            if let Some(room) = ActiveCall::global(cx).read(cx).room() {
 137                let romo_id_fut = room.read(cx).room_id();
 138                cx.spawn(async move |workspace, cx| {
 139                    let room_id = romo_id_fut.await.context("Failed to get livekit room")?;
 140                    workspace.update(cx, |workspace, cx| {
 141                        cx.write_to_clipboard(ClipboardItem::new_string(room_id));
 142                        workspace.show_toast(
 143                            workspace::Toast::new(
 144                                NotificationId::unique::<RoomIdCopiedToast>(),
 145                                "Room ID copied to clipboard",
 146                            )
 147                            .autohide(),
 148                            cx,
 149                        );
 150                    })
 151                })
 152                .detach_and_notify_err(window, cx);
 153            } else {
 154                workspace.show_error(&"There’s no active call; join one first.", cx);
 155            }
 156        });
 157        workspace.register_action(|workspace, _: &ShareProject, window, cx| {
 158            let project = workspace.project().clone();
 159            println!("{project:?}");
 160            window.defer(cx, move |_window, cx| {
 161                ActiveCall::global(cx).update(cx, move |call, cx| {
 162                    if let Some(room) = call.room() {
 163                        println!("{room:?}");
 164                        if room.read(cx).is_sharing_project() {
 165                            call.unshare_project(project, cx).ok();
 166                        } else {
 167                            call.share_project(project, cx).detach_and_log_err(cx);
 168                        }
 169                    }
 170                });
 171            });
 172        });
 173        workspace.register_action(|_, _: &ScreenShare, window, cx| {
 174            let room = ActiveCall::global(cx).read(cx).room().cloned();
 175            if let Some(room) = room {
 176                window.defer(cx, move |_window, cx| {
 177                    room.update(cx, |room, cx| {
 178                        if room.is_sharing_screen() {
 179                            room.unshare_screen(true, cx).ok();
 180                        } else {
 181                            let sources = cx.screen_capture_sources();
 182
 183                            cx.spawn(async move |room, cx| {
 184                                let sources = sources.await??;
 185                                let first = sources.into_iter().next();
 186                                if let Some(first) = first {
 187                                    room.update(cx, |room, cx| room.share_screen(first, cx))?
 188                                        .await
 189                                } else {
 190                                    Ok(())
 191                                }
 192                            })
 193                            .detach_and_log_err(cx);
 194                        };
 195                    });
 196                });
 197            }
 198        });
 199    })
 200    .detach();
 201}
 202
 203#[derive(Debug)]
 204pub enum ChannelEditingState {
 205    Create {
 206        location: Option<ChannelId>,
 207        pending_name: Option<String>,
 208    },
 209    Rename {
 210        location: ChannelId,
 211        pending_name: Option<String>,
 212    },
 213}
 214
 215impl ChannelEditingState {
 216    fn pending_name(&self) -> Option<String> {
 217        match self {
 218            ChannelEditingState::Create { pending_name, .. } => pending_name.clone(),
 219            ChannelEditingState::Rename { pending_name, .. } => pending_name.clone(),
 220        }
 221    }
 222}
 223
 224pub struct CollabPanel {
 225    width: Option<Pixels>,
 226    fs: Arc<dyn Fs>,
 227    focus_handle: FocusHandle,
 228    channel_clipboard: Option<ChannelMoveClipboard>,
 229    pending_serialization: Task<Option<()>>,
 230    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 231    list_state: ListState,
 232    filter_editor: Entity<Editor>,
 233    channel_name_editor: Entity<Editor>,
 234    channel_editing_state: Option<ChannelEditingState>,
 235    entries: Vec<ListEntry>,
 236    selection: Option<usize>,
 237    channel_store: Entity<ChannelStore>,
 238    user_store: Entity<UserStore>,
 239    client: Arc<Client>,
 240    project: Entity<Project>,
 241    match_candidates: Vec<StringMatchCandidate>,
 242    subscriptions: Vec<Subscription>,
 243    collapsed_sections: Vec<Section>,
 244    collapsed_channels: Vec<ChannelId>,
 245    workspace: WeakEntity<Workspace>,
 246}
 247
 248#[derive(Serialize, Deserialize)]
 249struct SerializedCollabPanel {
 250    width: Option<Pixels>,
 251    collapsed_channels: Option<Vec<u64>>,
 252}
 253
 254#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
 255enum Section {
 256    ActiveCall,
 257    Channels,
 258    ChannelInvites,
 259    ContactRequests,
 260    Contacts,
 261    Online,
 262    Offline,
 263}
 264
 265#[derive(Clone, Debug)]
 266enum ListEntry {
 267    Header(Section),
 268    CallParticipant {
 269        user: Arc<User>,
 270        peer_id: Option<PeerId>,
 271        is_pending: bool,
 272        role: proto::ChannelRole,
 273    },
 274    ParticipantProject {
 275        project_id: u64,
 276        worktree_root_names: Vec<String>,
 277        host_user_id: u64,
 278        is_last: bool,
 279    },
 280    ParticipantScreen {
 281        peer_id: Option<PeerId>,
 282        is_last: bool,
 283    },
 284    IncomingRequest(Arc<User>),
 285    OutgoingRequest(Arc<User>),
 286    ChannelInvite(Arc<Channel>),
 287    Channel {
 288        channel: Arc<Channel>,
 289        depth: usize,
 290        has_children: bool,
 291        // `None` when the channel is a parent of a matched channel.
 292        string_match: Option<StringMatch>,
 293    },
 294    ChannelNotes {
 295        channel_id: ChannelId,
 296    },
 297    ChannelEditor {
 298        depth: usize,
 299    },
 300    Contact {
 301        contact: Arc<Contact>,
 302        calling: bool,
 303    },
 304    ContactPlaceholder,
 305}
 306
 307impl CollabPanel {
 308    pub fn new(
 309        workspace: &mut Workspace,
 310        window: &mut Window,
 311        cx: &mut Context<Workspace>,
 312    ) -> Entity<Self> {
 313        cx.new(|cx| {
 314            let filter_editor = cx.new(|cx| {
 315                let mut editor = Editor::single_line(window, cx);
 316                editor.set_placeholder_text("Search channels…", window, cx);
 317                editor
 318            });
 319
 320            cx.subscribe(&filter_editor, |this: &mut Self, _, event, cx| {
 321                if let editor::EditorEvent::BufferEdited = event {
 322                    let query = this.filter_editor.read(cx).text(cx);
 323                    if !query.is_empty() {
 324                        this.selection.take();
 325                    }
 326                    this.update_entries(true, cx);
 327                    if !query.is_empty() {
 328                        this.selection = this
 329                            .entries
 330                            .iter()
 331                            .position(|entry| !matches!(entry, ListEntry::Header(_)));
 332                    }
 333                }
 334            })
 335            .detach();
 336
 337            let channel_name_editor = cx.new(|cx| Editor::single_line(window, cx));
 338
 339            cx.subscribe_in(
 340                &channel_name_editor,
 341                window,
 342                |this: &mut Self, _, event, window, cx| {
 343                    if let editor::EditorEvent::Blurred = event {
 344                        if let Some(state) = &this.channel_editing_state
 345                            && state.pending_name().is_some()
 346                        {
 347                            return;
 348                        }
 349                        this.take_editing_state(window, cx);
 350                        this.update_entries(false, cx);
 351                        cx.notify();
 352                    }
 353                },
 354            )
 355            .detach();
 356
 357            let mut this = Self {
 358                width: None,
 359                focus_handle: cx.focus_handle(),
 360                channel_clipboard: None,
 361                fs: workspace.app_state().fs.clone(),
 362                pending_serialization: Task::ready(None),
 363                context_menu: None,
 364                list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)),
 365                channel_name_editor,
 366                filter_editor,
 367                entries: Vec::default(),
 368                channel_editing_state: None,
 369                selection: None,
 370                channel_store: ChannelStore::global(cx),
 371                user_store: workspace.user_store().clone(),
 372                project: workspace.project().clone(),
 373                subscriptions: Vec::default(),
 374                match_candidates: Vec::default(),
 375                collapsed_sections: vec![Section::Offline],
 376                collapsed_channels: Vec::default(),
 377                workspace: workspace.weak_handle(),
 378                client: workspace.app_state().client.clone(),
 379            };
 380
 381            this.update_entries(false, cx);
 382
 383            let active_call = ActiveCall::global(cx);
 384            this.subscriptions
 385                .push(cx.observe(&this.user_store, |this, _, cx| {
 386                    this.update_entries(true, cx)
 387                }));
 388            this.subscriptions
 389                .push(cx.observe(&this.channel_store, move |this, _, cx| {
 390                    this.update_entries(true, cx)
 391                }));
 392            this.subscriptions
 393                .push(cx.observe(&active_call, |this, _, cx| this.update_entries(true, cx)));
 394            this.subscriptions.push(cx.subscribe_in(
 395                &this.channel_store,
 396                window,
 397                |this, _channel_store, e, window, cx| match e {
 398                    ChannelEvent::ChannelCreated(channel_id)
 399                    | ChannelEvent::ChannelRenamed(channel_id) => {
 400                        if this.take_editing_state(window, cx) {
 401                            this.update_entries(false, cx);
 402                            this.selection = this.entries.iter().position(|entry| {
 403                                if let ListEntry::Channel { channel, .. } = entry {
 404                                    channel.id == *channel_id
 405                                } else {
 406                                    false
 407                                }
 408                            });
 409                        }
 410                    }
 411                },
 412            ));
 413
 414            this
 415        })
 416    }
 417
 418    pub async fn load(
 419        workspace: WeakEntity<Workspace>,
 420        mut cx: AsyncWindowContext,
 421    ) -> anyhow::Result<Entity<Self>> {
 422        let serialized_panel = match workspace
 423            .read_with(&cx, |workspace, _| {
 424                CollabPanel::serialization_key(workspace)
 425            })
 426            .ok()
 427            .flatten()
 428        {
 429            Some(serialization_key) => cx
 430                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 431                .await
 432                .context("reading collaboration panel from key value store")
 433                .log_err()
 434                .flatten()
 435                .map(|panel| serde_json::from_str::<SerializedCollabPanel>(&panel))
 436                .transpose()
 437                .log_err()
 438                .flatten(),
 439            None => None,
 440        };
 441
 442        workspace.update_in(&mut cx, |workspace, window, cx| {
 443            let panel = CollabPanel::new(workspace, window, cx);
 444            if let Some(serialized_panel) = serialized_panel {
 445                panel.update(cx, |panel, cx| {
 446                    panel.width = serialized_panel.width.map(|w| w.round());
 447                    panel.collapsed_channels = serialized_panel
 448                        .collapsed_channels
 449                        .unwrap_or_else(Vec::new)
 450                        .iter()
 451                        .map(|cid| ChannelId(*cid))
 452                        .collect();
 453                    cx.notify();
 454                });
 455            }
 456            panel
 457        })
 458    }
 459
 460    fn serialization_key(workspace: &Workspace) -> Option<String> {
 461        workspace
 462            .database_id()
 463            .map(|id| i64::from(id).to_string())
 464            .or(workspace.session_id())
 465            .map(|id| format!("{}-{:?}", COLLABORATION_PANEL_KEY, id))
 466    }
 467
 468    fn serialize(&mut self, cx: &mut Context<Self>) {
 469        let Some(serialization_key) = self
 470            .workspace
 471            .read_with(cx, |workspace, _| CollabPanel::serialization_key(workspace))
 472            .ok()
 473            .flatten()
 474        else {
 475            return;
 476        };
 477        let width = self.width;
 478        let collapsed_channels = self.collapsed_channels.clone();
 479        self.pending_serialization = cx.background_spawn(
 480            async move {
 481                KEY_VALUE_STORE
 482                    .write_kvp(
 483                        serialization_key,
 484                        serde_json::to_string(&SerializedCollabPanel {
 485                            width,
 486                            collapsed_channels: Some(
 487                                collapsed_channels.iter().map(|cid| cid.0).collect(),
 488                            ),
 489                        })?,
 490                    )
 491                    .await?;
 492                anyhow::Ok(())
 493            }
 494            .log_err(),
 495        );
 496    }
 497
 498    fn scroll_to_item(&mut self, ix: usize) {
 499        self.list_state.scroll_to_reveal_item(ix)
 500    }
 501
 502    fn update_entries(&mut self, select_same_item: bool, cx: &mut Context<Self>) {
 503        let channel_store = self.channel_store.read(cx);
 504        let user_store = self.user_store.read(cx);
 505        let query = self.filter_editor.read(cx).text(cx);
 506        let executor = cx.background_executor().clone();
 507
 508        let prev_selected_entry = self.selection.and_then(|ix| self.entries.get(ix).cloned());
 509        let old_entries = mem::take(&mut self.entries);
 510        let mut scroll_to_top = false;
 511
 512        if let Some(room) = ActiveCall::global(cx).read(cx).room() {
 513            self.entries.push(ListEntry::Header(Section::ActiveCall));
 514            if !old_entries
 515                .iter()
 516                .any(|entry| matches!(entry, ListEntry::Header(Section::ActiveCall)))
 517            {
 518                scroll_to_top = true;
 519            }
 520
 521            if !self.collapsed_sections.contains(&Section::ActiveCall) {
 522                let room = room.read(cx);
 523
 524                if query.is_empty()
 525                    && let Some(channel_id) = room.channel_id()
 526                {
 527                    self.entries.push(ListEntry::ChannelNotes { channel_id });
 528                }
 529
 530                // Populate the active user.
 531                if let Some(user) = user_store.current_user() {
 532                    self.match_candidates.clear();
 533                    self.match_candidates
 534                        .push(StringMatchCandidate::new(0, &user.github_login));
 535                    let matches = executor.block(match_strings(
 536                        &self.match_candidates,
 537                        &query,
 538                        true,
 539                        true,
 540                        usize::MAX,
 541                        &Default::default(),
 542                        executor.clone(),
 543                    ));
 544                    if !matches.is_empty() {
 545                        let user_id = user.id;
 546                        self.entries.push(ListEntry::CallParticipant {
 547                            user,
 548                            peer_id: None,
 549                            is_pending: false,
 550                            role: room.local_participant().role,
 551                        });
 552                        let mut projects = room.local_participant().projects.iter().peekable();
 553                        while let Some(project) = projects.next() {
 554                            self.entries.push(ListEntry::ParticipantProject {
 555                                project_id: project.id,
 556                                worktree_root_names: project.worktree_root_names.clone(),
 557                                host_user_id: user_id,
 558                                is_last: projects.peek().is_none() && !room.is_sharing_screen(),
 559                            });
 560                        }
 561                        if room.is_sharing_screen() {
 562                            self.entries.push(ListEntry::ParticipantScreen {
 563                                peer_id: None,
 564                                is_last: true,
 565                            });
 566                        }
 567                    }
 568                }
 569
 570                // Populate remote participants.
 571                self.match_candidates.clear();
 572                self.match_candidates
 573                    .extend(room.remote_participants().values().map(|participant| {
 574                        StringMatchCandidate::new(
 575                            participant.user.id as usize,
 576                            &participant.user.github_login,
 577                        )
 578                    }));
 579                let mut matches = executor.block(match_strings(
 580                    &self.match_candidates,
 581                    &query,
 582                    true,
 583                    true,
 584                    usize::MAX,
 585                    &Default::default(),
 586                    executor.clone(),
 587                ));
 588                matches.sort_by(|a, b| {
 589                    let a_is_guest = room.role_for_user(a.candidate_id as u64)
 590                        == Some(proto::ChannelRole::Guest);
 591                    let b_is_guest = room.role_for_user(b.candidate_id as u64)
 592                        == Some(proto::ChannelRole::Guest);
 593                    a_is_guest
 594                        .cmp(&b_is_guest)
 595                        .then_with(|| a.string.cmp(&b.string))
 596                });
 597                for mat in matches {
 598                    let user_id = mat.candidate_id as u64;
 599                    let participant = &room.remote_participants()[&user_id];
 600                    self.entries.push(ListEntry::CallParticipant {
 601                        user: participant.user.clone(),
 602                        peer_id: Some(participant.peer_id),
 603                        is_pending: false,
 604                        role: participant.role,
 605                    });
 606                    let mut projects = participant.projects.iter().peekable();
 607                    while let Some(project) = projects.next() {
 608                        self.entries.push(ListEntry::ParticipantProject {
 609                            project_id: project.id,
 610                            worktree_root_names: project.worktree_root_names.clone(),
 611                            host_user_id: participant.user.id,
 612                            is_last: projects.peek().is_none() && !participant.has_video_tracks(),
 613                        });
 614                    }
 615                    if participant.has_video_tracks() {
 616                        self.entries.push(ListEntry::ParticipantScreen {
 617                            peer_id: Some(participant.peer_id),
 618                            is_last: true,
 619                        });
 620                    }
 621                }
 622
 623                // Populate pending participants.
 624                self.match_candidates.clear();
 625                self.match_candidates
 626                    .extend(room.pending_participants().iter().enumerate().map(
 627                        |(id, participant)| {
 628                            StringMatchCandidate::new(id, &participant.github_login)
 629                        },
 630                    ));
 631                let matches = executor.block(match_strings(
 632                    &self.match_candidates,
 633                    &query,
 634                    true,
 635                    true,
 636                    usize::MAX,
 637                    &Default::default(),
 638                    executor.clone(),
 639                ));
 640                self.entries
 641                    .extend(matches.iter().map(|mat| ListEntry::CallParticipant {
 642                        user: room.pending_participants()[mat.candidate_id].clone(),
 643                        peer_id: None,
 644                        is_pending: true,
 645                        role: proto::ChannelRole::Member,
 646                    }));
 647            }
 648        }
 649
 650        let mut request_entries = Vec::new();
 651
 652        self.entries.push(ListEntry::Header(Section::Channels));
 653
 654        if channel_store.channel_count() > 0 || self.channel_editing_state.is_some() {
 655            self.match_candidates.clear();
 656            self.match_candidates.extend(
 657                channel_store
 658                    .ordered_channels()
 659                    .enumerate()
 660                    .map(|(ix, (_, channel))| StringMatchCandidate::new(ix, &channel.name)),
 661            );
 662            let mut channels = channel_store
 663                .ordered_channels()
 664                .map(|(_, chan)| chan)
 665                .collect::<Vec<_>>();
 666            let matches = executor.block(match_strings(
 667                &self.match_candidates,
 668                &query,
 669                true,
 670                true,
 671                usize::MAX,
 672                &Default::default(),
 673                executor.clone(),
 674            ));
 675
 676            let matches_by_id: HashMap<_, _> = matches
 677                .iter()
 678                .map(|mat| (channels[mat.candidate_id].id, mat.clone()))
 679                .collect();
 680
 681            let channel_ids_of_matches_or_parents: HashSet<_> = matches
 682                .iter()
 683                .flat_map(|mat| {
 684                    let match_channel = channels[mat.candidate_id];
 685
 686                    match_channel
 687                        .parent_path
 688                        .iter()
 689                        .copied()
 690                        .chain(Some(match_channel.id))
 691                })
 692                .collect();
 693
 694            channels.retain(|chan| channel_ids_of_matches_or_parents.contains(&chan.id));
 695
 696            if let Some(state) = &self.channel_editing_state
 697                && matches!(state, ChannelEditingState::Create { location: None, .. })
 698            {
 699                self.entries.push(ListEntry::ChannelEditor { depth: 0 });
 700            }
 701
 702            let should_respect_collapse = query.is_empty();
 703            let mut collapse_depth = None;
 704
 705            for (idx, channel) in channels.into_iter().enumerate() {
 706                let depth = channel.parent_path.len();
 707
 708                if should_respect_collapse {
 709                    if collapse_depth.is_none() && self.is_channel_collapsed(channel.id) {
 710                        collapse_depth = Some(depth);
 711                    } else if let Some(collapsed_depth) = collapse_depth {
 712                        if depth > collapsed_depth {
 713                            continue;
 714                        }
 715                        if self.is_channel_collapsed(channel.id) {
 716                            collapse_depth = Some(depth);
 717                        } else {
 718                            collapse_depth = None;
 719                        }
 720                    }
 721                }
 722
 723                let has_children = channel_store
 724                    .channel_at_index(idx + 1)
 725                    .is_some_and(|next_channel| next_channel.parent_path.ends_with(&[channel.id]));
 726
 727                match &self.channel_editing_state {
 728                    Some(ChannelEditingState::Create {
 729                        location: parent_id,
 730                        ..
 731                    }) if *parent_id == Some(channel.id) => {
 732                        self.entries.push(ListEntry::Channel {
 733                            channel: channel.clone(),
 734                            depth,
 735                            has_children: false,
 736                            string_match: matches_by_id.get(&channel.id).map(|mat| (*mat).clone()),
 737                        });
 738                        self.entries
 739                            .push(ListEntry::ChannelEditor { depth: depth + 1 });
 740                    }
 741                    Some(ChannelEditingState::Rename {
 742                        location: parent_id,
 743                        ..
 744                    }) if parent_id == &channel.id => {
 745                        self.entries.push(ListEntry::ChannelEditor { depth });
 746                    }
 747                    _ => {
 748                        self.entries.push(ListEntry::Channel {
 749                            channel: channel.clone(),
 750                            depth,
 751                            has_children,
 752                            string_match: matches_by_id.get(&channel.id).map(|mat| (*mat).clone()),
 753                        });
 754                    }
 755                }
 756            }
 757        }
 758
 759        let channel_invites = channel_store.channel_invitations();
 760        if !channel_invites.is_empty() {
 761            self.match_candidates.clear();
 762            self.match_candidates.extend(
 763                channel_invites
 764                    .iter()
 765                    .enumerate()
 766                    .map(|(ix, channel)| StringMatchCandidate::new(ix, &channel.name)),
 767            );
 768            let matches = executor.block(match_strings(
 769                &self.match_candidates,
 770                &query,
 771                true,
 772                true,
 773                usize::MAX,
 774                &Default::default(),
 775                executor.clone(),
 776            ));
 777            request_entries.extend(
 778                matches
 779                    .iter()
 780                    .map(|mat| ListEntry::ChannelInvite(channel_invites[mat.candidate_id].clone())),
 781            );
 782
 783            if !request_entries.is_empty() {
 784                self.entries
 785                    .push(ListEntry::Header(Section::ChannelInvites));
 786                if !self.collapsed_sections.contains(&Section::ChannelInvites) {
 787                    self.entries.append(&mut request_entries);
 788                }
 789            }
 790        }
 791
 792        self.entries.push(ListEntry::Header(Section::Contacts));
 793
 794        request_entries.clear();
 795        let incoming = user_store.incoming_contact_requests();
 796        if !incoming.is_empty() {
 797            self.match_candidates.clear();
 798            self.match_candidates.extend(
 799                incoming
 800                    .iter()
 801                    .enumerate()
 802                    .map(|(ix, user)| StringMatchCandidate::new(ix, &user.github_login)),
 803            );
 804            let matches = executor.block(match_strings(
 805                &self.match_candidates,
 806                &query,
 807                true,
 808                true,
 809                usize::MAX,
 810                &Default::default(),
 811                executor.clone(),
 812            ));
 813            request_entries.extend(
 814                matches
 815                    .iter()
 816                    .map(|mat| ListEntry::IncomingRequest(incoming[mat.candidate_id].clone())),
 817            );
 818        }
 819
 820        let outgoing = user_store.outgoing_contact_requests();
 821        if !outgoing.is_empty() {
 822            self.match_candidates.clear();
 823            self.match_candidates.extend(
 824                outgoing
 825                    .iter()
 826                    .enumerate()
 827                    .map(|(ix, user)| StringMatchCandidate::new(ix, &user.github_login)),
 828            );
 829            let matches = executor.block(match_strings(
 830                &self.match_candidates,
 831                &query,
 832                true,
 833                true,
 834                usize::MAX,
 835                &Default::default(),
 836                executor.clone(),
 837            ));
 838            request_entries.extend(
 839                matches
 840                    .iter()
 841                    .map(|mat| ListEntry::OutgoingRequest(outgoing[mat.candidate_id].clone())),
 842            );
 843        }
 844
 845        if !request_entries.is_empty() {
 846            self.entries
 847                .push(ListEntry::Header(Section::ContactRequests));
 848            if !self.collapsed_sections.contains(&Section::ContactRequests) {
 849                self.entries.append(&mut request_entries);
 850            }
 851        }
 852
 853        let contacts = user_store.contacts();
 854        if !contacts.is_empty() {
 855            self.match_candidates.clear();
 856            self.match_candidates.extend(
 857                contacts
 858                    .iter()
 859                    .enumerate()
 860                    .map(|(ix, contact)| StringMatchCandidate::new(ix, &contact.user.github_login)),
 861            );
 862
 863            let matches = executor.block(match_strings(
 864                &self.match_candidates,
 865                &query,
 866                true,
 867                true,
 868                usize::MAX,
 869                &Default::default(),
 870                executor.clone(),
 871            ));
 872
 873            let (online_contacts, offline_contacts) = matches
 874                .iter()
 875                .partition::<Vec<_>, _>(|mat| contacts[mat.candidate_id].online);
 876
 877            for (matches, section) in [
 878                (online_contacts, Section::Online),
 879                (offline_contacts, Section::Offline),
 880            ] {
 881                if !matches.is_empty() {
 882                    self.entries.push(ListEntry::Header(section));
 883                    if !self.collapsed_sections.contains(&section) {
 884                        let active_call = &ActiveCall::global(cx).read(cx);
 885                        for mat in matches {
 886                            let contact = &contacts[mat.candidate_id];
 887                            self.entries.push(ListEntry::Contact {
 888                                contact: contact.clone(),
 889                                calling: active_call.pending_invites().contains(&contact.user.id),
 890                            });
 891                        }
 892                    }
 893                }
 894            }
 895        }
 896
 897        if incoming.is_empty() && outgoing.is_empty() && contacts.is_empty() {
 898            self.entries.push(ListEntry::ContactPlaceholder);
 899        }
 900
 901        if select_same_item {
 902            if let Some(prev_selected_entry) = prev_selected_entry {
 903                self.selection.take();
 904                for (ix, entry) in self.entries.iter().enumerate() {
 905                    if *entry == prev_selected_entry {
 906                        self.selection = Some(ix);
 907                        break;
 908                    }
 909                }
 910            }
 911        } else {
 912            self.selection = self.selection.and_then(|prev_selection| {
 913                if self.entries.is_empty() {
 914                    None
 915                } else {
 916                    Some(prev_selection.min(self.entries.len() - 1))
 917                }
 918            });
 919        }
 920
 921        let old_scroll_top = self.list_state.logical_scroll_top();
 922        self.list_state.reset(self.entries.len());
 923
 924        if scroll_to_top {
 925            self.list_state.scroll_to(ListOffset::default());
 926        } else {
 927            // Attempt to maintain the same scroll position.
 928            if let Some(old_top_entry) = old_entries.get(old_scroll_top.item_ix) {
 929                let new_scroll_top = self
 930                    .entries
 931                    .iter()
 932                    .position(|entry| entry == old_top_entry)
 933                    .map(|item_ix| ListOffset {
 934                        item_ix,
 935                        offset_in_item: old_scroll_top.offset_in_item,
 936                    })
 937                    .or_else(|| {
 938                        let entry_after_old_top = old_entries.get(old_scroll_top.item_ix + 1)?;
 939                        let item_ix = self
 940                            .entries
 941                            .iter()
 942                            .position(|entry| entry == entry_after_old_top)?;
 943                        Some(ListOffset {
 944                            item_ix,
 945                            offset_in_item: Pixels::ZERO,
 946                        })
 947                    })
 948                    .or_else(|| {
 949                        let entry_before_old_top =
 950                            old_entries.get(old_scroll_top.item_ix.saturating_sub(1))?;
 951                        let item_ix = self
 952                            .entries
 953                            .iter()
 954                            .position(|entry| entry == entry_before_old_top)?;
 955                        Some(ListOffset {
 956                            item_ix,
 957                            offset_in_item: Pixels::ZERO,
 958                        })
 959                    });
 960
 961                self.list_state
 962                    .scroll_to(new_scroll_top.unwrap_or(old_scroll_top));
 963            }
 964        }
 965
 966        cx.notify();
 967    }
 968
 969    fn render_call_participant(
 970        &self,
 971        user: &Arc<User>,
 972        peer_id: Option<PeerId>,
 973        is_pending: bool,
 974        role: proto::ChannelRole,
 975        is_selected: bool,
 976        cx: &mut Context<Self>,
 977    ) -> ListItem {
 978        let user_id = user.id;
 979        let is_current_user =
 980            self.user_store.read(cx).current_user().map(|user| user.id) == Some(user_id);
 981        let tooltip = format!("Follow {}", user.github_login);
 982
 983        let is_call_admin = ActiveCall::global(cx).read(cx).room().is_some_and(|room| {
 984            room.read(cx).local_participant().role == proto::ChannelRole::Admin
 985        });
 986
 987        ListItem::new(user.github_login.clone())
 988            .start_slot(Avatar::new(user.avatar_uri.clone()))
 989            .child(render_participant_name_and_handle(user))
 990            .toggle_state(is_selected)
 991            .end_slot(if is_pending {
 992                Label::new("Calling").color(Color::Muted).into_any_element()
 993            } else if is_current_user {
 994                IconButton::new("leave-call", IconName::Exit)
 995                    .style(ButtonStyle::Subtle)
 996                    .on_click(move |_, window, cx| Self::leave_call(window, cx))
 997                    .tooltip(Tooltip::text("Leave Call"))
 998                    .into_any_element()
 999            } else if role == proto::ChannelRole::Guest {
1000                Label::new("Guest").color(Color::Muted).into_any_element()
1001            } else if role == proto::ChannelRole::Talker {
1002                Label::new("Mic only")
1003                    .color(Color::Muted)
1004                    .into_any_element()
1005            } else {
1006                div().into_any_element()
1007            })
1008            .when_some(peer_id, |el, peer_id| {
1009                if role == proto::ChannelRole::Guest {
1010                    return el;
1011                }
1012                el.tooltip(Tooltip::text(tooltip.clone()))
1013                    .on_click(cx.listener(move |this, _, window, cx| {
1014                        this.workspace
1015                            .update(cx, |workspace, cx| workspace.follow(peer_id, window, cx))
1016                            .ok();
1017                    }))
1018            })
1019            .when(is_call_admin, |el| {
1020                el.on_secondary_mouse_down(cx.listener(
1021                    move |this, event: &MouseDownEvent, window, cx| {
1022                        this.deploy_participant_context_menu(
1023                            event.position,
1024                            user_id,
1025                            role,
1026                            window,
1027                            cx,
1028                        )
1029                    },
1030                ))
1031            })
1032    }
1033
1034    fn render_participant_project(
1035        &self,
1036        project_id: u64,
1037        worktree_root_names: &[String],
1038        host_user_id: u64,
1039        is_last: bool,
1040        is_selected: bool,
1041        window: &mut Window,
1042        cx: &mut Context<Self>,
1043    ) -> impl IntoElement {
1044        let project_name: SharedString = if worktree_root_names.is_empty() {
1045            "untitled".to_string()
1046        } else {
1047            worktree_root_names.join(", ")
1048        }
1049        .into();
1050
1051        ListItem::new(project_id as usize)
1052            .toggle_state(is_selected)
1053            .on_click(cx.listener(move |this, _, window, cx| {
1054                this.workspace
1055                    .update(cx, |workspace, cx| {
1056                        let app_state = workspace.app_state().clone();
1057                        workspace::join_in_room_project(project_id, host_user_id, app_state, cx)
1058                            .detach_and_prompt_err(
1059                                "Failed to join project",
1060                                window,
1061                                cx,
1062                                |_, _, _| None,
1063                            );
1064                    })
1065                    .ok();
1066            }))
1067            .start_slot(
1068                h_flex()
1069                    .gap_1()
1070                    .child(render_tree_branch(is_last, false, window, cx))
1071                    .child(IconButton::new(0, IconName::Folder)),
1072            )
1073            .child(Label::new(project_name.clone()))
1074            .tooltip(Tooltip::text(format!("Open {}", project_name)))
1075    }
1076
1077    fn render_participant_screen(
1078        &self,
1079        peer_id: Option<PeerId>,
1080        is_last: bool,
1081        is_selected: bool,
1082        window: &mut Window,
1083        cx: &mut Context<Self>,
1084    ) -> impl IntoElement {
1085        let id = peer_id.map_or(usize::MAX, |id| id.as_u64() as usize);
1086
1087        ListItem::new(("screen", id))
1088            .toggle_state(is_selected)
1089            .start_slot(
1090                h_flex()
1091                    .gap_1()
1092                    .child(render_tree_branch(is_last, false, window, cx))
1093                    .child(IconButton::new(0, IconName::Screen)),
1094            )
1095            .child(Label::new("Screen"))
1096            .when_some(peer_id, |this, _| {
1097                this.on_click(cx.listener(move |this, _, window, cx| {
1098                    this.workspace
1099                        .update(cx, |workspace, cx| {
1100                            workspace.open_shared_screen(peer_id.unwrap(), window, cx)
1101                        })
1102                        .ok();
1103                }))
1104                .tooltip(Tooltip::text("Open shared screen"))
1105            })
1106    }
1107
1108    fn take_editing_state(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1109        if self.channel_editing_state.take().is_some() {
1110            self.channel_name_editor.update(cx, |editor, cx| {
1111                editor.set_text("", window, cx);
1112            });
1113            true
1114        } else {
1115            false
1116        }
1117    }
1118
1119    fn render_channel_notes(
1120        &self,
1121        channel_id: ChannelId,
1122        is_selected: bool,
1123        window: &mut Window,
1124        cx: &mut Context<Self>,
1125    ) -> impl IntoElement {
1126        let channel_store = self.channel_store.read(cx);
1127        let has_channel_buffer_changed = channel_store.has_channel_buffer_changed(channel_id);
1128        ListItem::new("channel-notes")
1129            .toggle_state(is_selected)
1130            .on_click(cx.listener(move |this, _, window, cx| {
1131                this.open_channel_notes(channel_id, window, cx);
1132            }))
1133            .start_slot(
1134                h_flex()
1135                    .relative()
1136                    .gap_1()
1137                    .child(render_tree_branch(false, true, window, cx))
1138                    .child(IconButton::new(0, IconName::File))
1139                    .children(has_channel_buffer_changed.then(|| {
1140                        div()
1141                            .w_1p5()
1142                            .absolute()
1143                            .right(px(2.))
1144                            .top(px(2.))
1145                            .child(Indicator::dot().color(Color::Info))
1146                    })),
1147            )
1148            .child(Label::new("notes"))
1149            .tooltip(Tooltip::text("Open Channel Notes"))
1150    }
1151
1152    fn has_subchannels(&self, ix: usize) -> bool {
1153        self.entries.get(ix).is_some_and(|entry| {
1154            if let ListEntry::Channel { has_children, .. } = entry {
1155                *has_children
1156            } else {
1157                false
1158            }
1159        })
1160    }
1161
1162    fn deploy_participant_context_menu(
1163        &mut self,
1164        position: Point<Pixels>,
1165        user_id: u64,
1166        role: proto::ChannelRole,
1167        window: &mut Window,
1168        cx: &mut Context<Self>,
1169    ) {
1170        let this = cx.entity();
1171        if !(role == proto::ChannelRole::Guest
1172            || role == proto::ChannelRole::Talker
1173            || role == proto::ChannelRole::Member)
1174        {
1175            return;
1176        }
1177
1178        let context_menu = ContextMenu::build(window, cx, |mut context_menu, window, _| {
1179            if role == proto::ChannelRole::Guest {
1180                context_menu = context_menu.entry(
1181                    "Grant Mic Access",
1182                    None,
1183                    window.handler_for(&this, move |_, window, cx| {
1184                        ActiveCall::global(cx)
1185                            .update(cx, |call, cx| {
1186                                let Some(room) = call.room() else {
1187                                    return Task::ready(Ok(()));
1188                                };
1189                                room.update(cx, |room, cx| {
1190                                    room.set_participant_role(
1191                                        user_id,
1192                                        proto::ChannelRole::Talker,
1193                                        cx,
1194                                    )
1195                                })
1196                            })
1197                            .detach_and_prompt_err(
1198                                "Failed to grant mic access",
1199                                window,
1200                                cx,
1201                                |_, _, _| None,
1202                            )
1203                    }),
1204                );
1205            }
1206            if role == proto::ChannelRole::Guest || role == proto::ChannelRole::Talker {
1207                context_menu = context_menu.entry(
1208                    "Grant Write Access",
1209                    None,
1210                    window.handler_for(&this, move |_, window, cx| {
1211                        ActiveCall::global(cx)
1212                            .update(cx, |call, cx| {
1213                                let Some(room) = call.room() else {
1214                                    return Task::ready(Ok(()));
1215                                };
1216                                room.update(cx, |room, cx| {
1217                                    room.set_participant_role(
1218                                        user_id,
1219                                        proto::ChannelRole::Member,
1220                                        cx,
1221                                    )
1222                                })
1223                            })
1224                            .detach_and_prompt_err("Failed to grant write access", window, cx, |e, _, _| {
1225                                match e.error_code() {
1226                                    ErrorCode::NeedsCla => Some("This user has not yet signed the CLA at https://zed.dev/cla.".into()),
1227                                    _ => None,
1228                                }
1229                            })
1230                    }),
1231                );
1232            }
1233            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Talker {
1234                let label = if role == proto::ChannelRole::Talker {
1235                    "Mute"
1236                } else {
1237                    "Revoke Access"
1238                };
1239                context_menu = context_menu.entry(
1240                    label,
1241                    None,
1242                    window.handler_for(&this, move |_, window, cx| {
1243                        ActiveCall::global(cx)
1244                            .update(cx, |call, cx| {
1245                                let Some(room) = call.room() else {
1246                                    return Task::ready(Ok(()));
1247                                };
1248                                room.update(cx, |room, cx| {
1249                                    room.set_participant_role(
1250                                        user_id,
1251                                        proto::ChannelRole::Guest,
1252                                        cx,
1253                                    )
1254                                })
1255                            })
1256                            .detach_and_prompt_err(
1257                                "Failed to revoke access",
1258                                window,
1259                                cx,
1260                                |_, _, _| None,
1261                            )
1262                    }),
1263                );
1264            }
1265
1266            context_menu
1267        });
1268
1269        window.focus(&context_menu.focus_handle(cx));
1270        let subscription = cx.subscribe_in(
1271            &context_menu,
1272            window,
1273            |this, _, _: &DismissEvent, window, cx| {
1274                if this.context_menu.as_ref().is_some_and(|context_menu| {
1275                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
1276                }) {
1277                    cx.focus_self(window);
1278                }
1279                this.context_menu.take();
1280                cx.notify();
1281            },
1282        );
1283        self.context_menu = Some((context_menu, position, subscription));
1284    }
1285
1286    fn deploy_channel_context_menu(
1287        &mut self,
1288        position: Point<Pixels>,
1289        channel_id: ChannelId,
1290        ix: usize,
1291        window: &mut Window,
1292        cx: &mut Context<Self>,
1293    ) {
1294        let clipboard_channel_name = self.channel_clipboard.as_ref().and_then(|clipboard| {
1295            self.channel_store
1296                .read(cx)
1297                .channel_for_id(clipboard.channel_id)
1298                .map(|channel| channel.name.clone())
1299        });
1300        let this = cx.entity();
1301
1302        let context_menu = ContextMenu::build(window, cx, |mut context_menu, window, cx| {
1303            if self.has_subchannels(ix) {
1304                let expand_action_name = if self.is_channel_collapsed(channel_id) {
1305                    "Expand Subchannels"
1306                } else {
1307                    "Collapse Subchannels"
1308                };
1309                context_menu = context_menu.entry(
1310                    expand_action_name,
1311                    None,
1312                    window.handler_for(&this, move |this, window, cx| {
1313                        this.toggle_channel_collapsed(channel_id, window, cx)
1314                    }),
1315                );
1316            }
1317
1318            context_menu = context_menu
1319                .entry(
1320                    "Open Notes",
1321                    None,
1322                    window.handler_for(&this, move |this, window, cx| {
1323                        this.open_channel_notes(channel_id, window, cx)
1324                    }),
1325                )
1326                .entry(
1327                    "Copy Channel Link",
1328                    None,
1329                    window.handler_for(&this, move |this, _, cx| {
1330                        this.copy_channel_link(channel_id, cx)
1331                    }),
1332                )
1333                .entry(
1334                    "Copy Channel Notes Link",
1335                    None,
1336                    window.handler_for(&this, move |this, _, cx| {
1337                        this.copy_channel_notes_link(channel_id, cx)
1338                    }),
1339                );
1340
1341            let mut has_destructive_actions = false;
1342            if self.channel_store.read(cx).is_channel_admin(channel_id) {
1343                has_destructive_actions = true;
1344                context_menu = context_menu
1345                    .separator()
1346                    .entry(
1347                        "New Subchannel",
1348                        None,
1349                        window.handler_for(&this, move |this, window, cx| {
1350                            this.new_subchannel(channel_id, window, cx)
1351                        }),
1352                    )
1353                    .entry(
1354                        "Rename",
1355                        Some(Box::new(SecondaryConfirm)),
1356                        window.handler_for(&this, move |this, window, cx| {
1357                            this.rename_channel(channel_id, window, cx)
1358                        }),
1359                    );
1360
1361                if let Some(channel_name) = clipboard_channel_name {
1362                    context_menu = context_menu.separator().entry(
1363                        format!("Move '#{}' here", channel_name),
1364                        None,
1365                        window.handler_for(&this, move |this, window, cx| {
1366                            this.move_channel_on_clipboard(channel_id, window, cx)
1367                        }),
1368                    );
1369                }
1370
1371                if self.channel_store.read(cx).is_root_channel(channel_id) {
1372                    context_menu = context_menu.separator().entry(
1373                        "Manage Members",
1374                        None,
1375                        window.handler_for(&this, move |this, window, cx| {
1376                            this.manage_members(channel_id, window, cx)
1377                        }),
1378                    )
1379                } else {
1380                    context_menu = context_menu.entry(
1381                        "Move this channel",
1382                        None,
1383                        window.handler_for(&this, move |this, window, cx| {
1384                            this.start_move_channel(channel_id, window, cx)
1385                        }),
1386                    );
1387                    if self.channel_store.read(cx).is_public_channel(channel_id) {
1388                        context_menu = context_menu.separator().entry(
1389                            "Make Channel Private",
1390                            None,
1391                            window.handler_for(&this, move |this, window, cx| {
1392                                this.set_channel_visibility(
1393                                    channel_id,
1394                                    ChannelVisibility::Members,
1395                                    window,
1396                                    cx,
1397                                )
1398                            }),
1399                        )
1400                    } else {
1401                        context_menu = context_menu.separator().entry(
1402                            "Make Channel Public",
1403                            None,
1404                            window.handler_for(&this, move |this, window, cx| {
1405                                this.set_channel_visibility(
1406                                    channel_id,
1407                                    ChannelVisibility::Public,
1408                                    window,
1409                                    cx,
1410                                )
1411                            }),
1412                        )
1413                    }
1414                }
1415
1416                context_menu = context_menu.entry(
1417                    "Delete",
1418                    None,
1419                    window.handler_for(&this, move |this, window, cx| {
1420                        this.remove_channel(channel_id, window, cx)
1421                    }),
1422                );
1423            }
1424
1425            if self.channel_store.read(cx).is_root_channel(channel_id) {
1426                if !has_destructive_actions {
1427                    context_menu = context_menu.separator()
1428                }
1429                context_menu = context_menu.entry(
1430                    "Leave Channel",
1431                    None,
1432                    window.handler_for(&this, move |this, window, cx| {
1433                        this.leave_channel(channel_id, window, cx)
1434                    }),
1435                );
1436            }
1437
1438            context_menu
1439        });
1440
1441        window.focus(&context_menu.focus_handle(cx));
1442        let subscription = cx.subscribe_in(
1443            &context_menu,
1444            window,
1445            |this, _, _: &DismissEvent, window, cx| {
1446                if this.context_menu.as_ref().is_some_and(|context_menu| {
1447                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
1448                }) {
1449                    cx.focus_self(window);
1450                }
1451                this.context_menu.take();
1452                cx.notify();
1453            },
1454        );
1455        self.context_menu = Some((context_menu, position, subscription));
1456
1457        cx.notify();
1458    }
1459
1460    fn deploy_contact_context_menu(
1461        &mut self,
1462        position: Point<Pixels>,
1463        contact: Arc<Contact>,
1464        window: &mut Window,
1465        cx: &mut Context<Self>,
1466    ) {
1467        let this = cx.entity();
1468        let in_room = ActiveCall::global(cx).read(cx).room().is_some();
1469
1470        let context_menu = ContextMenu::build(window, cx, |mut context_menu, _, _| {
1471            let user_id = contact.user.id;
1472
1473            if contact.online && !contact.busy {
1474                let label = if in_room {
1475                    format!("Invite {} to join", contact.user.github_login)
1476                } else {
1477                    format!("Call {}", contact.user.github_login)
1478                };
1479                context_menu = context_menu.entry(label, None, {
1480                    let this = this.clone();
1481                    move |window, cx| {
1482                        this.update(cx, |this, cx| {
1483                            this.call(user_id, window, cx);
1484                        });
1485                    }
1486                });
1487            }
1488
1489            context_menu.entry("Remove Contact", None, {
1490                let this = this.clone();
1491                move |window, cx| {
1492                    this.update(cx, |this, cx| {
1493                        this.remove_contact(
1494                            contact.user.id,
1495                            &contact.user.github_login,
1496                            window,
1497                            cx,
1498                        );
1499                    });
1500                }
1501            })
1502        });
1503
1504        window.focus(&context_menu.focus_handle(cx));
1505        let subscription = cx.subscribe_in(
1506            &context_menu,
1507            window,
1508            |this, _, _: &DismissEvent, window, cx| {
1509                if this.context_menu.as_ref().is_some_and(|context_menu| {
1510                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
1511                }) {
1512                    cx.focus_self(window);
1513                }
1514                this.context_menu.take();
1515                cx.notify();
1516            },
1517        );
1518        self.context_menu = Some((context_menu, position, subscription));
1519
1520        cx.notify();
1521    }
1522
1523    fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1524        self.filter_editor.update(cx, |editor, cx| {
1525            if editor.buffer().read(cx).len(cx).0 > 0 {
1526                editor.set_text("", window, cx);
1527                true
1528            } else {
1529                false
1530            }
1531        })
1532    }
1533
1534    fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1535        if cx.stop_active_drag(window) {
1536            return;
1537        } else if self.take_editing_state(window, cx) {
1538            window.focus(&self.filter_editor.focus_handle(cx));
1539        } else if !self.reset_filter_editor_text(window, cx) {
1540            self.focus_handle.focus(window);
1541        }
1542
1543        if self.context_menu.is_some() {
1544            self.context_menu.take();
1545            cx.notify();
1546        }
1547
1548        self.update_entries(false, cx);
1549    }
1550
1551    fn select_next(&mut self, _: &SelectNext, _: &mut Window, cx: &mut Context<Self>) {
1552        let ix = self.selection.map_or(0, |ix| ix + 1);
1553        if ix < self.entries.len() {
1554            self.selection = Some(ix);
1555        }
1556
1557        if let Some(ix) = self.selection {
1558            self.scroll_to_item(ix)
1559        }
1560        cx.notify();
1561    }
1562
1563    fn select_previous(&mut self, _: &SelectPrevious, _: &mut Window, cx: &mut Context<Self>) {
1564        let ix = self.selection.take().unwrap_or(0);
1565        if ix > 0 {
1566            self.selection = Some(ix - 1);
1567        }
1568
1569        if let Some(ix) = self.selection {
1570            self.scroll_to_item(ix)
1571        }
1572        cx.notify();
1573    }
1574
1575    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1576        if self.confirm_channel_edit(window, cx) {
1577            return;
1578        }
1579
1580        if let Some(selection) = self.selection
1581            && let Some(entry) = self.entries.get(selection)
1582        {
1583            match entry {
1584                ListEntry::Header(section) => match section {
1585                    Section::ActiveCall => Self::leave_call(window, cx),
1586                    Section::Channels => self.new_root_channel(window, cx),
1587                    Section::Contacts => self.toggle_contact_finder(window, cx),
1588                    Section::ContactRequests
1589                    | Section::Online
1590                    | Section::Offline
1591                    | Section::ChannelInvites => {
1592                        self.toggle_section_expanded(*section, cx);
1593                    }
1594                },
1595                ListEntry::Contact { contact, calling } => {
1596                    if contact.online && !contact.busy && !calling {
1597                        self.call(contact.user.id, window, cx);
1598                    }
1599                }
1600                ListEntry::ParticipantProject {
1601                    project_id,
1602                    host_user_id,
1603                    ..
1604                } => {
1605                    if let Some(workspace) = self.workspace.upgrade() {
1606                        let app_state = workspace.read(cx).app_state().clone();
1607                        workspace::join_in_room_project(*project_id, *host_user_id, app_state, cx)
1608                            .detach_and_prompt_err(
1609                                "Failed to join project",
1610                                window,
1611                                cx,
1612                                |_, _, _| None,
1613                            );
1614                    }
1615                }
1616                ListEntry::ParticipantScreen { peer_id, .. } => {
1617                    let Some(peer_id) = peer_id else {
1618                        return;
1619                    };
1620                    if let Some(workspace) = self.workspace.upgrade() {
1621                        workspace.update(cx, |workspace, cx| {
1622                            workspace.open_shared_screen(*peer_id, window, cx)
1623                        });
1624                    }
1625                }
1626                ListEntry::Channel { channel, .. } => {
1627                    let is_active = maybe!({
1628                        let call_channel = ActiveCall::global(cx)
1629                            .read(cx)
1630                            .room()?
1631                            .read(cx)
1632                            .channel_id()?;
1633
1634                        Some(call_channel == channel.id)
1635                    })
1636                    .unwrap_or(false);
1637                    if is_active {
1638                        self.open_channel_notes(channel.id, window, cx)
1639                    } else {
1640                        self.join_channel(channel.id, window, cx)
1641                    }
1642                }
1643                ListEntry::ContactPlaceholder => self.toggle_contact_finder(window, cx),
1644                ListEntry::CallParticipant { user, peer_id, .. } => {
1645                    if Some(user) == self.user_store.read(cx).current_user().as_ref() {
1646                        Self::leave_call(window, cx);
1647                    } else if let Some(peer_id) = peer_id {
1648                        self.workspace
1649                            .update(cx, |workspace, cx| workspace.follow(*peer_id, window, cx))
1650                            .ok();
1651                    }
1652                }
1653                ListEntry::IncomingRequest(user) => {
1654                    self.respond_to_contact_request(user.id, true, window, cx)
1655                }
1656                ListEntry::ChannelInvite(channel) => {
1657                    self.respond_to_channel_invite(channel.id, true, cx)
1658                }
1659                ListEntry::ChannelNotes { channel_id } => {
1660                    self.open_channel_notes(*channel_id, window, cx)
1661                }
1662                ListEntry::OutgoingRequest(_) => {}
1663                ListEntry::ChannelEditor { .. } => {}
1664            }
1665        }
1666    }
1667
1668    fn insert_space(&mut self, _: &InsertSpace, window: &mut Window, cx: &mut Context<Self>) {
1669        if self.channel_editing_state.is_some() {
1670            self.channel_name_editor.update(cx, |editor, cx| {
1671                editor.insert(" ", window, cx);
1672            });
1673        } else if self.filter_editor.focus_handle(cx).is_focused(window) {
1674            self.filter_editor.update(cx, |editor, cx| {
1675                editor.insert(" ", window, cx);
1676            });
1677        }
1678    }
1679
1680    fn confirm_channel_edit(&mut self, window: &mut Window, cx: &mut Context<CollabPanel>) -> bool {
1681        if let Some(editing_state) = &mut self.channel_editing_state {
1682            match editing_state {
1683                ChannelEditingState::Create {
1684                    location,
1685                    pending_name,
1686                    ..
1687                } => {
1688                    if pending_name.is_some() {
1689                        return false;
1690                    }
1691                    let channel_name = self.channel_name_editor.read(cx).text(cx);
1692
1693                    *pending_name = Some(channel_name.clone());
1694
1695                    let create = self.channel_store.update(cx, |channel_store, cx| {
1696                        channel_store.create_channel(&channel_name, *location, cx)
1697                    });
1698                    if location.is_none() {
1699                        cx.spawn_in(window, async move |this, cx| {
1700                            let channel_id = create.await?;
1701                            this.update_in(cx, |this, window, cx| {
1702                                this.show_channel_modal(
1703                                    channel_id,
1704                                    channel_modal::Mode::InviteMembers,
1705                                    window,
1706                                    cx,
1707                                )
1708                            })
1709                        })
1710                        .detach_and_prompt_err(
1711                            "Failed to create channel",
1712                            window,
1713                            cx,
1714                            |_, _, _| None,
1715                        );
1716                    } else {
1717                        create.detach_and_prompt_err(
1718                            "Failed to create channel",
1719                            window,
1720                            cx,
1721                            |_, _, _| None,
1722                        );
1723                    }
1724                    cx.notify();
1725                }
1726                ChannelEditingState::Rename {
1727                    location,
1728                    pending_name,
1729                } => {
1730                    if pending_name.is_some() {
1731                        return false;
1732                    }
1733                    let channel_name = self.channel_name_editor.read(cx).text(cx);
1734                    *pending_name = Some(channel_name.clone());
1735
1736                    self.channel_store
1737                        .update(cx, |channel_store, cx| {
1738                            channel_store.rename(*location, &channel_name, cx)
1739                        })
1740                        .detach();
1741                    cx.notify();
1742                }
1743            }
1744            cx.focus_self(window);
1745            true
1746        } else {
1747            false
1748        }
1749    }
1750
1751    fn toggle_section_expanded(&mut self, section: Section, cx: &mut Context<Self>) {
1752        if let Some(ix) = self.collapsed_sections.iter().position(|s| *s == section) {
1753            self.collapsed_sections.remove(ix);
1754        } else {
1755            self.collapsed_sections.push(section);
1756        }
1757        self.update_entries(false, cx);
1758    }
1759
1760    fn collapse_selected_channel(
1761        &mut self,
1762        _: &CollapseSelectedChannel,
1763        window: &mut Window,
1764        cx: &mut Context<Self>,
1765    ) {
1766        let Some(channel_id) = self.selected_channel().map(|channel| channel.id) else {
1767            return;
1768        };
1769
1770        if self.is_channel_collapsed(channel_id) {
1771            return;
1772        }
1773
1774        self.toggle_channel_collapsed(channel_id, window, cx);
1775    }
1776
1777    fn expand_selected_channel(
1778        &mut self,
1779        _: &ExpandSelectedChannel,
1780        window: &mut Window,
1781        cx: &mut Context<Self>,
1782    ) {
1783        let Some(id) = self.selected_channel().map(|channel| channel.id) else {
1784            return;
1785        };
1786
1787        if !self.is_channel_collapsed(id) {
1788            return;
1789        }
1790
1791        self.toggle_channel_collapsed(id, window, cx)
1792    }
1793
1794    fn toggle_channel_collapsed(
1795        &mut self,
1796        channel_id: ChannelId,
1797        window: &mut Window,
1798        cx: &mut Context<Self>,
1799    ) {
1800        match self.collapsed_channels.binary_search(&channel_id) {
1801            Ok(ix) => {
1802                self.collapsed_channels.remove(ix);
1803            }
1804            Err(ix) => {
1805                self.collapsed_channels.insert(ix, channel_id);
1806            }
1807        };
1808        self.serialize(cx);
1809        self.update_entries(true, cx);
1810        cx.notify();
1811        cx.focus_self(window);
1812    }
1813
1814    fn is_channel_collapsed(&self, channel_id: ChannelId) -> bool {
1815        self.collapsed_channels.binary_search(&channel_id).is_ok()
1816    }
1817
1818    fn leave_call(window: &mut Window, cx: &mut App) {
1819        ActiveCall::global(cx)
1820            .update(cx, |call, cx| call.hang_up(cx))
1821            .detach_and_prompt_err("Failed to hang up", window, cx, |_, _, _| None);
1822    }
1823
1824    fn toggle_contact_finder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1825        if let Some(workspace) = self.workspace.upgrade() {
1826            workspace.update(cx, |workspace, cx| {
1827                workspace.toggle_modal(window, cx, |window, cx| {
1828                    let mut finder = ContactFinder::new(self.user_store.clone(), window, cx);
1829                    finder.set_query(self.filter_editor.read(cx).text(cx), window, cx);
1830                    finder
1831                });
1832            });
1833        }
1834    }
1835
1836    fn new_root_channel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1837        self.channel_editing_state = Some(ChannelEditingState::Create {
1838            location: None,
1839            pending_name: None,
1840        });
1841        self.update_entries(false, cx);
1842        self.select_channel_editor();
1843        window.focus(&self.channel_name_editor.focus_handle(cx));
1844        cx.notify();
1845    }
1846
1847    fn select_channel_editor(&mut self) {
1848        self.selection = self
1849            .entries
1850            .iter()
1851            .position(|entry| matches!(entry, ListEntry::ChannelEditor { .. }));
1852    }
1853
1854    fn new_subchannel(
1855        &mut self,
1856        channel_id: ChannelId,
1857        window: &mut Window,
1858        cx: &mut Context<Self>,
1859    ) {
1860        self.collapsed_channels
1861            .retain(|channel| *channel != channel_id);
1862        self.channel_editing_state = Some(ChannelEditingState::Create {
1863            location: Some(channel_id),
1864            pending_name: None,
1865        });
1866        self.update_entries(false, cx);
1867        self.select_channel_editor();
1868        window.focus(&self.channel_name_editor.focus_handle(cx));
1869        cx.notify();
1870    }
1871
1872    fn manage_members(
1873        &mut self,
1874        channel_id: ChannelId,
1875        window: &mut Window,
1876        cx: &mut Context<Self>,
1877    ) {
1878        self.show_channel_modal(channel_id, channel_modal::Mode::ManageMembers, window, cx);
1879    }
1880
1881    fn remove_selected_channel(&mut self, _: &Remove, window: &mut Window, cx: &mut Context<Self>) {
1882        if let Some(channel) = self.selected_channel() {
1883            self.remove_channel(channel.id, window, cx)
1884        }
1885    }
1886
1887    fn rename_selected_channel(
1888        &mut self,
1889        _: &SecondaryConfirm,
1890        window: &mut Window,
1891        cx: &mut Context<Self>,
1892    ) {
1893        if let Some(channel) = self.selected_channel() {
1894            self.rename_channel(channel.id, window, cx);
1895        }
1896    }
1897
1898    fn rename_channel(
1899        &mut self,
1900        channel_id: ChannelId,
1901        window: &mut Window,
1902        cx: &mut Context<Self>,
1903    ) {
1904        let channel_store = self.channel_store.read(cx);
1905        if !channel_store.is_channel_admin(channel_id) {
1906            return;
1907        }
1908        if let Some(channel) = channel_store.channel_for_id(channel_id).cloned() {
1909            self.channel_editing_state = Some(ChannelEditingState::Rename {
1910                location: channel_id,
1911                pending_name: None,
1912            });
1913            self.channel_name_editor.update(cx, |editor, cx| {
1914                editor.set_text(channel.name.clone(), window, cx);
1915                editor.select_all(&Default::default(), window, cx);
1916            });
1917            window.focus(&self.channel_name_editor.focus_handle(cx));
1918            self.update_entries(false, cx);
1919            self.select_channel_editor();
1920        }
1921    }
1922
1923    fn open_selected_channel_notes(
1924        &mut self,
1925        _: &OpenSelectedChannelNotes,
1926        window: &mut Window,
1927        cx: &mut Context<Self>,
1928    ) {
1929        if let Some(channel) = self.selected_channel() {
1930            self.open_channel_notes(channel.id, window, cx);
1931        }
1932    }
1933
1934    fn set_channel_visibility(
1935        &mut self,
1936        channel_id: ChannelId,
1937        visibility: ChannelVisibility,
1938        window: &mut Window,
1939        cx: &mut Context<Self>,
1940    ) {
1941        self.channel_store
1942            .update(cx, |channel_store, cx| {
1943                channel_store.set_channel_visibility(channel_id, visibility, cx)
1944            })
1945            .detach_and_prompt_err("Failed to set channel visibility", window, cx, |e, _, _| match e.error_code() {
1946                ErrorCode::BadPublicNesting =>
1947                    if e.error_tag("direction") == Some("parent") {
1948                        Some("To make a channel public, its parent channel must be public.".to_string())
1949                    } else {
1950                        Some("To make a channel private, all of its subchannels must be private.".to_string())
1951                    },
1952                _ => None
1953            });
1954    }
1955
1956    fn start_move_channel(
1957        &mut self,
1958        channel_id: ChannelId,
1959        _window: &mut Window,
1960        _cx: &mut Context<Self>,
1961    ) {
1962        self.channel_clipboard = Some(ChannelMoveClipboard { channel_id });
1963    }
1964
1965    fn start_move_selected_channel(
1966        &mut self,
1967        _: &StartMoveChannel,
1968        window: &mut Window,
1969        cx: &mut Context<Self>,
1970    ) {
1971        if let Some(channel) = self.selected_channel() {
1972            self.start_move_channel(channel.id, window, cx);
1973        }
1974    }
1975
1976    fn move_channel_on_clipboard(
1977        &mut self,
1978        to_channel_id: ChannelId,
1979        window: &mut Window,
1980        cx: &mut Context<CollabPanel>,
1981    ) {
1982        if let Some(clipboard) = self.channel_clipboard.take() {
1983            self.move_channel(clipboard.channel_id, to_channel_id, window, cx)
1984        }
1985    }
1986
1987    fn move_channel(
1988        &self,
1989        channel_id: ChannelId,
1990        to: ChannelId,
1991        window: &mut Window,
1992        cx: &mut Context<Self>,
1993    ) {
1994        self.channel_store
1995            .update(cx, |channel_store, cx| {
1996                channel_store.move_channel(channel_id, to, cx)
1997            })
1998            .detach_and_prompt_err("Failed to move channel", window, cx, |e, _, _| {
1999                match e.error_code() {
2000                    ErrorCode::BadPublicNesting => {
2001                        Some("Public channels must have public parents".into())
2002                    }
2003                    ErrorCode::CircularNesting => {
2004                        Some("You cannot move a channel into itself".into())
2005                    }
2006                    ErrorCode::WrongMoveTarget => {
2007                        Some("You cannot move a channel into a different root channel".into())
2008                    }
2009                    _ => None,
2010                }
2011            })
2012    }
2013
2014    fn move_channel_up(&mut self, _: &MoveChannelUp, window: &mut Window, cx: &mut Context<Self>) {
2015        if let Some(channel) = self.selected_channel() {
2016            self.channel_store.update(cx, |store, cx| {
2017                store
2018                    .reorder_channel(channel.id, proto::reorder_channel::Direction::Up, cx)
2019                    .detach_and_prompt_err("Failed to move channel up", window, cx, |_, _, _| None)
2020            });
2021        }
2022    }
2023
2024    fn move_channel_down(
2025        &mut self,
2026        _: &MoveChannelDown,
2027        window: &mut Window,
2028        cx: &mut Context<Self>,
2029    ) {
2030        if let Some(channel) = self.selected_channel() {
2031            self.channel_store.update(cx, |store, cx| {
2032                store
2033                    .reorder_channel(channel.id, proto::reorder_channel::Direction::Down, cx)
2034                    .detach_and_prompt_err("Failed to move channel down", window, cx, |_, _, _| {
2035                        None
2036                    })
2037            });
2038        }
2039    }
2040
2041    fn open_channel_notes(
2042        &mut self,
2043        channel_id: ChannelId,
2044        window: &mut Window,
2045        cx: &mut Context<Self>,
2046    ) {
2047        if let Some(workspace) = self.workspace.upgrade() {
2048            ChannelView::open(channel_id, None, workspace, window, cx).detach();
2049        }
2050    }
2051
2052    fn show_inline_context_menu(
2053        &mut self,
2054        _: &Secondary,
2055        window: &mut Window,
2056        cx: &mut Context<Self>,
2057    ) {
2058        let Some(bounds) = self
2059            .selection
2060            .and_then(|ix| self.list_state.bounds_for_item(ix))
2061        else {
2062            return;
2063        };
2064
2065        if let Some(channel) = self.selected_channel() {
2066            self.deploy_channel_context_menu(
2067                bounds.center(),
2068                channel.id,
2069                self.selection.unwrap(),
2070                window,
2071                cx,
2072            );
2073            cx.stop_propagation();
2074            return;
2075        };
2076
2077        if let Some(contact) = self.selected_contact() {
2078            self.deploy_contact_context_menu(bounds.center(), contact, window, cx);
2079            cx.stop_propagation();
2080        }
2081    }
2082
2083    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
2084        let mut dispatch_context = KeyContext::new_with_defaults();
2085        dispatch_context.add("CollabPanel");
2086        dispatch_context.add("menu");
2087
2088        let identifier = if self.channel_name_editor.focus_handle(cx).is_focused(window)
2089            || self.filter_editor.focus_handle(cx).is_focused(window)
2090        {
2091            "editing"
2092        } else {
2093            "not_editing"
2094        };
2095
2096        dispatch_context.add(identifier);
2097        dispatch_context
2098    }
2099
2100    fn selected_channel(&self) -> Option<&Arc<Channel>> {
2101        self.selection
2102            .and_then(|ix| self.entries.get(ix))
2103            .and_then(|entry| match entry {
2104                ListEntry::Channel { channel, .. } => Some(channel),
2105                _ => None,
2106            })
2107    }
2108
2109    fn selected_contact(&self) -> Option<Arc<Contact>> {
2110        self.selection
2111            .and_then(|ix| self.entries.get(ix))
2112            .and_then(|entry| match entry {
2113                ListEntry::Contact { contact, .. } => Some(contact.clone()),
2114                _ => None,
2115            })
2116    }
2117
2118    fn show_channel_modal(
2119        &mut self,
2120        channel_id: ChannelId,
2121        mode: channel_modal::Mode,
2122        window: &mut Window,
2123        cx: &mut Context<Self>,
2124    ) {
2125        let workspace = self.workspace.clone();
2126        let user_store = self.user_store.clone();
2127        let channel_store = self.channel_store.clone();
2128
2129        cx.spawn_in(window, async move |_, cx| {
2130            workspace.update_in(cx, |workspace, window, cx| {
2131                workspace.toggle_modal(window, cx, |window, cx| {
2132                    ChannelModal::new(
2133                        user_store.clone(),
2134                        channel_store.clone(),
2135                        channel_id,
2136                        mode,
2137                        window,
2138                        cx,
2139                    )
2140                });
2141            })
2142        })
2143        .detach();
2144    }
2145
2146    fn leave_channel(&self, channel_id: ChannelId, window: &mut Window, cx: &mut Context<Self>) {
2147        let Some(user_id) = self.user_store.read(cx).current_user().map(|u| u.id) else {
2148            return;
2149        };
2150        let Some(channel) = self.channel_store.read(cx).channel_for_id(channel_id) else {
2151            return;
2152        };
2153        let prompt_message = format!("Are you sure you want to leave \"#{}\"?", channel.name);
2154        let answer = window.prompt(
2155            PromptLevel::Warning,
2156            &prompt_message,
2157            None,
2158            &["Leave", "Cancel"],
2159            cx,
2160        );
2161        cx.spawn_in(window, async move |this, cx| {
2162            if answer.await? != 0 {
2163                return Ok(());
2164            }
2165            this.update(cx, |this, cx| {
2166                this.channel_store.update(cx, |channel_store, cx| {
2167                    channel_store.remove_member(channel_id, user_id, cx)
2168                })
2169            })?
2170            .await
2171        })
2172        .detach_and_prompt_err("Failed to leave channel", window, cx, |_, _, _| None)
2173    }
2174
2175    fn remove_channel(
2176        &mut self,
2177        channel_id: ChannelId,
2178        window: &mut Window,
2179        cx: &mut Context<Self>,
2180    ) {
2181        let channel_store = self.channel_store.clone();
2182        if let Some(channel) = channel_store.read(cx).channel_for_id(channel_id) {
2183            let prompt_message = format!(
2184                "Are you sure you want to remove the channel \"{}\"?",
2185                channel.name
2186            );
2187            let answer = window.prompt(
2188                PromptLevel::Warning,
2189                &prompt_message,
2190                None,
2191                &["Remove", "Cancel"],
2192                cx,
2193            );
2194            cx.spawn_in(window, async move |this, cx| {
2195                if answer.await? == 0 {
2196                    channel_store
2197                        .update(cx, |channels, _| channels.remove_channel(channel_id))?
2198                        .await
2199                        .notify_async_err(cx);
2200                    this.update_in(cx, |_, window, cx| cx.focus_self(window))
2201                        .ok();
2202                }
2203                anyhow::Ok(())
2204            })
2205            .detach();
2206        }
2207    }
2208
2209    fn remove_contact(
2210        &mut self,
2211        user_id: u64,
2212        github_login: &str,
2213        window: &mut Window,
2214        cx: &mut Context<Self>,
2215    ) {
2216        let user_store = self.user_store.clone();
2217        let prompt_message = format!(
2218            "Are you sure you want to remove \"{}\" from your contacts?",
2219            github_login
2220        );
2221        let answer = window.prompt(
2222            PromptLevel::Warning,
2223            &prompt_message,
2224            None,
2225            &["Remove", "Cancel"],
2226            cx,
2227        );
2228        cx.spawn_in(window, async move |_, cx| {
2229            if answer.await? == 0 {
2230                user_store
2231                    .update(cx, |store, cx| store.remove_contact(user_id, cx))?
2232                    .await
2233                    .notify_async_err(cx);
2234            }
2235            anyhow::Ok(())
2236        })
2237        .detach_and_prompt_err("Failed to remove contact", window, cx, |_, _, _| None);
2238    }
2239
2240    fn respond_to_contact_request(
2241        &mut self,
2242        user_id: u64,
2243        accept: bool,
2244        window: &mut Window,
2245        cx: &mut Context<Self>,
2246    ) {
2247        self.user_store
2248            .update(cx, |store, cx| {
2249                store.respond_to_contact_request(user_id, accept, cx)
2250            })
2251            .detach_and_prompt_err(
2252                "Failed to respond to contact request",
2253                window,
2254                cx,
2255                |_, _, _| None,
2256            );
2257    }
2258
2259    fn respond_to_channel_invite(
2260        &mut self,
2261        channel_id: ChannelId,
2262        accept: bool,
2263        cx: &mut Context<Self>,
2264    ) {
2265        self.channel_store
2266            .update(cx, |store, cx| {
2267                store.respond_to_channel_invite(channel_id, accept, cx)
2268            })
2269            .detach();
2270    }
2271
2272    fn call(&mut self, recipient_user_id: u64, window: &mut Window, cx: &mut Context<Self>) {
2273        ActiveCall::global(cx)
2274            .update(cx, |call, cx| {
2275                call.invite(recipient_user_id, Some(self.project.clone()), cx)
2276            })
2277            .detach_and_prompt_err("Call failed", window, cx, |_, _, _| None);
2278    }
2279
2280    fn join_channel(&self, channel_id: ChannelId, window: &mut Window, cx: &mut Context<Self>) {
2281        let Some(workspace) = self.workspace.upgrade() else {
2282            return;
2283        };
2284        let Some(handle) = window.window_handle().downcast::<Workspace>() else {
2285            return;
2286        };
2287        workspace::join_channel(
2288            channel_id,
2289            workspace.read(cx).app_state().clone(),
2290            Some(handle),
2291            cx,
2292        )
2293        .detach_and_prompt_err("Failed to join channel", window, cx, |_, _, _| None)
2294    }
2295
2296    fn copy_channel_link(&mut self, channel_id: ChannelId, cx: &mut Context<Self>) {
2297        let channel_store = self.channel_store.read(cx);
2298        let Some(channel) = channel_store.channel_for_id(channel_id) else {
2299            return;
2300        };
2301        let item = ClipboardItem::new_string(channel.link(cx));
2302        cx.write_to_clipboard(item)
2303    }
2304
2305    fn copy_channel_notes_link(&mut self, channel_id: ChannelId, cx: &mut Context<Self>) {
2306        let channel_store = self.channel_store.read(cx);
2307        let Some(channel) = channel_store.channel_for_id(channel_id) else {
2308            return;
2309        };
2310        let item = ClipboardItem::new_string(channel.notes_link(None, cx));
2311        cx.write_to_clipboard(item)
2312    }
2313
2314    fn render_signed_out(&mut self, cx: &mut Context<Self>) -> Div {
2315        let collab_blurb = "Work with your team in realtime with collaborative editing, voice, shared notes and more.";
2316
2317        v_flex()
2318            .gap_6()
2319            .p_4()
2320            .child(Label::new(collab_blurb))
2321            .child(
2322                v_flex()
2323                    .gap_2()
2324                    .child(
2325                        Button::new("sign_in", "Sign in")
2326                            .icon_color(Color::Muted)
2327                            .icon(IconName::Github)
2328                            .icon_position(IconPosition::Start)
2329                            .style(ButtonStyle::Filled)
2330                            .full_width()
2331                            .on_click(cx.listener(|this, _, window, cx| {
2332                                let client = this.client.clone();
2333                                cx.spawn_in(window, async move |_, cx| {
2334                                    client
2335                                        .connect(true, cx)
2336                                        .await
2337                                        .into_response()
2338                                        .notify_async_err(cx);
2339                                })
2340                                .detach()
2341                            })),
2342                    )
2343                    .child(
2344                        v_flex().w_full().items_center().child(
2345                            Label::new("Sign in to enable collaboration.")
2346                                .color(Color::Muted)
2347                                .size(LabelSize::Small),
2348                        ),
2349                    ),
2350            )
2351    }
2352
2353    fn render_list_entry(
2354        &mut self,
2355        ix: usize,
2356        window: &mut Window,
2357        cx: &mut Context<Self>,
2358    ) -> AnyElement {
2359        let entry = &self.entries[ix];
2360
2361        let is_selected = self.selection == Some(ix);
2362        match entry {
2363            ListEntry::Header(section) => {
2364                let is_collapsed = self.collapsed_sections.contains(section);
2365                self.render_header(*section, is_selected, is_collapsed, cx)
2366                    .into_any_element()
2367            }
2368            ListEntry::Contact { contact, calling } => self
2369                .render_contact(contact, *calling, is_selected, cx)
2370                .into_any_element(),
2371            ListEntry::ContactPlaceholder => self
2372                .render_contact_placeholder(is_selected, cx)
2373                .into_any_element(),
2374            ListEntry::IncomingRequest(user) => self
2375                .render_contact_request(user, true, is_selected, cx)
2376                .into_any_element(),
2377            ListEntry::OutgoingRequest(user) => self
2378                .render_contact_request(user, false, is_selected, cx)
2379                .into_any_element(),
2380            ListEntry::Channel {
2381                channel,
2382                depth,
2383                has_children,
2384                string_match,
2385            } => self
2386                .render_channel(
2387                    channel,
2388                    *depth,
2389                    *has_children,
2390                    is_selected,
2391                    ix,
2392                    string_match.as_ref(),
2393                    cx,
2394                )
2395                .into_any_element(),
2396            ListEntry::ChannelEditor { depth } => self
2397                .render_channel_editor(*depth, window, cx)
2398                .into_any_element(),
2399            ListEntry::ChannelInvite(channel) => self
2400                .render_channel_invite(channel, is_selected, cx)
2401                .into_any_element(),
2402            ListEntry::CallParticipant {
2403                user,
2404                peer_id,
2405                is_pending,
2406                role,
2407            } => self
2408                .render_call_participant(user, *peer_id, *is_pending, *role, is_selected, cx)
2409                .into_any_element(),
2410            ListEntry::ParticipantProject {
2411                project_id,
2412                worktree_root_names,
2413                host_user_id,
2414                is_last,
2415            } => self
2416                .render_participant_project(
2417                    *project_id,
2418                    worktree_root_names,
2419                    *host_user_id,
2420                    *is_last,
2421                    is_selected,
2422                    window,
2423                    cx,
2424                )
2425                .into_any_element(),
2426            ListEntry::ParticipantScreen { peer_id, is_last } => self
2427                .render_participant_screen(*peer_id, *is_last, is_selected, window, cx)
2428                .into_any_element(),
2429            ListEntry::ChannelNotes { channel_id } => self
2430                .render_channel_notes(*channel_id, is_selected, window, cx)
2431                .into_any_element(),
2432        }
2433    }
2434
2435    fn render_signed_in(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
2436        self.channel_store.update(cx, |channel_store, _| {
2437            channel_store.initialize();
2438        });
2439        v_flex()
2440            .size_full()
2441            .gap_1()
2442            .child(
2443                h_flex()
2444                    .p_2()
2445                    .h(Tab::container_height(cx))
2446                    .gap_1p5()
2447                    .border_b_1()
2448                    .border_color(cx.theme().colors().border)
2449                    .child(
2450                        Icon::new(IconName::MagnifyingGlass)
2451                            .size(IconSize::Small)
2452                            .color(Color::Muted),
2453                    )
2454                    .child(self.render_filter_input(&self.filter_editor, cx)),
2455            )
2456            .child(
2457                list(
2458                    self.list_state.clone(),
2459                    cx.processor(Self::render_list_entry),
2460                )
2461                .size_full(),
2462            )
2463    }
2464
2465    fn render_filter_input(
2466        &self,
2467        editor: &Entity<Editor>,
2468        cx: &mut Context<Self>,
2469    ) -> impl IntoElement {
2470        let settings = ThemeSettings::get_global(cx);
2471        let text_style = TextStyle {
2472            color: if editor.read(cx).read_only(cx) {
2473                cx.theme().colors().text_disabled
2474            } else {
2475                cx.theme().colors().text
2476            },
2477            font_family: settings.ui_font.family.clone(),
2478            font_features: settings.ui_font.features.clone(),
2479            font_fallbacks: settings.ui_font.fallbacks.clone(),
2480            font_size: rems(0.875).into(),
2481            font_weight: settings.ui_font.weight,
2482            font_style: FontStyle::Normal,
2483            line_height: relative(1.3),
2484            ..Default::default()
2485        };
2486
2487        EditorElement::new(
2488            editor,
2489            EditorStyle {
2490                local_player: cx.theme().players().local(),
2491                text: text_style,
2492                ..Default::default()
2493            },
2494        )
2495    }
2496
2497    fn render_header(
2498        &self,
2499        section: Section,
2500        is_selected: bool,
2501        is_collapsed: bool,
2502        cx: &mut Context<Self>,
2503    ) -> impl IntoElement {
2504        let mut channel_link = None;
2505        let mut channel_tooltip_text = None;
2506        let mut channel_icon = None;
2507
2508        let text = match section {
2509            Section::ActiveCall => {
2510                let channel_name = maybe!({
2511                    let channel_id = ActiveCall::global(cx).read(cx).channel_id(cx)?;
2512
2513                    let channel = self.channel_store.read(cx).channel_for_id(channel_id)?;
2514
2515                    channel_link = Some(channel.link(cx));
2516                    (channel_icon, channel_tooltip_text) = match channel.visibility {
2517                        proto::ChannelVisibility::Public => {
2518                            (Some("icons/public.svg"), Some("Copy public channel link."))
2519                        }
2520                        proto::ChannelVisibility::Members => {
2521                            (Some("icons/hash.svg"), Some("Copy private channel link."))
2522                        }
2523                    };
2524
2525                    Some(channel.name.as_ref())
2526                });
2527
2528                if let Some(name) = channel_name {
2529                    SharedString::from(name.to_string())
2530                } else {
2531                    SharedString::from("Current Call")
2532                }
2533            }
2534            Section::ContactRequests => SharedString::from("Requests"),
2535            Section::Contacts => SharedString::from("Contacts"),
2536            Section::Channels => SharedString::from("Channels"),
2537            Section::ChannelInvites => SharedString::from("Invites"),
2538            Section::Online => SharedString::from("Online"),
2539            Section::Offline => SharedString::from("Offline"),
2540        };
2541
2542        let button = match section {
2543            Section::ActiveCall => channel_link.map(|channel_link| {
2544                let channel_link_copy = channel_link;
2545                IconButton::new("channel-link", IconName::Copy)
2546                    .icon_size(IconSize::Small)
2547                    .size(ButtonSize::None)
2548                    .visible_on_hover("section-header")
2549                    .on_click(move |_, _, cx| {
2550                        let item = ClipboardItem::new_string(channel_link_copy.clone());
2551                        cx.write_to_clipboard(item)
2552                    })
2553                    .tooltip(Tooltip::text("Copy channel link"))
2554                    .into_any_element()
2555            }),
2556            Section::Contacts => Some(
2557                IconButton::new("add-contact", IconName::Plus)
2558                    .on_click(
2559                        cx.listener(|this, _, window, cx| this.toggle_contact_finder(window, cx)),
2560                    )
2561                    .tooltip(Tooltip::text("Search for new contact"))
2562                    .into_any_element(),
2563            ),
2564            Section::Channels => Some(
2565                IconButton::new("add-channel", IconName::Plus)
2566                    .on_click(cx.listener(|this, _, window, cx| this.new_root_channel(window, cx)))
2567                    .tooltip(Tooltip::text("Create a channel"))
2568                    .into_any_element(),
2569            ),
2570            _ => None,
2571        };
2572
2573        let can_collapse = match section {
2574            Section::ActiveCall | Section::Channels | Section::Contacts => false,
2575            Section::ChannelInvites
2576            | Section::ContactRequests
2577            | Section::Online
2578            | Section::Offline => true,
2579        };
2580
2581        h_flex().w_full().group("section-header").child(
2582            ListHeader::new(text)
2583                .when(can_collapse, |header| {
2584                    header.toggle(Some(!is_collapsed)).on_toggle(cx.listener(
2585                        move |this, _, _, cx| {
2586                            this.toggle_section_expanded(section, cx);
2587                        },
2588                    ))
2589                })
2590                .inset(true)
2591                .end_slot::<AnyElement>(button)
2592                .toggle_state(is_selected),
2593        )
2594    }
2595
2596    fn render_contact(
2597        &self,
2598        contact: &Arc<Contact>,
2599        calling: bool,
2600        is_selected: bool,
2601        cx: &mut Context<Self>,
2602    ) -> impl IntoElement {
2603        let online = contact.online;
2604        let busy = contact.busy || calling;
2605        let github_login = contact.user.github_login.clone();
2606        let item = ListItem::new(github_login.clone())
2607            .indent_level(1)
2608            .indent_step_size(px(20.))
2609            .toggle_state(is_selected)
2610            .child(
2611                h_flex()
2612                    .w_full()
2613                    .justify_between()
2614                    .child(render_participant_name_and_handle(&contact.user))
2615                    .when(calling, |el| {
2616                        el.child(Label::new("Calling").color(Color::Muted))
2617                    })
2618                    .when(!calling, |el| {
2619                        el.child(
2620                            IconButton::new("contact context menu", IconName::Ellipsis)
2621                                .icon_color(Color::Muted)
2622                                .visible_on_hover("")
2623                                .on_click(cx.listener({
2624                                    let contact = contact.clone();
2625                                    move |this, event: &ClickEvent, window, cx| {
2626                                        this.deploy_contact_context_menu(
2627                                            event.position(),
2628                                            contact.clone(),
2629                                            window,
2630                                            cx,
2631                                        );
2632                                    }
2633                                })),
2634                        )
2635                    }),
2636            )
2637            .on_secondary_mouse_down(cx.listener({
2638                let contact = contact.clone();
2639                move |this, event: &MouseDownEvent, window, cx| {
2640                    this.deploy_contact_context_menu(event.position, contact.clone(), window, cx);
2641                }
2642            }))
2643            .start_slot(
2644                // todo handle contacts with no avatar
2645                Avatar::new(contact.user.avatar_uri.clone())
2646                    .indicator::<AvatarAvailabilityIndicator>(if online {
2647                        Some(AvatarAvailabilityIndicator::new(match busy {
2648                            true => ui::CollaboratorAvailability::Busy,
2649                            false => ui::CollaboratorAvailability::Free,
2650                        }))
2651                    } else {
2652                        None
2653                    }),
2654            );
2655
2656        div()
2657            .id(github_login.clone())
2658            .group("")
2659            .child(item)
2660            .tooltip(move |_, cx| {
2661                let text = if !online {
2662                    format!(" {} is offline", &github_login)
2663                } else if busy {
2664                    format!(" {} is on a call", &github_login)
2665                } else {
2666                    let room = ActiveCall::global(cx).read(cx).room();
2667                    if room.is_some() {
2668                        format!("Invite {} to join call", &github_login)
2669                    } else {
2670                        format!("Call {}", &github_login)
2671                    }
2672                };
2673                Tooltip::simple(text, cx)
2674            })
2675    }
2676
2677    fn render_contact_request(
2678        &self,
2679        user: &Arc<User>,
2680        is_incoming: bool,
2681        is_selected: bool,
2682        cx: &mut Context<Self>,
2683    ) -> impl IntoElement {
2684        let github_login = user.github_login.clone();
2685        let user_id = user.id;
2686        let is_response_pending = self.user_store.read(cx).is_contact_request_pending(user);
2687        let color = if is_response_pending {
2688            Color::Muted
2689        } else {
2690            Color::Default
2691        };
2692
2693        let controls = if is_incoming {
2694            vec![
2695                IconButton::new("decline-contact", IconName::Close)
2696                    .on_click(cx.listener(move |this, _, window, cx| {
2697                        this.respond_to_contact_request(user_id, false, window, cx);
2698                    }))
2699                    .icon_color(color)
2700                    .tooltip(Tooltip::text("Decline invite")),
2701                IconButton::new("accept-contact", IconName::Check)
2702                    .on_click(cx.listener(move |this, _, window, cx| {
2703                        this.respond_to_contact_request(user_id, true, window, cx);
2704                    }))
2705                    .icon_color(color)
2706                    .tooltip(Tooltip::text("Accept invite")),
2707            ]
2708        } else {
2709            let github_login = github_login.clone();
2710            vec![
2711                IconButton::new("remove_contact", IconName::Close)
2712                    .on_click(cx.listener(move |this, _, window, cx| {
2713                        this.remove_contact(user_id, &github_login, window, cx);
2714                    }))
2715                    .icon_color(color)
2716                    .tooltip(Tooltip::text("Cancel invite")),
2717            ]
2718        };
2719
2720        ListItem::new(github_login.clone())
2721            .indent_level(1)
2722            .indent_step_size(px(20.))
2723            .toggle_state(is_selected)
2724            .child(
2725                h_flex()
2726                    .w_full()
2727                    .justify_between()
2728                    .child(Label::new(github_login))
2729                    .child(h_flex().children(controls)),
2730            )
2731            .start_slot(Avatar::new(user.avatar_uri.clone()))
2732    }
2733
2734    fn render_channel_invite(
2735        &self,
2736        channel: &Arc<Channel>,
2737        is_selected: bool,
2738        cx: &mut Context<Self>,
2739    ) -> ListItem {
2740        let channel_id = channel.id;
2741        let response_is_pending = self
2742            .channel_store
2743            .read(cx)
2744            .has_pending_channel_invite_response(channel);
2745        let color = if response_is_pending {
2746            Color::Muted
2747        } else {
2748            Color::Default
2749        };
2750
2751        let controls = [
2752            IconButton::new("reject-invite", IconName::Close)
2753                .on_click(cx.listener(move |this, _, _, cx| {
2754                    this.respond_to_channel_invite(channel_id, false, cx);
2755                }))
2756                .icon_color(color)
2757                .tooltip(Tooltip::text("Decline invite")),
2758            IconButton::new("accept-invite", IconName::Check)
2759                .on_click(cx.listener(move |this, _, _, cx| {
2760                    this.respond_to_channel_invite(channel_id, true, cx);
2761                }))
2762                .icon_color(color)
2763                .tooltip(Tooltip::text("Accept invite")),
2764        ];
2765
2766        ListItem::new(("channel-invite", channel.id.0 as usize))
2767            .toggle_state(is_selected)
2768            .child(
2769                h_flex()
2770                    .w_full()
2771                    .justify_between()
2772                    .child(Label::new(channel.name.clone()))
2773                    .child(h_flex().children(controls)),
2774            )
2775            .start_slot(
2776                Icon::new(IconName::Hash)
2777                    .size(IconSize::Small)
2778                    .color(Color::Muted),
2779            )
2780    }
2781
2782    fn render_contact_placeholder(&self, is_selected: bool, cx: &mut Context<Self>) -> ListItem {
2783        ListItem::new("contact-placeholder")
2784            .child(Icon::new(IconName::Plus))
2785            .child(Label::new("Add a Contact"))
2786            .toggle_state(is_selected)
2787            .on_click(cx.listener(|this, _, window, cx| this.toggle_contact_finder(window, cx)))
2788    }
2789
2790    fn render_channel(
2791        &self,
2792        channel: &Channel,
2793        depth: usize,
2794        has_children: bool,
2795        is_selected: bool,
2796        ix: usize,
2797        string_match: Option<&StringMatch>,
2798        cx: &mut Context<Self>,
2799    ) -> impl IntoElement {
2800        let channel_id = channel.id;
2801
2802        let is_active = maybe!({
2803            let call_channel = ActiveCall::global(cx)
2804                .read(cx)
2805                .room()?
2806                .read(cx)
2807                .channel_id()?;
2808            Some(call_channel == channel_id)
2809        })
2810        .unwrap_or(false);
2811        let channel_store = self.channel_store.read(cx);
2812        let is_public = channel_store
2813            .channel_for_id(channel_id)
2814            .map(|channel| channel.visibility)
2815            == Some(proto::ChannelVisibility::Public);
2816        let disclosed =
2817            has_children.then(|| self.collapsed_channels.binary_search(&channel.id).is_err());
2818
2819        let has_notes_notification = channel_store.has_channel_buffer_changed(channel_id);
2820
2821        const FACEPILE_LIMIT: usize = 3;
2822        let participants = self.channel_store.read(cx).channel_participants(channel_id);
2823
2824        let face_pile = if participants.is_empty() {
2825            None
2826        } else {
2827            let extra_count = participants.len().saturating_sub(FACEPILE_LIMIT);
2828            let result = Facepile::new(
2829                participants
2830                    .iter()
2831                    .map(|user| Avatar::new(user.avatar_uri.clone()).into_any_element())
2832                    .take(FACEPILE_LIMIT)
2833                    .chain(if extra_count > 0 {
2834                        Some(
2835                            Label::new(format!("+{extra_count}"))
2836                                .ml_2()
2837                                .into_any_element(),
2838                        )
2839                    } else {
2840                        None
2841                    })
2842                    .collect::<SmallVec<_>>(),
2843            );
2844
2845            Some(result)
2846        };
2847
2848        let width = self.width.unwrap_or(px(240.));
2849        let root_id = channel.root_id();
2850
2851        div()
2852            .h_6()
2853            .id(channel_id.0 as usize)
2854            .group("")
2855            .flex()
2856            .w_full()
2857            .when(!channel.is_root_channel(), |el| {
2858                el.on_drag(channel.clone(), move |channel, _, _, cx| {
2859                    cx.new(|_| DraggedChannelView {
2860                        channel: channel.clone(),
2861                        width,
2862                    })
2863                })
2864            })
2865            .drag_over::<Channel>({
2866                move |style, dragged_channel: &Channel, _window, cx| {
2867                    if dragged_channel.root_id() == root_id {
2868                        style.bg(cx.theme().colors().ghost_element_hover)
2869                    } else {
2870                        style
2871                    }
2872                }
2873            })
2874            .on_drop(
2875                cx.listener(move |this, dragged_channel: &Channel, window, cx| {
2876                    if dragged_channel.root_id() != root_id {
2877                        return;
2878                    }
2879                    this.move_channel(dragged_channel.id, channel_id, window, cx);
2880                }),
2881            )
2882            .child(
2883                ListItem::new(channel_id.0 as usize)
2884                    // Add one level of depth for the disclosure arrow.
2885                    .indent_level(depth + 1)
2886                    .indent_step_size(px(20.))
2887                    .toggle_state(is_selected || is_active)
2888                    .toggle(disclosed)
2889                    .on_toggle(cx.listener(move |this, _, window, cx| {
2890                        this.toggle_channel_collapsed(channel_id, window, cx)
2891                    }))
2892                    .on_click(cx.listener(move |this, _, window, cx| {
2893                        if is_active {
2894                            this.open_channel_notes(channel_id, window, cx)
2895                        } else {
2896                            this.join_channel(channel_id, window, cx)
2897                        }
2898                    }))
2899                    .on_secondary_mouse_down(cx.listener(
2900                        move |this, event: &MouseDownEvent, window, cx| {
2901                            this.deploy_channel_context_menu(
2902                                event.position,
2903                                channel_id,
2904                                ix,
2905                                window,
2906                                cx,
2907                            )
2908                        },
2909                    ))
2910                    .start_slot(
2911                        div()
2912                            .relative()
2913                            .child(
2914                                Icon::new(if is_public {
2915                                    IconName::Public
2916                                } else {
2917                                    IconName::Hash
2918                                })
2919                                .size(IconSize::Small)
2920                                .color(Color::Muted),
2921                            )
2922                            .children(has_notes_notification.then(|| {
2923                                div()
2924                                    .w_1p5()
2925                                    .absolute()
2926                                    .right(px(-1.))
2927                                    .top(px(-1.))
2928                                    .child(Indicator::dot().color(Color::Info))
2929                            })),
2930                    )
2931                    .child(
2932                        h_flex()
2933                            .id(channel_id.0 as usize)
2934                            .child(match string_match {
2935                                None => Label::new(channel.name.clone()).into_any_element(),
2936                                Some(string_match) => HighlightedLabel::new(
2937                                    channel.name.clone(),
2938                                    string_match.positions.clone(),
2939                                )
2940                                .into_any_element(),
2941                            })
2942                            .children(face_pile.map(|face_pile| face_pile.p_1())),
2943                    ),
2944            )
2945            .child(
2946                h_flex().absolute().right(rems(0.)).h_full().child(
2947                    h_flex()
2948                        .h_full()
2949                        .bg(cx.theme().colors().background)
2950                        .rounded_l_sm()
2951                        .gap_1()
2952                        .px_1()
2953                        .child(
2954                            IconButton::new("channel_notes", IconName::Reader)
2955                                .style(ButtonStyle::Filled)
2956                                .shape(ui::IconButtonShape::Square)
2957                                .icon_size(IconSize::Small)
2958                                .icon_color(if has_notes_notification {
2959                                    Color::Default
2960                                } else {
2961                                    Color::Muted
2962                                })
2963                                .on_click(cx.listener(move |this, _, window, cx| {
2964                                    this.open_channel_notes(channel_id, window, cx)
2965                                }))
2966                                .tooltip(Tooltip::text("Open channel notes")),
2967                        )
2968                        .visible_on_hover(""),
2969                ),
2970            )
2971            .tooltip({
2972                let channel_store = self.channel_store.clone();
2973                move |_window, cx| {
2974                    cx.new(|_| JoinChannelTooltip {
2975                        channel_store: channel_store.clone(),
2976                        channel_id,
2977                        has_notes_notification,
2978                    })
2979                    .into()
2980                }
2981            })
2982    }
2983
2984    fn render_channel_editor(
2985        &self,
2986        depth: usize,
2987        _window: &mut Window,
2988        _cx: &mut Context<Self>,
2989    ) -> impl IntoElement {
2990        let item = ListItem::new("channel-editor")
2991            .inset(false)
2992            // Add one level of depth for the disclosure arrow.
2993            .indent_level(depth + 1)
2994            .indent_step_size(px(20.))
2995            .start_slot(
2996                Icon::new(IconName::Hash)
2997                    .size(IconSize::Small)
2998                    .color(Color::Muted),
2999            );
3000
3001        if let Some(pending_name) = self
3002            .channel_editing_state
3003            .as_ref()
3004            .and_then(|state| state.pending_name())
3005        {
3006            item.child(Label::new(pending_name))
3007        } else {
3008            item.child(self.channel_name_editor.clone())
3009        }
3010    }
3011}
3012
3013fn render_tree_branch(
3014    is_last: bool,
3015    overdraw: bool,
3016    window: &mut Window,
3017    cx: &mut App,
3018) -> impl IntoElement {
3019    let rem_size = window.rem_size();
3020    let line_height = window.text_style().line_height_in_pixels(rem_size);
3021    let width = rem_size * 1.5;
3022    let thickness = px(1.);
3023    let color = cx.theme().colors().text;
3024
3025    canvas(
3026        |_, _, _| {},
3027        move |bounds, _, window, _| {
3028            let start_x = (bounds.left() + bounds.right() - thickness) / 2.;
3029            let start_y = (bounds.top() + bounds.bottom() - thickness) / 2.;
3030            let right = bounds.right();
3031            let top = bounds.top();
3032
3033            window.paint_quad(fill(
3034                Bounds::from_corners(
3035                    point(start_x, top),
3036                    point(
3037                        start_x + thickness,
3038                        if is_last {
3039                            start_y
3040                        } else {
3041                            bounds.bottom() + if overdraw { px(1.) } else { px(0.) }
3042                        },
3043                    ),
3044                ),
3045                color,
3046            ));
3047            window.paint_quad(fill(
3048                Bounds::from_corners(point(start_x, start_y), point(right, start_y + thickness)),
3049                color,
3050            ));
3051        },
3052    )
3053    .w(width)
3054    .h(line_height)
3055}
3056
3057fn render_participant_name_and_handle(user: &User) -> impl IntoElement {
3058    Label::new(if let Some(ref display_name) = user.name {
3059        format!("{display_name} ({})", user.github_login)
3060    } else {
3061        user.github_login.to_string()
3062    })
3063}
3064
3065impl Render for CollabPanel {
3066    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3067        v_flex()
3068            .key_context(self.dispatch_context(window, cx))
3069            .on_action(cx.listener(CollabPanel::cancel))
3070            .on_action(cx.listener(CollabPanel::select_next))
3071            .on_action(cx.listener(CollabPanel::select_previous))
3072            .on_action(cx.listener(CollabPanel::confirm))
3073            .on_action(cx.listener(CollabPanel::insert_space))
3074            .on_action(cx.listener(CollabPanel::remove_selected_channel))
3075            .on_action(cx.listener(CollabPanel::show_inline_context_menu))
3076            .on_action(cx.listener(CollabPanel::rename_selected_channel))
3077            .on_action(cx.listener(CollabPanel::open_selected_channel_notes))
3078            .on_action(cx.listener(CollabPanel::collapse_selected_channel))
3079            .on_action(cx.listener(CollabPanel::expand_selected_channel))
3080            .on_action(cx.listener(CollabPanel::start_move_selected_channel))
3081            .on_action(cx.listener(CollabPanel::move_channel_up))
3082            .on_action(cx.listener(CollabPanel::move_channel_down))
3083            .track_focus(&self.focus_handle)
3084            .size_full()
3085            .child(if !self.client.status().borrow().is_or_was_connected() {
3086                self.render_signed_out(cx)
3087            } else {
3088                self.render_signed_in(window, cx)
3089            })
3090            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3091                deferred(
3092                    anchored()
3093                        .position(*position)
3094                        .anchor(gpui::Corner::TopLeft)
3095                        .child(menu.clone()),
3096                )
3097                .with_priority(1)
3098            }))
3099    }
3100}
3101
3102impl EventEmitter<PanelEvent> for CollabPanel {}
3103
3104impl Panel for CollabPanel {
3105    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3106        CollaborationPanelSettings::get_global(cx).dock
3107    }
3108
3109    fn position_is_valid(&self, position: DockPosition) -> bool {
3110        matches!(position, DockPosition::Left | DockPosition::Right)
3111    }
3112
3113    fn set_position(
3114        &mut self,
3115        position: DockPosition,
3116        _window: &mut Window,
3117        cx: &mut Context<Self>,
3118    ) {
3119        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3120            settings.collaboration_panel.get_or_insert_default().dock = Some(position.into())
3121        });
3122    }
3123
3124    fn size(&self, _window: &Window, cx: &App) -> Pixels {
3125        self.width
3126            .unwrap_or_else(|| CollaborationPanelSettings::get_global(cx).default_width)
3127    }
3128
3129    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
3130        self.width = size;
3131        cx.notify();
3132        cx.defer_in(window, |this, _, cx| {
3133            this.serialize(cx);
3134        });
3135    }
3136
3137    fn icon(&self, _window: &Window, cx: &App) -> Option<ui::IconName> {
3138        CollaborationPanelSettings::get_global(cx)
3139            .button
3140            .then_some(ui::IconName::UserGroup)
3141    }
3142
3143    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3144        Some("Collab Panel")
3145    }
3146
3147    fn toggle_action(&self) -> Box<dyn gpui::Action> {
3148        Box::new(ToggleFocus)
3149    }
3150
3151    fn persistent_name() -> &'static str {
3152        "CollabPanel"
3153    }
3154
3155    fn panel_key() -> &'static str {
3156        COLLABORATION_PANEL_KEY
3157    }
3158
3159    fn activation_priority(&self) -> u32 {
3160        6
3161    }
3162}
3163
3164impl Focusable for CollabPanel {
3165    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3166        self.filter_editor.focus_handle(cx)
3167    }
3168}
3169
3170impl PartialEq for ListEntry {
3171    fn eq(&self, other: &Self) -> bool {
3172        match self {
3173            ListEntry::Header(section_1) => {
3174                if let ListEntry::Header(section_2) = other {
3175                    return section_1 == section_2;
3176                }
3177            }
3178            ListEntry::CallParticipant { user: user_1, .. } => {
3179                if let ListEntry::CallParticipant { user: user_2, .. } = other {
3180                    return user_1.id == user_2.id;
3181                }
3182            }
3183            ListEntry::ParticipantProject {
3184                project_id: project_id_1,
3185                ..
3186            } => {
3187                if let ListEntry::ParticipantProject {
3188                    project_id: project_id_2,
3189                    ..
3190                } = other
3191                {
3192                    return project_id_1 == project_id_2;
3193                }
3194            }
3195            ListEntry::ParticipantScreen {
3196                peer_id: peer_id_1, ..
3197            } => {
3198                if let ListEntry::ParticipantScreen {
3199                    peer_id: peer_id_2, ..
3200                } = other
3201                {
3202                    return peer_id_1 == peer_id_2;
3203                }
3204            }
3205            ListEntry::Channel {
3206                channel: channel_1, ..
3207            } => {
3208                if let ListEntry::Channel {
3209                    channel: channel_2, ..
3210                } = other
3211                {
3212                    return channel_1.id == channel_2.id;
3213                }
3214            }
3215            ListEntry::ChannelNotes { channel_id } => {
3216                if let ListEntry::ChannelNotes {
3217                    channel_id: other_id,
3218                } = other
3219                {
3220                    return channel_id == other_id;
3221                }
3222            }
3223            ListEntry::ChannelInvite(channel_1) => {
3224                if let ListEntry::ChannelInvite(channel_2) = other {
3225                    return channel_1.id == channel_2.id;
3226                }
3227            }
3228            ListEntry::IncomingRequest(user_1) => {
3229                if let ListEntry::IncomingRequest(user_2) = other {
3230                    return user_1.id == user_2.id;
3231                }
3232            }
3233            ListEntry::OutgoingRequest(user_1) => {
3234                if let ListEntry::OutgoingRequest(user_2) = other {
3235                    return user_1.id == user_2.id;
3236                }
3237            }
3238            ListEntry::Contact {
3239                contact: contact_1, ..
3240            } => {
3241                if let ListEntry::Contact {
3242                    contact: contact_2, ..
3243                } = other
3244                {
3245                    return contact_1.user.id == contact_2.user.id;
3246                }
3247            }
3248            ListEntry::ChannelEditor { depth } => {
3249                if let ListEntry::ChannelEditor { depth: other_depth } = other {
3250                    return depth == other_depth;
3251                }
3252            }
3253            ListEntry::ContactPlaceholder => {
3254                if let ListEntry::ContactPlaceholder = other {
3255                    return true;
3256                }
3257            }
3258        }
3259        false
3260    }
3261}
3262
3263struct DraggedChannelView {
3264    channel: Channel,
3265    width: Pixels,
3266}
3267
3268impl Render for DraggedChannelView {
3269    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3270        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
3271        h_flex()
3272            .font_family(ui_font)
3273            .bg(cx.theme().colors().background)
3274            .w(self.width)
3275            .p_1()
3276            .gap_1()
3277            .child(
3278                Icon::new(
3279                    if self.channel.visibility == proto::ChannelVisibility::Public {
3280                        IconName::Public
3281                    } else {
3282                        IconName::Hash
3283                    },
3284                )
3285                .size(IconSize::Small)
3286                .color(Color::Muted),
3287            )
3288            .child(Label::new(self.channel.name.clone()))
3289    }
3290}
3291
3292struct JoinChannelTooltip {
3293    channel_store: Entity<ChannelStore>,
3294    channel_id: ChannelId,
3295    #[allow(unused)]
3296    has_notes_notification: bool,
3297}
3298
3299impl Render for JoinChannelTooltip {
3300    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3301        tooltip_container(cx, |container, cx| {
3302            let participants = self
3303                .channel_store
3304                .read(cx)
3305                .channel_participants(self.channel_id);
3306
3307            container
3308                .child(Label::new("Join channel"))
3309                .children(participants.iter().map(|participant| {
3310                    h_flex()
3311                        .gap_2()
3312                        .child(Avatar::new(participant.avatar_uri.clone()))
3313                        .child(render_participant_name_and_handle(participant))
3314                }))
3315        })
3316    }
3317}