collab_panel.rs

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