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