A platform for community discussion. Free, open, simple.
FEATURE: introduces group channels (#24288)
Joffrey JAFFEUXab832cc865ff
diff --git a/app/assets/stylesheets/common/components/user-status-message.scss b/app/assets/stylesheets/common/components/user-status-message.scssindex 3c2b384593d..f3107865f8c 100644--- a/app/assets/stylesheets/common/components/user-status-message.scss+++ b/app/assets/stylesheets/common/components/user-status-message.scss@@ -1,4 +1,7 @@[data-content][data-identifier="user-status-message-tooltip"] {+ display: flex;+ align-items: center;+.emoji {width: 1em;height: 1em;@@ -16,7 +19,7 @@}.user-status-tooltip-until {- margin-top: 0.1rem;color: var(--primary-medium);+ padding-left: 0.25rem;}}diff --git a/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb b/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rbindex d35d63df59c..a60769128e7 100644--- a/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb@@ -28,4 +28,12 @@ class Chat::Api::ChannelsMembershipsController < Chat::Api::ChannelsController},)end++ def create+ with_service(Chat::AddUsersToChannel) do+ on_failed_policy(:can_add_users_to_channel) do+ render_json_error(I18n.t("chat.errors.users_cant_be_added_to_channel"))+ end+ end+ endenddiff --git a/plugins/chat/app/models/chat/category_channel.rb b/plugins/chat/app/models/chat/category_channel.rbindex bf23f561cde..e23a37f1a7c 100644--- a/plugins/chat/app/models/chat/category_channel.rb+++ b/plugins/chat/app/models/chat/category_channel.rb@@ -27,21 +27,5 @@ module Chatself.slug = Slug.for(self.title.strip, "")self.slug = "" if duplicate_slug?end-- def ensure_slug_ok- if self.slug.present?- # if we don't unescape it first we strip the % from the encoded version- slug = SiteSetting.slug_generation_method == "encoded" ? CGI.unescape(self.slug) : self.slug- self.slug = Slug.for(slug, "", method: :encoded)-- if self.slug.blank?- errors.add(:slug, :invalid)- elsif SiteSetting.slug_generation_method == "ascii" && !CGI.unescape(self.slug).ascii_only?- errors.add(:slug, I18n.t("chat.category_channel.errors.slug_contains_non_ascii_chars"))- elsif duplicate_slug?- errors.add(:slug, I18n.t("chat.category_channel.errors.is_already_in_use"))- end- end- endendenddiff --git a/plugins/chat/app/models/chat/channel.rb b/plugins/chat/app/models/chat/channel.rbindex 791be5b7b60..8e585bb0b09 100644--- a/plugins/chat/app/models/chat/channel.rb+++ b/plugins/chat/app/models/chat/channel.rb@@ -27,6 +27,7 @@ module Chatclass_name: "Chat::Message",foreign_key: :last_message_id,optional: true+def last_messagesuper || NullMessage.newend@@ -109,8 +110,28 @@ module Chat%i[allowed_user_ids allowed_group_ids chatable_url].each { |name| define_method(name) { nil } }+ def ensure_slug_ok+ if self.slug.present?+ # if we don't unescape it first we strip the % from the encoded version+ slug = SiteSetting.slug_generation_method == "encoded" ? CGI.unescape(self.slug) : self.slug+ self.slug = Slug.for(slug, "", method: :encoded)++ if self.slug.blank?+ errors.add(:slug, :invalid)+ elsif SiteSetting.slug_generation_method == "ascii" && !CGI.unescape(self.slug).ascii_only?+ errors.add(:slug, I18n.t("chat.category_channel.errors.slug_contains_non_ascii_chars"))+ elsif duplicate_slug?+ errors.add(:slug, I18n.t("chat.category_channel.errors.is_already_in_use"))+ end+ end+ end+def membership_for(user)- user_chat_channel_memberships.find_by(user: user)+ if user_chat_channel_memberships.loaded?+ user_chat_channel_memberships.detect { |m| m.user_id == user.id }+ else+ user_chat_channel_memberships.find_by(user: user)+ endenddef add(user)@@ -177,6 +198,7 @@ module ChatAND (users.suspended_till IS NULL OR users.suspended_till <= CURRENT_TIMESTAMP)AND NOT users.stagedAND user_chat_channel_memberships.following+ and users.id > 0GROUP BY user_chat_channel_memberships.chat_channel_id) subqueryWHERE channels.id = subquery.chat_channel_iddiff --git a/plugins/chat/app/models/chat/direct_message.rb b/plugins/chat/app/models/chat/direct_message.rbindex 58fbf39d6b1..c45038e1ff8 100644--- a/plugins/chat/app/models/chat/direct_message.rb+++ b/plugins/chat/app/models/chat/direct_message.rb@@ -19,6 +19,7 @@ module Chatdef for_user_ids(user_ids)joins(:users)+ .where(group: false).group("direct_message_channels.id").having("ARRAY[?] = ARRAY_AGG(users.id ORDER BY users.id)", user_ids.sort).first@@ -30,6 +31,8 @@ module Chatenddef chat_channel_title_for_user(chat_channel, acting_user)+ return chat_channel.name if group && chat_channel.name.present?+users =(direct_message_users.map(&:user) - [acting_user]).map { |user| user || Chat::NullUser.new }@@ -66,6 +69,7 @@ end# Table name: direct_message_channels## id :bigint not null, primary key+# group :boolean# created_at :datetime not null# updated_at :datetime not null#diff --git a/plugins/chat/app/models/chat/direct_message_channel.rb b/plugins/chat/app/models/chat/direct_message_channel.rbindex 44dd3bf3bc4..30077776344 100644--- a/plugins/chat/app/models/chat/direct_message_channel.rb+++ b/plugins/chat/app/models/chat/direct_message_channel.rb@@ -20,12 +20,8 @@ module Chatdirect_message.chat_channel_title_for_user(self, user)end- def ensure_slug_ok- true- end-def generate_auto_slug- self.slug = nil+ false if !self.slug.present?endendenddiff --git a/plugins/chat/app/models/chat/message.rb b/plugins/chat/app/models/chat/message.rbindex 8cbe3ff5d03..c3a5ea2cce8 100644--- a/plugins/chat/app/models/chat/message.rb+++ b/plugins/chat/app/models/chat/message.rb@@ -114,7 +114,7 @@ module Chatreturn uploads.first.original_filename if cooked.blank? && uploads.present?# this may return blank for some complex things like quotes, that is acceptable- PrettyText.excerpt(cooked, max_length, strip_links: true)+ PrettyText.excerpt(cooked, max_length, strip_links: true, keep_mentions: true)enddef censored_excerpt(max_length: 50)diff --git a/plugins/chat/app/queries/chat/channel_memberships_query.rb b/plugins/chat/app/queries/chat/channel_memberships_query.rbindex 294ca724c89..d2141c8eb64 100644--- a/plugins/chat/app/queries/chat/channel_memberships_query.rb+++ b/plugins/chat/app/queries/chat/channel_memberships_query.rb@@ -7,8 +7,10 @@ module ChatChat::UserChatChannelMembership.joins(:user).includes(:user)- .where(user: User.activated.not_suspended.not_staged)- .where(chat_channel: channel, following: true)+ .where(user: User.human_users.activated.not_suspended.not_staged)+ .where(chat_channel: channel)++ query = query.where(following: true) if channel.category_channel?return query.count if count_onlydiff --git a/plugins/chat/app/serializers/chat/basic_user_serializer.rb b/plugins/chat/app/serializers/chat/basic_user_serializer.rbnew file mode 100644index 00000000000..8daaf74cddf--- /dev/null+++ b/plugins/chat/app/serializers/chat/basic_user_serializer.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++module Chat+ class BasicUserSerializer < BasicUserSerializer+ attributes :can_chat, :has_chat_enabled++ def can_chat+ SiteSetting.chat_enabled && scope&.can_chat?+ end++ def has_chat_enabled+ can_chat && object.user_option&.chat_enabled+ end+ end+enddiff --git a/plugins/chat/app/serializers/chat/channel_serializer.rb b/plugins/chat/app/serializers/chat/channel_serializer.rbindex 9ed2dcde225..a6c4b87bea7 100644--- a/plugins/chat/app/serializers/chat/channel_serializer.rb+++ b/plugins/chat/app/serializers/chat/channel_serializer.rb@@ -88,7 +88,7 @@ module Chatenddef include_auto_join_users?- scope.can_edit_chat_channel?+ object.category_channel? && scope.can_edit_chat_channel?(object)enddef include_current_user_membership?diff --git a/plugins/chat/app/serializers/chat/direct_message_serializer.rb b/plugins/chat/app/serializers/chat/direct_message_serializer.rbindex b2497c73f73..1c857ae2dd6 100644--- a/plugins/chat/app/serializers/chat/direct_message_serializer.rb+++ b/plugins/chat/app/serializers/chat/direct_message_serializer.rb@@ -2,9 +2,9 @@module Chatclass DirectMessageSerializer < ApplicationSerializer- attributes :id+ attribute :group- has_many :users, serializer: Chat::ChatableUserSerializer, embed: :objects+ has_many :users, serializer: ::Chat::ChatableUserSerializer, embed: :objectsdef usersusers = object.direct_message_users.map(&:user).map { |u| u || Chat::NullUser.new }diff --git a/plugins/chat/app/serializers/chat/message_serializer.rb b/plugins/chat/app/serializers/chat/message_serializer.rbindex 9c0a55a86cb..3a3c10c06be 100644--- a/plugins/chat/app/serializers/chat/message_serializer.rb+++ b/plugins/chat/app/serializers/chat/message_serializer.rb@@ -37,7 +37,7 @@ module Chatdef mentioned_usersobject.chat_mentions- .includes(:user)+ .includes(user: :user_status).map(&:user).compact.sort_by(&:id)diff --git a/plugins/chat/app/serializers/chat/thread_preview_serializer.rb b/plugins/chat/app/serializers/chat/thread_preview_serializer.rbindex 72f97282678..1ec04c3504f 100644--- a/plugins/chat/app/serializers/chat/thread_preview_serializer.rb+++ b/plugins/chat/app/serializers/chat/thread_preview_serializer.rb@@ -7,8 +7,8 @@ module Chat:last_reply_id,:participant_count,:reply_count- has_many :participant_users, serializer: BasicUserSerializer, embed: :objects- has_one :last_reply_user, serializer: BasicUserSerializer, embed: :objects+ has_many :participant_users, serializer: ::BasicUserSerializer, embed: :objects+ has_one :last_reply_user, serializer: ::BasicUserSerializer, embed: :objectsdef initialize(object, opts)super(object, opts)diff --git a/plugins/chat/app/serializers/chat/user_channel_membership_serializer.rb b/plugins/chat/app/serializers/chat/user_channel_membership_serializer.rbindex 8dd02a7ffa1..5abd13c372c 100644--- a/plugins/chat/app/serializers/chat/user_channel_membership_serializer.rb+++ b/plugins/chat/app/serializers/chat/user_channel_membership_serializer.rb@@ -2,10 +2,10 @@module Chatclass UserChannelMembershipSerializer < BaseChannelMembershipSerializer- has_one :user, serializer: BasicUserSerializer, embed: :objects+ has_one :user, serializer: ::Chat::BasicUserSerializer, embed: :objectsdef user- object.user+ object.user || Chat::NullUser.newendendenddiff --git a/plugins/chat/app/services/chat/add_users_to_channel.rb b/plugins/chat/app/services/chat/add_users_to_channel.rbnew file mode 100644index 00000000000..6303fbc8bd4--- /dev/null+++ b/plugins/chat/app/services/chat/add_users_to_channel.rb@@ -0,0 +1,149 @@+# frozen_string_literal: true++module Chat+ # Service responsible to add users to a channel.+ # The guardian passed in is the "acting user" when adding users.+ # The service is essentially creating memberships for the users.+ #+ # @example+ # ::Chat::AddUsersToChannel.call(+ # guardian: guardian,+ # channel_id: 1,+ # usernames: ["bob", "alice"]+ # )+ #+ class AddUsersToChannel+ include Service::Base++ # @!method call(guardian:, **params_to_create)+ # @param [Guardian] guardian+ # @param [Integer] id of the channel+ # @param [Hash] params_to_create+ # @option params_to_create [Array<String>] usernames+ # @return [Service::Base::Context]+ contract+ model :channel+ policy :can_add_users_to_channel+ model :users, optional: true++ transaction do+ step :upsert_memberships+ step :recompute_users_count+ step :notice_channel+ end++ # @!visibility private+ class Contract+ attribute :usernames, :array+ validates :usernames, presence: true++ attribute :channel_id, :integer+ validates :channel_id, presence: true++ validate :usernames_length++ def usernames_length+ if usernames && usernames.length > SiteSetting.chat_max_direct_message_users + 1 # 1 for current user+ errors.add(+ :usernames,+ "should have less than #{SiteSetting.chat_max_direct_message_users} elements",+ )+ end+ end+ end++ private++ def can_add_users_to_channel(guardian:, channel:, **)+ (guardian.user.admin? || channel.joined_by?(guardian.user)) &&+ channel.direct_message_channel? && channel.chatable.group+ end++ def fetch_users(contract:, channel:, **)+ ::User.where(+ "username IN (?) AND id NOT IN (?)",+ [*contract.usernames],+ channel.chatable.direct_message_users.select(:user_id),+ ).to_a+ end++ def fetch_channel(contract:, **)+ ::Chat::Channel.includes(:chatable).find_by(id: contract.channel_id)+ end++ def upsert_memberships(channel:, users:, **)+ always_level = ::Chat::UserChatChannelMembership::NOTIFICATION_LEVELS[:always]++ memberships =+ users.map do |user|+ {+ user_id: user.id,+ chat_channel_id: channel.id,+ muted: false,+ following: true,+ desktop_notification_level: always_level,+ mobile_notification_level: always_level,+ created_at: Time.zone.now,+ updated_at: Time.zone.now,+ }+ end++ if memberships.blank?+ context.added_user_ids = []+ return+ end++ context.added_user_ids =+ ::Chat::UserChatChannelMembership+ .upsert_all(+ memberships,+ unique_by: %i[user_id chat_channel_id],+ returning: Arel.sql("user_id, (xmax = '0') as inserted"),+ )+ .select { |row| row["inserted"] }+ .map { |row| row["user_id"] }++ ::Chat::DirectMessageUser.upsert_all(+ context.added_user_ids.map do |id|+ {+ user_id: id,+ direct_message_channel_id: channel.chatable.id,+ created_at: Time.zone.now,+ updated_at: Time.zone.now,+ }+ end,+ unique_by: %i[direct_message_channel_id user_id],+ )+ end++ def recompute_users_count(channel:, **)+ return if context.added_user_ids.blank?++ channel.update!(+ user_count: ::Chat::ChannelMembershipsQuery.count(channel),+ user_count_stale: false,+ )+ end++ def notice_channel(guardian:, channel:, users:, **)+ added_users = users.select { |u| context.added_user_ids.include?(u.id) }++ return if added_users.blank?++ result =+ ::Chat::CreateMessage.call(+ guardian: Discourse.system_user.guardian,+ chat_channel_id: channel.id,+ message:+ I18n.t(+ "chat.channel.users_invited_to_channel",+ invited_users: added_users.map { |u| "@#{u.username}" }.join(", "),+ inviting_user: "@#{guardian.user.username}",+ count: added_users.count,+ ),+ )++ fail!(failure: "Failed to notice the channel") if result.failure?+ end+ end+enddiff --git a/plugins/chat/app/services/chat/create_direct_message_channel.rb b/plugins/chat/app/services/chat/create_direct_message_channel.rbindex 1b5600bcf53..8ce61377ed2 100644--- a/plugins/chat/app/services/chat/create_direct_message_channel.rb+++ b/plugins/chat/app/services/chat/create_direct_message_channel.rb@@ -7,7 +7,7 @@ module Chat# are passed in.## @example- # Service::Chat::CreateDirectMessageChannel.call(+ # ::Chat::CreateDirectMessageChannel.call(# guardian: guardian,# target_usernames: ["bob", "alice"]# )@@ -32,10 +32,13 @@ module Chatclass_name: Chat::DirectMessageChannel::CanCommunicateAllPartiesPolicymodel :direct_message, :fetch_or_create_direct_messagemodel :channel, :fetch_or_create_channel+ step :set_optional_namestep :update_memberships+ step :recompute_users_count# @!visibility privateclass Contract+ attribute :name, :stringattribute :target_usernames, :arrayvalidates :target_usernames, presence: trueend@@ -58,17 +61,26 @@ module Chat!user_comm_screener.actor_disallowing_all_pms?end- def fetch_or_create_direct_message(target_users:, **)- Chat::DirectMessage.for_user_ids(target_users.map(&:id)) ||- Chat::DirectMessage.create(user_ids: target_users.map(&:id))+ def fetch_or_create_direct_message(target_users:, contract:, **)+ ids = target_users.map(&:id)++ if ids.size > 2 || contract.name.present?+ ::Chat::DirectMessage.create(user_ids: ids, group: true)+ else+ ::Chat::DirectMessage.for_user_ids(ids) || ::Chat::DirectMessage.create(user_ids: ids)+ endenddef fetch_or_create_channel(direct_message:, **)- Chat::DirectMessageChannel.find_or_create_by(chatable: direct_message)+ ::Chat::DirectMessageChannel.find_or_create_by(chatable: direct_message)+ end++ def set_optional_name(channel:, contract:, **)+ channel.update!(name: contract.name) if contract.name&.length&.positive?enddef update_memberships(channel:, target_users:, **)- always_level = Chat::UserChatChannelMembership::NOTIFICATION_LEVELS[:always]+ always_level = ::Chat::UserChatChannelMembership::NOTIFICATION_LEVELS[:always]memberships =target_users.map do |user|@@ -84,10 +96,17 @@ module Chat}end- Chat::UserChatChannelMembership.upsert_all(+ ::Chat::UserChatChannelMembership.upsert_all(memberships,unique_by: %i[user_id chat_channel_id],)end++ def recompute_users_count(channel:, **)+ channel.update!(+ user_count: ::Chat::ChannelMembershipsQuery.count(channel),+ user_count_stale: false,+ )+ endendenddiff --git a/plugins/chat/app/services/chat/create_message.rb b/plugins/chat/app/services/chat/create_message.rbindex 51e14ddf01e..4adcdae34d8 100644--- a/plugins/chat/app/services/chat/create_message.rb+++ b/plugins/chat/app/services/chat/create_message.rb@@ -22,9 +22,9 @@ module Chatpolicy :no_silenced_usercontractmodel :channel+ step :enforce_system_membershippolicy :allowed_to_join_channelpolicy :allowed_to_create_message_in_channel, class_name: Chat::Channel::MessageCreationPolicy- step :enforce_system_membershipmodel :channel_membershipmodel :reply, optional: truepolicy :ensure_reply_consistency@@ -76,7 +76,13 @@ module Chatenddef enforce_system_membership(guardian:, channel:, **)- channel.add(guardian.user) if guardian.user.is_system_user?+ if guardian.user&.is_system_user?+ channel.add(guardian.user)++ if channel.direct_message_channel?+ channel.chatable.direct_message_users.find_or_create_by!(user: guardian.user)+ end+ endenddef fetch_channel_membership(guardian:, channel:, **)diff --git a/plugins/chat/app/services/chat/list_channel_messages.rb b/plugins/chat/app/services/chat/list_channel_messages.rbindex affcfabbe07..7fd4f2093f5 100644--- a/plugins/chat/app/services/chat/list_channel_messages.rb+++ b/plugins/chat/app/services/chat/list_channel_messages.rb@@ -59,7 +59,7 @@ module Chatprivatedef fetch_channel(contract:, **)- ::Chat::Channel.strict_loading.includes(:chatable).find_by(id: contract.channel_id)+ ::Chat::Channel.includes(:chatable).find_by(id: contract.channel_id)enddef fetch_optional_membership(channel:, guardian:, **)diff --git a/plugins/chat/app/services/chat/search_chatable.rb b/plugins/chat/app/services/chat/search_chatable.rbindex d0edb6435dd..30e45541d64 100644--- a/plugins/chat/app/services/chat/search_chatable.rb+++ b/plugins/chat/app/services/chat/search_chatable.rb@@ -15,78 +15,65 @@ module Chat# @return [Service::Base::Context]contract- step :set_modestep :clean_term- step :fetch_memberships- step :fetch_users- step :fetch_category_channels- step :fetch_direct_message_channels+ model :memberships, optional: true+ model :users, optional: true+ model :category_channels, optional: true+ model :direct_message_channels, optional: true# @!visibility privateclass Contract- attribute :term, default: ""+ attribute :term, :string, default: ""+ attribute :include_users, :boolean, default: true+ attribute :include_category_channels, :boolean, default: true+ attribute :include_direct_message_channels, :boolean, default: true+ attribute :excluded_memberships_channel_id, :integerendprivate- def set_mode- context.mode =- if context.contract.term&.start_with?("#")- :channel- elsif context.contract.term&.start_with?("@")- :user- else- :all- end- end-def clean_term(contract:, **)context.term = contract.term.downcase&.gsub(/^#+/, "")&.gsub(/^@+/, "")&.stripenddef fetch_memberships(guardian:, **)- context.memberships = ::Chat::ChannelMembershipManager.all_for_user(guardian.user)+ ::Chat::ChannelMembershipManager.all_for_user(guardian.user)end- def fetch_users(guardian:, **)+ def fetch_users(guardian:, contract:, **)+ return unless contract.include_usersreturn unless guardian.can_create_direct_message?- return if context.mode == :channel- context.users = search_users(context.term, guardian)+ search_users(context, guardian, contract)end- def fetch_category_channels(guardian:, **)- return if context.mode == :user+ def fetch_category_channels(guardian:, contract:, **)+ return unless contract.include_category_channelsreturn if !SiteSetting.enable_public_channels- context.category_channels =- ::Chat::ChannelFetcher.secured_public_channel_search(- guardian,- filter_on_category_name: false,- match_filter_on_starts_with: false,- filter: context.term,- status: :open,- limit: 10,- )+ ::Chat::ChannelFetcher.secured_public_channel_search(+ guardian,+ filter_on_category_name: false,+ match_filter_on_starts_with: false,+ filter: context.term,+ status: :open,+ limit: 10,+ )end- def fetch_direct_message_channels(guardian:, **args)- return if context.mode == :user-- user_ids = nil- if context.term.length > 0- user_ids =- (context.users.nil? ? search_users(context.term, guardian) : context.users).map(&:id)- end+ def fetch_direct_message_channels(guardian:, users:, contract:, **args)+ return unless contract.include_direct_message_channelschannels =::Chat::ChannelFetcher.secured_direct_message_channels_search(guardian.user.id,guardian,limit: 10,- user_ids: user_ids,+ match_filter_on_starts_with: false,+ filter: context.term,) || []- if user_ids.present? && context.mode == :all+ if users && contract.include_users+ user_ids = users.map(&:id)channels =channels.reject do |channel|channel_user_ids = channel.allowed_user_ids - [guardian.user.id]@@ -96,17 +83,31 @@ module Chatendend- context.direct_message_channels = channels+ channelsend- def search_users(term, guardian)- user_search = ::UserSearch.new(term, limit: 10)+ def search_users(context, guardian, contract)+ user_search = ::UserSearch.new(context.term, limit: 10)- if term.blank?- user_search.scoped_users.includes(:user_option)+ if context.term.blank?+ user_search = user_search.scoped_users.real.includes(:user_option)else- user_search.search.includes(:user_option)+ user_search = user_search.search.real.includes(:user_option)end++ if context.excluded_memberships_channel_id+ user_search =+ user_search.where(+ "NOT EXISTS (+ SELECT 1+ FROM user_chat_channel_memberships+ WHERE user_chat_channel_memberships.user_id = users.id AND user_chat_channel_memberships.chat_channel_id = ?+ )",+ context.excluded_memberships_channel_id,+ )+ end++ user_searchendendenddiff --git a/plugins/chat/app/services/chat/update_channel.rb b/plugins/chat/app/services/chat/update_channel.rbindex fdd7cd5f85e..6960fe44236 100644--- a/plugins/chat/app/services/chat/update_channel.rb+++ b/plugins/chat/app/services/chat/update_channel.rb@@ -7,7 +7,7 @@ module Chat# and threading_enabled are also editable.## @example- # Service::Chat::UpdateChannel.call(+ # ::Chat::UpdateChannel.call(# channel_id: 2,# guardian: guardian,# name: "SuperChannel",@@ -26,13 +26,13 @@ module Chat# @option params_to_edit [String,nil] name# @option params_to_edit [String,nil] description# @option params_to_edit [String,nil] slug+ # @option params_to_edit [Boolean] threading_enabled# @option params_to_edit [Boolean] auto_join_users Only valid for {CategoryChannel}. Whether active users# with permission to see the category should automatically join the channel.# @option params_to_edit [Boolean] allow_channel_wide_mentions Allow the use of @here and @all in the channel.# @return [Service::Base::Context]model :channel, :fetch_channel- policy :no_direct_message_channelpolicy :check_channel_permissioncontract default_values_from: :channelstep :update_channel@@ -62,12 +62,8 @@ module ChatChat::Channel.find_by(id: channel_id)end- def no_direct_message_channel(channel:, **)- !channel.direct_message_channel?- end-def check_channel_permission(guardian:, channel:, **)- guardian.can_preview_chat_channel?(channel) && guardian.can_edit_chat_channel?+ guardian.can_preview_chat_channel?(channel) && guardian.can_edit_chat_channel?(channel)enddef update_channel(channel:, contract:, **)diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-info.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-info.gjsindex e3f63cfe966..3bc5690ee73 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-info.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-info.gjs@@ -1,14 +1,19 @@import Component from "@glimmer/component";+import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { inject as service } from "@ember/service";+import DButton from "discourse/components/d-button";import icon from "discourse-common/helpers/d-icon";import I18n from "discourse-i18n";+import ChatModalEditChannelName from "discourse/plugins/chat/discourse/components/chat/modal/edit-channel-name";import ChatChannelStatus from "discourse/plugins/chat/discourse/components/chat-channel-status";import ChatChannelTitle from "discourse/plugins/chat/discourse/components/chat-channel-title";export default class ChatChannelMessageEmojiPicker extends Component {@service chatChannelInfoRouteOriginManager;@service site;+ @service modal;+ @service chatGuardian;membersLabel = I18n.t("chat.channel_info.tabs.members");settingsLabel = I18n.t("chat.channel_info.tabs.settings");@@ -16,13 +21,25 @@ export default class ChatChannelMessageEmojiPicker extends Component {backToAllChannelsLabel = I18n.t("chat.channel_info.back_to_channel");get showTabs() {+ return this.site.desktopView && this.args.channel.isOpen;+ }++ get canEditChannel() {return (- this.site.desktopView &&- this.args.channel.membershipsCount > 1 &&- this.args.channel.isOpen+ this.chatGuardian.canEditChatChannel() &&+ (this.args.channel.isCategoryChannel ||+ (this.args.channel.isDirectMessageChannel &&+ this.args.channel.chatable.group)));}+ @action+ editChannelTitle() {+ return this.modal.show(ChatModalEditChannelName, {+ model: this.args.channel,+ });+ }+<template><div class="chat-full-page-header"><div class="chat-channel-header-details">@@ -48,6 +65,14 @@ export default class ChatChannelMessageEmojiPicker extends Component {</div><ChatChannelTitle @channel={{@channel}} />++ {{#if this.canEditChannel}}+ <DButton+ @icon="pencil-alt"+ class="btn-flat"+ @action={{this.editChannelTitle}}+ />+ {{/if}}</div></div>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-members.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-members.gjsindex bdd47713ae6..035b958d0ac 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-members.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-members.gjs@@ -1,25 +1,32 @@import Component from "@glimmer/component";import { cached, tracked } from "@glimmer/tracking";-import { hash } from "@ember/helper";+import { fn, hash } from "@ember/helper";+import { on } from "@ember/modifier";import { action } from "@ember/object";import { schedule } from "@ember/runloop";import { inject as service } from "@ember/service";import { modifier } from "ember-modifier";import isElementInViewport from "discourse/lib/is-element-in-viewport";+import DiscourseURL, { userPath } from "discourse/lib/url";import { INPUT_DELAY } from "discourse-common/config/environment";+import icon from "discourse-common/helpers/d-icon";import discourseDebounce from "discourse-common/lib/debounce";import I18n from "discourse-i18n";-import gt from "truth-helpers/helpers/gt";+import MessageCreator from "discourse/plugins/chat/discourse/components/chat/message-creator";import ChatUserInfo from "discourse/plugins/chat/discourse/components/chat-user-info";import DcFilterInput from "discourse/plugins/chat/discourse/components/dc-filter-input";+import { MODES } from "./chat/message-creator/constants";export default class ChatChannelMembers extends Component {+ @service appEvents;@service chatApi;@service modal;@service loadingSlider;@tracked filter = "";+ @tracked showAddMembers = false;+ addMemberLabel = I18n.t("chat.members_view.add_member");filterPlaceholder = I18n.t("chat.members_view.filter_placeholder");noMembershipsFoundLabel = I18n.t("chat.channel.no_memberships_found");noMembershipsLabel = I18n.t("chat.channel.no_memberships");@@ -30,6 +37,22 @@ export default class ChatChannelMembers extends Component {});});+ onEnter = modifier((element, [callback]) => {+ const handler = (event) => {+ if (event.key !== "Enter") {+ return;+ }++ callback(event);+ };++ element.addEventListener("keydown", handler);++ return () => {+ element.removeEventListener("keydown", handler);+ };+ });+fill = modifier((element) => {this.resizeObserver = new ResizeObserver(() => {if (isElementInViewport(element)) {@@ -78,27 +101,75 @@ export default class ChatChannelMembers extends Component {this.load();}+ @action+ addMember() {+ this.showAddMembers = true;+ }++ @action+ hideAddMember() {+ this.showAddMembers = false;+ }++ @action+ openMemberCard(user, event) {+ event.preventDefault();+ DiscourseURL.routeTo(userPath(user.username_lower));+ }+async debouncedLoad() {this.loadingSlider.transitionStarted();await this.members.load({ limit: 20 });this.loadingSlider.transitionEnded();}+ get addMembersMode() {+ return MODES.add_members;+ }+<template>- <div class="chat-channel-members">- <DcFilterInput- @class="chat-channel-members__filter"- @filterAction={{this.mutFilter}}- @icons={{hash right="search"}}- placeholder={{this.filterPlaceholder}}- {{this.focusInput}}+ {{#if this.showAddMembers}}+ <MessageCreator+ @mode={{this.addMembersMode}}+ @channel={{@channel}}+ @onClose={{this.hideAddMember}}+ @onCancel={{this.hideAddMember}}/>+ {{else}}+ <div class="chat-channel-members">+ <DcFilterInput+ @class="chat-channel-members__filter"+ @filterAction={{this.mutFilter}}+ @icons={{hash right="search"}}+ placeholder={{this.filterPlaceholder}}+ {{this.focusInput}}+ />- {{#if (gt @channel.membershipsCount 0)}}<ul class="chat-channel-members__list" {{this.fill}}>+ {{#if @channel.chatable.group}}+ <li+ class="chat-channel-members__list-item -add-member"+ role="button"+ {{on "click" this.addMember}}+ {{this.onEnter this.addMember}}+ tabindex="0"+ >+ {{icon "plus"}}+ <span>{{this.addMemberLabel}}</span>+ </li>+ {{/if}}{{#each this.members as |membership|}}- <li class="chat-channel-members__list-item">- <ChatUserInfo @user={{membership.user}} @avatarSize="tiny" />+ <li+ class="chat-channel-members__list-item -member"+ {{on "click" (fn this.openMemberCard membership.user)}}+ {{this.onEnter (fn this.openMemberCard membership.user)}}+ tabindex="0"+ >+ <ChatUserInfo+ @user={{membership.user}}+ @avatarSize="tiny"+ @interactive={{false}}+ /></li>{{else}}{{#if this.noResults}}@@ -114,11 +185,7 @@ export default class ChatChannelMembers extends Component {<div {{this.loadMore}}><br /></div>- {{else}}- <p class="alert alert-info">- {{this.noMembershipsLabel}}- </p>- {{/if}}- </div>+ </div>+ {{/if}}</template>}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings.gjsindex 84df9ac1ef8..c7af8b917fe 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings.gjs@@ -69,10 +69,6 @@ export default class ChatAboutScreen extends Component {return this.chatGuardian.canEditChatChannel();}- get shouldRenderTitleSection() {- return this.args.channel.isCategoryChannel;- }-get shouldRenderDescriptionSection() {return this.args.channel.isCategoryChannel;}@@ -293,7 +289,7 @@ export default class ChatAboutScreen extends Component {}@action- onEditChannelName() {+ onEditChannelTitle() {return this.modal.show(ChatModalEditChannelName, {model: this.args.channel,});@@ -309,39 +305,37 @@ export default class ChatAboutScreen extends Component {<template><div class="chat-channel-settings"><ChatForm as |form|>- {{#if this.shouldRenderTitleSection}}- <form.section @title={{this.titleSectionTitle}} as |section|>- <section.row>- <:default>- <div class="chat-channel-settings__name">- {{replaceEmoji @channel.title}}+ <form.section @title={{this.titleSectionTitle}} as |section|>+ <section.row>+ <:default>+ <div class="chat-channel-settings__name">+ {{replaceEmoji @channel.title}}+ </div>++ {{#if @channel.isCategoryChannel}}+ <div class="chat-channel-settings__slug">+ <LinkTo+ @route="chat.channel"+ @models={{@channel.routeModels}}+ >+ /chat/c/{{@channel.slug}}/{{@channel.id}}+ </LinkTo></div>+ {{/if}}+ </:default>- {{#if @channel.isCategoryChannel}}- <div class="chat-channel-settings__slug">- <LinkTo- @route="chat.channel"- @models={{@channel.routeModels}}- >- /chat/c/{{@channel.slug}}/{{@channel.id}}- </LinkTo>- </div>- {{/if}}- </:default>-- <:action>- {{#if this.canEditChannel}}- <DButton- @label="chat.channel_settings.edit"- @action={{this.onEditChannelName}}- class="edit-name-slug-btn btn-flat"- />- {{/if}}- </:action>+ <:action>+ {{#if this.canEditChannel}}+ <DButton+ @label="chat.channel_settings.edit"+ @action={{this.onEditChannelTitle}}+ class="edit-name-slug-btn btn-flat"+ />+ {{/if}}+ </:action>- </section.row>- </form.section>- {{/if}}+ </section.row>+ </form.section>{{#if this.shouldRenderDescriptionSection}}<form.section @title={{this.descriptionSectionTitle}} as |section|>@@ -567,7 +561,7 @@ export default class ChatAboutScreen extends Component {@channel={{@channel}}@options={{hashjoinClass="btn-primary"- leaveClass="btn-flat"+ leaveClass="btn-danger"joinIcon="sign-in-alt"leaveIcon="sign-out-alt"}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.gjsnew file mode 100644index 00000000000..b33add9d8c0--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.gjs@@ -0,0 +1,111 @@+import Component from "@glimmer/component";+import { get, hash } from "@ember/helper";+import { inject as service } from "@ember/service";+import { htmlSafe } from "@ember/template";+import PluginOutlet from "discourse/components/plugin-outlet";+import UserStatusMessage from "discourse/components/user-status-message";+import replaceEmoji from "discourse/helpers/replace-emoji";+import icon from "discourse-common/helpers/d-icon";+import ChatUserAvatar from "discourse/plugins/chat/discourse/components/chat-user-avatar";++export default class ChatChannelTitle extends Component {+ @service currentUser;++ get firstUser() {+ return this.args.channel.chatable.users[0];+ }++ get users() {+ return this.args.channel.chatable.users;+ }++ get groupDirectMessage() {+ return (+ this.args.channel.isDirectMessageChannel &&+ this.args.channel.chatable.group+ );+ }++ get groupsDirectMessageTitle() {+ return this.args.channel.title || this.usernames;+ }++ get usernames() {+ return this.users.mapBy("username").join(", ");+ }++ get channelColorStyle() {+ return htmlSafe(`color: #${this.args.channel.chatable.color}`);+ }++ get showUserStatus() {+ return !!(this.users.length === 1 && this.users[0].status);+ }++ <template>+ {{#if @channel.isDirectMessageChannel}}+ <div class="chat-channel-title is-dm">+ {{#if this.groupDirectMessage}}+ <span class="chat-channel-title__users-count">+ {{@channel.membershipsCount}}+ </span>+ {{else}}+ <div class="chat-channel-title__avatar">+ <ChatUserAvatar @user={{this.firstUser}} @interactive={{false}} />+ </div>+ {{/if}}++ <div class="chat-channel-title__user-info">+ <div class="chat-channel-title__usernames">+ {{#if this.groupDirectMessage}}+ <span class="chat-channel-title__name">+ {{this.groupsDirectMessageTitle}}+ </span>+ {{else}}+ <span class="chat-channel-title__name">+ {{this.firstUser.username}}+ </span>+ {{#if this.showUserStatus}}+ <UserStatusMessage+ @class="chat-channel-title__user-status-message"+ @status={{get this.users "0.status"}}+ @showDescription={{if this.site.mobileView "true"}}+ />+ {{/if}}+ <PluginOutlet+ @name="after-chat-channel-username"+ @outletArgs={{hash user=@user}}+ @tagName=""+ @connectorTagName=""+ />+ {{/if}}++ </div>+ </div>++ {{#if (has-block)}}+ {{yield}}+ {{/if}}+ </div>+ {{else if @channel.isCategoryChannel}}+ <div class="chat-channel-title is-category">+ <span+ class="chat-channel-title__category-badge"+ style={{this.channelColorStyle}}+ >+ {{icon "d-chat"}}+ {{#if @channel.chatable.read_restricted}}+ {{icon "lock" class="chat-channel-title__restricted-category-icon"}}+ {{/if}}+ </span>+ <span class="chat-channel-title__name">+ {{replaceEmoji @channel.title}}+ </span>++ {{#if (has-block)}}+ {{yield}}+ {{/if}}+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.hbsdeleted file mode 100644index 712abf29dbd..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.hbs+++ /dev/null@@ -1,67 +0,0 @@-{{#if @channel.isDirectMessageChannel}}- <div class="chat-channel-title is-dm">- {{#if @channel.chatable.users.length}}- <div class="chat-channel-title__avatar">- {{#if this.multiDm}}- <span class="chat-channel-title__users-count">- {{@channel.chatable.users.length}}- </span>- {{else}}- <ChatUserAvatar @user={{get @channel.chatable.users "0"}} />- {{/if}}- </div>- {{/if}}-- <div class="chat-channel-title__user-info">- <div class="chat-channel-title__usernames">- {{#if @channel.chatable.users.length}}- {{#if this.multiDm}}- <span class="chat-channel-title__name">{{this.usernames}}</span>- {{else}}- {{#let (get @channel.chatable.users "0") as |user|}}- <span class="chat-channel-title__name">{{user.username}}</span>- {{#if this.showUserStatus}}- <UserStatusMessage- @class="chat-channel-title__user-status-message"- @status={{get @channel.chatable.users "0.status"}}- @showDescription={{if this.site.mobileView "true"}}- />- {{/if}}- <PluginOutlet- @name="after-chat-channel-username"- @outletArgs={{hash user=user}}- @tagName=""- @connectorTagName=""- />- {{/let}}- {{/if}}- {{else}}- <span class="chat-channel-title__name">Add users</span>- {{/if}}- </div>- </div>-- {{#if (has-block)}}- {{yield}}- {{/if}}- </div>-{{else if @channel.isCategoryChannel}}- <div class="chat-channel-title is-category">- <span- class="chat-channel-title__category-badge"- style={{this.channelColorStyle}}- >- {{d-icon "d-chat"}}- {{#if @channel.chatable.read_restricted}}- {{d-icon "lock" class="chat-channel-title__restricted-category-icon"}}- {{/if}}- </span>- <span class="chat-channel-title__name">- {{replace-emoji @channel.title}}- </span>-- {{#if (has-block)}}- {{yield}}- {{/if}}- </div>-{{/if}}\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.jsdeleted file mode 100644index 3fd41b2b9ac..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-title.js+++ /dev/null@@ -1,24 +0,0 @@-import Component from "@glimmer/component";-import { htmlSafe } from "@ember/template";--export default class ChatChannelTitle extends Component {- get users() {- return this.args.channel.chatable.users;- }-- get multiDm() {- return this.users.length > 1;- }-- get usernames() {- return this.users.mapBy("username").join(", ");- }-- get channelColorStyle() {- return htmlSafe(`color: #${this.args.channel.chatable.color}`);- }-- get showUserStatus() {- return !!(this.users.length === 1 && this.users[0].status);- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.gjsnew file mode 100644index 00000000000..c502c71c055--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.gjs@@ -0,0 +1,118 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { inject as service } from "@ember/service";+import DButton from "discourse/components/d-button";+import concatClass from "discourse/helpers/concat-class";+import icon from "discourse-common/helpers/d-icon";+import and from "truth-helpers/helpers/and";+import or from "truth-helpers/helpers/or";+import ChatModalEditChannelName from "discourse/plugins/chat/discourse/components/chat/modal/edit-channel-name";+import ThreadsListButton from "discourse/plugins/chat/discourse/components/chat/thread/threads-list-button";+import ChatChannelStatus from "discourse/plugins/chat/discourse/components/chat-channel-status";+import ChatChannelTitle from "discourse/plugins/chat/discourse/components/chat-channel-title";++export default class ChatFullPageHeader extends Component {+ @service chatGuardian;+ @service chatStateManager;+ @service modal;+ @service router;+ @service site;++ get displayed() {+ return this.args.displayed ?? true;+ }++ get showThreadsListButton() {+ return (+ this.args.channel.threadingEnabled &&+ this.router.currentRoute.name !== "chat.channel.threads" &&+ this.router.currentRoute.name !== "chat.channel.thread.index" &&+ this.router.currentRoute.name !== "chat.channel.thread"+ );+ }++ get canEditChannel() {+ if (+ this.args.channel.isCategoryChannel &&+ this.chatGuardian.canEditChatChannel()+ ) {+ return true;+ }++ if (+ this.args.channel.isDirectMessageChannel &&+ this.args.channel.chatable.group+ ) {+ return true;+ }++ return false;+ }++ @action+ editChannelTitle() {+ return this.modal.show(ChatModalEditChannelName, {+ model: this.args.channel,+ });+ }++ <template>+ {{#if (and this.chatStateManager.isFullPageActive this.displayed)}}+ <div+ class={{concatClass+ "chat-full-page-header"+ (unless @channel.isFollowing "-not-following")+ }}+ >+ <div class="chat-channel-header-details">+ {{#if this.site.mobileView}}+ <div class="chat-full-page-header__left-actions">+ <LinkTo+ @route="chat"+ class="chat-full-page-header__back-btn no-text btn-flat"+ >+ {{icon "chevron-left"}}+ </LinkTo>+ </div>+ {{/if}}++ <LinkTo+ @route="chat.channel.info"+ @models={{@channel.routeModels}}+ class="chat-channel-title-wrapper"+ >+ <ChatChannelTitle @channel={{@channel}} />+ </LinkTo>++ {{#if this.canEditChannel}}+ <DButton+ @icon="pencil-alt"+ class="btn-flat"+ @action={{this.editChannelTitle}}+ />+ {{/if}}++ {{#if (or @channel.threadingEnabled this.site.desktopView)}}+ <div class="chat-full-page-header__right-actions">+ {{#if this.site.desktopView}}+ <DButton+ @icon="discourse-compress"+ @title="chat.close_full_page"+ class="open-drawer-btn btn-flat"+ @action={{@onCloseFullScreen}}+ />+ {{/if}}++ {{#if this.showThreadsListButton}}+ <ThreadsListButton @channel={{@channel}} />+ {{/if}}+ </div>+ {{/if}}+ </div>+ </div>++ <ChatChannelStatus @channel={{@channel}} />+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.hbsdeleted file mode 100644index 304b9bc5549..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.hbs+++ /dev/null@@ -1,48 +0,0 @@-{{#if (and this.chatStateManager.isFullPageActive this.displayed)}}- <div- class={{concat-class- "chat-full-page-header"- (unless @channel.isFollowing "-not-following")- }}- >- <div class="chat-channel-header-details">- {{#if this.site.mobileView}}- <div class="chat-full-page-header__left-actions">- <LinkTo- @route="chat"- class="chat-full-page-header__back-btn no-text btn-flat"- >- {{d-icon "chevron-left"}}- </LinkTo>- </div>- {{/if}}-- <LinkTo- @route="chat.channel.info"- @models={{@channel.routeModels}}- class="chat-channel-title-wrapper"- >- <ChatChannelTitle @channel={{@channel}} />- </LinkTo>-- {{#if (or @channel.threadingEnabled this.site.desktopView)}}- <div class="chat-full-page-header__right-actions">- {{#if this.site.desktopView}}- <DButton- @icon="discourse-compress"- @title="chat.close_full_page"- class="open-drawer-btn btn-flat"- @action={{@onCloseFullScreen}}- />- {{/if}}-- {{#if this.showThreadsListButton}}- <Chat::Thread::ThreadsListButton @channel={{@channel}} />- {{/if}}- </div>- {{/if}}- </div>- </div>-- <ChatChannelStatus @channel={{@channel}} />-{{/if}}\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.js b/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.jsdeleted file mode 100644index aad1dd7935f..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat-full-page-header.js+++ /dev/null@@ -1,21 +0,0 @@-import Component from "@glimmer/component";-import { inject as service } from "@ember/service";--export default class ChatFullPageHeader extends Component {- @service site;- @service chatStateManager;- @service router;-- get displayed() {- return this.args.displayed ?? true;- }-- get showThreadsListButton() {- return (- this.args.channel.threadingEnabled &&- this.router.currentRoute.name !== "chat.channel.threads" &&- this.router.currentRoute.name !== "chat.channel.thread.index" &&- this.router.currentRoute.name !== "chat.channel.thread"- );- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjsindex f4b4cd1e211..83f96bda4d4 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjs@@ -3,6 +3,7 @@ import { inject as service } from "@ember/service";import { htmlSafe } from "@ember/template";import concatClass from "discourse/helpers/concat-class";import { renderAvatar } from "discourse/helpers/user-avatar";+import { userPath } from "discourse/lib/url";export default class ChatUserAvatar extends Component {@service chat;@@ -37,19 +38,23 @@ export default class ChatUserAvatar extends Component {);}+ get userPath() {+ return userPath(this.args.user.username);+ }+<template><divclass={{concatClass "chat-user-avatar" (if this.isOnline "is-online")}}data-username={{@user.username}}>{{#if this.interactive}}- <div- role="button"- class="chat-user-avatar__container clickable"+ <a+ class="chat-user-avatar__container"+ href={{this.userPath}}data-user-card={{@user.username}}>{{this.avatar}}- </div>+ </a>{{else}}{{this.avatar}}{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-user-info.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-user-info.gjsindex edc5170f268..7f5c967efcd 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-user-info.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-user-info.gjs@@ -12,14 +12,25 @@ export default class ChatUserInfo extends Component {return userPath(this.args.user.username);}+ get interactive() {+ return this.args.interactive ?? false;+ }+<template>{{#if @user}}- <a href={{this.userPath}} data-user-card={{@user.username}}>- <ChatUserAvatar @user={{@user}} @avatarSize={{this.avatarSize}} />- </a>- <a href={{this.userPath}} data-user-card={{@user.username}}>+ <ChatUserAvatar+ @user={{@user}}+ @avatarSize={{this.avatarSize}}+ @interactive={{this.interactive}}+ />++ {{#if this.interactive}}+ <a href={{this.userPath}} data-user-card={{@user.username}}>+ <ChatUserDisplayName @user={{@user}} />+ </a>+ {{else}}<ChatUserDisplayName @user={{@user}} />- </a>+ {{/if}}{{/if}}</template>}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/composer/channel.js b/plugins/chat/assets/javascripts/discourse/components/chat/composer/channel.jsindex 5a90e973b2e..a5bc9008c35 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/composer/channel.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat/composer/channel.js@@ -93,19 +93,25 @@ export default class ChatComposerChannel extends ChatComposer {#messageRecipients(channel) {if (channel.isDirectMessageChannel) {- const directMessageRecipients = channel.chatable.users;- if (- directMessageRecipients.length === 1 &&- directMessageRecipients[0].id === this.currentUser.id- ) {- return I18n.t("chat.placeholder_self");+ if (channel.chatable.group && channel.title) {+ return I18n.t("chat.placeholder_channel", {+ channelName: `#${channel.title}`,+ });+ } else {+ const directMessageRecipients = channel.chatable.users;+ if (+ directMessageRecipients.length === 1 &&+ directMessageRecipients[0].id === this.currentUser.id+ ) {+ return I18n.t("chat.placeholder_self");+ }++ return I18n.t("chat.placeholder_users", {+ commaSeparatedNames: directMessageRecipients+ .map((u) => u.name || `@${u.username}`)+ .join(I18n.t("word_connector.comma")),+ });}-- return I18n.t("chat.placeholder_users", {- commaSeparatedNames: directMessageRecipients- .map((u) => u.name || `@${u.username}`)- .join(I18n.t("word_connector.comma")),- });} else {return I18n.t("chat.placeholder_channel", {channelName: `#${channel.title}`,diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator.hbsdeleted file mode 100644index c0bbc86234e..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator.hbs+++ /dev/null@@ -1,141 +0,0 @@-<div class="chat-message-creator__container">- <div class="chat-message-creator">- <div- class="chat-message-creator__selection-container"- {{did-insert this.focusInput}}- ...attributes- >- <div class="chat-message-creator__selection">- <div class="chat-message-creator__search-icon-container">- {{d-icon "search" class="chat-message-creator__search-icon"}}- </div>-- {{#each this.selection as |selection|}}- <div- class={{concat-class- "chat-message-creator__selection-item"- (concat "-" selection.type)- (if- (includes this.activeSelectionIdentifiers selection.identifier)- "-active"- )- }}- tabindex="-1"- data-id={{selection.identifier}}- {{on "click" (fn this.removeSelection selection.identifier)}}- >- {{component- (concat "chat/message-creator/" selection.type "-selection")- selection=selection- }}- <i- class="chat-message-creator__selection__remove-btn"- aria-hidden="true"- >- {{d-icon "times"}}- </i>- </div>- {{/each}}-- <Input- class="chat-message-creator__input"- {{did-insert this.setQueryElement}}- {{on "input" this.handleInput}}- {{on "keydown" this.handleKeydown}}- placeholder={{this.placeholder}}- @value={{readonly this.query}}- @type="text"- />- </div>-- <DButton- class="chat-message-creator__close-btn btn-flat"- @icon="times"- @action={{@onClose}}- />- </div>-- {{#if this.showResults}}- <div class="chat-message-creator__content-container" role="presentation">- <div- class="chat-message-creator__content"- role="listbox"- aria-multiselectable="true"- tabindex="-1"- >- {{#if this.searchRequest.loading}}- <div class="chat-message-creator__loader-container">- <div class="chat-message-creator__loader spinner small"></div>- </div>- {{else}}- {{#each this.searchRequest.value as |result|}}- <div- class={{concat-class- "chat-message-creator__row"- (concat "-" result.type)- (unless result.enabled "-disabled")- (if- (eq this.activeResultIdentifier result.identifier) "-active"- )- (if- (includes this.selectionIdentifiers result.identifier)- "-selected"- )- }}- data-id={{result.identifier}}- tabindex="-1"- role="option"- {{on "click" (fn this.handleRowClick result.identifier)}}- {{on "mousemove" (fn (mut this.activeResult) result)}}- {{on "keydown" this.handleKeydown}}- aria-selected={{if- (includes this.selectionIdentifiers result.identifier)- "true"- "false"- }}- >- {{component- (concat "chat/message-creator/" result.type "-row")- content=result- selected=(includes- this.selectionIdentifiers result.identifier- )- active=(eq this.activeResultIdentifier result.identifier)- hasSelectedUsers=this.hasSelectedUsers- }}- </div>- {{else}}- {{#if this.query.length}}- <div class="chat-message-creator__no-items-container">- <span class="chat-message-creator__no-items">- {{i18n "chat.new_message_modal.no_items"}}- </span>- </div>- {{/if}}- {{/each}}- {{/if}}- </div>- </div>- {{/if}}-- {{#if this.showFooter}}- <div class="chat-message-creator__footer-container">- <div class="chat-message-creator__footer">- {{#if this.showShortcut}}- <div class="chat-message-creator__shortcut">- {{this.shortcutLabel}}- </div>- {{/if}}-- {{#if this.hasSelectedUsers}}- <DButton- class="chat-message-creator__open-dm-btn btn-primary"- @action={{fn this.openChannel this.selection}}- @translatedLabel={{this.openChannelLabel}}- />- {{/if}}- </div>- </div>- {{/if}}- </div>-</div>\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator.jsdeleted file mode 100644index f5638ed681e..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator.js+++ /dev/null@@ -1,546 +0,0 @@-import Component from "@glimmer/component";-import { cached, tracked } from "@glimmer/tracking";-import { getOwner, setOwner } from "@ember/application";-import { action } from "@ember/object";-import { schedule } from "@ember/runloop";-import { inject as service } from "@ember/service";-import { htmlSafe } from "@ember/template";-import { TrackedArray } from "@ember-compat/tracked-built-ins";-import { escapeExpression } from "discourse/lib/utilities";-import { INPUT_DELAY } from "discourse-common/config/environment";-import discourseDebounce from "discourse-common/lib/debounce";-import I18n from "discourse-i18n";-import ChatChatable from "discourse/plugins/chat/discourse/models/chat-chatable";--const MAX_RESULTS = 10;-const USER_PREFIX = "@";-const CHANNEL_PREFIX = "#";-const CHANNEL_TYPE = "channel";-const USER_TYPE = "user";--class Search {- @service("chat-api") api;- @service chat;- @service chatChannelsManager;-- @tracked loading = false;- @tracked value = [];- @tracked query = "";-- constructor(owner, options = {}) {- setOwner(this, owner);-- options.preload ??= false;- options.onlyUsers ??= false;-- if (!options.term && !options.preload) {- return;- }-- if (!options.term && options.preload) {- this.value = this.#loadExistingChannels();- return;- }-- this.loading = true;-- this.api- .chatables({ term: options.term })- .then((results) => {- let chatables = [- ...results.users,- ...results.direct_message_channels,- ...results.category_channels,- ];-- if (options.excludeUserId) {- chatables = chatables.filter(- (item) => item.identifier !== `u-${options.excludeUserId}`- );- }-- this.value = chatables- .map((item) => {- const chatable = ChatChatable.create(item);- chatable.tracking = this.#injectTracking(chatable);- return chatable;- })- .slice(0, MAX_RESULTS);- })- .catch(() => (this.value = []))- .finally(() => (this.loading = false));- }-- #loadExistingChannels() {- return this.chatChannelsManager.allChannels- .map((channel) => {- let chatable;- if (channel.chatable?.users?.length === 1) {- chatable = ChatChatable.createUser(channel.chatable.users[0]);- chatable.tracking = this.#injectTracking(chatable);- } else {- chatable = ChatChatable.createChannel(channel);- chatable.tracking = channel.tracking;- }- return chatable;- })- .filter(Boolean)- .slice(0, MAX_RESULTS);- }-- #injectTracking(chatable) {- switch (chatable.type) {- case CHANNEL_TYPE:- return this.chatChannelsManager.allChannels.find(- (channel) => channel.id === chatable.model.id- )?.tracking;- break;- case USER_TYPE:- return this.chatChannelsManager.directMessageChannels.find(- (channel) =>- channel.chatable.users.length === 1 &&- channel.chatable.users[0].id === chatable.model.id- )?.tracking;- break;- }- }-}--export default class ChatMessageCreator extends Component {- @service("chat-api") api;- @service("chat-channel-composer") composer;- @service chat;- @service site;- @service router;- @service currentUser;- @service siteSettings;-- @tracked selection = new TrackedArray();- @tracked activeSelection = new TrackedArray();- @tracked query = "";- @tracked queryElement = null;- @tracked loading = false;- @tracked activeSelectionIdentifiers = new TrackedArray();- @tracked selectedIdentifiers = [];- @tracked _activeResultIdentifier = null;-- get placeholder() {- if (- this.siteSettings.enable_public_channels &&- this.chat.userCanDirectMessage- ) {- if (this.hasSelectedUsers) {- return I18n.t("chat.new_message_modal.user_search_placeholder");- } else {- return I18n.t("chat.new_message_modal.default_search_placeholder");- }- } else if (this.siteSettings.enable_public_channels) {- return I18n.t(- "chat.new_message_modal.default_channel_search_placeholder"- );- } else if (this.chat.userCanDirectMessage) {- if (this.hasSelectedUsers) {- return I18n.t("chat.new_message_modal.user_search_placeholder");- } else {- return I18n.t("chat.new_message_modal.default_user_search_placeholder");- }- }- }-- get showFooter() {- return this.showShortcut || this.hasSelectedUsers;- }-- get showResults() {- if (this.hasSelectedUsers && !this.query.length) {- return false;- }-- return true;- }-- get shortcutLabel() {- let username;-- if (this.activeResult?.isUser) {- username = this.activeResult.model.username;- } else {- username = this.activeResult.model.chatable.users[0].username;- }-- return htmlSafe(- I18n.t("chat.new_message_modal.add_user_long", {- username: escapeExpression(username),- })- );- }-- get showShortcut() {- return (- !this.hasSelectedUsers &&- this.searchRequest?.value?.length &&- this.site.desktopView &&- (this.activeResult?.isUser || this.activeResult?.isSingleUserChannel)- );- }-- get activeResultIdentifier() {- return (- this._activeResultIdentifier ||- this.searchRequest.value.find((result) => result.enabled)?.identifier- );- }-- get hasSelectedUsers() {- return this.selection.some((s) => s.isUser);- }-- get activeResult() {- return this.searchRequest.value.findBy(- "identifier",- this.activeResultIdentifier- );- }-- set activeResult(result) {- if (!result?.enabled) {- return;- }-- this._activeResultIdentifier = result?.identifier;- }-- get selectionIdentifiers() {- return this.selection.mapBy("identifier");- }-- get openChannelLabel() {- const users = this.selection.mapBy("model");-- return I18n.t("chat.placeholder_users", {- commaSeparatedNames: users- .map((u) => u.name || u.username)- .join(I18n.t("word_connector.comma")),- });- }-- @cached- get searchRequest() {- let term = this.query;-- if (term?.length) {- if (this.hasSelectedUsers && term.startsWith(CHANNEL_PREFIX)) {- term = term.replace(/^#/, USER_PREFIX);- }-- if (this.hasSelectedUsers && !term.startsWith(USER_PREFIX)) {- term = USER_PREFIX + term;- }- }-- return new Search(getOwner(this), {- term,- preload: !this.selection?.length,- onlyUsers: this.hasSelectedUsers,- excludeUserId: this.hasSelectedUsers ? this.currentUser?.id : null,- });- }-- @action- onFilter(term) {- this._activeResultIdentifier = null;- this.activeSelectionIdentifiers = [];- this.query = term;- }-- @action- setQueryElement(element) {- this.queryElement = element;- }-- @action- focusInput() {- schedule("afterRender", () => {- this.queryElement.focus();- });- }-- @action- handleKeydown(event) {- if (event.key === "Escape") {- if (this.activeSelectionIdentifiers.length > 0) {- this.activeSelectionIdentifiers = [];- event.preventDefault();- event.stopPropagation();- return;- }- }-- if (event.key === "a" && (event.metaKey || event.ctrlKey)) {- this.activeSelectionIdentifiers = this.selection.mapBy("identifier");- return;- }-- if (event.key === "Enter") {- if (this.activeSelectionIdentifiers.length > 0) {- this.activeSelectionIdentifiers.forEach((identifier) => {- this.removeSelection(identifier);- });- this.activeSelectionIdentifiers = [];- event.preventDefault();- return;- } else if (this.activeResultIdentifier) {- this.toggleSelection(this.activeResultIdentifier, {- altSelection: event.shiftKey || event.ctrlKey,- });- event.preventDefault();- return;- } else if (this.query?.length === 0) {- this.openChannel(this.selection);- event.preventDefault();- return;- }- }-- if (event.key === "ArrowDown" && this.searchRequest.value.length > 0) {- this.activeSelectionIdentifiers = [];- this._activeResultIdentifier = this.#getNextResult()?.identifier;- event.preventDefault();- return;- }-- if (event.key === "ArrowUp" && this.searchRequest.value.length > 0) {- this.activeSelectionIdentifiers = [];- this._activeResultIdentifier = this.#getPreviousResult()?.identifier;- event.preventDefault();- return;- }-- const digit = this.#getDigit(event.code);- if (event.ctrlKey && digit) {- this._activeResultIdentifier = this.searchRequest.value.objectAt(- digit - 1- )?.identifier;- event.preventDefault();- return;- }-- if (event.target.selectionEnd !== 0 || event.target.selectionStart !== 0) {- return;- }-- if (event.key === "Backspace" && this.selection.length) {- if (!this.activeSelectionIdentifiers.length) {- this.activeSelectionIdentifiers = [this.#getLastSelection().identifier];- event.preventDefault();- return;- } else {- this.activeSelectionIdentifiers.forEach((identifier) => {- this.removeSelection(identifier);- });- this.activeSelectionIdentifiers = [];- event.preventDefault();- return;- }- }-- if (event.key === "ArrowLeft" && !event.shiftKey) {- this._activeResultIdentifier = null;- this.activeSelectionIdentifiers = [- this.#getPreviousSelection()?.identifier,- ].filter(Boolean);- event.preventDefault();- return;- }-- if (event.key === "ArrowRight" && !event.shiftKey) {- this._activeResultIdentifier = null;- this.activeSelectionIdentifiers = [- this.#getNextSelection()?.identifier,- ].filter(Boolean);- event.preventDefault();- return;- }- }-- @action- replaceActiveSelection(selection) {- this.activeSelection.clear();- this.activeSelection.push(selection.identifier);- }-- @action- handleInput(event) {- discourseDebounce(this, this.onFilter, event.target.value, INPUT_DELAY);- }-- @action- toggleSelection(identifier, options = {}) {- if (this.selectionIdentifiers.includes(identifier)) {- this.removeSelection(identifier, options);- } else {- this.addSelection(identifier, options);- }-- this.focusInput();- }-- @action- handleRowClick(identifier, event) {- this.toggleSelection(identifier, {- altSelection: event.shiftKey || event.ctrlKey,- });- event.preventDefault();- }-- @action- removeSelection(identifier) {- this.selection = this.selection.filter(- (selection) => selection.identifier !== identifier- );-- this.#handleSelectionChange();- }-- @action- addSelection(identifier, options = {}) {- let selection = this.searchRequest.value.findBy("identifier", identifier);-- if (!selection || !selection.enabled) {- return;- }-- if (selection.type === CHANNEL_TYPE && !selection.isSingleUserChannel) {- this.openChannel([selection]);- return;- }-- if (- !this.hasSelectedUsers &&- !options.altSelection &&- !this.site.mobileView- ) {- this.openChannel([selection]);- return;- }-- if (selection.isSingleUserChannel) {- const user = selection.model.chatable.users[0];- selection = new ChatChatable({- identifier: `u-${user.id}`,- type: USER_TYPE,- model: user,- });- }-- this.selection = [- ...this.selection.filter((s) => s.type !== CHANNEL_TYPE),- selection,- ];- this.#handleSelectionChange();- }-- @action- openChannel(selection) {- if (selection.length === 1 && selection[0].type === CHANNEL_TYPE) {- const channel = selection[0].model;- this.router.transitionTo("chat.channel", ...channel.routeModels);- this.args.onClose?.();- return;- }-- const users = selection.filterBy("type", USER_TYPE).mapBy("model");- this.chat- .upsertDmChannelForUsernames(users.mapBy("username"))- .then((channel) => {- if (!channel) {- return;- }-- this.router.transitionTo("chat.channel", ...channel.routeModels);- this.args.onClose?.();- });- }-- #handleSelectionChange() {- this.query = "";- this.activeSelectionIdentifiers = [];- this._activeResultIdentifier = null;- }-- #getPreviousSelection() {- return this.#getPrevious(- this.selection,- this.activeSelectionIdentifiers?.[0]- );- }-- #getNextSelection() {- return this.#getNext(this.selection, this.activeSelectionIdentifiers?.[0]);- }-- #getLastSelection() {- return this.selection[this.selection.length - 1];- }-- #getPreviousResult() {- return this.#getPrevious(- this.searchRequest.value,- this.activeResultIdentifier- );- }-- #getNextResult() {- return this.#getNext(this.searchRequest.value, this.activeResultIdentifier);- }-- #getNext(list, currentIdentifier = null) {- if (list.length === 0) {- return null;- }-- list = list.filterBy("enabled");-- if (currentIdentifier) {- const currentIndex = list.mapBy("identifier").indexOf(currentIdentifier);-- if (currentIndex < list.length - 1) {- return list.objectAt(currentIndex + 1);- } else {- return list[0];- }- } else {- return list[0];- }- }-- #getPrevious(list, currentIdentifier = null) {- if (list.length === 0) {- return null;- }-- list = list.filterBy("enabled");-- if (currentIdentifier) {- const currentIndex = list.mapBy("identifier").indexOf(currentIdentifier);-- if (currentIndex > 0) {- return list.objectAt(currentIndex - 1);- } else {- return list.objectAt(list.length - 1);- }- } else {- return list.objectAt(list.length - 1);- }- }-- #getDigit(input) {- if (typeof input === "string") {- const match = input.match(/Digit(\d+)/);- if (match) {- return parseInt(match[1], 10);- }- }- return false;- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/add-members.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/add-members.gjsnew file mode 100644index 00000000000..e274f1280e9--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/add-members.gjs@@ -0,0 +1,83 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { inject as service } from "@ember/service";+import DButton from "discourse/components/d-button";+import { popupAjaxError } from "discourse/lib/ajax-error";+import I18n from "discourse-i18n";+import gte from "truth-helpers/helpers/gte";+import MembersCount from "./members-count";+import MembersSelector from "./members-selector";++export default class AddMembers extends Component {+ @service chat;+ @service chatApi;+ @service router;+ @service toasts;+ @service siteSettings;+ @service loadingSlider;++ get membersCount() {+ return (+ this.args.members?.length + (this.args.channel?.membershipsCount ?? 0)+ );+ }++ @action+ async saveGroupMembers() {+ try {+ this.loadingSlider.transitionStarted();++ await this.chatApi.addMembersToChannel(+ this.args.channel.id,+ this.args.members.mapBy("model.username")+ );++ this.toasts.success({ data: { message: I18n.t("saved") } });+ this.router.transitionTo(+ "chat.channel",+ ...this.args.channel.routeModels+ );+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.loadingSlider.transitionEnded();+ }+ }++ <template>+ <div class="chat-message-creator__add-members-container">+ <div class="chat-message-creator__add-members">+ <MembersCount+ @count={{this.membersCount}}+ @max={{this.siteSettings.chat_max_direct_message_users}}+ />++ <MembersSelector+ @channel={{@channel}}+ @members={{@members}}+ @onChange={{@onChangeMembers}}+ @close={{@close}}+ @cancel={{@cancel}}+ @maxReached={{gte+ this.membersCount+ this.siteSettings.chat_max_direct_message_users+ }}+ />++ {{#if @members.length}}+ <div class="chat-message-creator__add-members-footer-container">+ <div class="chat-message-creator__add-members-footer">+ <DButton class="btn-flat" @label="cancel" @action={{@cancel}} />++ <DButton+ class="btn-primary add-to-channel"+ @label="chat.direct_message_creator.add_to_channel"+ @action={{this.saveGroupMembers}}+ />+ </div>+ </div>+ {{/if}}+ </div>+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel-row.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel-row.hbsdeleted file mode 100644index ac4f7767f7a..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel-row.hbs+++ /dev/null@@ -1,11 +0,0 @@-<ChatChannelTitle @channel={{@content.model}} />--{{#if (gt @content.tracking.unreadCount 0)}}- <div- class={{concat-class "unread-indicator" (if this.isUrgent "-urgent")}}- ></div>-{{/if}}--{{#if this.site.desktopView}}- <span class="action-indicator">{{this.openChannelLabel}}</span>-{{/if}}\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel-row.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel-row.jsdeleted file mode 100644index c35b80009e1..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel-row.js+++ /dev/null@@ -1,20 +0,0 @@-import Component from "@glimmer/component";-import { inject as service } from "@ember/service";-import { htmlSafe } from "@ember/template";-import I18n from "discourse-i18n";--export default class ChatMessageCreatorChannelRow extends Component {- @service site;-- get openChannelLabel() {- return htmlSafe(I18n.t("chat.new_message_modal.open_channel"));- }-- get isUrgent() {- return (- this.args.content.model.isDirectMessageChannel ||- (this.args.content.model.isCategoryChannel &&- this.args.content.model.tracking.mentionCount > 0)- );- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel.gjsnew file mode 100644index 00000000000..5c7fd55c17d--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/channel.gjs@@ -0,0 +1,29 @@+import Component from "@glimmer/component";+import { inject as service } from "@ember/service";+import concatClass from "discourse/helpers/concat-class";+import gt from "truth-helpers/helpers/gt";+import ChatChannelTitle from "discourse/plugins/chat/discourse/components/chat-channel-title";++export default class Channel extends Component {+ @service currentUser;++ get isUrgent() {+ return (+ this.args.item.model.isDirectMessageChannel ||+ (this.args.item.model.isCategoryChannel &&+ this.args.item.model.tracking.mentionCount > 0)+ );+ }++ <template>+ <div class="chat-message-creator__chatable-category-channel">+ <ChatChannelTitle @channel={{@item.model}} />++ {{#if (gt @item.tracking.unreadCount 0)}}+ <div+ class={{concatClass "unread-indicator" (if this.isUrgent "-urgent")}}+ ></div>+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/constants.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/constants.jsnew file mode 100644index 00000000000..9599cff4f48--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/constants.js@@ -0,0 +1,5 @@+export const MODES = {+ search: "SEARCH",+ new_group: "NEW_GROUP",+ add_members: "ADD_MEMBERS",+};diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/index.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/index.gjsnew file mode 100644index 00000000000..189795fffea--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/index.gjs@@ -0,0 +1,54 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import AddMembers from "./add-members";+import { MODES } from "./constants";+import NewGroup from "./new-group";+import Search from "./search";++export default class ChatMessageCreator extends Component {+ @tracked mode = MODES.search;+ @tracked members = [];++ get componentForMode() {+ switch (this.args.mode ?? this.mode) {+ case MODES.search:+ return Search;+ case MODES.new_group:+ return NewGroup;+ case MODES.add_members:+ return AddMembers;+ }+ }++ @action+ changeMode(mode, members = []) {+ this.mode = mode;+ this.changeMembers(members);+ }++ @action+ changeMembers(members) {+ this.members = members;+ }++ @action+ cancelAction() {+ return this.args.onCancel?.() || this.changeMode(MODES.search);+ }++ <template>+ <div class="chat-message-creator-container">+ <div class="chat-message-creator">+ <this.componentForMode+ @channel={{@channel}}+ @onChangeMode={{this.changeMode}}+ @onChangeMembers={{this.changeMembers}}+ @close={{@onClose}}+ @cancel={{this.cancelAction}}+ @members={{this.members}}+ />+ </div>+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.jsnew file mode 100644index 00000000000..e560fa764e5--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.js@@ -0,0 +1,91 @@+import { getOwner, setOwner } from "@ember/application";+import { inject as service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { bind } from "discourse-common/utils/decorators";+import ChatChatable from "discourse/plugins/chat/discourse/models/chat-chatable";++const MAX_RESULTS = 10;++export default class ChatablesLoader {+ @service chatChannelsManager;+ @service loadingSlider;++ constructor(context) {+ setOwner(this, getOwner(context));+ }++ @bind+ async search(+ term,+ options = {+ includeUsers: true,+ includeCategoryChannels: true,+ includeDirectMessageChannels: true,+ excludedUserIds: null,+ preloadChannels: false,+ }+ ) {+ this.request?.abort();++ if (!term && options.preloadChannels) {+ return this.#preloadedChannels();+ }++ if (!term) {+ return [];+ }++ try {+ this.loadingSlider.transitionStarted();+ this.request = ajax("/chat/api/chatables", {+ data: {+ term,+ include_users: options.includeUsers,+ include_category_channels: options.includeCategoryChannels,+ include_direct_message_channels: options.includeDirectMessageChannels,+ excluded_memberships_channel_id: options.excludedMembershipsChannelId,+ },+ });+ const results = await this.request;+ this.loadingSlider.transitionEnded();++ return [+ ...results.users,+ ...results.direct_message_channels,+ ...results.category_channels,+ ]+ .map((item) => {+ const chatable = ChatChatable.create(item);+ chatable.tracking = this.#injectTracking(chatable);+ return chatable;+ })+ .slice(0, MAX_RESULTS);+ } catch (e) {+ popupAjaxError(e);+ }+ }++ #preloadedChannels() {+ return this.chatChannelsManager.allChannels+ .map((channel) => {+ let chatable;+ if (channel.chatable?.users?.length === 1) {+ chatable = ChatChatable.createUser(channel.chatable.users[0]);+ chatable.tracking = this.#injectTracking(chatable);+ } else {+ chatable = ChatChatable.createChannel(channel);+ chatable.tracking = channel.tracking;+ }+ return chatable;+ })+ .filter(Boolean)+ .slice(0, MAX_RESULTS);+ }++ #injectTracking(chatable) {+ return this.chatChannelsManager.allChannels.find(+ (channel) => channel.id === chatable.model.id+ )?.tracking;+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/iterate-list.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/iterate-list.jsnew file mode 100644index 00000000000..fb4e21069c0--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/iterate-list.js@@ -0,0 +1,39 @@+export function getNext(list, current = null) {+ if (list.length === 0) {+ return null;+ }++ list = list.filterBy("enabled");++ if (current?.identifier) {+ const currentIndex = list.mapBy("identifier").indexOf(current?.identifier);++ if (currentIndex < list.length - 1) {+ return list.objectAt(currentIndex + 1);+ } else {+ return list[0];+ }+ } else {+ return list[0];+ }+}++export function getPrevious(list, current = null) {+ if (list.length === 0) {+ return null;+ }++ list = list.filterBy("enabled");++ if (current?.identifier) {+ const currentIndex = list.mapBy("identifier").indexOf(current?.identifier);++ if (currentIndex > 0) {+ return list.objectAt(currentIndex - 1);+ } else {+ return list.objectAt(list.length - 1);+ }+ } else {+ return list.objectAt(list.length - 1);+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list-action.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list-action.gjsnew file mode 100644index 00000000000..c6a5fd7e1bd--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list-action.gjs@@ -0,0 +1,12 @@+import Component from "@glimmer/component";+import DButton from "discourse/components/d-button";++export default class ListAction extends Component {+ <template>+ <DButton+ class="btn btn-flat"+ @icon={{@item.icon}}+ @translatedLabel={{@item.label}}+ />+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list-handler.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list-handler.gjsnew file mode 100644index 00000000000..02c22125e0b--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list-handler.gjs@@ -0,0 +1,46 @@+import Component from "@glimmer/component";+import { modifier } from "ember-modifier";+import { getNext, getPrevious } from "./lib/iterate-list";++export default class ListHandler extends Component {+ handleKeydown = modifier((element) => {+ const handler = (event) => {+ if (event.key === "ArrowDown") {+ event.preventDefault();+ event.stopPropagation();++ this.args.onHighlight(+ getNext(this.args.items, this.args.highlightedItem)+ );+ } else if (event.key === "ArrowUp") {+ event.preventDefault();+ event.stopPropagation();++ this.args.onHighlight(+ getPrevious(this.args.items, this.args.highlightedItem)+ );+ } else if (event.key === "Enter" && this.args.highlightedItem) {+ event.preventDefault();+ event.stopPropagation();++ if (event.shiftKey && this.args.onShifSelect) {+ this.args.onShifSelect(this.args.highlightedItem);+ } else {+ this.args.onSelect(this.args.highlightedItem);+ }+ }+ };++ element.addEventListener("keydown", handler);++ return () => {+ element.removeEventListener("keydown", handler);+ };+ });++ <template>+ <span style="display: contents" {{this.handleKeydown}} ...attributes>+ {{yield}}+ </span>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list.gjsnew file mode 100644index 00000000000..0f4e59689ad--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/list.gjs@@ -0,0 +1,85 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import concatClass from "discourse/helpers/concat-class";+import I18n from "discourse-i18n";+import eq from "truth-helpers/helpers/eq";+import Channel from "./channel";+import ListAction from "./list-action";+import User from "./user";++export default class List extends Component {+ cantAddMoreMembersLabel = I18n.t(+ "chat.new_message_modal.cant_add_more_members"+ );++ componentForItem(type) {+ switch (type) {+ case "list-action":+ return ListAction;+ case "user":+ return User;+ case "channel":+ return Channel;+ }+ }++ @action+ handleEnter(item, event) {+ if (event.key !== "Enter") {+ return;+ }++ if (event.shiftKey && this.args.onShiftSelect) {+ this.args.onShiftSelect?.(item);+ } else {+ this.args.onSelect?.(item);+ }+ }++ @action+ handleClick(item, event) {+ if (event.shiftKey && this.args.onShiftSelect) {+ this.args.onShiftSelect?.(item);+ } else {+ this.args.onSelect?.(item);+ }+ }++ <template>+ {{#if @items}}+ <div class="chat-message-creator__list-container">+ {{#if @maxReached}}+ <div+ class="chat-message-creator__warning-max-members"+ >{{this.cantAddMoreMembersLabel}}</div>+ {{else}}+ <ul class="chat-message-creator__list">+ {{#each @items as |item|}}+ <li+ class={{concatClass+ "chat-message-creator__list-item"+ (if+ (eq item.identifier @highlightedItem.identifier)+ "-highlighted"+ )+ }}+ {{on "click" (fn this.handleClick item)}}+ {{on "keypress" (fn this.handleEnter item)}}+ {{on "mousemove" (fn @onHighlight item)}}+ {{on "mouseleave" (fn @onHighlight null)}}+ role="button"+ tabindex="0"+ data-identifier={{item.identifier}}+ id={{item.id}}+ >+ {{component (this.componentForItem item.type) item=item}}+ </li>+ {{/each}}+ </ul>+ {{/if}}+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/member.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/member.gjsnew file mode 100644index 00000000000..c7a170f5525--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/member.gjs@@ -0,0 +1,28 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import DButton from "discourse/components/d-button";+import concatClass from "discourse/helpers/concat-class";+import icon from "discourse-common/helpers/d-icon";+import ChatUserAvatar from "discourse/plugins/chat/discourse/components/chat-user-avatar";++export default class Member extends Component {+ <template>+ <DButton+ class={{concatClass+ "chat-message-creator__member btn-default"+ (if @highlighted "-highlighted")+ }}+ @action={{fn @onSelect @member}}+ >+ <ChatUserAvatar+ @user={{@member.model}}+ @interactive={{false}}+ @showPresence={{false}}+ />+ <span class="chat-message-creator__member-username">+ {{@member.model.username}}+ </span>+ {{icon "times"}}+ </DButton>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members-count.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members-count.gjsnew file mode 100644index 00000000000..905da71d8bb--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members-count.gjs@@ -0,0 +1,24 @@+import Component from "@glimmer/component";+import concatClass from "discourse/helpers/concat-class";+import I18n from "discourse-i18n";+import eq from "truth-helpers/helpers/eq";++export default class MembersCount extends Component {+ get countLabel() {+ return I18n.t("chat.direct_message_creator.members_counter", {+ count: this.args.count,+ max: this.args.max,+ });+ }++ <template>+ <div+ class={{concatClass+ "chat-message-creator__members-count"+ (if (eq @count @max) "-reached-limit")+ }}+ >+ {{this.countLabel}}+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members-selector.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members-selector.gjsnew file mode 100644index 00000000000..005db489b17--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members-selector.gjs@@ -0,0 +1,141 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { inject as service } from "@ember/service";+import DButton from "discourse/components/d-button";+import { INPUT_DELAY } from "discourse-common/config/environment";+import discourseDebounce from "discourse-common/lib/debounce";+import I18n from "discourse-i18n";+import ChatablesLoader from "./lib/chatables-loader";+import List from "./list";+import ListHandler from "./list-handler";+import Members from "./members";++export default class MembersSelector extends Component {+ @service siteSettings;++ @tracked chatables = [];+ @tracked filter = "";+ @tracked highlightedMember;+ @tracked highlightedChatable;++ placeholder = I18n.t("chat.direct_message_creator.group_name");++ get items() {+ return this.chatables.filter(+ (c) => !this.highlightedMemberIds.includes(c.model.id)+ );+ }++ get highlightedMemberIds() {+ return this.args.members.map((u) => u.model.id);+ }++ @action+ highlightMember(member) {+ this.highlightedMember = member;+ }++ @action+ highlightChatable(chatable) {+ this.highlightedChatable = chatable;+ }++ @action+ selectChatable(chatable) {+ if (+ this.args.members.length + (this.args.channel?.membershipsCount ?? 0) >=+ this.siteSettings.chat_max_direct_message_users+ ) {+ return;+ }++ if (this.highlightedMemberIds.includes(chatable.model.id)) {+ this.unselectMember(chatable);+ } else {+ this.args.onChange?.([...this.args.members, chatable]);+ this.highlightedChatable = this.items[0];+ }++ this.filter = "";+ this.focusFilterAction?.();+ this.highlightedMember = null;+ }++ @action+ registerFocusFilterAction(actionFn) {+ this.focusFilterAction = actionFn;+ }++ @action+ onFilter(event) {+ this.searchHandler = discourseDebounce(+ this,+ this.fetch,+ event.target.value,+ INPUT_DELAY+ );+ }++ @action+ async fetch(term) {+ this.highlightedMember = null;++ const loader = new ChatablesLoader(this);+ this.chatables = await loader.search(term, {+ includeCategoryChannels: false,+ includeDirectMessageChannels: false,+ excludedMembershipsChannelId: this.args.channel?.id,+ });++ this.highlightedChatable = this.items[0];+ }++ @action+ unselectMember(removedMember) {+ this.args.onChange?.(+ this.args.members.filter((member) => member !== removedMember)+ );+ this.highlightedMember = null;+ this.highlightedChatable = this.items[0];+ this.focusFilterAction?.();+ }++ <template>+ <ListHandler+ @items={{this.items}}+ @highlightedItem={{this.highlightedChatable}}+ @onHighlight={{this.highlightChatable}}+ @onSelect={{this.selectChatable}}+ >+ <div class="chat-message-creator__add-members-header-container">+ <div class="chat-message-creator__add-members-header">+ <Members+ @filter={{this.filter}}+ @members={{@members}}+ @highlightedMember={{this.highlightedMember}}+ @onFilter={{this.onFilter}}+ @registerFocusFilterAction={{this.registerFocusFilterAction}}+ @onHighlightMember={{this.highlightMember}}+ @onSelectMember={{this.unselectMember}}+ />++ <DButton+ class="btn-flat chat-message-creator__add-members__close-btn"+ @action={{@cancel}}+ @icon="times"+ />+ </div>+ </div>++ <List+ @items={{this.items}}+ @highlightedItem={{this.highlightedChatable}}+ @onSelect={{this.selectChatable}}+ @onHighlight={{this.highlightChatable}}+ @maxReached={{@maxReached}}+ />++ </ListHandler>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members.gjsnew file mode 100644index 00000000000..ca51b9262d3--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/members.gjs@@ -0,0 +1,100 @@+import Component from "@glimmer/component";+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import icon from "discourse-common/helpers/d-icon";+import I18n from "discourse-i18n";+import eq from "truth-helpers/helpers/eq";+import { getNext, getPrevious } from "./lib/iterate-list";+import Member from "./member";++export default class Members extends Component {+ addMoreMembersLabel = I18n.t(+ "chat.new_message_modal.user_search_placeholder"+ );++ @action+ onFilter() {+ this.args.onFilter(...arguments);+ }++ @action+ registerFocusFilterAction(element) {+ this.args.registerFocusFilterAction(() => element.focus());+ }++ @action+ handleKeypress(event) {+ if (event.key === "Backspace" && event.target.value === "") {+ event.preventDefault();+ event.stopPropagation();++ if (!this.args.highlightedMember) {+ this.args.onHighlightMember(this.args.members.lastObject);+ } else {+ this.args.onSelectMember(this.args.highlightedMember);+ }++ return;+ }++ if (event.key === "ArrowLeft" && event.target.value === "") {+ event.preventDefault();+ event.stopPropagation();++ this.args.onHighlightMember(+ getPrevious(this.args.members, this.args.highlightedMember)+ );++ return;+ }+ if (event.key === "ArrowRight" && event.target.value === "") {+ event.preventDefault();+ event.stopPropagation();++ this.args.onHighlightMember(+ getNext(this.args.members, this.args.highlightedMember)+ );++ return;+ }++ if (event.key === "Enter" && this.args.highlightedMember) {+ event.preventDefault();+ event.stopPropagation();++ this.args.onSelectMember(this.args.highlightedMember);++ return;+ }++ this.highlightedMember = null;+ }++ <template>+ <div class="chat-message-creator__members-container">+ <div class="chat-message-creator__members">+ {{icon "search"}}++ {{#each @members as |member|}}+ <Member+ @member={{member}}+ @onSelect={{@onSelectMember}}+ @highlighted={{eq member @highlightedMember}}+ />+ {{/each}}++ <Input+ placeholder={{this.addMoreMembersLabel}}+ class="chat-message-creator__members-input"+ @value={{@filter}}+ autofocus={{true}}+ {{on "input" this.onFilter}}+ {{on "keydown" this.handleKeypress}}+ {{didInsert this.registerFocusFilterAction}}+ />+ </div>+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/new-group.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/new-group.gjsnew file mode 100644index 00000000000..d1bcce99b63--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/new-group.gjs@@ -0,0 +1,97 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { Input } from "@ember/component";+import { action } from "@ember/object";+import { inject as service } from "@ember/service";+import DButton from "discourse/components/d-button";+import { popupAjaxError } from "discourse/lib/ajax-error";+import I18n from "discourse-i18n";+import gte from "truth-helpers/helpers/gte";+import MembersCount from "./members-count";+import MembersSelector from "./members-selector";++export default class NewGroup extends Component {+ @service chat;+ @service router;+ @service siteSettings;++ @tracked newGroupTitle = "";++ placeholder = I18n.t("chat.direct_message_creator.group_name");+ cancelLabel = I18n.t("cancel");++ get membersCount() {+ return this.args.members?.length;+ }++ @action+ async createGroup() {+ try {+ const channel = await this.chat.upsertDmChannelForUsernames(+ this.args.members.mapBy("model.username"),+ this.newGroupTitle+ );++ if (!channel) {+ return;+ }++ this.args.close?.();+ this.router.transitionTo("chat.channel", ...channel.routeModels);+ } catch (error) {+ popupAjaxError(error);+ }+ }++ <template>+ <div class="chat-message-creator__new-group-container">+ <div class="chat-message-creator__new-group">+ <div class="chat-message-creator__new-group-header-container">+ <div class="chat-message-creator__new-group-header">+ <Input+ name="channel-name"+ class="chat-message-creator__new-group-header__input"+ placeholder={{this.placeholder}}+ @value={{this.newGroupTitle}}+ />++ <MembersCount+ @count={{this.membersCount}}+ @max={{this.siteSettings.chat_max_direct_message_users}}+ />+ </div>+ </div>++ <MembersSelector+ @members={{@members}}+ @channel={{@channel}}+ @onChange={{@onChangeMembers}}+ @close={{@close}}+ @cancel={{@cancel}}+ @maxReached={{gte+ this.membersCount+ this.siteSettings.chat_max_direct_message_users+ }}+ />++ {{#if @members.length}}+ <div class="chat-message-creator__new-group-footer-container">+ <div class="chat-message-creator__new-group-footer">+ <DButton+ class="btn-primary btn-flat"+ @label={{this.cancelLabel}}+ @action={{@cancel}}+ />+ <DButton+ class="btn-primary create-chat-group"+ @label="chat.new_message_modal.create_new_group_chat"+ @action={{this.createGroup}}+ />++ </div>+ </div>+ {{/if}}+ </div>+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/search-input.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/search-input.gjsnew file mode 100644index 00000000000..bce963d7f03--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/search-input.gjs@@ -0,0 +1,25 @@+import Component from "@glimmer/component";+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import icon from "discourse-common/helpers/d-icon";+import I18n from "discourse-i18n";++export default class ChatMessageCreatorSearchInput extends Component {+ filterPlaceholder = I18n.t("chat.new_message_modal.filter");++ <template>+ <div class="chat-message-creator__search-input-container">+ <div class="chat-message-creator__search-input">+ {{icon+ "search"+ class="chat-message-creator__search-input__search-icon"+ }}+ <Input+ class="chat-message-creator__search-input__input"+ placeholder={{this.filterPlaceholder}}+ {{on "input" @onFilter}}+ />+ </div>+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/search.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/search.gjsnew file mode 100644index 00000000000..efae2193a54--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/search.gjs@@ -0,0 +1,132 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { inject as service } from "@ember/service";+import DButton from "discourse/components/d-button";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { INPUT_DELAY } from "discourse-common/config/environment";+import discourseDebounce from "discourse-common/lib/debounce";+import I18n from "discourse-i18n";+import { MODES } from "./constants";+import ChatablesLoader from "./lib/chatables-loader";+import List from "./list";+import ListHandler from "./list-handler";+import SearchInput from "./search-input";++export default class ChatMessageCreatorSearch extends Component {+ @service chat;+ @service router;++ @tracked chatables = [];+ @tracked highlightedChatable;++ get items() {+ return [+ {+ identifier: "new-group",+ type: "list-action",+ label: I18n.t("chat.new_message_modal.new_group_chat"),+ enabled: true,+ icon: "users",+ id: "new-group-chat",+ },+ ...this.chatables,+ ];+ }++ @action+ prefillAddMembers(item) {+ this.args.onChangeMode(MODES.new_group, [item]);+ }++ @action+ highlightChatable(chatable) {+ this.highlightedChatable = chatable;+ }++ @action+ async selectChatable(item) {+ switch (item.type) {+ case "list-action":+ this.args.onChangeMode(MODES.new_group);+ break;+ case "user":+ await this.startOneToOneChannel(item.model.username);+ break;+ default:+ this.router.transitionTo("chat.channel", ...item.model.routeModels);+ this.args.close();+ break;+ }+ }++ @action+ onFilter(event) {+ this.searchHandler = discourseDebounce(+ this,+ this.fetch,+ event.target.value,+ INPUT_DELAY+ );+ }++ @action+ async fetch(term) {+ const loader = new ChatablesLoader(this);+ this.chatables = await loader.search(term, { preloadChannels: true });++ this.highlightedChatable = this.items[0];+ }++ async startOneToOneChannel(username) {+ try {+ const channel = await this.chat.upsertDmChannelForUsernames([username]);++ if (!channel) {+ return;+ }++ this.args.close?.();+ this.router.transitionTo("chat.channel", ...channel.routeModels);+ } catch (error) {+ popupAjaxError(error);+ }+ }++ <template>+ <ListHandler+ @items={{this.items}}+ @highlightedItem={{this.highlightedChatable}}+ @onHighlight={{this.highlightChatable}}+ @onSelect={{this.selectChatable}}+ @onShifSelect={{this.prefillAddMembers}}+ >+ <div class="chat-message-creator__search-container">+ <div class="chat-message-creator__search">+ <div+ class="chat-message-creator__section"+ {{didInsert (fn this.fetch null)}}+ >+ <SearchInput @onFilter={{this.onFilter}} />++ <DButton+ class="btn-flat chat-message-creator__search-input__cancel-button"+ @icon="times"+ @action={{@close}}+ />+ </div>++ <List+ @items={{this.items}}+ @highlightedItem={{this.highlightedChatable}}+ @onSelect={{this.selectChatable}}+ @onHighlight={{this.highlightChatable}}+ @onShiftSelect={{this.prefillAddMembers}}+ />+ </div>+ </div>+ </ListHandler>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-row.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-row.hbsdeleted file mode 100644index 640fd839332..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-row.hbs+++ /dev/null@@ -1,36 +0,0 @@-<ChatUserAvatar @user={{@content.model}} />-<ChatUserDisplayName @user={{@content.model}} />--{{#if (gt @content.tracking.unreadCount 0)}}- <div class="unread-indicator -urgent"></div>-{{/if}}--{{user-status @content.model currentUser=this.currentUser}}--{{#unless @content.enabled}}- <span class="disabled-text">- {{i18n "chat.new_message_modal.disabled_user"}}- </span>-{{/unless}}--{{#if @selected}}- {{#if this.site.mobileView}}- <span class="selection-indicator -add">- {{d-icon "check"}}- </span>- {{else}}- <span- class={{concat-class "selection-indicator" (if @active "-remove" "-add")}}- >- {{d-icon (if @active "times" "check")}}- </span>- {{/if}}-{{else}}- {{#if this.site.desktopView}}- {{#if @hasSelectedUsers}}- <span class="action-indicator">{{this.addUserLabel}}</span>- {{else}}- <span class="action-indicator">{{this.openChannelLabel}}</span>- {{/if}}- {{/if}}-{{/if}}\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-row.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-row.jsdeleted file mode 100644index 9709010bfbb..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-row.js+++ /dev/null@@ -1,17 +0,0 @@-import Component from "@glimmer/component";-import { inject as service } from "@ember/service";-import { htmlSafe } from "@ember/template";-import I18n from "discourse-i18n";--export default class ChatMessageCreatorUserRow extends Component {- @service currentUser;- @service site;-- get openChannelLabel() {- return htmlSafe(I18n.t("chat.new_message_modal.open_channel"));- }-- get addUserLabel() {- return htmlSafe(I18n.t("chat.new_message_modal.add_user_short"));- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-selection.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-selection.hbsdeleted file mode 100644index ef9cca035f6..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user-selection.hbs+++ /dev/null@@ -1,5 +0,0 @@-<ChatUserAvatar @user={{@selection.model}} @showPresence={{false}} />--<span class="chat-message-creator__selection-item__username">- {{@selection.model.username}}-</span>\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user.gjsnew file mode 100644index 00000000000..836f0c1a405--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/user.gjs@@ -0,0 +1,32 @@+import Component from "@glimmer/component";+import { inject as service } from "@ember/service";+import userStatus from "discourse/helpers/user-status";+import I18n from "discourse-i18n";+import gt from "truth-helpers/helpers/gt";+import ChatUserAvatar from "discourse/plugins/chat/discourse/components/chat-user-avatar";+import ChatUserDisplayName from "discourse/plugins/chat/discourse/components/chat-user-display-name";++export default class ChatableUser extends Component {+ @service currentUser;++ disabledUserLabel = I18n.t("chat.new_message_modal.disabled_user");++ <template>+ <div class="chat-message-creator__chatable-user">+ <ChatUserAvatar @user={{@item.model}} @interactive={{false}} />+ <ChatUserDisplayName @user={{@item.model}} />++ {{#if (gt @item.tracking.unreadCount 0)}}+ <div class="unread-indicator -urgent"></div>+ {{/if}}++ {{userStatus @item.model currentUser=this.currentUser}}++ {{#unless @item.enabled}}+ <span class="disabled-text">+ {{this.disabledUserLabel}}+ </span>+ {{/unless}}+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/modal/edit-channel-name.js b/plugins/chat/assets/javascripts/discourse/components/chat/modal/edit-channel-name.jsindex 80b4971a6f1..381433ac582 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/modal/edit-channel-name.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat/modal/edit-channel-name.js@@ -6,16 +6,19 @@ import { inject as service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { extractError } from "discourse/lib/ajax-error";import discourseDebounce from "discourse-common/lib/debounce";+import slugifyChannel from "discourse/plugins/chat/discourse/lib/slugify-channel";const SLUG_MAX_LENGTH = 100;export default class ChatModalEditChannelName extends Component {@service chatApi;+ @service router;@service siteSettings;@tracked editedName = this.channel.title;@tracked editedSlug = this.channel.slug;- @tracked autoGeneratedSlug = "";+ @tracked+ autoGeneratedSlug = this.channel.slug ?? slugifyChannel(this.channel);@tracked flash;#generateSlugHandler = null;@@ -34,17 +37,23 @@ export default class ChatModalEditChannelName extends Component {}@action- onSave() {- return this.chatApi- .updateChannel(this.channel.id, {+ async onSave() {+ try {+ const result = await this.chatApi.updateChannel(this.channel.id, {name: this.editedName,slug: this.editedSlug || this.autoGeneratedSlug || this.channel.slug,- })- .then((result) => {- this.channel.title = result.channel.title;- this.args.closeModal();- })- .catch((error) => (this.flash = extractError(error)));+ });++ this.channel.title = result.channel.title;+ this.channel.slug = result.channel.slug;+ await this.args.closeModal();+ await this.router.replaceWith(+ "chat.channel",+ ...this.channel.routeModels+ );+ } catch (error) {+ this.flash = extractError(error);+ }}@action@@ -75,13 +84,16 @@ export default class ChatModalEditChannelName extends Component {);}- // intentionally not showing AJAX error for this, we will autogenerate- // the slug server-side if they leave it blank- #generateSlug(name) {- return ajax("/slugs.json", { type: "POST", data: { name } }).then(- (response) => {- this.autoGeneratedSlug = response.slug;- }- );+ async #generateSlug(name) {+ try {+ await ajax("/slugs.json", { type: "POST", data: { name } }).then(+ (response) => {+ this.autoGeneratedSlug = response.slug;+ }+ );+ } catch (error) {+ // eslint-disable-next-line no-console+ console.log(error);+ }}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.gjsnew file mode 100644index 00000000000..3bce3f92a37--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.gjs@@ -0,0 +1,28 @@+import Component from "@glimmer/component";+import { inject as service } from "@ember/service";+import DModal from "discourse/components/d-modal";+import MessageCreator from "discourse/plugins/chat/discourse/components/chat/message-creator";++export default class ChatModalNewMessage extends Component {+ @service chat;+ @service siteSettings;++ get shouldRender() {+ return (+ this.siteSettings.enable_public_channels || this.chat.userCanDirectMessage+ );+ }++ <template>+ {{#if this.shouldRender}}+ <DModal+ @closeModal={{@closeModal}}+ class="chat-modal-new-message"+ @title="chat.new_message_modal.title"+ @inline={{@inline}}+ >+ <MessageCreator @onClose={{@closeModal}} @channel={{@model}} />+ </DModal>+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.hbsdeleted file mode 100644index 883cf9903b2..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.hbs+++ /dev/null@@ -1,10 +0,0 @@-{{#if this.shouldRender}}- <DModal- @closeModal={{@closeModal}}- class="chat-modal-new-message"- @title="chat.new_message_modal.title"- @inline={{@inline}}- >- <Chat::MessageCreator @onClose={{@closeModal}} />- </DModal>-{{/if}}\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.js b/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.jsdeleted file mode 100644index 4252333fd2b..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/modal/new-message.js+++ /dev/null@@ -1,13 +0,0 @@-import Component from "@glimmer/component";-import { inject as service } from "@ember/service";--export default class ChatModalNewMessage extends Component {- @service chat;- @service siteSettings;-- get shouldRender() {- return (- this.siteSettings.enable_public_channels || this.chat.userCanDirectMessage- );- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjsnew file mode 100644index 00000000000..56b2264fc63--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjs@@ -0,0 +1,36 @@+import Component from "@glimmer/component";+import { inject as service } from "@ember/service";+import I18n from "I18n";++export default class ThreadHeaderUnreadIndicator extends Component {+ @service currentUser;++ unreadCountLabel = I18n.t("chat.unread_threads_count", {+ count: this.cappedUnreadCount,+ });++ get unreadCount() {+ return this.args.channel.threadsManager.unreadThreadCount;+ }++ get showUnreadIndicator() {+ return !this.currentUser.isInDoNotDisturb() && this.unreadCount > 0;+ }++ get cappedUnreadCount() {+ return this.unreadCount > 99 ? "99+" : this.unreadCount;+ }++ <template>+ {{#if this.showUnreadIndicator}}+ <div+ class="chat-thread-header-unread-indicator"+ title={{this.unreadCountLabel}}+ >+ <div+ class="chat-thread-header-unread-indicator__number"+ >{{this.cappedUnreadCount}}</div>+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.hbsdeleted file mode 100644index d29401a549c..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.hbs+++ /dev/null@@ -1,11 +0,0 @@-{{#if this.showUnreadIndicator}}- <div- class="chat-thread-header-unread-indicator"- aria-label={{i18n "chat.unread_threads_count" count=this.unreadCountLabel}}- title={{i18n "chat.unread_threads_count" count=this.unreadCountLabel}}- >- <div- class="chat-thread-header-unread-indicator__number"- >{{this.unreadCountLabel}}</div>- </div>-{{/if}}\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.js b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.jsdeleted file mode 100644index f81c0ca7755..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.js+++ /dev/null@@ -1,22 +0,0 @@-import Component from "@glimmer/component";-import { inject as service } from "@ember/service";--export default class ChatThreadHeaderUnreadIndicator extends Component {- @service currentUser;-- get currentUserInDnD() {- return this.currentUser.isInDoNotDisturb();- }-- get unreadCount() {- return this.args.channel.threadsManager.unreadThreadCount;- }-- get showUnreadIndicator() {- return !this.currentUserInDnD && this.unreadCount > 0;- }-- get unreadCountLabel() {- return this.unreadCount > 99 ? "99+" : this.unreadCount;- }-}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.gjsnew file mode 100644index 00000000000..c3c6c9ad9cc--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.gjs@@ -0,0 +1,28 @@+import Component from "@glimmer/component";+import { LinkTo } from "@ember/routing";+import concatClass from "discourse/helpers/concat-class";+import icon from "discourse-common/helpers/d-icon";+import I18n from "I18n";+import ThreadHeaderUnreadIndicator from "discourse/plugins/chat/discourse/components/chat/thread/header-unread-indicator";++export default class ThreadsListButton extends Component {+ threadsListLabel = I18n.t("chat.threads.list");++ <template>+ <LinkTo+ @route="chat.channel.threads"+ @models={{@channel.routeModels}}+ title={{this.threadsListLabel}}+ class={{concatClass+ "chat-threads-list-button"+ "btn"+ "btn-flat"+ (if @channel.threadsManager.unreadThreadCount "has-unreads")+ }}+ >+ {{icon "discourse-threads"}}++ <ThreadHeaderUnreadIndicator @channel={{@channel}} />+ </LinkTo>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.hbs b/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.hbsdeleted file mode 100644index c4b7263d1b3..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.hbs+++ /dev/null@@ -1,13 +0,0 @@-<LinkTo- @route="chat.channel.threads"- @models={{@channel.routeModels}}- title={{i18n "chat.threads.list"}}- class={{concat-class- "chat-threads-list-button btn btn-flat"- (if @channel.threadsManager.unreadThreadCount "has-unreads")- }}->- {{d-icon "discourse-threads"}}-- <Chat::Thread::HeaderUnreadIndicator @channel={{@channel}} />-</LinkTo>\ No newline at end of filediff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.js b/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.jsdeleted file mode 100644index c383e020f9d..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread/threads-list-button.js+++ /dev/null@@ -1,3 +0,0 @@-import Component from "@glimmer/component";--export default class ChatThreadsListButton extends Component {}diff --git a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbs b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbsindex df0b6921b7c..a4017c71e3b 100644--- a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbs@@ -6,7 +6,7 @@@icon={{this.options.leaveIcon}}@disabled={{this.isLoading}}class={{concat-class- "toggle-channel-membership-button -leave btn-flat"+ "toggle-channel-membership-button -leave"this.options.leaveClass}}/>diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.jsindex abb06ed438e..5997dcde074 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js@@ -206,10 +206,18 @@ export default {api.addSidebarSection((BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {const SidebarChatDirectMessagesSectionLink = class extends BaseCustomSidebarSectionLink {- constructor({ channel, chatService }) {+ route = "chat.channel";+ suffixType = "icon";+ suffixCSSClass = "urgent";+ hoverType = "icon";+ hoverValue = "times";+ hoverTitle = I18n.t("chat.direct_messages.leave");++ constructor({ channel, chatService, currentUser }) {super(...arguments);this.channel = channel;this.chatService = chatService;+ this.currentUser = currentUser;if (this.oneOnOneMessage) {const user = this.channel.chatable.users[0];@@ -226,6 +234,20 @@ export default {}}+ get oneOnOneMessage() {+ return this.channel.chatable.users.length === 1;+ }++ get contentComponentArgs() {+ return this.channel.chatable.users[0].get("status");+ }++ get contentComponent() {+ if (this.oneOnOneMessage) {+ return "user-status-message";+ }+ }+get name() {return this.channel.slugifiedTitle;}@@ -246,10 +268,6 @@ export default {return classes.join(" ");}- get route() {- return "chat.channel";- }-get models() {return this.channel.routeModels;}@@ -260,53 +278,42 @@ export default {});}- get oneOnOneMessage() {- return this.channel.chatable.users.length === 1;- }-- get contentComponentArgs() {- return this.channel.chatable.users[0].get("status");- }-- get contentComponent() {- return "user-status-message";- }-get text() {- const username = this.channel.escapedTitle.replaceAll("@", "");- if (this.oneOnOneMessage) {+ if (this.channel.chatable.group) {+ return this.channel.title;+ } else {+ const username = this.channel.escapedTitle.replaceAll("@", "");return htmlSafe(`${escapeExpression(username)}${decorateUsername(escapeExpression(username))}`);- } else {- return username;}}get prefixType() {- if (this.oneOnOneMessage) {- return "image";- } else {+ if (this.channel.chatable.group) {return "text";+ } else {+ return "image";}}get prefixValue() {- if (this.channel.chatable.users.length === 1) {+ if (this.channel.chatable.group) {+ return this.channel.membershipsCount;+ } else {return avatarUrl(this.channel.chatable.users[0].avatar_template,"tiny");- } else {- return this.channel.chatable.users.length;}}get prefixCSSClass() {const activeUsers = this.chatService.presenceChannel.users;const user = this.channel.chatable.users[0];+if (!!activeUsers?.findBy("id", user?.id) ||!!activeUsers?.findBy("username", user?.username)@@ -316,26 +323,10 @@ export default {return "";}- get suffixType() {- return "icon";- }-get suffixValue() {return this.channel.tracking.unreadCount > 0 ? "circle" : "";}- get suffixCSSClass() {- return "urgent";- }-- get hoverType() {- return "icon";- }-- get hoverValue() {- return "times";- }-get hoverAction() {return (event) => {event.stopPropagation();@@ -343,16 +334,13 @@ export default {this.chatService.unfollowChannel(this.channel);};}-- get hoverTitle() {- return I18n.t("chat.direct_messages.leave");- }};const SidebarChatDirectMessagesSection = class extends BaseCustomSidebarSection {@service site;@service modal;@service router;+ @service currentUser;@trackeduserCanDirectMessage = this.chatService.userCanDirectMessage;@@ -363,6 +351,7 @@ export default {if (container.isDestroyed) {return;}+this.chatService = container.lookup("service:chat");this.chatChannelsManager = container.lookup("service:chat-channels-manager"@@ -375,6 +364,7 @@ export default {new SidebarChatDirectMessagesSectionLink({channel,chatService: this.chatService,+ currentUser: this.currentUser,}));}diff --git a/plugins/chat/assets/javascripts/discourse/lib/fabricators.js b/plugins/chat/assets/javascripts/discourse/lib/fabricators.jsindex 41e6bea0a56..a7189ce0dcb 100644--- a/plugins/chat/assets/javascripts/discourse/lib/fabricators.js+++ b/plugins/chat/assets/javascripts/discourse/lib/fabricators.js@@ -52,21 +52,29 @@ function messageFabricator(args = {}) {function channelFabricator(args = {}) {const id = args.id || sequence++;+ const chatable = args.chatable || categoryFabricator();const channel = ChatChannel.create({id,chatable_type:- args.chatable?.type ||- args.chatable_type ||- CHATABLE_TYPES.categoryChannel,- chatable_id: args.chatable?.id || args.chatable_id,- title: args.title || "General",+ (chatable instanceof Category+ ? CHATABLE_TYPES.categoryChannel+ : CHATABLE_TYPES.directMessageChannel) ||+ chatable?.type ||+ args.chatable_type,+ chatable_id: chatable?.id || args.chatable_id,+ title: args.title+ ? args.title+ : chatable instanceof Category+ ? "General"+ : null,description: args.description,- chatable: args.chatable || categoryFabricator(),+ chatable,status: args.status || CHANNEL_STATUSES.open,- slug: args.chatable?.slug || "general",+ slug: chatable?.slug || chatable instanceof Category ? "general" : null,meta: Object.assign({ can_delete_self: true }, args.meta || {}),archive_failed: args.archive_failed ?? false,+ memberships_count: args.memberships_count ?? 0,});channel.lastMessage = messageFabricator({ channel });@@ -78,7 +86,7 @@ function categoryFabricator(args = {}) {return Category.create({id: args.id || sequence++,color: args.color || "D56353",- read_restricted: false,+ read_restricted: args.read_restricted ?? false,name: args.name || "General",slug: args.slug || "general",});@@ -86,8 +94,8 @@ function categoryFabricator(args = {}) {function directMessageFabricator(args = {}) {return ChatDirectMessage.create({- id: args.id || sequence++,- users: args.users || [userFabricator(), userFabricator()],+ group: args.group ?? false,+ users: args.users ?? [userFabricator(), userFabricator()],});}@@ -96,6 +104,8 @@ function directMessageChannelFabricator(args = {}) {args.chatable ||directMessageFabricator({id: args.chatable_id || sequence++,+ group: args.group ?? false,+ users: args.users,});return channelFabricator(@@ -103,6 +113,7 @@ function directMessageChannelFabricator(args = {}) {chatable_type: CHATABLE_TYPES.directMessageChannel,chatable_id: directMessage.id,chatable: directMessage,+ memberships_count: directMessage.users.length,}));}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.jsindex ccc6415b9a6..35cad514bc7 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js@@ -61,6 +61,7 @@ export default class ChatChannel {@tracked status;@tracked activeThread = null;@tracked meta;+ @tracked chatableId;@tracked chatableType;@tracked chatableUrl;@tracked autoJoinUsers = false;@@ -89,12 +90,7 @@ export default class ChatChannel {this.threadingEnabled = args.threading_enabled;this.autoJoinUsers = args.auto_join_users;this.allowChannelWideMentions = args.allow_channel_wide_mentions;- this.chatable = this.isDirectMessageChannel- ? ChatDirectMessage.create({- id: args.chatable?.id,- users: args.chatable?.users,- })- : Category.create(args.chatable);+ this.chatable = this.#initChatable(args.chatable || []);this.currentUserMembership = args.current_user_membership;if (args.archive_completed || args.archive_failed) {@@ -245,4 +241,23 @@ export default class ChatChannel {this._lastMessage = ChatMessage.create(this, message);}}++ #initChatable(chatable) {+ if (+ !chatable ||+ chatable instanceof Category ||+ chatable instanceof ChatDirectMessage+ ) {+ return chatable;+ } else {+ if (this.isDirectMessageChannel) {+ return ChatDirectMessage.create({+ users: chatable?.users,+ group: chatable?.group,+ });+ } else {+ return Category.create(chatable);+ }+ }+ }}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-chatable.js b/plugins/chat/assets/javascripts/discourse/models/chat-chatable.jsindex 3bb7924fa99..0d93034821e 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-chatable.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-chatable.js@@ -1,5 +1,6 @@import { tracked } from "@glimmer/tracking";import { inject as service } from "@ember/service";+import Category from "discourse/models/category";import User from "discourse/models/user";import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";@@ -66,7 +67,7 @@ export default class ChatChatable {return this.type === "user";}- get isSingleUserChannel() {- return this.type === "channel" && this.model?.chatable?.users?.length === 1;+ get isCategory() {+ return this instanceof Category;}}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-direct-message.js b/plugins/chat/assets/javascripts/discourse/models/chat-direct-message.jsindex 5b374e9908b..df0ee97e60f 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-direct-message.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-direct-message.js@@ -7,13 +7,13 @@ export default class ChatDirectMessage {return new ChatDirectMessage(args);}- @tracked id;@tracked users = null;+ @tracked group = false;type = CHATABLE_TYPES.directMessageChannel;constructor(args = {}) {- this.id = args.id;+ this.group = args.group ?? false;this.users = this.#initUsers(args.users || []);}@@ -21,9 +21,9 @@ export default class ChatDirectMessage {return users.map((user) => {if (!user || user instanceof User) {return user;+ } else {+ return User.create(user);}-- return User.create(user);});}}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.jsindex bf1733e2032..8243321e2ed 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.js@@ -5,7 +5,7 @@ export default class ChatChannelInfoMembersRoute extends DiscourseRoute {@service router;afterModel(model) {- if (!model.isOpen || model.membershipsCount < 1) {+ if (!model.isOpen) {return this.router.replaceWith("chat.channel.info.settings");}}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-api.js b/plugins/chat/assets/javascripts/discourse/services/chat-api.jsindex 618700f001f..d38968844c8 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-api.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-api.js@@ -490,6 +490,18 @@ export default class ChatApi extends Service {return this.#getRequest(`/channels/${channelId}/summarize`, options);}+ /**+ * Add members to a channel.+ *+ * @param {number} channelId - The ID of the channel.+ * @param {Array<string>} usernames - The usernames of the users to add.+ */+ addMembersToChannel(channelId, usernames) {+ return this.#postRequest(`/channels/${channelId}/memberships`, {+ usernames,+ });+ }+get #basePath() {return "/chat/api";}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat.js b/plugins/chat/assets/javascripts/discourse/services/chat.jsindex 6d8c55ee38a..4ce30b11360 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat.js@@ -385,10 +385,10 @@ export default class Chat extends Service {// @param {array} usernames - The usernames to create or fetch the direct message// channel for. The current user will automatically be included in the channel// when it is created.- upsertDmChannelForUsernames(usernames) {+ upsertDmChannelForUsernames(usernames, name = null) {return ajax("/chat/api/direct-message-channels.json", {method: "POST",- data: { target_usernames: usernames.uniq() },+ data: { target_usernames: usernames.uniq(), name },}).then((response) => {const channel = this.chatChannelsManager.store(response.channel);diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-info.scss b/plugins/chat/assets/stylesheets/common/chat-channel-info.scssindex 3993019c0d6..74515e9db4c 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-info.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-info.scss@@ -1,8 +1,12 @@.chat-channel-info {display: flex;- flex-direction: column;height: 100%;padding: 1rem;+ flex-direction: column;++ .chat-message-creator__container {+ width: 100%;+ }&__nav {.nav-pills {@@ -12,6 +16,15 @@}}+.chat-channel-members__add-members {+ display: flex;+ gap: 1rem;++ .chat-message-creator-container {+ width: 100%;+ }+}+// Info header.chat-channel-info-header {display: flex;diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-members.scss b/plugins/chat/assets/stylesheets/common/chat-channel-members.scssindex 40a07573bce..70857126ce6 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-members.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-members.scss@@ -1,6 +1,6 @@.chat-channel-members {- width: 50%;- min-width: 320px;+ max-width: 500px;+ width: 100%;&__filter {margin-bottom: 1rem;@@ -10,18 +10,41 @@display: flex;margin: 0;flex-direction: column;- gap: 0.5rem;&-item {display: flex;- gap: 0.5rem;list-style: none;border-bottom: 1px solid var(--primary-low);- height: 42px;align-items: center;+ box-sizing: border-box;+ padding: 0.5rem;+ cursor: pointer;- &.-no-results {- box-sizing: border-box;+ .avatar {+ cursor: pointer;+ }++ &:hover {+ background: var(--primary-very-low);+ }++ &.-member {+ .chat-user-avatar {+ margin-right: 0.5rem;+ }+ }++ &.-add-member {+ color: var(--tertiary);+ cursor: pointer;++ .d-icon {+ background: var(--primary-low);+ color: var(--tertiary);+ padding: 5px;+ border-radius: 50%;+ margin-right: 0.5rem;+ }}&:last-child {diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-settings.scss b/plugins/chat/assets/stylesheets/common/chat-channel-settings.scssindex 86023946e05..49e25ad8c10 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-settings.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-settings.scss@@ -1,6 +1,5 @@.chat-channel-settings {- width: 50%;- min-width: 320px;+ width: 100%;.chat-channel-settings__slug {max-width: 250px;diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-title.scss b/plugins/chat/assets/stylesheets/common/chat-channel-title.scssindex a1c21cf4a70..f6a951e8446 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-title.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-title.scss@@ -74,11 +74,12 @@width: 22px;height: 22px;box-sizing: border-box;- text-align: center;+ justify-content: center;font-weight: 700;font-size: var(--font-down-1);align-items: center;padding: 0.25rem 0.5rem;+ color: var(--primary-high);}.chat-channel-title__category-badge {diff --git a/plugins/chat/assets/stylesheets/common/chat-form.scss b/plugins/chat/assets/stylesheets/common/chat-form.scssindex 4071798448a..cd4800d6332 100644--- a/plugins/chat/assets/stylesheets/common/chat-form.scss+++ b/plugins/chat/assets/stylesheets/common/chat-form.scss@@ -29,10 +29,8 @@}&-content {- background: var(--primary-very-low);gap: 1rem;display: flex;- padding: 1rem;flex-direction: column;}}diff --git a/plugins/chat/assets/stylesheets/common/chat-message-creator.scss b/plugins/chat/assets/stylesheets/common/chat-message-creator.scssindex 32625438d7f..fa82212b0f8 100644--- a/plugins/chat/assets/stylesheets/common/chat-message-creator.scss+++ b/plugins/chat/assets/stylesheets/common/chat-message-creator.scss@@ -1,333 +1,249 @@-@keyframes popIn {- 0% {- transform: scale(0.1);- opacity: 0;- }- 100% {- transform: scale(1);- opacity: 1;- }+.chat-message-creator__section {+ display: flex;+ width: 100%;+ padding-inline: 1rem 0.5rem;+ box-sizing: border-box;}-.chat-message-creator {+.chat-message-creator__add-members {display: flex;- align-items: center;- width: 100%;+ gap: 1rem;flex-direction: column;+}- --row-height: 36px;-- &__search-icon {- color: var(--primary-medium);+.chat-message-creator__participants-count {+ white-space: nowrap;+}- &-container {- display: flex;- align-items: center;- height: var(--row-height);- padding-inline: 0.25rem;- box-sizing: border-box;- }+.chat-message-creator__member {+ @media (prefers-reduced-motion: no-preference) {+ animation: popIn 0.1s ease-out;}+}- &__container {- display: flex;- align-items: center;- width: 100%;- box-sizing: border-box;+.chat-message-creator__member {+ padding: 0 0.25rem;+ border-radius: var(--border-radius);+ background: var(--primary-very-low);+ gap: 0.25rem;- > * {- box-sizing: border-box;- }+ //I think this class isnt working atm?+ &.-highlighted {+ border-color: var(--tertiary);}- &__row {- display: flex;- padding-inline: 0.25rem;- align-items: center;- border-radius: var(--d-border-radius);- height: var(--row-height);-- .unread-indicator {- background: var(--tertiary);- width: 8px;- height: 8px;- display: flex;- border-radius: 50%;- margin-left: 0.5rem;-- &.-urgent {- background: var(--success);- }- }-- .selection-indicator {- visibility: hidden;-- font-size: var(--font-down-2);- margin-left: auto;+ &:hover {+ .discourse-no-touch & {+ background: var(--primary-very-low);+ color: var(--primary);+ border-color: var(--tertiary);- &.-add {- color: var(--success);- }-- &.-remove {- color: var(--danger);+ .d-icon {+ color: var(--primary);}}+ }- .action-indicator {- display: none;- margin-left: auto;- white-space: nowrap;- font-size: var(--font-down-1);- color: var(--secondary-medium);- align-items: center;- padding-right: 0.25rem;-- kbd {- margin-left: 0.25rem;- }- }+ .d-icon {+ margin-left: 0.25rem;+ }+}- &.-active {- .action-indicator {- display: flex;- }- }+.chat-message-creator__add-members__close-btn {+ align-self: flex-start;+ margin-top: 10px;+}- .chat-channel-title__name {- margin-left: 0;- }+.chat-message-creator__add-members-header {+ display: flex;+ flex-grow: 1;+ gap: 0.5rem;- .chat-channel-title__avatar,- .chat-channel-title__category-badge,- .chat-user-avatar {- width: 28px;- height: 28px;- display: flex;- align-items: center;- justify-content: center;- }+ &-container {+ display: flex;+ }+}- .chat-channel-title {- &__users-count {- width: 24px;- height: 24px;- padding: 0;- justify-content: center;- }- }+.chat-message-creator__new-group-header {+ display: flex;+ align-items: center;+ flex-grow: 1;+ padding-inline: 1rem;- .chat-channel-title__name,- .chat-user-display-name {- @include ellipsis;- padding-left: 0.5rem;- }+ &-container {+ display: flex;+ flex-grow: 1;+ padding-bottom: 0.5rem;+ border-bottom: 1px solid var(--primary-low);+ }- &.-selected {- .selection-indicator {- visibility: visible;- }- }+ &__input {+ padding-inline: 0 !important;+ width: 100% !important;+ margin: 0 !important;+ border: 0 !important;+ outline: 0 !important;+ }+}- &.-disabled {- opacity: 0.25;- }+.chat-message-creator__new-group-footer {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-grow: 1;+ gap: 1rem;+ padding: 1rem 1rem 0;- &.-active {- cursor: pointer;+ &-container {+ display: flex;+ flex-grow: 1;+ border-top: 1px solid var(--primary-low);+ }+}- .chat-user-display-name {- color: var(--primary);- }- }+.chat-message-creator__participants-count {+ white-space: nowrap;+}- &.-user {- &.-disabled {- .chat-user-display-name__username.-first {- font-weight: normal;- }- }- .disabled-text {- margin-left: auto;- white-space: nowrap;- padding-left: 0.25rem;- }- }+.chat-message-creator__warning-max-members {+ padding-inline: 1rem;+}++.chat-message-creator__members {+ display: flex;+ align-items: center;+ flex-grow: 1;+ padding: 0.5rem;+ background: var(--primary-low);+ flex-wrap: wrap;+ gap: 0.5rem;+ border-radius: var(--border-radius);+ min-height: 50px;+ box-sizing: border-box;++ .d-icon-search {+ color: var(--primary-high);}- &__content {- box-sizing: border-box;+ &-container {display: flex;- flex-direction: column;- flex: 1;- width: 100%;-- &-container {- display: flex;- flex: 1;- width: 100%;- box-sizing: border-box;- padding: 0.25rem 1rem 1rem 1rem;- }+ flex-grow: 1;}- &__close-btn {- margin-bottom: auto;- margin-left: 0.25rem;- height: 44px;- width: 44px;- min-width: 44px;- border-radius: var(--d-button-border-radius);+ &-input {+ background: none !important;+ margin: 0 !important;+ border: 0 !important;+ outline: 0 !important;+ min-width: 200px;+ flex-grow: 1;+ padding-inline: 0 !important;}+}- &__selection {- flex: 1 1 auto;- flex-direction: row;- flex-wrap: wrap;- display: flex;- background: var(--secondary-very-high);- border-radius: var(--d-input-border-radius);- padding: 3px;- position: relative;-- &-container {- display: flex;- box-sizing: border-box;- width: 100%;- align-items: center;- padding: 1rem;- box-sizing: border-box;- }+.chat-message-creator__members-count {+ white-space: nowrap;+ color: var(--primary-medium);+ &.-reached-limit {+ color: var(--danger);}+}- &__input[type="text"],- &__input[type="text"]:focus {- background: none;- appearance: none;- outline: none;- border: 0;- resize: none;- box-sizing: border-box;- min-width: 150px;- height: var(--row-height);- flex: 1;- width: auto;- padding: 0 5px;- margin: 0;- box-sizing: border-box;- display: inline-flex;- }+.chat-message-creator__add-members-footer {+ display: flex;+ flex-grow: 1;+ justify-content: flex-end;+ padding-top: 1rem;+ border-top: 1px solid var(--primary-low);- &__loader {- &-container {- display: flex;- align-items: center;- padding-inline: 0.5rem;- height: var(--row-height);- }+ &-container {+ display: flex;}+}- &__selection-item {- align-items: center;+.chat-message-creator__list {+ list-style: none;+ margin: 0;+ gap: 0.25rem;+ display: flex;+ flex-direction: column;++ &-item {box-sizing: border-box;cursor: pointer;- display: inline-flex;- background: var(--primary-very-low);- border-radius: var(--border-radius);- border: 1px solid var(--primary-low);- height: calc(var(--row-height) - 6);- padding-inline: 0.25rem;- margin: 3px;- @media (prefers-reduced-motion: no-preference) {- animation: popIn 0.1s ease-out;- }-- .d-icon-times {- margin-top: 4px;- }-- .chat-channel-title__name {- padding-inline: 0.25rem;- }+ padding: 0.5rem 1rem;+ display: flex;+ align-items: center;- &__username {- padding-inline: 0.25rem;+ .d-icon-users {+ padding: 2px 2px;+ box-sizing: border-box;+ color: var(--tertiary);+ background: var(--primary-low);+ border-radius: 100%;+ width: 18px;+ height: 18px;}- &.-active {- border-color: var(--secondary-high);+ .btn {+ padding: 0;}- &-remove-btn {- padding-inline: 0.25rem;- font-size: var(--font-down-2);- display: flex;- align-items: center;+ &.-highlighted {+ background: var(--tertiary-very-low);}+ }+}- &:hover {- border-color: var(--primary-medium);+.chat-message-creator__chatable-user {+ display: flex;+ align-items: center;- .chat-message-creator__selection__remove-btn {- color: var(--danger);- }- }+ .chat-user-display-name {+ padding-left: 0.5rem;}+}- &__no-items {- &-container {- display: flex;- align-items: center;- height: var(--row-height);- margin-left: 0.5rem;- }- }+.chat-message-creator__search-input {+ display: flex;+ align-items: center;+ background: var(--secondary-very-high);+ width: 100%;+ box-sizing: border-box;+ height: 42px;+ padding: 0 0.5rem;- &__footer {+ &-container {display: flex;- align-items: flex-end;- justify-content: space-between;- flex-direction: row;- width: 100%;-- &-container {- margin-top: auto;- display: flex;- width: 100%;- padding: 1rem;- box-sizing: border-box;- border-top: 1px solid var(--primary-low);- }+ flex-grow: 1;}- &__open-dm-btn {- display: flex;- margin-left: auto;- @include ellipsis;- padding: 0.5rem;- max-width: 40%;+ &__search-icon {+ background: none !important;+ color: var(--primary-medium);+ }- .d-button-label {- @include ellipsis;- }+ &__input {+ width: 100% !important;}- &__shortcut {- display: flex;- align-items: center;- font-size: var(--font-down-2);- color: var(--secondary-medium);- flex: 3;-- span {- margin-left: 0.25rem;- display: inline-flex;- line-height: 17px;- }+ &__input,+ &__input:focus {+ margin: 0 !important;+ border: 0 !important;+ appearance: none !important;+ outline: none !important;+ background: none !important;+ }+}- kbd {- margin-inline: 0.25rem;- }+@keyframes popIn {+ 0% {+ transform: scale(0.1);+ opacity: 0;+ }+ 100% {+ transform: scale(1);+ opacity: 1;}}diff --git a/plugins/chat/assets/stylesheets/common/chat-modal-new-message.scss b/plugins/chat/assets/stylesheets/common/chat-modal-new-message.scssindex da33bf6813e..18c982e2c1b 100644--- a/plugins/chat/assets/stylesheets/common/chat-modal-new-message.scss+++ b/plugins/chat/assets/stylesheets/common/chat-modal-new-message.scss@@ -31,4 +31,16 @@margin: 10px auto auto auto;}}++ .chat-message-creator__search,+ .chat-message-creator__new-group {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding-block: 1rem;+ }++ .chat-message-creator__add-members-header-container {+ padding-inline: 1rem;+ }}diff --git a/plugins/chat/assets/stylesheets/common/dc-filter-input.scss b/plugins/chat/assets/stylesheets/common/dc-filter-input.scssindex 711cff93f3d..549fd8540d3 100644--- a/plugins/chat/assets/stylesheets/common/dc-filter-input.scss+++ b/plugins/chat/assets/stylesheets/common/dc-filter-input.scss@@ -18,6 +18,7 @@}.d-icon {+ color: var(--primary-medium);margin: 0 0.5rem;}}diff --git a/plugins/chat/assets/stylesheets/desktop/chat-channel-info.scss b/plugins/chat/assets/stylesheets/desktop/chat-channel-info.scssnew file mode 100644index 00000000000..62eb938bc95--- /dev/null+++ b/plugins/chat/assets/stylesheets/desktop/chat-channel-info.scss@@ -0,0 +1,3 @@+.chat-channel-info {+ max-width: 500px;+}diff --git a/plugins/chat/assets/stylesheets/desktop/chat-message-creator.scss b/plugins/chat/assets/stylesheets/desktop/chat-message-creator.scssindex c69516aaab6..5c6ce534b5c 100644--- a/plugins/chat/assets/stylesheets/desktop/chat-message-creator.scss+++ b/plugins/chat/assets/stylesheets/desktop/chat-message-creator.scss@@ -1,7 +1,7 @@-.chat-message-creator {- &__row {- &.-active {- background: var(--tertiary-very-low);- }- }-}+// .chat-message-creator {+// &__row {+// &.-active {+// background: var(--tertiary-very-low);+// }+// }+// }diff --git a/plugins/chat/assets/stylesheets/desktop/index.scss b/plugins/chat/assets/stylesheets/desktop/index.scssindex 859b736a081..dcc9e2f6c84 100644--- a/plugins/chat/assets/stylesheets/desktop/index.scss+++ b/plugins/chat/assets/stylesheets/desktop/index.scss@@ -5,6 +5,7 @@@import "chat-index-full-page";@import "chat-message-actions";@import "chat-message";+@import "chat-channel-info";@import "chat-message-creator";@import "chat-message-thread-indicator";@import "sidebar-extensions";diff --git a/plugins/chat/assets/stylesheets/mobile/chat-channel-settings.scss b/plugins/chat/assets/stylesheets/mobile/chat-channel-settings.scssindex 871658cf968..3ebc181bc34 100644--- a/plugins/chat/assets/stylesheets/mobile/chat-channel-settings.scss+++ b/plugins/chat/assets/stylesheets/mobile/chat-channel-settings.scss@@ -1,3 +1,3 @@.chat-channel-settings {- width: 100%;+ min-width: 320px;}diff --git a/plugins/chat/assets/stylesheets/mobile/chat-form.scss b/plugins/chat/assets/stylesheets/mobile/chat-form.scssnew file mode 100644index 00000000000..df7bbc1a424--- /dev/null+++ b/plugins/chat/assets/stylesheets/mobile/chat-form.scss@@ -0,0 +1,6 @@+.chat-form__section {+ &-content {+ background: var(--primary-very-low);+ padding: 1rem;+ }+}diff --git a/plugins/chat/assets/stylesheets/mobile/chat-message-creator.scss b/plugins/chat/assets/stylesheets/mobile/chat-message-creator.scssindex 5f9b7ad18f8..e69de29bb2d 100644--- a/plugins/chat/assets/stylesheets/mobile/chat-message-creator.scss+++ b/plugins/chat/assets/stylesheets/mobile/chat-message-creator.scss@@ -1,40 +0,0 @@-.chat-message-creator {- &__open-dm-btn {- width: 100%;- max-width: 100%;- }-- &__row {- padding-block: 0.5rem;- }-- .chat-channel-title__name,- .chat-user-display-name {- font-size: var(--font-up-1);- }-- .chat-channel-title__category-badge {- display: flex;- align-items: center;- justify-content: center;- padding-inline: 2px;- width: 24px;- height: 24px;-- svg:not(.chat-channel-title__restricted-category-icon) {- height: inherit;- width: inherit;- }- }-- .chat-user-avatar {- &__container {- padding: 0;- }- img {- width: 28px;- height: 28px;- box-sizing: border-box;- }- }-}diff --git a/plugins/chat/assets/stylesheets/mobile/chat-modal-new-message.scss b/plugins/chat/assets/stylesheets/mobile/chat-modal-new-message.scssnew file mode 100644index 00000000000..08b5130f850--- /dev/null+++ b/plugins/chat/assets/stylesheets/mobile/chat-modal-new-message.scss@@ -0,0 +1,9 @@+.chat-modal-new-message {+ .modal-inner-container {+ max-height: 100vh;+ }++ .modal-body {+ max-height: inherit;+ }+}diff --git a/plugins/chat/assets/stylesheets/mobile/index.scss b/plugins/chat/assets/stylesheets/mobile/index.scssindex 7e3065003e4..ab100b50e15 100644--- a/plugins/chat/assets/stylesheets/mobile/index.scss+++ b/plugins/chat/assets/stylesheets/mobile/index.scss@@ -16,3 +16,5 @@@import "chat-channel-row";@import "chat-channel-members";@import "chat-channel-settings";+@import "chat-form";+@import "chat-modal-new-message";diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex f2ec9c8124d..21e71a05f34 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -310,6 +310,7 @@ en:members_view:filter_placeholder: Find members+ add_member: Add Memberabout_view:associated_topic: Linked topic@@ -333,9 +334,15 @@ en:default_search_placeholder: "#a-channel, @somebody or anything"default_channel_search_placeholder: "#a-channel"default_user_search_placeholder: "@somebody"- user_search_placeholder: "...add more users"+ user_search_placeholder: "...add more members"disabled_user: "has disabled chat"no_items: "No items"+ create_group_placeholder: "Group chat name (optional)"+ participants_counter: "%{selection_count}/%{max} participants"+ new_group_chat: "New group chat"+ filter: "Filter"+ cant_add_more_members: "Maximum number of members reached"+ create_new_group_chat: "Create group chat"channel_edit_name_slug_modal:title: Edit channel@@ -350,10 +357,15 @@ en:description: Tell people what this channel is all aboutdirect_message_creator:+ add_to_channel: "Add to channel"title: New Messageprefix: "To:"no_results: No resultsselected_user_title: "Deselect %{username}"+ group_name: "Group chat name (optional)"+ members_counter:+ one: "%{count}/%{max} member"+ other: "%{count}/%{max} members"channel:no_memberships: This channel has no membersdiff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.ymlindex 3570773734c..b2ab31734af 100644--- a/plugins/chat/config/locales/server.en.yml+++ b/plugins/chat/config/locales/server.en.yml@@ -53,6 +53,7 @@ en:chat:deleted_chat_username: deletederrors:+ users_cant_be_added_to_channel: "Users can't be added to this channel."channel_exists_for_category: "A channel already exists for this category and name"channel_new_message_disallowed:archived: "The channel is archived, no new messages can be sent"@@ -130,6 +131,9 @@ en:transcript_title: "Transcript of previous messages in %{channel_name}"transcript_body: "To give you more context, we included a transcript of the previous messages in this conversation (up to ten):\n\n%{transcript}"channel:+ users_invited_to_channel:+ one: "%{invited_users} has been invited by %{inviting_user}."+ other: "%{invited_users} have been invited by %{inviting_user}."archive:first_post_raw: "This topic is an archive of the [%{channel_name}](%{channel_url}) chat channel."messages_moved:diff --git a/plugins/chat/config/routes.rb b/plugins/chat/config/routes.rbindex 60a862f3bc6..d8c9cfaf1fe 100644--- a/plugins/chat/config/routes.rb+++ b/plugins/chat/config/routes.rb@@ -18,6 +18,7 @@ Chat::Engine.routes.draw dopost "/channels/:channel_id/invites" => "channels_invites#create"post "/channels/:channel_id/archives" => "channels_archives#create"get "/channels/:channel_id/memberships" => "channels_memberships#index"+ post "/channels/:channel_id/memberships" => "channels_memberships#create"delete "/channels/:channel_id/memberships/me" => "channels_current_user_membership#destroy"post "/channels/:channel_id/memberships/me" => "channels_current_user_membership#create"put "/channels/:channel_id/notifications-settings/me" =>diff --git a/plugins/chat/db/migrate/20231006160650_add_group_field_to_direct_message_channels.rb b/plugins/chat/db/migrate/20231006160650_add_group_field_to_direct_message_channels.rbnew file mode 100644index 00000000000..6c48c2841e9--- /dev/null+++ b/plugins/chat/db/migrate/20231006160650_add_group_field_to_direct_message_channels.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddGroupFieldToDirectMessageChannels < ActiveRecord::Migration[7.0]+ def change+ add_column :direct_message_channels, :group, :boolean, default: false, null: false+ end+enddiff --git a/plugins/chat/db/migrate/20231006161051_set_multiusers_direct_message_channels_as_group.rb b/plugins/chat/db/migrate/20231006161051_set_multiusers_direct_message_channels_as_group.rbnew file mode 100644index 00000000000..585c503fc0f--- /dev/null+++ b/plugins/chat/db/migrate/20231006161051_set_multiusers_direct_message_channels_as_group.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true++class SetMultiusersDirectMessageChannelsAsGroup < ActiveRecord::Migration[7.0]+ def change+ execute <<-SQL+ UPDATE direct_message_channels+ SET "group" = true+ WHERE id IN (+ SELECT direct_message_channel_id+ FROM direct_message_users+ GROUP BY direct_message_channel_id+ HAVING COUNT(user_id) > 2+ );+ SQL+ end+enddiff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rbindex b5f55dfd24f..e0fd9986356 100644--- a/plugins/chat/lib/chat/channel_fetcher.rb+++ b/plugins/chat/lib/chat/channel_fetcher.rb@@ -88,7 +88,17 @@ module Chatallowed_channel_ids = generate_allowed_channel_ids_sql(guardian, exclude_dm_channels: true)- channels = Chat::Channel.includes(:last_message, chatable: [:topic_only_relative_url])+ channels =+ Chat::Channel.includes(+ :last_message,+ chatable: %i[+ topic_only_relative_url+ uploaded_background+ uploaded_background_dark+ uploaded_logo+ uploaded_logo_dark+ ],+ )channels = channels.includes(:chat_channel_archive) if options[:include_archives]channels =@@ -175,18 +185,6 @@ module Chatenddef self.secured_direct_message_channels_search(user_id, guardian, options = {})- query =- Chat::Channel.strict_loading.includes(- last_message: [:uploads],- chatable: [{ direct_message_users: [user: :user_option] }, :users],- )- query = query.includes(chatable: [{ users: :user_status }]) if SiteSetting.enable_user_status- query = query.joins(:user_chat_channel_memberships)- query =- query.joins(- "LEFT JOIN chat_messages last_message ON last_message.id = chat_channels.last_message_id",- )-scoped_channels =Chat::Channel.joins(@@ -197,36 +195,48 @@ module Chat).where("direct_message_users.user_id = :user_id", user_id: user_id)- if options[:user_ids]- scoped_channels =- scoped_channels.where(- "EXISTS (- SELECT 1- FROM direct_message_channels AS dmc- INNER JOIN direct_message_users AS dmu ON dmu.direct_message_channel_id = dmc.id- WHERE dmc.id = chat_channels.chatable_id AND dmu.user_id IN (:user_ids)- )",- user_ids: options[:user_ids],+ query =+ Chat::Channel+ .strict_loading+ .where(id: scoped_channels)+ .includes(+ last_message: [:uploads],+ chatable: [{ direct_message_users: [user: :user_option] }, :users],+ )+ .joins(+ "LEFT JOIN chat_messages last_message ON last_message.id = chat_channels.last_message_id",+ )++ query = query.includes(chatable: [{ users: :user_status }]) if SiteSetting.enable_user_status++ if options[:filter]+ if options[:match_filter_on_starts_with]+ filter_sql = "#{options[:filter].downcase}%"+ else+ filter_sql = "%#{options[:filter].downcase}%"+ end++ query =+ query.joins(user_chat_channel_memberships: :user).where(+ "chat_channels.name ILIKE :filter OR chat_channels.slug ILIKE :filter OR users.username ILIKE :filter",+ filter: filter_sql,)endif options.key?(:following)+ following_params = { user_id: user_id }+ following_params[:following] = options[:following] if options[:following].present?query =- query.where(- user_chat_channel_memberships: {- user_id: user_id,- following: options[:following],- },+ query.joins(:user_chat_channel_memberships).where(+ user_chat_channel_memberships: following_params,)- else- query = query.where(user_chat_channel_memberships: { user_id: user_id })endquery =- query- .where(chatable_type: Chat::Channel.direct_channel_chatable_types)- .where(chat_channels: { id: scoped_channels })- .order("last_message.created_at DESC NULLS LAST")+ query.order("last_message.created_at DESC NULLS LAST").group(+ "chat_channels.id",+ "last_message.id",+ )channels = query.to_apreload_fields =diff --git a/plugins/chat/lib/chat/guardian_extensions.rb b/plugins/chat/lib/chat/guardian_extensions.rbindex 14116678535..faeefa96739 100644--- a/plugins/chat/lib/chat/guardian_extensions.rb+++ b/plugins/chat/lib/chat/guardian_extensions.rb@@ -38,8 +38,12 @@ module Chat# Channel status intentionally has no bearing on whether the channel# name and description can be edited.- def can_edit_chat_channel?- is_staff?+ def can_edit_chat_channel?(channel)+ if channel.direct_message_channel?+ channel.chatable.group && (is_staff? || channel.chatable.user_can_access?(@user))+ elsif channel.category_channel?+ is_staff?+ endend# The only part of the thread that can be changed is the titlediff --git a/plugins/chat/lib/chat/user_extension.rb b/plugins/chat/lib/chat/user_extension.rbindex d5c7e14c926..366b5b26243 100644--- a/plugins/chat/lib/chat/user_extension.rb+++ b/plugins/chat/lib/chat/user_extension.rb@@ -13,6 +13,8 @@ module Chatdependent: :destroyhas_many :chat_message_reactions, class_name: "Chat::MessageReaction", dependent: :destroyhas_many :chat_mentions, class_name: "Chat::Mention"+ has_many :direct_message_users, class_name: "Chat::DirectMessageUser"+ has_many :direct_messages, through: :direct_message_users, class_name: "Chat::DirectMessage"endendenddiff --git a/plugins/chat/spec/fabricators/chat_fabricator.rb b/plugins/chat/spec/fabricators/chat_fabricator.rbindex b3c73a7f91c..3548100418f 100644--- a/plugins/chat/spec/fabricators/chat_fabricator.rb+++ b/plugins/chat/spec/fabricators/chat_fabricator.rb@@ -33,9 +33,13 @@ Fabricator(:private_category_channel, from: :category_channel) doendFabricator(:direct_message_channel, from: :chat_channel) do- transient :users, following: true, with_membership: true+ transient :users, :group, following: true, with_membership: truechatable do |attrs|- Fabricate(:direct_message, users: attrs[:users] || [Fabricate(:user), Fabricate(:user)])+ Fabricate(+ :direct_message,+ users: attrs[:users] || [Fabricate(:user), Fabricate(:user)],+ group: attrs[:group] || false,+ )endstatus { :open }name nildiff --git a/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb b/plugins/chat/spec/lib/chat/guardian_extensions_spec.rbindex 8f922c98400..5ccaadb4b55 100644--- a/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb+++ b/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb@@ -46,9 +46,39 @@ RSpec.describe Chat::GuardianExtensions doexpect(staff_guardian.can_create_chat_channel?).to eq(true)end- it "only staff can edit chat channels" do- expect(guardian.can_edit_chat_channel?).to eq(false)- expect(staff_guardian.can_edit_chat_channel?).to eq(true)+ context "when category channel" do+ it "allows staff to edit chat channels" do+ expect(guardian.can_edit_chat_channel?(channel)).to eq(false)+ expect(staff_guardian.can_edit_chat_channel?(channel)).to eq(true)+ end+ end++ context "when direct message channel" do+ context "when member of channel" do+ context "when group" do+ before do+ dm_channel.chatable.update!(group: true)+ add_users_to_channel(user, dm_channel)+ end++ it "allows to edit the channel" do+ expect(user.guardian.can_edit_chat_channel?(dm_channel)).to eq(true)+ end+ end++ context "when not group" do+ it "doesn’t allow to edit the channel" do+ Chat::DirectMessageUser.create(user: user, direct_message: dm_channel.chatable)+ expect(user.guardian.can_edit_chat_channel?(dm_channel)).to eq(false)+ end+ end+ end++ context "when not member of channel" do+ it "doesn’t allow to edit the channel" do+ expect(user.guardian.can_edit_chat_channel?(dm_channel)).to eq(false)+ end+ endendit "only staff can close chat channels" dodiff --git a/plugins/chat/spec/plugin_helper.rb b/plugins/chat/spec/plugin_helper.rbindex 7925d56f746..df600159485 100644--- a/plugins/chat/spec/plugin_helper.rb+++ b/plugins/chat/spec/plugin_helper.rb@@ -102,6 +102,17 @@ module ChatSpecHelpersservice_failed!(result) if result.failure?resultend++ def add_users_to_channel(users, channel, user: Discourse.system_user)+ result =+ ::Chat::AddUsersToChannel.call(+ guardian: user.guardian,+ channel_id: channel.id,+ usernames: Array(users).map(&:username),+ )+ service_failed!(result) if result.failure?+ result+ endendRSpec.configure do |config|diff --git a/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rbnew file mode 100644index 00000000000..f4f30ec3f13--- /dev/null+++ b/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rb@@ -0,0 +1,55 @@+# frozen_string_literal: true++RSpec.describe Chat::Api::ChannelsMembershipsController do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) do+ Fabricate(:direct_message_channel, group: true, users: [current_user, Fabricate(:user)])+ end++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ channel_1.add(current_user)+ sign_in(current_user)+ end++ describe "#create" do+ describe "success" do+ it "works" do+ add_users_to_channel(current_user, channel_1)+ post "/chat/api/channels/#{channel_1.id}/memberships",+ params: {+ usernames: [Fabricate(:user).username],+ }++ expect(response.status).to eq(200)+ end+ end++ context "when users can't be added" do+ before { channel_1.chatable.update(group: false) }++ it "returns a 422" do+ post "/chat/api/channels/#{channel_1.id}/memberships",+ params: {+ usernames: [Fabricate(:user).username],+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"].first).to eq(+ I18n.t("chat.errors.users_cant_be_added_to_channel"),+ )+ end+ end++ context "when channel is not found" do+ before { channel_1.chatable.update!(group: false) }++ it "returns a 404" do+ get "/chat/api/channels/-999/messages", params: { usernames: [Fabricate(:user).username] }++ expect(response.status).to eq(404)+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/chat/api/chatables_controller_spec.rb b/plugins/chat/spec/requests/chat/api/chatables_controller_spec.rbindex 8892ef4b680..4b68d9a7935 100644--- a/plugins/chat/spec/requests/chat/api/chatables_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/chatables_controller_spec.rb@@ -14,13 +14,16 @@ RSpec.describe Chat::Api::ChatablesController dodescribe "without chat permissions" doit "errors errors for anon" doget "/chat/api/chatables"+expect(response.status).to eq(403)endit "errors when user cannot chat" doSiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff]sign_in(current_user)+get "/chat/api/chatables"+expect(response.status).to eq(403)endend@@ -28,9 +31,11 @@ RSpec.describe Chat::Api::ChatablesController dodescribe "with chat permissions" dofab!(:channel_1) { Fabricate(:chat_channel) }- before { sign_in(current_user) }+ before { channel_1.add(current_user) }it "returns results" do+ sign_in(current_user)+get "/chat/api/chatables", params: { term: channel_1.name }expect(response.status).to eq(200)diff --git a/plugins/chat/spec/requests/chat/api/direct_messages_controller_spec.rb b/plugins/chat/spec/requests/chat/api/direct_messages_controller_spec.rbindex b3458d47c23..52606de7cb8 100644--- a/plugins/chat/spec/requests/chat/api/direct_messages_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/direct_messages_controller_spec.rb@@ -23,7 +23,10 @@ RSpec.describe Chat::Api::DirectMessagesController dodescribe "#create" dobefore { Group.refresh_automatic_groups! }- shared_examples "creating dms" do+ describe "dm with one other user" do+ let(:usernames) { user1.username }+ let(:direct_message_user_ids) { [current_user.id, user1.id] }+it "creates a new dm channel with username(s) provided" doexpect {post "/chat/api/direct-message-channels.json", params: { target_usernames: [usernames] }@@ -35,31 +38,55 @@ RSpec.describe Chat::Api::DirectMessagesController doit "returns existing dm channel if one exists for username(s)" docreate_dm_channel(direct_message_user_ids)+expect {post "/chat/api/direct-message-channels.json", params: { target_usernames: [usernames] }}.not_to change { Chat::DirectMessage.count }endend- describe "dm with one other user" do- let(:usernames) { user1.username }- let(:direct_message_user_ids) { [current_user.id, user1.id] }-- include_examples "creating dms"- end-describe "dm with myself" dolet(:usernames) { [current_user.username] }let(:direct_message_user_ids) { [current_user.id] }- include_examples "creating dms"+ it "creates a new dm channel with username(s) provided" do+ expect {+ post "/chat/api/direct-message-channels.json", params: { target_usernames: [usernames] }+ }.to change { Chat::DirectMessage.count }.by(1)+ expect(Chat::DirectMessage.last.direct_message_users.map(&:user_id)).to match_array(+ direct_message_user_ids,+ )+ end++ it "returns existing dm channel if one exists for username(s)" do+ create_dm_channel(direct_message_user_ids)++ expect {+ post "/chat/api/direct-message-channels.json", params: { target_usernames: [usernames] }+ }.not_to change { Chat::DirectMessage.count }+ endenddescribe "dm with two other users" dolet(:usernames) { [user1, user2, user3].map(&:username) }let(:direct_message_user_ids) { [current_user.id, user1.id, user2.id, user3.id] }- include_examples "creating dms"+ it "creates a new dm channel with username(s) provided" do+ expect {+ post "/chat/api/direct-message-channels.json", params: { target_usernames: [usernames] }+ }.to change { Chat::DirectMessage.count }.by(1)+ expect(Chat::DirectMessage.last.direct_message_users.map(&:user_id)).to match_array(+ direct_message_user_ids,+ )+ end++ it "createsa new dm channel" do+ create_dm_channel(direct_message_user_ids)++ expect {+ post "/chat/api/direct-message-channels.json", params: { target_usernames: [usernames] }+ }.to change { Chat::DirectMessage.count }.by(1)+ endendit "creates Chat::UserChatChannelMembership records" dodiff --git a/plugins/chat/spec/requests/chat_controller_spec.rb b/plugins/chat/spec/requests/chat_controller_spec.rbindex 2a7f17c205a..2246c1b83b1 100644--- a/plugins/chat/spec/requests/chat_controller_spec.rb+++ b/plugins/chat/spec/requests/chat_controller_spec.rb@@ -611,6 +611,7 @@ RSpec.describe Chat::ChatController doexpect(response.status).to eq(403)Chat::DirectMessageUser.create(user: user, direct_message: dm_channel.chatable)+expect {post "/chat/drafts.json", params: { chat_channel_id: dm_channel.id, data: "{}" }}.to change { Chat::Draft.count }.by(1)diff --git a/plugins/chat/spec/services/chat/add_users_to_channel_spec.rb b/plugins/chat/spec/services/chat/add_users_to_channel_spec.rbnew file mode 100644index 00000000000..3dab885c27c--- /dev/null+++ b/plugins/chat/spec/services/chat/add_users_to_channel_spec.rb@@ -0,0 +1,104 @@+# frozen_string_literal: true++RSpec.describe Chat::AddUsersToChannel do+ describe described_class::Contract, type: :model do+ subject(:contract) { described_class.new(usernames: [], channel_id: nil) }++ it { is_expected.to validate_presence_of :channel_id }+ it { is_expected.to validate_presence_of :usernames }+ end++ describe ".call" do+ subject(:result) { described_class.call(params) }++ fab!(:current_user) { Fabricate(:user) }+ fab!(:users) { Fabricate.times(5, :user) }+ fab!(:direct_message) { Fabricate(:direct_message, users: [current_user], group: true) }+ fab!(:channel) { Fabricate(:direct_message_channel, chatable: direct_message) }++ let(:guardian) { Guardian.new(current_user) }+ let(:params) do+ { guardian: guardian, channel_id: channel.id, usernames: users.map(&:username) }+ end++ context "when all steps pass" do+ before { channel.add(current_user) }++ it "fetches users to add" do+ expect(result.users.map(&:username)).to contain_exactly(*users.map(&:username))+ end++ it "doesn't include existing direct message users" do+ Chat::DirectMessageUser.create!(user: users.first, direct_message: direct_message)++ expect(result.users.map(&:username)).to contain_exactly(*users[1..-1].map(&:username))+ end++ it "creates memberships" do+ expect { result }.to change { channel.user_chat_channel_memberships.count }.by(+ users.count + 1,+ ) # +1 for system user creating the notice message and added to the channel+ end++ it "creates direct messages users" do+ expect { result }.to change { ::Chat::DirectMessageUser.count }.by(users.count + 1) # +1 for system user creating the notice message and added to the channel+ end++ it "updates users count" do+ expect { result }.to change { channel.reload.user_count }.by(users.count + 1) # +1 for system user creating the notice message and added to the channel+ end++ it "creates a chat message to show added users" do+ added_users = result.users++ channel.chat_messages.last.tap do |message|+ expect(message.message).to eq(+ I18n.t(+ "chat.channel.users_invited_to_channel",+ invited_users: added_users.map { |u| "@#{u.username}" }.join(", "),+ inviting_user: "@#{current_user.username}",+ count: added_users.count,+ ),+ )+ expect(message.user).to eq(Discourse.system_user)+ end+ end+ end++ context "when there are too many usernames" do+ before { SiteSetting.chat_max_direct_message_users = 2 }++ it { is_expected.to fail_a_contract }+ end++ context "when channel is not found" do+ before { params[:channel_id] = -999 }++ it { is_expected.to fail_to_find_a_model(:channel) }+ end++ context "when user don't have access to channel" do+ fab!(:channel) { Fabricate(:private_category_channel, group: Fabricate(:group)) }++ it { is_expected.to fail_a_policy(:can_add_users_to_channel) }+ end++ context "when channel is not a group" do+ before { direct_message.update!(group: false) }++ it { is_expected.to fail_a_policy(:can_add_users_to_channel) }+ end++ context "when channel is not a direct message channel" do+ fab!(:channel) { Fabricate(:chat_channel) }++ it { is_expected.to fail_a_policy(:can_add_users_to_channel) }+ end++ context "when user is not admin and not a member of the channel" do+ fab!(:current_user) { Fabricate(:user) }++ it { is_expected.to fail_a_policy(:can_add_users_to_channel) }+ end+ end+enddiff --git a/plugins/chat/spec/services/chat/create_direct_message_channel_spec.rb b/plugins/chat/spec/services/chat/create_direct_message_channel_spec.rbindex e90ec4c7e5f..0082d20d460 100644--- a/plugins/chat/spec/services/chat/create_direct_message_channel_spec.rb+++ b/plugins/chat/spec/services/chat/create_direct_message_channel_spec.rb@@ -26,7 +26,9 @@ RSpec.describe Chat::CreateDirectMessageChannel dofab!(:user_2) { Fabricate(:user, username: "elaine") }let(:guardian) { Guardian.new(current_user) }- let(:params) { { guardian: guardian, target_usernames: %w[lechuck elaine] } }+ let(:target_usernames) { [user_1.username, user_2.username] }+ let(:name) { "" }+ let(:params) { { guardian: guardian, target_usernames: target_usernames, name: name } }before { Group.refresh_automatic_groups! }@@ -35,6 +37,10 @@ RSpec.describe Chat::CreateDirectMessageChannel doexpect(result).to be_a_successend+ it "updates user count" do+ expect(result.channel.user_count).to eq(3) # current user + user_1 + user_2+ end+it "creates the channel" doexpect { result }.to change { Chat::Channel.count }expect(result.channel.chatable).to have_attributes(@@ -58,16 +64,59 @@ RSpec.describe Chat::CreateDirectMessageChannel doendcontext "when there is an existing direct message channel for the target users" do- before { described_class.call(params) }+ context "when a name has been given" do+ let(:target_usernames) { [user_1.username] }+ let(:name) { "Monkey Island" }++ it "creates a second channel" do+ described_class.call(params)- it "does not create a channel" do- expect { result }.to not_change { Chat::Channel.count }.and not_change {- Chat::DirectMessage.count- }+ expect { result }.to change { Chat::Channel.count }.and change {+ Chat::DirectMessage.count+ }+ endend- it "does not double-insert the channel memberships" do- expect { result }.not_to change { Chat::UserChatChannelMembership.count }+ context "when the channel has more than one user" do+ let(:target_usernames) { [user_1.username, user_2.username] }++ it "creates a second channel" do+ described_class.call(params)++ expect { result }.to change { Chat::Channel.count }.and change {+ Chat::DirectMessage.count+ }+ end+ end++ context "when the channel has one user and no name" do+ let(:target_usernames) { [user_1.username] }++ it "reuses the existing channel" do+ existing_channel = described_class.call(params).channel++ expect(result.channel.id).to eq(existing_channel.id)+ end+ end++ context "when theres also a group channel with same users" do+ let(:target_usernames) { [user_1.username] }++ it "returns the non group existing channel" do+ group_channel = described_class.call(params.merge(name: "cats")).channel+ channel = described_class.call(params).channel++ expect(result.channel.id).to_not eq(group_channel.id)+ expect(result.channel.id).to eq(channel.id)+ end+ end+ end++ context "when a name is given" do+ let(:name) { "Monkey Island" }++ it "sets it as the channel name" do+ expect(result.channel.name).to eq(name)endendenddiff --git a/plugins/chat/spec/services/chat/search_chatable_spec.rb b/plugins/chat/spec/services/chat/search_chatable_spec.rbindex 831032a7f58..ba6619198d8 100644--- a/plugins/chat/spec/services/chat/search_chatable_spec.rb+++ b/plugins/chat/spec/services/chat/search_chatable_spec.rb@@ -7,20 +7,34 @@ RSpec.describe Chat::SearchChatable dofab!(:current_user) { Fabricate(:user, username: "bob-user") }fab!(:sam) { Fabricate(:user, username: "sam-user") }fab!(:charlie) { Fabricate(:user, username: "charlie-user") }+ fab!(:alain) { Fabricate(:user, username: "alain-user") }fab!(:channel_1) { Fabricate(:chat_channel, name: "bob-channel") }fab!(:channel_2) { Fabricate(:direct_message_channel, users: [current_user, sam]) }fab!(:channel_3) { Fabricate(:direct_message_channel, users: [current_user, sam, charlie]) }fab!(:channel_4) { Fabricate(:direct_message_channel, users: [sam, charlie]) }+ fab!(:channel_5) { Fabricate(:direct_message_channel, users: [current_user, charlie, alain]) }let(:guardian) { Guardian.new(current_user) }- let(:params) { { guardian: guardian, term: term } }let(:term) { "" }+ let(:include_users) { false }+ let(:include_category_channels) { false }+ let(:include_direct_message_channels) { false }+ let(:excluded_memberships_channel_id) { nil }+ let(:params) do+ {+ guardian: guardian,+ term: term,+ include_users: include_users,+ include_category_channels: include_category_channels,+ include_direct_message_channels: include_direct_message_channels,+ excluded_memberships_channel_id: excluded_memberships_channel_id,+ }+ endbefore doSiteSetting.direct_message_enabled_groups = Group::AUTO_GROUPS[:everyone]# simpler user search without having to worry about user search dataSiteSetting.enable_names = false- return unless guardian.can_create_direct_message?channel_1.add(current_user)end@@ -29,118 +43,144 @@ RSpec.describe Chat::SearchChatable doexpect(result).to be_a_successend- it "returns chatables" do+ it "cleans the term" do+ params[:term] = "#bob"+ expect(result.term).to eq("bob")++ params[:term] = "@bob"+ expect(result.term).to eq("bob")+ end++ it "fetches user memberships" doexpect(result.memberships).to contain_exactly(channel_1.membership_for(current_user),channel_2.membership_for(current_user),channel_3.membership_for(current_user),+ channel_5.membership_for(current_user),)- expect(result.category_channels).to contain_exactly(channel_1)- expect(result.direct_message_channels).to contain_exactly(channel_2, channel_3)- expect(result.users).to include(current_user, sam)end- it "doesn’t return direct message of other users" do- expect(result.direct_message_channels).to_not include(channel_4)- end+ context "when including users" do+ let(:include_users) { true }- context "with private channel" do- fab!(:private_channel_1) { Fabricate(:private_category_channel, name: "private") }- let(:term) { "#private" }+ it "fetches users" do+ expect(result.users).to include(current_user, sam, charlie, alain)+ end++ it "can filter usernames" do+ params[:term] = "sam"- it "doesn’t return category channels you can't access" do- expect(result.category_channels).to_not include(private_channel_1)+ expect(result.users).to contain_exactly(sam)end- end- context "when public channels are disabled" do- it "does not return category channels" do- SiteSetting.enable_public_channels = false+ it "can filter users with a membership to a specific channel" do+ params[:excluded_memberships_channel_id] = channel_1.id- expect(described_class.call(params).category_channels).to be_blank+ expect(result.users).to_not include(current_user)endend- end- context "when term is prefixed with #" do- let(:term) { "#" }+ context "when not including users" do+ let(:include_users) { false }- it "doesn’t return users" do- expect(result.users).to be_blank- expect(result.category_channels).to contain_exactly(channel_1)- expect(result.direct_message_channels).to contain_exactly(channel_2, channel_3)+ it "doesn’t fetch users" do+ expect(result.users).to be_nil+ endend- end- context "when term is prefixed with @" do- let(:term) { "@" }+ context "when including category channels" do+ let(:include_category_channels) { true }- it "doesn’t return channels" do- expect(result.users).to include(current_user, sam)- expect(result.category_channels).to be_blank- expect(result.direct_message_channels).to be_blank- end- end+ it "fetches category channels" do+ expect(result.category_channels).to include(channel_1)+ end- context "when filtering" do- context "with full match" do- let(:term) { "bob" }+ it "can filter titles" do+ searched_channel = Fabricate(:chat_channel, name: "beaver")+ params[:term] = "beaver"- it "returns matching channels" do- expect(result.users).to contain_exactly(current_user)- expect(result.category_channels).to contain_exactly(channel_1)- expect(result.direct_message_channels).to contain_exactly(channel_2, channel_3)+ expect(result.category_channels).to contain_exactly(searched_channel)end- end- context "with partial match" do- let(:term) { "cha" }+ it "can filter slugs" do+ searched_channel = Fabricate(:chat_channel, name: "beaver", slug: "something")+ params[:term] = "something"++ expect(result.category_channels).to contain_exactly(searched_channel)+ end++ it "doesn’t include category channels you can't access" do+ Fabricate(:private_category_channel)- it "returns matching channels" do- expect(result.users).to contain_exactly(charlie)expect(result.category_channels).to contain_exactly(channel_1)- expect(result.direct_message_channels).to contain_exactly(channel_3)endend- end- context "when filtering with non existing term" do- let(:term) { "xxxxxxxxxx" }+ context "when not including category channels" do+ let(:include_category_channels) { false }- it "returns matching channels" do- expect(result.users).to be_blank- expect(result.category_channels).to be_blank- expect(result.direct_message_channels).to be_blank+ it "doesn’t fetch category channels" do+ expect(result.category_channels).to be_nil+ endend- end- context "when filtering with @prefix" do- let(:term) { "@bob" }+ context "when including direct message channels" do+ let(:include_direct_message_channels) { true }- it "returns matching channels" do- expect(result.users).to contain_exactly(current_user)- expect(result.category_channels).to be_blank- expect(result.direct_message_channels).to be_blank- end- end+ it "fetches direct message channels" do+ expect(result.direct_message_channels).to contain_exactly(channel_2, channel_3, channel_5)+ end- context "when filtering with #prefix" do- let(:term) { "#bob" }+ it "doesn’t fetches inaccessible direct message channels" do+ expect(result.direct_message_channels).to_not include(channel_4)+ end- it "returns matching channels" do- expect(result.users).to be_blank- expect(result.category_channels).to contain_exactly(channel_1)- expect(result.direct_message_channels).to contain_exactly(channel_2, channel_3)- end- end+ it "can filter by title" do+ searched_channel =+ Fabricate(:direct_message_channel, users: [current_user, sam, charlie], name: "koala")+ params[:term] = "koala"++ expect(result.direct_message_channels).to contain_exactly(searched_channel)+ end- context "when current user can't created direct messages" do- let(:term) { "@bob" }+ it "can filter by slug" do+ searched_channel =+ Fabricate(+ :direct_message_channel,+ users: [current_user, sam, charlie],+ slug: "capybara",+ )+ params[:term] = "capybara"- before { SiteSetting.direct_message_enabled_groups = Group::AUTO_GROUPS[:staff] }+ expect(result.direct_message_channels).to contain_exactly(searched_channel)+ end++ it "can filter by users" do+ cedric = Fabricate(:user, username: "cedric")+ searched_channel =+ Fabricate(:direct_message_channel, users: [current_user, cedric], slug: "capybara")+ searched_channel.add(cedric)+ params[:term] = "cedric"++ expect(result.direct_message_channels).to contain_exactly(searched_channel)+ end++ context "when also includes users" do+ let(:include_users) { true }- it "doesn’t return users" do- expect(result.users).to be_blank+ it "excludes one to one direct message channels with user" do+ expect(result.users).to include(sam)+ expect(result.direct_message_channels).to contain_exactly(channel_3, channel_5)+ end+ end+ end++ context "when not including direct message channels" do+ let(:include_direct_message_channels) { false }++ it "doesn’t fetch direct message channels" do+ expect(result.direct_message_channels).to be_nil+ endendendenddiff --git a/plugins/chat/spec/services/chat/update_channel_spec.rb b/plugins/chat/spec/services/chat/update_channel_spec.rbindex e2445925e7a..84e4fb89e0f 100644--- a/plugins/chat/spec/services/chat/update_channel_spec.rb+++ b/plugins/chat/spec/services/chat/update_channel_spec.rb@@ -23,12 +23,6 @@ RSpec.describe Chat::UpdateChannel doit { is_expected.to fail_a_policy(:check_channel_permission) }end- context "when the user tries to edit a DM channel" do- fab!(:channel) { Fabricate(:direct_message_channel, users: [current_user, Fabricate(:user)]) }-- it { is_expected.to fail_a_policy(:no_direct_message_channel) }- end-context "when channel is a category one" docontext "when a valid user provides valid params" dolet(:message) dodiff --git a/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json b/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.jsonindex 4111fe5fa22..b19f6d7bd8e 100644--- a/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json+++ b/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json@@ -15,7 +15,6 @@"muted": { "type": "boolean" },"desktop_notification_level": { "type": "string" },"mobile_notification_level": { "type": "string" },- "last_viewed_at": { "type": "string" },"following": { "type": "boolean" },"user": {"type": ["object", "null"],@@ -24,7 +23,9 @@"id": { "type": "number" },"name": { "type": "string" },"avatar_template": { "type": "string" },- "username": { "type": "string" }+ "username": { "type": "string" },+ "can_chat": { "type": "boolean" },+ "has_chat_enabled": { "type": "boolean" }}},"last_viewed_at": { "type": "datetime" }diff --git a/plugins/chat/spec/system/channel_members_page_spec.rb b/plugins/chat/spec/system/channel_members_page_spec.rbindex c3b411aabb3..8a2c02c9fa4 100644--- a/plugins/chat/spec/system/channel_members_page_spec.rb+++ b/plugins/chat/spec/system/channel_members_page_spec.rb@@ -26,7 +26,7 @@ RSpec.describe "Channel - Info - Members page", type: :system doit "redirects to settings page" dochat_page.visit_channel_members(channel_1)- expect(page).to have_current_path("/chat/c/#{channel_1.slug}/#{channel_1.id}/info/settings")+ expect(page).to have_current_path("/chat/c/#{channel_1.slug}/#{channel_1.id}/info/members")endend@@ -64,4 +64,42 @@ RSpec.describe "Channel - Info - Members page", type: :system doendendend++ context "when category channel" do+ it "doesn’t allow to add members" do+ chat_page.visit_channel_members(channel_1)++ expect(chat_page).to have_no_css(".chat-channel-members__list-item.-add-member")+ end+ end++ context "when category channel" do+ fab!(:channel_1) do+ Fabricate(+ :direct_message_channel,+ slug: "test-channel",+ users: [current_user, Fabricate(:user), Fabricate(:user)],+ group: true,+ )+ end++ it "allows to add members" do+ new_user = Fabricate(:user)+ chat_page.visit_channel_members(channel_1)+ chat_page.find(".chat-channel-members__list-item.-add-member").click+ chat_page.find(".chat-message-creator__members-input").fill_in(with: new_user.username)+ chat_page.find(".chat-message-creator__list-item").click+ chat_page.find(".add-to-channel").click++ expect(chat_page).to have_current_path("/chat/c/#{channel_1.slug}/#{channel_1.id}")+ expect(chat_page).to have_content(+ I18n.t(+ "chat.channel.users_invited_to_channel",+ invited_users: "@#{new_user.username}",+ inviting_user: "@#{current_user.username}",+ count: 1,+ ),+ )+ end+ endenddiff --git a/plugins/chat/spec/system/channel_settings_page_spec.rb b/plugins/chat/spec/system/channel_settings_page_spec.rbindex 1e6631d69b9..b81907dfdbf 100644--- a/plugins/chat/spec/system/channel_settings_page_spec.rb+++ b/plugins/chat/spec/system/channel_settings_page_spec.rb@@ -159,6 +159,8 @@ RSpec.describe "Channel - Info - Settings page", type: :system docontext "as staff" dofab!(:current_user) { Fabricate(:admin) }+ before { channel_1.add(current_user) }+it "can edit name" dochat_page.visit_channel_settings(channel_1)@@ -170,7 +172,7 @@ RSpec.describe "Channel - Info - Settings page", type: :system doedit_modal.fill_and_save_name(name)- expect(channel_settings_page).to have_name(name)+ expect(page).to have_content(name)endit "can edit description" do@@ -191,6 +193,7 @@ RSpec.describe "Channel - Info - Settings page", type: :system doit "can edit slug" dochat_page.visit_channel_settings(channel_1)+edit_modal = channel_settings_page.open_edit_modalslug = "gonzo-slug"@@ -199,7 +202,7 @@ RSpec.describe "Channel - Info - Settings page", type: :system doedit_modal.fill_and_save_slug(slug)- expect(channel_settings_page).to have_slug(slug)+ expect(page).to have_current_path("/chat/c/gonzo-slug/#{channel_1.id}")endit "can clear the slug to use the autogenerated version based on the name" do@@ -213,7 +216,7 @@ RSpec.describe "Channel - Info - Settings page", type: :system doedit_modal.wait_for_auto_generated_slugedit_modal.save_changes- expect(channel_settings_page).to have_slug("test-channel")+ expect(page).to have_current_path("/chat/c/test-channel/#{channel_1.id}")endit "shows settings page" dodiff --git a/plugins/chat/spec/system/chat_message_creator_spec.rb b/plugins/chat/spec/system/chat_message_creator_spec.rbnew file mode 100644index 00000000000..3d7838704b0--- /dev/null+++ b/plugins/chat/spec/system/chat_message_creator_spec.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++RSpec.describe "Flag message", type: :system do+ let(:chat_page) { PageObjects::Pages::Chat.new }++ fab!(:current_user) { Fabricate(:user) }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ it "lists preloaded channels by default" do+ channel_1 = Fabricate(:chat_channel)+ channel_1.add(current_user)++ visit("/")+ chat_page.open_new_message++ expect(chat_page.message_creator).to be_listing(channel_1)+ end++ it "can filter channels" do+ channel_1 = Fabricate(:chat_channel)+ channel_2 = Fabricate(:chat_channel)+ channel_1.add(current_user)+ channel_2.add(current_user)++ visit("/")+ chat_page.open_new_message+ chat_page.message_creator.filter(channel_2.title)++ expect(chat_page.message_creator).to be_listing(channel_2)+ expect(chat_page.message_creator).to be_not_listing(channel_1)+ end++ it "can filter users" do+ user_1 = Fabricate(:user)+ user_2 = Fabricate(:user)++ visit("/")+ chat_page.open_new_message+ chat_page.message_creator.filter(user_2.username)++ expect(chat_page.message_creator).to be_listing(user_2)+ expect(chat_page.message_creator).to be_not_listing(user_1)+ end++ it "can filter direct message channels" do+ channel_1 = Fabricate(:direct_message_channel, users: [current_user])+ channel_2 =+ Fabricate(+ :direct_message_channel,+ users: [current_user, Fabricate(:user), Fabricate(:user, username: "user_1")],+ )++ visit("/")+ chat_page.open_new_message+ chat_page.message_creator.filter("user_1")++ expect(chat_page.message_creator).to be_listing(channel_2)+ expect(chat_page.message_creator).to be_not_listing(channel_1)+ end++ it "can create a new group message" do+ user_1 = Fabricate(:user)+ user_2 = Fabricate(:user)++ visit("/")+ chat_page.prefers_full_page+ chat_page.open_new_message+ chat_page.find("#new-group-chat").click+ chat_page.find(".chat-message-creator__new-group-header__input").fill_in(with: "cats")+ chat_page.find(".chat-message-creator__members-input").fill_in(with: user_1.username)+ chat_page.message_creator.click_row(user_1)+ chat_page.find(".chat-message-creator__members-input").fill_in(with: user_2.username)+ chat_page.message_creator.click_row(user_2)+ page.find(".create-chat-group").click++ expect(page).to have_current_path(%r{/chat/c/cats/\d+})+ end+enddiff --git a/plugins/chat/spec/system/drawer_spec.rb b/plugins/chat/spec/system/drawer_spec.rbindex 3f7b68a8250..d98862fea1e 100644--- a/plugins/chat/spec/system/drawer_spec.rb+++ b/plugins/chat/spec/system/drawer_spec.rb@@ -24,7 +24,7 @@ RSpec.describe "Drawer", type: :system dodrawer_page.open_channel(channel)page.find(".chat-channel-title").click- expect(page).to have_current_path("/chat/c/#{channel.slug}/#{channel.id}/info/settings")+ expect(page).to have_current_path("/chat/c/#{channel.slug}/#{channel.id}/info/members")endendenddiff --git a/plugins/chat/spec/system/new_message_spec.rb b/plugins/chat/spec/system/new_message_spec.rbdeleted file mode 100644index f201c33ed14..00000000000--- a/plugins/chat/spec/system/new_message_spec.rb+++ /dev/null@@ -1,470 +0,0 @@-# frozen_string_literal: true--RSpec.describe "New message", type: :system do- fab!(:current_user) { Fabricate(:admin) }-- let(:chat_page) { PageObjects::Pages::Chat.new }-- before do- # simpler user search without having to worry about user search data- SiteSetting.enable_names = false-- chat_system_bootstrap- sign_in(current_user)- end-- it "cmd + k opens new message" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator).to be_opened- end-- context "when public channels are disabled" do- fab!(:channel_1) { Fabricate(:chat_channel) }-- before do- SiteSetting.enable_public_channels = false- channel_1.add(current_user)- end-- it "doesn’t list public channels" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator).to be_not_listing(channel_1)- end-- it "has a correct placeholder" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator.input["placeholder"]).to eq(- I18n.t("js.chat.new_message_modal.default_user_search_placeholder"),- )- end- end-- context "when selecting more users than allowed" do- fab!(:current_user) { Fabricate(:trust_level_1) }- fab!(:user_1) { Fabricate(:user) }- fab!(:user_2) { Fabricate(:user) }-- before { SiteSetting.chat_max_direct_message_users = 1 }-- it "shows an error" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.filter(user_1.username)- chat_page.message_creator.shift_click_row(user_1)- chat_page.message_creator.filter(user_2.username)- chat_page.message_creator.shift_click_row(user_2)- chat_page.message_creator.click_cta-- expect(page).to have_content(- I18n.t(- "chat.errors.over_chat_max_direct_message_users",- count: SiteSetting.chat_max_direct_message_users,- ),- )- end- end-- context "when public channels are disabled and user can't create direct message" do- fab!(:current_user) { Fabricate(:user) }-- before do- SiteSetting.enable_public_channels = false- SiteSetting.direct_message_enabled_groups = Group::AUTO_GROUPS[:staff]- end-- it "doesn’t list public channels" do- visit("/")- chat_page.open_new_message(ensure_open: false)-- expect(chat_page.message_creator).to be_closed- end- end-- context "when the content is not filtered" do- fab!(:channel_1) { Fabricate(:chat_channel) }- fab!(:channel_2) { Fabricate(:chat_channel) }- fab!(:user_1) { Fabricate(:user) }- fab!(:user_2) { Fabricate(:user) }- fab!(:direct_message_channel_1) do- Fabricate(:direct_message_channel, users: [current_user, user_1])- end- fab!(:direct_message_channel_2) { Fabricate(:direct_message_channel, users: [user_1, user_2]) }-- before { channel_1.add(current_user) }-- it "lists channels the user is following" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator).to be_listing(channel_1)- expect(chat_page.message_creator).to be_not_listing(channel_2)- expect(chat_page.message_creator).to be_not_listing(direct_message_channel_2)- expect(chat_page.message_creator).to be_listing(user_1)- expect(chat_page.message_creator).to be_not_listing(user_2)- end- end-- context "with no selection" do- context "with unread state" do- fab!(:user_1) { Fabricate(:user) }- fab!(:channel_1) { Fabricate(:chat_channel) }- fab!(:channel_2) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }-- before do- channel_1.add(user_1)- channel_1.add(current_user)- Fabricate(:chat_message, chat_channel: channel_1, user: user_1)- Fabricate(:chat_message, chat_channel: channel_2, user: user_1)- end-- it "shows the correct state" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator).to have_unread_row(channel_1, urgent: false)- expect(chat_page.message_creator).to have_unread_row(user_1, urgent: true)- end- end-- context "when clicking a row" do- context "when the row is a channel" do- fab!(:channel_1) { Fabricate(:chat_channel) }-- before { channel_1.add(current_user) }-- it "opens the channel" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.click_row(channel_1)-- expect(chat_page).to have_drawer(channel_id: channel_1.id)- end- end-- context "when the row is a user" do- fab!(:user_1) { Fabricate(:user) }- fab!(:channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }-- it "opens the channel" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.click_row(user_1)-- expect(chat_page).to have_drawer(channel_id: channel_1.id)- end- end- end-- context "when shift clicking a row" do- context "when the row is a channel" do- fab!(:channel_1) { Fabricate(:chat_channel) }-- before { channel_1.add(current_user) }-- it "opens the channel" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.shift_click_row(channel_1)-- expect(chat_page).to have_drawer(channel_id: channel_1.id)- end- end-- context "when the row is a user" do- fab!(:user_1) { Fabricate(:user) }- fab!(:channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }-- it "adds the user" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.shift_click_row(user_1)-- expect(chat_page.message_creator).to be_selecting(user_1)- end- end- end-- context "when pressing enter" do- context "when the row is a channel" do- fab!(:channel_1) { Fabricate(:chat_channel) }-- before { channel_1.add(current_user) }-- it "opens the channel" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.click_row(channel_1)-- expect(chat_page).to have_drawer(channel_id: channel_1.id)- end- end-- context "when the row is a user" do- fab!(:user_1) { Fabricate(:user) }- fab!(:channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }-- it "opens the channel" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.click_row(user_1)-- expect(chat_page).to have_drawer(channel_id: channel_1.id)- end- end- end-- context "when pressing shift+enter" do- context "when the row is a channel" do- fab!(:channel_1) { Fabricate(:chat_channel) }-- before { channel_1.add(current_user) }-- it "opens the channel" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.shift_enter_shortcut-- expect(chat_page).to have_drawer(channel_id: channel_1.id)- end- end-- context "when the row is a user" do- fab!(:user_1) { Fabricate(:user) }- fab!(:channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }-- it "adds the user" do- visit("/")- chat_page.open_new_message- chat_page.message_creator.shift_enter_shortcut-- expect(chat_page.message_creator).to be_selecting(user_1)- end- end- end-- context "when navigating content with arrows" do- fab!(:channel_1) { Fabricate(:chat_channel, name: "channela") }- fab!(:channel_2) { Fabricate(:chat_channel, name: "channelb") }-- before do- channel_1.add(current_user)- channel_2.add(current_user)- end-- it "changes active content" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator).to be_listing(channel_1, active: true)-- chat_page.message_creator.arrow_down_shortcut-- expect(chat_page.message_creator).to be_listing(channel_2, active: true)-- chat_page.message_creator.arrow_down_shortcut-- expect(chat_page.message_creator).to be_listing(channel_1, active: true)-- chat_page.message_creator.arrow_up_shortcut-- expect(chat_page.message_creator).to be_listing(channel_2, active: true)- end- end-- context "with disabled content" do- fab!(:user_1) { Fabricate(:user) }- fab!(:channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }-- before { user_1.user_option.update!(chat_enabled: false) }-- it "doesn’t make the content active" do- visit("/")- chat_page.open_new_message-- expect(chat_page.message_creator).to be_listing(user_1, inactive: true, disabled: true)- end- end- end-- context "when filtering" do- fab!(:channel_1) { Fabricate(:chat_channel, name: "bob-channel") }- fab!(:user_1) { Fabricate(:user, username: "bob-user") }- fab!(:user_2) { Fabricate(:user) }- fab!(:channel_2) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }- fab!(:channel_3) { Fabricate(:direct_message_channel, users: [current_user, user_1, user_2]) }-- before { channel_1.add(current_user) }-- context "when query is the name of the category" do- fab!(:category) { Fabricate(:category, name: "dev") }- fab!(:channel_1) { Fabricate(:category_channel, chatable: category, name: "something dev") }- fab!(:channel_2) { Fabricate(:category_channel, chatable: category, name: "something else") }-- it "favors the channel name" do- visit("/")- chat_page.open_new_message-- chat_page.message_creator.filter("dev")-- expect(chat_page.message_creator).to be_listing(channel_1)- expect(chat_page.message_creator).to be_not_listing(channel_2)- end- end-- context "with no prefix" do- it "lists all matching content" do- visit("/")- chat_page.open_new_message-- chat_page.message_creator.filter("bob")-- expect(chat_page.message_creator).to be_listing(channel_1)- expect(chat_page.message_creator).to be_not_listing(channel_2)- expect(chat_page.message_creator).to be_listing(channel_3)- expect(chat_page.message_creator).to be_listing(user_1)- expect(chat_page.message_creator).to be_not_listing(user_2)- end- end-- context "with channel prefix" do- it "lists matching channel" do- visit("/")- chat_page.open_new_message-- chat_page.message_creator.filter("#bob")-- expect(chat_page.message_creator).to be_listing(channel_1)- expect(chat_page.message_creator).to be_not_listing(channel_2)- expect(chat_page.message_creator).to be_listing(channel_3)- expect(chat_page.message_creator).to be_not_listing(user_1)- expect(chat_page.message_creator).to be_not_listing(user_2)- end- end-- context "with user prefix" do- it "lists matching users" do- visit("/")- chat_page.open_new_message-- chat_page.message_creator.filter("@bob")-- expect(chat_page.message_creator).to be_not_listing(channel_1)- expect(chat_page.message_creator).to be_not_listing(channel_2)- expect(chat_page.message_creator).to be_not_listing(channel_3)- expect(chat_page.message_creator).to be_listing(user_1)- expect(chat_page.message_creator).to be_not_listing(user_2)- end- end- end-- context "with selection" do- fab!(:channel_1) { Fabricate(:chat_channel, name: "bob-channel") }- fab!(:user_1) { Fabricate(:user, username: "bob-user") }- fab!(:user_2) { Fabricate(:user, username: "bobby-user") }- fab!(:user_3) { Fabricate(:user, username: "sam-user") }- fab!(:channel_2) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }- fab!(:channel_3) { Fabricate(:direct_message_channel, users: [current_user, user_2]) }-- before do- channel_1.add(current_user)- visit("/")- chat_page.open_new_message- chat_page.message_creator.shift_click_row(user_1)- end-- context "when pressing enter" do- it "opens the channel" do- chat_page.message_creator.enter_shortcut-- expect(chat_page).to have_drawer(channel_id: channel_2.id)- end- end-- context "when clicking cta" do- it "opens the channel" do- chat_page.message_creator.click_cta-- expect(chat_page).to have_drawer(channel_id: channel_2.id)- end- end-- context "when filtering" do- it "shows only matching users regardless of prefix" do- chat_page.message_creator.filter("#bob")-- expect(chat_page.message_creator).to be_listing(user_1)- expect(chat_page.message_creator).to be_listing(user_2)- expect(chat_page.message_creator).to be_not_listing(user_3)- expect(chat_page.message_creator).to be_not_listing(channel_1)- expect(chat_page.message_creator).to be_not_listing(channel_2)- expect(chat_page.message_creator).to be_not_listing(channel_3)- end-- it "shows selected user as selected in content" do- chat_page.message_creator.filter("@bob")-- expect(chat_page.message_creator).to be_listing(user_1, selected: true)- expect(chat_page.message_creator).to be_listing(user_2, selected: false)- end- end-- context "when clicking another user" do- it "adds it to the selection" do- chat_page.message_creator.filter("@bob")- chat_page.message_creator.click_row(user_2)-- expect(chat_page.message_creator).to be_selecting(user_1)- expect(chat_page.message_creator).to be_selecting(user_2)- end- end-- context "when pressing backspace" do- it "removes it" do- chat_page.message_creator.backspace_shortcut-- expect(chat_page.message_creator).to be_selecting(user_1, active: true)-- chat_page.message_creator.backspace_shortcut-- expect(chat_page.message_creator).to be_not_selecting(user_1)- end- end-- context "when navigating selection with arrow left/right" do- it "changes active item" do- chat_page.message_creator.filter("@bob")- chat_page.message_creator.click_row(user_2)-- chat_page.message_creator.arrow_left_shortcut-- expect(chat_page.message_creator).to be_selecting(user_2, active: true)-- chat_page.message_creator.arrow_left_shortcut-- expect(chat_page.message_creator).to be_selecting(user_1, active: true)-- chat_page.message_creator.arrow_left_shortcut-- expect(chat_page.message_creator).to be_selecting(user_2, active: true)-- chat_page.message_creator.arrow_right_shortcut-- expect(chat_page.message_creator).to be_selecting(user_1, active: true)- end- end-- context "when clicking selection" do- it "removes it" do- chat_page.message_creator.click_item(user_1)-- expect(chat_page.message_creator).to be_not_selecting(user_1)- end- end- end-enddiff --git a/plugins/chat/spec/system/page_objects/chat/components/message_creator.rb b/plugins/chat/spec/system/page_objects/chat/components/message_creator.rbindex d6e8c692eb9..f874da4cccb 100644--- a/plugins/chat/spec/system/page_objects/chat/components/message_creator.rb+++ b/plugins/chat/spec/system/page_objects/chat/components/message_creator.rb@@ -13,7 +13,7 @@ module PageObjectsenddef input- component.find(".chat-message-creator__input")+ component.find(".chat-message-creator__search-input__input")enddef filter(query = "")@@ -104,7 +104,7 @@ module PageObjectsenddef build_row_selector(chatable, **args)- selector = ".chat-message-creator__row"+ selector = ".chat-message-creator__list-item"selector += content_selector(**args)selector += chatable_selector(chatable, **args)selector@@ -116,9 +116,9 @@ module PageObjectsselector = ".-selected" if args[:selected]selector = ":not(.-disabled)" if args[:enabled]if args[:active]- selector += ".-active"+ selector += ".-highlighted"elsif args[:inactive]- selector += ":not(.-active)"+ selector += ":not(.-highlighted)"endselectorend@@ -126,14 +126,11 @@ module PageObjectsdef chatable_selector(chatable, **args)selector = ""if chatable.try(:category_channel?)- selector += ".-channel"- selector += "[data-id='c-#{chatable.id}']"+ selector += "[data-identifier='c-#{chatable.id}']"elsif chatable.try(:direct_message_channel?)- selector += ".-channel"- selector += "[data-id='c-#{chatable.id}']"+ selector += "[data-identifier='c-#{chatable.id}']"else- selector += ".-user"- selector += "[data-id='u-#{chatable.id}']"+ selector += "[data-identifier='u-#{chatable.id}']"endselectorenddiff --git a/plugins/chat/spec/system/user_status/sidebar_spec.rb b/plugins/chat/spec/system/user_status/sidebar_spec.rbindex 7b210d04b18..355de88140c 100644--- a/plugins/chat/spec/system/user_status/sidebar_spec.rb+++ b/plugins/chat/spec/system/user_status/sidebar_spec.rb@@ -16,8 +16,6 @@ RSpec.describe "User status | sidebar", type: :system doendit "shows user status" do- Jobs.run_immediately!-visit("/")expect(find(".user-status-message .emoji")["alt"]).to eq("heart")@@ -26,8 +24,6 @@ RSpec.describe "User status | sidebar", type: :system docontext "when changing status" doit "updates status" do- Jobs.run_immediately!-visit("/")current_user.set_status!("offline", "tooth")@@ -38,8 +34,6 @@ RSpec.describe "User status | sidebar", type: :system docontext "when removing status" doit "removes status" do- Jobs.run_immediately!-visit("/")current_user.clear_status!diff --git a/plugins/chat/test/javascripts/components/chat-channel-title-test.js b/plugins/chat/test/javascripts/components/chat-channel-title-test.jsindex fc8630390b2..004b59aaf31 100644--- a/plugins/chat/test/javascripts/components/chat-channel-title-test.js+++ b/plugins/chat/test/javascripts/components/chat-channel-title-test.js@@ -10,9 +10,7 @@ module("Discourse Chat | Component | chat-channel-title", function (hooks) {setupRenderingTest(hooks);test("category channel", async function (assert) {- this.channel = fabricators.channel({- chatable_type: CHATABLE_TYPES.categoryChannel,- });+ this.channel = fabricators.channel();await render(hbs`<ChatChannelTitle @channel={{this.channel}} />`);@@ -39,8 +37,7 @@ module("Discourse Chat | Component | chat-channel-title", function (hooks) {test("category channel - read restricted", async function (assert) {this.channel = fabricators.channel({- chatable_type: CHATABLE_TYPES.categoryChannel,- chatable: { read_restricted: true },+ chatable: fabricators.category({ read_restricted: true }),});await render(hbs`<ChatChannelTitle @channel={{this.channel}} />`);@@ -50,8 +47,7 @@ module("Discourse Chat | Component | chat-channel-title", function (hooks) {test("category channel - not read restricted", async function (assert) {this.channel = fabricators.channel({- chatable_type: CHATABLE_TYPES.categoryChannel,- chatable: { read_restricted: false },+ chatable: fabricators.category({ read_restricted: false }),});await render(hbs`<ChatChannelTitle @channel={{this.channel}} />`);@@ -70,10 +66,7 @@ module("Discourse Chat | Component | chat-channel-title", function (hooks) {const user = this.channel.chatable.users[0];- assert.true(- exists(`.chat-user-avatar__container .avatar[title="${user.username}"]`)- );-+ assert.true(exists(`.chat-user-avatar .avatar[title="${user.username}"]`));assert.strictEqual(query(".chat-channel-title__name").innerText.trim(),user.username@@ -81,20 +74,15 @@ module("Discourse Chat | Component | chat-channel-title", function (hooks) {});test("direct message channel - multiple users", async function (assert) {- const channel = fabricators.directMessageChannel();-- channel.chatable.users.push({- id: 2,- username: "joffrey",- name: null,- avatar_template: "/letter_avatar_proxy/v3/letter/t/31188e/{size}.png",+ this.channel = fabricators.directMessageChannel({+ users: [fabricators.user(), fabricators.user(), fabricators.user()],});-- this.channel = channel;+ this.channel.chatable.group = true;await render(hbs`<ChatChannelTitle @channel={{this.channel}} />`);const users = this.channel.chatable.users;+assert.strictEqual(parseInt(query(".chat-channel-title__users-count").innerText.trim(), 10),users.lengthdiff --git a/plugins/chat/test/javascripts/components/chat-composer-placeholder-test.js b/plugins/chat/test/javascripts/components/chat-composer-placeholder-test.jsindex d383127b742..a5d1d83ea26 100644--- a/plugins/chat/test/javascripts/components/chat-composer-placeholder-test.js+++ b/plugins/chat/test/javascripts/components/chat-composer-placeholder-test.js@@ -36,6 +36,7 @@ module(this.channel = ChatChannel.create({chatable_type: "DirectMessage",chatable: {+ group: true,users: [{ name: "Tomtom" },{ name: "Steaky" },diff --git a/plugins/chat/test/javascripts/components/chat-user-info-test.js b/plugins/chat/test/javascripts/components/chat-user-info-test.jsindex f63c599b84e..26e06e5fab7 100644--- a/plugins/chat/test/javascripts/components/chat-user-info-test.js+++ b/plugins/chat/test/javascripts/components/chat-user-info-test.js@@ -11,14 +11,7 @@ module("Discourse Chat | Component | chat-user-info", function (hooks) {await render(hbs`<ChatUserInfo @user={{this.user}} />`);- assert- .dom(`a[data-user-card=${this.user.username}] div.chat-user-avatar`)- .exists();-- assert- .dom(- `a[data-user-card=${this.user.username}] span.chat-user-display-name`- )- .includesText(this.user.username);+ assert.dom().containsText(this.user.username);+ assert.dom().containsText(this.user.name);});});