A platform for community discussion. Free, open, simple.
FEATURE: Ability to star chat channels (#36142)
Keegan George0e0e716e0de1
diff --git a/plugins/chat/app/controllers/chat/api/channels_current_user_membership_controller.rb b/plugins/chat/app/controllers/chat/api/channels_current_user_membership_controller.rbindex 5f80112a537..9ca5d3cd215 100644--- a/plugins/chat/app/controllers/chat/api/channels_current_user_membership_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channels_current_user_membership_controller.rb@@ -11,6 +11,21 @@ class Chat::Api::ChannelsCurrentUserMembershipController < Chat::Api::ChannelsCo)end+ def update+ Chat::UpdateUserChannelMembership.call(service_params) do+ on_success do |membership:|+ render_serialized(membership, Chat::UserChannelMembershipSerializer, root: "membership")+ end+ on_model_not_found(:channel) { raise Discourse::NotFound }+ on_model_not_found(:membership) { raise Discourse::NotFound }+ on_failed_policy(:can_access_channel) { raise Discourse::InvalidAccess }+ on_failed_contract do |contract|+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ end+ end+def destroyChat::LeaveChannel.call(service_params) doon_success { render(json: success_json) }diff --git a/plugins/chat/app/models/chat/user_chat_channel_membership.rb b/plugins/chat/app/models/chat/user_chat_channel_membership.rbindex 6075e679b7f..736d4439f73 100644--- a/plugins/chat/app/models/chat/user_chat_channel_membership.rb+++ b/plugins/chat/app/models/chat/user_chat_channel_membership.rb@@ -25,20 +25,22 @@ end# Table name: user_chat_channel_memberships## id :bigint not null, primary key-# user_id :integer not null-# chat_channel_id :bigint not null-# last_read_message_id :bigint# following :boolean default(FALSE), not null+# join_mode :integer default("manual"), not null+# last_viewed_at :datetime not null# muted :boolean default(FALSE), not null+# notification_level :integer default("mention"), not null+# starred :boolean default(FALSE), not null# created_at :datetime not null# updated_at :datetime not null+# chat_channel_id :bigint not null+# last_read_message_id :bigint# last_unread_mention_when_emailed_id :bigint-# join_mode :integer default("manual"), not null-# last_viewed_at :datetime not null-# notification_level :integer default("mention"), not null+# user_id :integer not null## Indexes#-# user_chat_channel_memberships_index (user_id,chat_channel_id,notification_level,following)-# user_chat_channel_unique_memberships (user_id,chat_channel_id) UNIQUE+# index_user_chat_channel_memberships_on_user_id_and_starred (user_id,starred)+# user_chat_channel_memberships_index (user_id,chat_channel_id,notification_level,following)+# user_chat_channel_unique_memberships (user_id,chat_channel_id) UNIQUE#diff --git a/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb b/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rbindex 20f22b7226c..44dd45882ed 100644--- a/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb+++ b/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb@@ -7,6 +7,19 @@ module Chat:notification_level,:chat_channel_id,:last_read_message_id,- :last_viewed_at+ :last_viewed_at,+ :starred++ def starred+ if scope.user&.upcoming_change_enabled?(:star_chat_channels)+ object.starred+ else+ false+ end+ end++ def include_starred?+ scope.authenticated?+ endendenddiff --git a/plugins/chat/app/services/chat/update_user_channel_membership.rb b/plugins/chat/app/services/chat/update_user_channel_membership.rbnew file mode 100644index 00000000000..db5e85a0a54--- /dev/null+++ b/plugins/chat/app/services/chat/update_user_channel_membership.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++module Chat+ # Service responsible for updating a user's channel membership settings.+ # Currently supports updating the starred status of a channel.+ #+ # @example+ # ::Chat::UpdateUserChannelMembership.call(+ # guardian: guardian,+ # params: {+ # channel_id: 1,+ # starred: true+ # }+ # )+ #+ class UpdateUserChannelMembership+ include Service::Base++ # @!method self.call(guardian:, params:)+ # @param guardian [Guardian]+ # @param params [Hash]+ # @option params [Integer] :channel_id+ # @option params [Boolean] :starred++ params do+ attribute :channel_id, :integer+ attribute :starred, :boolean++ validates :channel_id, presence: true+ validates :starred, inclusion: { in: [true, false] }+ end++ model :channel+ model :membership+ policy :can_access_channel+ policy :can_use_starred_channels+ transaction { step :update_membership }++ private++ def fetch_channel(params:)+ Chat::Channel.find_by(id: params.channel_id)+ end++ def fetch_membership(channel:, guardian:)+ Chat::ChannelMembershipManager.new(channel).find_for_user(guardian.user)+ end++ def can_access_channel(guardian:, membership:)+ guardian.can_preview_chat_channel?(membership.chat_channel)+ end++ def can_use_starred_channels(guardian:)+ guardian.user.upcoming_change_enabled?(:star_chat_channels)+ end++ def update_membership(membership:, params:)+ membership.update!(starred: params.starred)+ end+ end+enddiff --git a/plugins/chat/assets/javascripts/discourse/chat-route-map.js b/plugins/chat/assets/javascripts/discourse/chat-route-map.jsindex a9f437145bd..b8312e6bd50 100644--- a/plugins/chat/assets/javascripts/discourse/chat-route-map.js+++ b/plugins/chat/assets/javascripts/discourse/chat-route-map.js@@ -15,6 +15,7 @@ export default function () {this.route("direct-messages");this.route("channels");+ this.route("starred-channels");this.route("threads");this.route("new-message");diff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjs b/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjsnew file mode 100644index 00000000000..9f9211ef716--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjs@@ -0,0 +1,30 @@+import Component from "@glimmer/component";+import { hash } from "@ember/helper";+import { service } from "@ember/service";+import { i18n } from "discourse-i18n";+import ChatChannelRow from "./chat-channel-row";++export default class ChannelsListStarred extends Component {+ @service chatChannelsManager;++ get channelList() {+ return this.args.channels || this.chatChannelsManager.starredChannels;+ }++ <template>+ <div class="channels-list-container starred-channels">+ {{#each this.channelList as |channel|}}+ <ChatChannelRow+ @channel={{channel}}+ @options={{hash leaveButton=channel.isDirectMessageChannel}}+ />+ {{else}}+ <div class="chat-channel-list__empty">+ <span class="chat-channel-list__empty-message">+ {{i18n "chat.starred_channels_empty"}}+ </span>+ </div>+ {{/each}}+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjsindex ee17f43cc1e..ddaaa77e55a 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjs@@ -8,7 +8,7 @@ import { gt } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";import ToggleChannelMembershipButton from "./toggle-channel-membership-button";-const ChatChannelCard = <template>+<template>{{#if @channel}}<divclass={{concatClass@@ -84,6 +84,4 @@ const ChatChannelCard = <template>{{/if}}</div>{{/if}}-</template>;--export default ChatChannelCard;+</template>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.gjsindex 65ac055a6f5..da8698671a2 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.gjs@@ -196,7 +196,9 @@ export default class ChatChannelRow extends Component {><ChannelIcon @channel={{@channel}} /><div class="chat-channel-row__info">- <ChannelName @channel={{@channel}} @unreadIndicator={{true}} />+ <div class="chat-channel-row__name-container">+ <ChannelName @channel={{@channel}} @unreadIndicator={{true}} />+ </div><ChatChannelMetadata @channel={{@channel}} />{{#if this.shouldRenderLastMessage}}<div class="chat-channel__last-message">diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjsindex 2d3e7c76119..bb2a316b430 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjs@@ -7,6 +7,7 @@ import { i18n } from "discourse-i18n";import {UnreadChannelsIndicator,UnreadDirectMessagesIndicator,+ UnreadStarredIndicator,UnreadThreadsIndicator,} from "discourse/plugins/chat/discourse/components/chat/footer/unread-indicator";@@ -18,6 +19,13 @@ export default class ChatFooter extends Component {@service chatChannelsManager;@service chatStateManager;+ get includeStarred() {+ return (+ this.siteSettings.star_chat_channels &&+ this.chatChannelsManager.hasStarredChannels+ );+ }+get includeThreads() {if (!this.siteSettings.chat_threads_enabled) {return false;@@ -36,6 +44,7 @@ export default class ChatFooter extends Component {get enabledRouteCount() {return [+ this.includeStarred,this.includeThreads,this.directMessagesEnabled,this.siteSettings.enable_public_channels,@@ -53,6 +62,23 @@ export default class ChatFooter extends Component {<template>{{#if this.shouldRenderFooter}}<nav class="c-footer">+ {{#if this.includeStarred}}+ <DButton+ @route="chat.starred-channels"+ @icon="star"+ @translatedLabel={{i18n "chat.starred"}}+ aria-label={{i18n "chat.starred"}}+ id="c-footer-starred"+ class={{concatClass+ "btn-transparent"+ "c-footer__item"+ (if (eq this.currentRouteName "chat.starred-channels") "--active")+ }}+ >+ <UnreadStarredIndicator />+ </DButton>+ {{/if}}+<DButton@route="chat.channels"@icon="comments"diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-indicators.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-indicators.gjsnew file mode 100644index 00000000000..ac0233b832d--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-indicators.gjs@@ -0,0 +1,63 @@+import Component from "@glimmer/component";+import UserStatusMessage from "discourse/components/user-status-message";+import icon from "discourse/helpers/d-icon";++/**+ * Displays unread indicators and user status for chat channels in the sidebar.+ *+ * @component ChatSidebarIndicators+ * @param {Object} @status - Channel status object containing unread counts and user status+ * @param {number} @status.unreadCount - Number of unread messages+ * @param {number} @status.unreadThreadsCount - Number of unread threads+ * @param {number} @status.mentionCount - Number of unread mentions+ * @param {number} @status.watchedThreadsUnreadCount - Number of unread watched threads+ * @param {boolean} @status.isDirectMessageChannel - Whether this is a DM channel+ * @param {Object} @status.userStatus - User status object for DM channels+ */+export default class ChatSidebarIndicators extends Component {+ /**+ * Determines if the channel has any unread content (messages or threads).+ *+ * @returns {boolean} True if there are unread messages or threads+ */+ get hasUnread() {+ return (+ this.args.status?.unreadCount > 0 ||+ this.args.status?.unreadThreadsCount > 0+ );+ }++ /**+ * Determines the urgency class for the unread indicator.+ * Returns "urgent" for mentions, watched threads, or any DM unreads.+ * Returns "unread" for regular unread messages.+ *+ * @returns {string} CSS class name - either "urgent" or "unread"+ */+ get urgencyClass() {+ const hasUrgent =+ this.args.status?.mentionCount > 0 ||+ this.args.status?.watchedThreadsUnreadCount > 0;++ // For DMs, treat all unreads as urgent+ const hasUnreadDM =+ this.args.status?.isDirectMessageChannel &&+ this.args.status?.unreadCount > 0;++ if (hasUrgent || hasUnreadDM) {+ return "urgent";+ }+ return "unread";+ }++ <template>+ {{#if @status.userStatus}}+ <UserStatusMessage @status={{@status.userStatus}} />+ {{/if}}+ {{#if this.hasUnread}}+ <span+ class="sidebar-section-link-content-badge icon {{this.urgencyClass}}"+ >{{icon "circle"}}</span>+ {{/if}}+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/starred-channels.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/starred-channels.gjsnew file mode 100644index 00000000000..b65833b1349--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/starred-channels.gjs@@ -0,0 +1,33 @@+import Component from "@glimmer/component";+import { service } from "@ember/service";+import { i18n } from "discourse-i18n";+import ChannelsListStarred from "discourse/plugins/chat/discourse/components/channels-list-starred";+import Navbar from "discourse/plugins/chat/discourse/components/chat/navbar";+import ChatFooter from "discourse/plugins/chat/discourse/components/chat-footer";++export default class ChatDrawerRoutesStarredChannels extends Component {+ @service chat;+ @service chatStateManager;++ <template>+ <div class="c-drawer-routes --starred-channels">+ <Navbar @onClick={{this.chat.toggleDrawer}} as |navbar|>+ <navbar.Title @title={{i18n "chat.starred"}} />+ <navbar.Actions as |a|>+ <a.SearchButton />+ <a.ToggleDrawerButton />+ <a.FullPageButton />+ <a.CloseDrawerButton />+ </navbar.Actions>+ </Navbar>++ {{#if this.chatStateManager.isDrawerExpanded}}+ <div class="chat-drawer-content">+ <ChannelsListStarred />+ </div>++ <ChatFooter />+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/footer/unread-indicator.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/footer/unread-indicator.gjsindex 0a7d8ec30ca..03b97ec9c1c 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/footer/unread-indicator.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/footer/unread-indicator.gjs@@ -3,6 +3,7 @@ import { service } from "@ember/service";const CHANNELS_TAB = "channels";const DMS_TAB = "dms";+const STARRED_TAB = "starred";const THREADS_TAB = "threads";const MAX_UNREAD_COUNT = 99;@@ -14,11 +15,16 @@ export const UnreadDirectMessagesIndicator = <template><FooterUnreadIndicator @badgeType={{DMS_TAB}} /></template>;+export const UnreadStarredIndicator = <template>+ <FooterUnreadIndicator @badgeType={{STARRED_TAB}} />+</template>;+export const UnreadThreadsIndicator = <template><FooterUnreadIndicator @badgeType={{THREADS_TAB}} /></template>;export default class FooterUnreadIndicator extends Component {+ @service chatChannelsManager;@service chatTrackingStateManager;badgeType = this.args.badgeType;@@ -31,6 +37,8 @@ export default class FooterUnreadIndicator extends Component {this.chatTrackingStateManager.directMessageUnreadCount +this.chatTrackingStateManager.directMessageMentionCount);+ } else if (this.badgeType === STARRED_TAB) {+ return this.starredChannelsUrgentCount;} else if (this.badgeType === THREADS_TAB) {return this.chatTrackingStateManager.watchedThreadsUnreadCount;} else {@@ -41,6 +49,8 @@ export default class FooterUnreadIndicator extends Component {get unreadCount() {if (this.badgeType === CHANNELS_TAB) {return this.chatTrackingStateManager.publicChannelUnreadCount;+ } else if (this.badgeType === STARRED_TAB) {+ return this.starredChannelsUnreadCount;} else if (this.badgeType === THREADS_TAB) {return this.chatTrackingStateManager.hasUnreadThreads ? 1 : 0;} else {@@ -61,6 +71,29 @@ export default class FooterUnreadIndicator extends Component {return totalCount > MAX_UNREAD_COUNT ? `${MAX_UNREAD_COUNT}+` : totalCount;}+ // Calculate urgent count for starred channels (DMs + mentions from public channels)+ get starredChannelsUrgentCount() {+ return this.chatChannelsManager.starredChannels.reduce((count, channel) => {+ if (channel.isDirectMessageChannel) {+ // DM unreads are always urgent+ return count + channel.tracking.unreadCount;+ } else {+ // Public channel mentions are urgent+ return count + channel.tracking.mentionCount;+ }+ }, 0);+ }++ // Calculate unread count for starred channels (public channel unreads only)+ get starredChannelsUnreadCount() {+ return this.chatChannelsManager.starredChannels.reduce((count, channel) => {+ if (channel.isCategoryChannel) {+ return count + channel.tracking.unreadCount;+ }+ return count;+ }, 0);+ }+<template>{{#if this.showUrgent}}<div class="c-unread-indicator -urgent">diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjsindex d6f354bde16..ee18cdc36bf 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjs@@ -1,10 +1,20 @@import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";+import DButton from "discourse/components/d-button";+import DTooltip from "discourse/float-kit/components/d-tooltip";+import concatClass from "discourse/helpers/concat-class";+import { i18n } from "discourse-i18n";import ChannelTitle from "discourse/plugins/chat/discourse/components/channel-title";export default class ChatNavbarChannelTitle extends Component {+ @service chatApi;@service chatStateManager;+ @service siteSettings;++ @tracked isTogglingStarred = false;get shouldLinkToSettings() {return (@@ -13,6 +23,51 @@ export default class ChatNavbarChannelTitle extends Component {);}+ get isStarred() {+ return this.args.channel?.currentUserMembership?.starred;+ }++ get starIcon() {+ return this.isStarred ? "star" : "far-star";+ }++ get starTooltip() {+ return this.isStarred+ ? i18n("chat.channel_settings.unstar_channel")+ : i18n("chat.channel_settings.star_channel");+ }++ get showStarButton() {+ return (+ this.args.channel?.currentUserMembership &&+ this.siteSettings.star_chat_channels+ );+ }++ @action+ async toggleStarred() {+ const channel = this.args.channel;+ if (!channel?.currentUserMembership || this.isTogglingStarred) {+ return;+ }++ this.isTogglingStarred = true;+ const newValue = !channel.currentUserMembership.starred;+ const previousValue = channel.currentUserMembership.starred;++ channel.currentUserMembership.starred = newValue;++ try {+ await this.chatApi.updateCurrentUserChannelMembership(channel.id, {+ starred: newValue,+ });+ } catch {+ channel.currentUserMembership.starred = previousValue;+ } finally {+ this.isTogglingStarred = false;+ }+ }+<template>{{#if @channel}}{{#if this.shouldLinkToSettings}}@@ -28,6 +83,25 @@ export default class ChatNavbarChannelTitle extends Component {<ChannelTitle @channel={{@channel}} /></div>{{/if}}+ {{#if this.showStarButton}}+ <DTooltip @placement="bottom">+ <:trigger>+ <DButton+ @action={{this.toggleStarred}}+ @icon={{this.starIcon}}+ @disabled={{this.isTogglingStarred}}+ class={{concatClass+ "btn-transparent"+ "c-navbar__star-channel-button"+ (if this.isStarred "--starred")+ }}+ />+ </:trigger>+ <:content>+ {{this.starTooltip}}+ </:content>+ </DTooltip>+ {{/if}}{{/if}}</template>}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/starred-channels.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/starred-channels.gjsnew file mode 100644index 00000000000..2d299bc22a0--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/starred-channels.gjs@@ -0,0 +1,25 @@+import Component from "@glimmer/component";+import { service } from "@ember/service";+import { i18n } from "discourse-i18n";+import ChannelsListStarred from "../../channels-list-starred";+import Navbar from "../navbar";++export default class ChatRoutesStarredChannels extends Component {+ @service site;++ <template>+ <div class="c-routes --starred-channels">+ <Navbar as |navbar|>+ <navbar.Title @title={{i18n "chat.starred"}} />+ <navbar.Actions as |action|>+ {{#if this.site.mobileView}}+ <action.SearchButton />+ {{/if}}+ <action.OpenDrawerButton />+ </navbar.Actions>+ </Navbar>++ <ChannelsListStarred />+ </div>+ </template>+}diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.jsindex f6025f3a4c3..ee5e071b275 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js@@ -3,7 +3,6 @@ import { get } from "@ember/object";import { service } from "@ember/service";import { dasherize } from "@ember/string";import { htmlSafe } from "@ember/template";-import UserStatusMessage from "discourse/components/user-status-message";import { decorateUsername } from "discourse/helpers/decorate-username-selector";import { avatarUrl } from "discourse/lib/avatar-utils";import { bind } from "discourse/lib/decorators";@@ -12,11 +11,248 @@ import { emojiUnescape } from "discourse/lib/text";import { escapeExpression } from "discourse/lib/utilities";import { i18n } from "discourse-i18n";import ChatModalNewMessage from "discourse/plugins/chat/discourse/components/chat/modal/new-message";+import ChatSidebarIndicators from "discourse/plugins/chat/discourse/components/chat-sidebar-indicators";import {CHAT_PANEL,initSidebarState,} from "discourse/plugins/chat/discourse/lib/init-sidebar-state";+const CHAT_STARRED_CHANNELS_SECTION = "chat-starred-channels";++function createChannelLink(BaseCustomSidebarSectionLink, options = {}) {+ const { showSuffix = true, enableHoverForPublicChannels = false } = options;++ return class extends BaseCustomSidebarSectionLink {+ route = "chat.channel";+ suffixType = "icon";+ hoverType = "icon";++ constructor({+ channel,+ chatService,+ currentUser,+ siteSettings,+ chatStateManager,+ }) {+ super(...arguments);+ this.channel = channel;+ this.chatService = chatService;+ this.siteSettings = siteSettings;+ this.currentUser = currentUser;+ this.chatStateManager = chatStateManager;++ if (this.isOneOnOneDM) {+ const user = this.channel.chatable.users?.[0];+ if (user?.username !== i18n("chat.deleted_chat_username")) {+ user.statusManager.trackStatus();+ }+ }+ }++ @bind+ willDestroy() {+ if (this.isOneOnOneDM) {+ this.channel.chatable.users?.[0]?.statusManager?.stopTrackingStatus();+ }+ }++ get isDM() {+ return this.channel.isDirectMessageChannel;+ }++ get isOneOnOneDM() {+ return this.isDM && this.channel.chatable.users.length === 1;+ }++ get name() {+ return this.isDM+ ? this.channel.slugifiedTitle+ : dasherize(this.channel.slugifiedTitle);+ }++ get classNames() {+ const classes = [];++ if (this.channel.currentUserMembership.muted) {+ classes.push("sidebar-section-link--muted");+ }++ if (+ this.channel.id === this.chatService.activeChannel?.id &&+ (this.chatStateManager.isDrawerExpanded ||+ this.chatStateManager.isFullPageActive)+ ) {+ classes.push("sidebar-section-link--active");+ }++ classes.push(`channel-${this.channel.id}`);++ return classes.join(" ");+ }++ get models() {+ return this.channel.routeModels;+ }++ get text() {+ if (this.isDM) {+ 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 htmlSafe(emojiUnescape(this.channel.escapedTitle));+ }+ }++ get title() {+ if (this.isDM) {+ if (this.channel.chatable.group) {+ return i18n("chat.placeholder_channel", {+ channelName: this.channel.escapedTitle,+ });+ } else {+ return i18n("chat.placeholder_users", {+ commaSeparatedNames: this.channel.escapedTitle,+ });+ }+ } else {+ return this.channel.escapedDescription+ ? htmlSafe(this.channel.escapedDescription)+ : `${this.channel.escapedTitle} ${i18n("chat.title")}`;+ }+ }++ get prefixType() {+ if (this.isDM) {+ if (this.channel.iconUploadUrl) {+ return "image";+ } else if (this.channel.emoji) {+ return "emoji";+ } else if (this.channel.chatable.group) {+ return "text";+ } else {+ return "image";+ }+ } else {+ return this.channel.emoji ? "emoji" : "icon";+ }+ }++ get prefixValue() {+ if (this.isDM) {+ if (this.channel.iconUploadUrl) {+ return this.channel.iconUploadUrl;+ } else if (this.channel.emoji) {+ return this.channel.emoji;+ } else if (this.channel.chatable.group) {+ return this.channel.membershipsCount;+ } else {+ return avatarUrl(+ this.channel.chatable.users[0].avatar_template,+ "tiny"+ );+ }+ } else {+ return this.channel.emoji ?? "d-chat";+ }+ }++ get prefixColor() {+ return this.isDM ? null : this.channel.chatable.color;+ }++ get prefixBadge() {+ return !this.isDM && this.channel.chatable.read_restricted ? "lock" : "";+ }++ get prefixCSSClass() {+ if (this.isDM) {+ const activeUsers = this.chatService.presenceChannel.users;+ const user = this.channel.chatable.users[0];++ if (+ !!activeUsers?.find((item) => get(item, "id") === user?.id) ||+ !!activeUsers?.find(+ (item) => get(item, "username") === user?.username+ )+ ) {+ return "active";+ }+ }+ return "";+ }++ get contentComponent() {+ return ChatSidebarIndicators;+ }++ get contentComponentArgs() {+ if (this.isDM) {+ return {+ userStatus: this.isOneOnOneDM+ ? this.channel.chatable.users[0].get("status")+ : null,+ unreadCount: this.channel.tracking.unreadCount,+ unreadThreadsCount: this.channel.unreadThreadsCountSinceLastViewed,+ mentionCount: this.channel.tracking.mentionCount,+ watchedThreadsUnreadCount:+ this.channel.tracking.watchedThreadsUnreadCount,+ isDirectMessageChannel: true,+ };+ } else {+ return {+ unreadCount: this.channel.tracking.unreadCount,+ unreadThreadsCount:+ this.chatService.activeChannel?.id !== this.channel.id+ ? this.channel.unreadThreadsCountSinceLastViewed+ : 0,+ mentionCount: this.channel.tracking.mentionCount,+ watchedThreadsUnreadCount:+ this.channel.tracking.watchedThreadsUnreadCount,+ isDirectMessageChannel: false,+ };+ }+ }++ get suffixValue() {+ return showSuffix ? "" : "";+ }++ get suffixCSSClass() {+ return showSuffix ? "" : "";+ }++ get hoverValue() {+ if (this.isDM) {+ return "xmark";+ }+ return enableHoverForPublicChannels ? "" : "";+ }++ get hoverTitle() {+ return this.isDM ? i18n("chat.direct_messages.close") : "";+ }++ get hoverAction() {+ if (this.isDM) {+ return (event) => {+ event.stopPropagation();+ event.preventDefault();+ this.chatService.unfollowChannel(this.channel);+ };+ }+ return null;+ }+ };+}+export default {name: "chat-sidebar",initialize(container) {@@ -152,15 +388,87 @@ export default {CHAT_PANEL);+ if (this.siteSettings.star_chat_channels) {+ api.addSidebarSection(+ (BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {+ const SidebarChatStarredChannelLink = createChannelLink(+ BaseCustomSidebarSectionLink,+ {+ showSuffix: false,+ enableHoverForPublicChannels: false,+ }+ );++ const SidebarChatStarredChannelsSection = class extends BaseCustomSidebarSection {+ @service currentUser;+ @service chatStateManager;+ @service siteSettings;++ constructor() {+ super(...arguments);++ if (container.isDestroyed) {+ return;+ }+ this.chatService = container.lookup("service:chat");+ this.chatChannelsManager = container.lookup(+ "service:chat-channels-manager"+ );+ }++ get sectionLinks() {+ return this.chatChannelsManager.starredChannels.map(+ (channel) =>+ new SidebarChatStarredChannelLink({+ channel,+ chatService: this.chatService,+ currentUser: this.currentUser,+ siteSettings: this.siteSettings,+ chatStateManager: this.chatStateManager,+ })+ );+ }++ get name() {+ return CHAT_STARRED_CHANNELS_SECTION;+ }++ get title() {+ return i18n("chat.starred_channels");+ }++ get text() {+ return i18n("chat.starred_channels");+ }++ get links() {+ return this.sectionLinks;+ }++ get displaySection() {+ return (+ this.chatStateManager.hasPreloadedChannels &&+ this.chatChannelsManager.hasStarredChannels+ );+ }+ };++ return SidebarChatStarredChannelsSection;+ },+ CHAT_PANEL+ );+ }+if (this.siteSettings.enable_public_channels) {api.addSidebarSection((BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {const SidebarChatChannelsSectionLink = class extends BaseCustomSidebarSectionLink {- constructor({ channel, chatService }) {+ constructor({ channel, chatService, siteSettings }) {super(...arguments);this.channel = channel;this.chatService = chatService;this.chatStateManager = chatStateManager;+ this.siteSettings = siteSettings;}get name() {@@ -221,31 +529,31 @@ export default {return this.channel.chatable.read_restricted ? "lock" : "";}- get suffixType() {- return "icon";+ get contentComponent() {+ return ChatSidebarIndicators;}- get suffixValue() {- return this.channel.tracking.unreadCount > 0 ||+ get contentComponentArgs() {+ return {+ unreadCount: this.channel.tracking.unreadCount,// We want to do this so we don't show a blue dot if the user is inside// the channel and a new unread thread comes in.- (this.chatService.activeChannel?.id !== this.channel.id &&- this.channel.unreadThreadsCountSinceLastViewed > 0)- ? "circle"- : "";- }-- get suffixCSSClass() {- return this.channel.tracking.mentionCount > 0 ||- this.channel.tracking.watchedThreadsUnreadCount > 0- ? "urgent"- : "unread";+ unreadThreadsCount:+ this.chatService.activeChannel?.id !== this.channel.id+ ? this.channel.unreadThreadsCountSinceLastViewed+ : 0,+ mentionCount: this.channel.tracking.mentionCount,+ watchedThreadsUnreadCount:+ this.channel.tracking.watchedThreadsUnreadCount,+ isDirectMessageChannel: false,+ };}};const SidebarChatChannelsSection = class extends BaseCustomSidebarSection {@service currentUser;@service chatStateManager;+ @service siteSettings;@trackedcurrentUserCanJoinPublicChannels =@@ -267,11 +575,16 @@ export default {}get sectionLinks() {- return this.chatChannelsManager.publicMessageChannels.map(+ const channels = this.siteSettings.star_chat_channels+ ? this.chatChannelsManager.unstarredPublicMessageChannels+ : this.chatChannelsManager.publicMessageChannels;++ return channels.map((channel) =>new SidebarChatChannelsSectionLink({channel,chatService: this.chatService,+ siteSettings: this.siteSettings,}));}@@ -340,10 +653,11 @@ export default {hoverValue = "xmark";hoverTitle = i18n("chat.direct_messages.close");- constructor({ channel, chatService, currentUser }) {+ constructor({ channel, chatService, currentUser, siteSettings }) {super(...arguments);this.channel = channel;this.chatService = chatService;+ this.siteSettings = siteSettings;this.currentUser = currentUser;this.chatStateManager = chatStateManager;@@ -366,14 +680,23 @@ export default {return this.channel.chatable.users.length === 1;}- get contentComponentArgs() {- return this.channel.chatable.users[0].get("status");+ get contentComponent() {+ return ChatSidebarIndicators;}- get contentComponent() {- if (this.oneOnOneMessage) {- return UserStatusMessage;- }+ get contentComponentArgs() {+ return {+ userStatus: this.oneOnOneMessage+ ? this.channel.chatable.users[0].get("status")+ : null,+ unreadCount: this.channel.tracking.unreadCount,+ unreadThreadsCount:+ this.channel.unreadThreadsCountSinceLastViewed,+ mentionCount: this.channel.tracking.mentionCount,+ watchedThreadsUnreadCount:+ this.channel.tracking.watchedThreadsUnreadCount,+ isDirectMessageChannel: true,+ };}get name() {@@ -474,21 +797,6 @@ export default {return "";}- get suffixValue() {- return this.channel.tracking.unreadCount > 0 ||- this.channel.unreadThreadsCountSinceLastViewed > 0- ? "circle"- : "";- }-- get suffixCSSClass() {- return this.channel.tracking.unreadCount > 0 ||- this.channel.tracking.mentionCount > 0 ||- this.channel.tracking.watchedThreadsUnreadCount > 0- ? "urgent"- : "unread";- }-get hoverAction() {return (event) => {event.stopPropagation();@@ -504,6 +812,7 @@ export default {@service router;@service currentUser;@service chatStateManager;+ @service siteSettings;constructor() {super(...arguments);@@ -519,15 +828,19 @@ export default {}get hideSectionHeader() {- return (- this.chatChannelsManager.truncatedDirectMessageChannels- .length === 0- );+ const channels = this.siteSettings.star_chat_channels+ ? this.chatChannelsManager+ .truncatedUnstarredDirectMessageChannels+ : this.chatChannelsManager.truncatedDirectMessageChannels;++ return channels.length === 0;}get sectionLinks() {- const channels =- this.chatChannelsManager.truncatedDirectMessageChannels;+ const channels = this.siteSettings.star_chat_channels+ ? this.chatChannelsManager+ .truncatedUnstarredDirectMessageChannels+ : this.chatChannelsManager.truncatedDirectMessageChannels;if (channels.length > 0) {return channels.map(@@ -536,6 +849,7 @@ export default {channel,chatService: this.chatService,currentUser: this.currentUser,+ siteSettings: this.siteSettings,}));} else {diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.jsindex c9544b73a26..fd0a0668869 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js@@ -4,6 +4,7 @@ export const READ_INTERVAL_MS = 1000;export const DEFAULT_MESSAGE_PAGE_SIZE = 50;export const THREAD_TITLE_PROMPT_THRESHOLD = 5;export const FOOTER_NAV_ROUTES = [+ "chat.starred-channels","chat.direct-messages","chat.channels","chat.threads",diff --git a/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js b/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.jsindex 09fecf5c526..3117199668d 100644--- a/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js+++ b/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js@@ -11,6 +11,7 @@ export default class UserChatChannelMembership {@tracked notificationLevel;@tracked lastReadMessageId;@tracked lastViewedAt;+ @tracked starred;@tracked user;constructor(args = {}) {@@ -19,6 +20,7 @@ export default class UserChatChannelMembership {this.notificationLevel = args.notification_level;this.lastReadMessageId = args.last_read_message_id;this.lastViewedAt = new Date(args.last_viewed_at);+ this.starred = args.starred;this.user = this.#initUserModel(args.user);}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.js b/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.jsnew file mode 100644index 00000000000..0cf7a86ee7f--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.js@@ -0,0 +1,33 @@+import { service } from "@ember/service";+import DiscourseRoute from "discourse/routes/discourse";++export default class ChatStarredChannelsRoute extends DiscourseRoute {+ @service chat;+ @service chatStateManager;+ @service router;+ @service site;++ activate() {+ this.chat.activeChannel = null;+ }++ async beforeModel() {+ // Redirect on desktop - mobile-only feature+ if (!this.site.mobileView) {+ const channel = this.chat.activeChannel;+ const lastKnownURL = this.chatStateManager.lastKnownChatURL;++ if (channel) {+ this.router.replaceWith("chat.channel", ...channel.routeModels);+ } else if (lastKnownURL) {+ this.router.replaceWith(lastKnownURL);+ } else {+ this.router.replaceWith("chat");+ }+ return;+ }++ // Load channels before rendering+ await this.chat.loadChannels();+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-api.js b/plugins/chat/assets/javascripts/discourse/services/chat-api.jsindex 4b0544bc2f5..4c285b2d951 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-api.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-api.js@@ -343,6 +343,17 @@ export default class ChatApi extends Service {).then((result) => UserChatChannelMembership.create(result.membership));}+ /**+ * Update membership settings of current user for a channel.+ * @param {number} channelId - The ID of the channel.+ * @param {object} data - The settings to modify.+ * @param {boolean} [data.starred] - Stars the channel.+ * @returns {Promise}+ */+ updateCurrentUserChannelMembership(channelId, data = {}) {+ return this.#putRequest(`/channels/${channelId}/memberships/me`, data);+ }+/*** Destroys the membership of current user on a channel.*diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.jsindex 13510a08f38..97ef1881986 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js@@ -162,12 +162,13 @@ export default class ChatChannelsManager extends Service {@cachedget publicMessageChannels() {- return this.channels- .filter(+ return this.#sortChannelsByProperty(+ this.channels.filter((channel) =>channel.isCategoryChannel && channel.currentUserMembership.following- )- .sort((a, b) => a?.slug?.localeCompare?.(b?.slug));+ ),+ "slug"+ );}get publicMessageChannelsWithActivity() {@@ -196,6 +197,101 @@ export default class ChatChannelsManager extends Service {return this.directMessageChannels.slice(0, DIRECT_MESSAGE_CHANNELS_LIMIT);}+ /**+ * Returns all channels (public and DM) that the current user has starred.+ * Public channels are sorted alphabetically by slug, DMs by title.+ *+ * @returns {ChatChannel[]} Array of starred channels+ */+ get starredChannels() {+ if (!this.siteSettings.star_chat_channels) {+ return [];+ }++ const starredPublic = this.channels+ .filter(+ (channel) =>+ channel.isCategoryChannel &&+ channel.currentUserMembership?.following &&+ channel.currentUserMembership?.starred+ )+ .sort((a, b) => (a.slug || "").localeCompare(b.slug || ""));++ const starredDMs = this.channels+ .filter(+ (channel) =>+ channel.isDirectMessageChannel &&+ channel.currentUserMembership?.following &&+ channel.currentUserMembership?.starred+ )+ .sort((a, b) => (a.title || "").localeCompare(b.title || ""));++ return [...starredPublic, ...starredDMs];+ }++ /**+ * Checks if the current user has any starred channels.+ *+ * @returns {boolean} True if user has starred at least one channel+ */+ get hasStarredChannels() {+ return this.starredChannels.length > 0;+ }++ /**+ * Returns public message channels that are not starred.+ * Falls back to all public channels if starring is disabled.+ * Channels are sorted with starred channels first, then by slug.+ *+ * @returns {ChatChannel[]} Array of unstarred public channels+ */+ get unstarredPublicMessageChannels() {+ if (!this.siteSettings.star_chat_channels) {+ return this.publicMessageChannels;+ }++ return this.#sortChannelsByProperty(+ this.channels.filter(+ (channel) =>+ channel.isCategoryChannel &&+ channel.currentUserMembership?.following &&+ !channel.currentUserMembership?.starred+ ),+ "slug"+ );+ }++ /**+ * Returns direct message channels that are not starred.+ * Falls back to all DM channels if starring is disabled.+ * Channels are sorted with starred channels first, then by activity.+ *+ * @returns {ChatChannel[]} Array of unstarred DM channels+ */+ get unstarredDirectMessageChannels() {+ if (!this.siteSettings.star_chat_channels) {+ return this.directMessageChannels;+ }++ return this.#sortDirectMessageChannels(+ this.channels.filter((channel) => {+ const membership = channel.currentUserMembership;+ return (+ channel.isDirectMessageChannel &&+ membership?.following &&+ !membership?.starred+ );+ })+ );+ }++ get truncatedUnstarredDirectMessageChannels() {+ return this.unstarredDirectMessageChannels.slice(+ 0,+ DIRECT_MESSAGE_CHANNELS_LIMIT+ );+ }+async #find(id) {try {const result = await this.chatApi.channel(id);@@ -243,96 +339,162 @@ export default class ChatChannelsManager extends Service {return this._cached[id];}- #sortChannelsByActivity(channels) {- return channels.sort((a, b) => {- const stats = {- a: {- urgent:- a.tracking.mentionCount + a.tracking.watchedThreadsUnreadCount,- unread: a.tracking.unreadCount + a.unreadThreadsCountSinceLastViewed,- },- b: {- urgent:- b.tracking.mentionCount + b.tracking.watchedThreadsUnreadCount,- unread: b.tracking.unreadCount + b.unreadThreadsCountSinceLastViewed,- },- };-- // if both channels have urgent count, sort by slug- // otherwise prioritize channel with urgent count- if (stats.a.urgent > 0 && stats.b.urgent > 0) {- return a.slug?.localeCompare?.(b.slug);- }+ /**+ * Compares two channels for sorting, prioritizing starred channels.+ * Returns a sort value if starred status differs, or if both are starred.+ * Returns null if both channels have the same starred status (both unstarred).+ *+ * @param {ChatChannel} a - First channel to compare+ * @param {ChatChannel} b - Second channel to compare+ * @param {string} property - Property name to use for sorting starred channels+ * @returns {number|null} Sort value (-1, 0, 1) or null if no starred sorting needed+ */+ #compareStarredChannels(a, b, property) {+ if (!this.siteSettings.star_chat_channels) {+ return null;+ }- if (stats.a.urgent > 0 || stats.b.urgent > 0) {- return stats.a.urgent > stats.b.urgent ? -1 : 1;- }+ const aStarred = a.currentUserMembership?.starred;+ const bStarred = b.currentUserMembership?.starred;- // if both channels have unread messages or threads, sort by slug- // otherwise prioritize channel with unread count- if (stats.a.unread > 0 && stats.b.unread > 0) {- return a.slug?.localeCompare?.(b.slug);- }+ // if both channels are starred, sort by the specified property+ if (aStarred && bStarred) {+ const aValue = a[property] || "";+ const bValue = b[property] || "";+ return aValue.localeCompare(bValue);+ }- if (stats.a.unread > 0 || stats.b.unread > 0) {- return stats.a.unread > stats.b.unread ? -1 : 1;- }+ // prioritize starred channels over non-starred+ if (aStarred || bStarred) {+ return aStarred ? -1 : 1;+ }- return a.slug?.localeCompare?.(b.slug);- });+ return null; // no starred sorting needed}- #sortDirectMessageChannels(channels) {- return channels.sort((a, b) => {- if (!a.lastMessage.id) {- return 1;- }-- if (!b.lastMessage.id) {- return -1;+ /**+ * Wraps a comparison function with starred channel prioritization.+ * Starred channels are always sorted first, then the provided comparison+ * function is used for unstarred channels.+ *+ * @param {string} property - Property name to use for sorting starred channels+ * @param {Function} compareFn - Comparison function for unstarred channels+ * @returns {Function} Wrapped comparison function+ */+ #withStarredPriority(property, compareFn) {+ return (a, b) => {+ const starredResult = this.#compareStarredChannels(a, b, property);+ if (starredResult !== null) {+ return starredResult;}+ return compareFn(a, b);+ };+ }- const aUrgent =- a.tracking.unreadCount +- a.tracking.mentionCount +- a.tracking.watchedThreadsUnreadCount;+ #sortChannelsByActivity(channels) {+ return channels.sort(+ this.#withStarredPriority("slug", (a, b) => {+ const stats = {+ a: {+ urgent:+ a.tracking.mentionCount + a.tracking.watchedThreadsUnreadCount,+ unread:+ a.tracking.unreadCount + a.unreadThreadsCountSinceLastViewed,+ },+ b: {+ urgent:+ b.tracking.mentionCount + b.tracking.watchedThreadsUnreadCount,+ unread:+ b.tracking.unreadCount + b.unreadThreadsCountSinceLastViewed,+ },+ };++ // if both channels have urgent count, sort by slug+ // otherwise prioritize channel with urgent count+ if (stats.a.urgent > 0 && stats.b.urgent > 0) {+ return a.slug?.localeCompare?.(b.slug);+ }++ if (stats.a.urgent > 0 || stats.b.urgent > 0) {+ return stats.a.urgent > stats.b.urgent ? -1 : 1;+ }++ // if both channels have unread messages or threads, sort by slug+ // otherwise prioritize channel with unread count+ if (stats.a.unread > 0 && stats.b.unread > 0) {+ return a.slug?.localeCompare?.(b.slug);+ }++ if (stats.a.unread > 0 || stats.b.unread > 0) {+ return stats.a.unread > stats.b.unread ? -1 : 1;+ }- const bUrgent =- b.tracking.unreadCount +- b.tracking.mentionCount +- b.tracking.watchedThreadsUnreadCount;+ return a.slug?.localeCompare?.(b.slug);+ })+ );+ }- const aUnread = a.unreadThreadsCountSinceLastViewed;- const bUnread = b.unreadThreadsCountSinceLastViewed;+ #sortChannelsByProperty(channels, property) {+ return channels.sort(+ this.#withStarredPriority(property, (a, b) => {+ return (a[property] || "").localeCompare(b[property] || "");+ })+ );+ }- // if both channels have urgent count, sort by last message date- if (aUrgent > 0 && bUrgent > 0) {+ #sortDirectMessageChannels(channels) {+ return channels.sort(+ this.#withStarredPriority("title", (a, b) => {+ if (!a.lastMessage.id) {+ return 1;+ }++ if (!b.lastMessage.id) {+ return -1;+ }++ const aUrgent =+ a.tracking.unreadCount ++ a.tracking.mentionCount ++ a.tracking.watchedThreadsUnreadCount;++ const bUrgent =+ b.tracking.unreadCount ++ b.tracking.mentionCount ++ b.tracking.watchedThreadsUnreadCount;++ const aUnread = a.unreadThreadsCountSinceLastViewed;+ const bUnread = b.unreadThreadsCountSinceLastViewed;++ // if both channels have urgent count, sort by last message date+ if (aUrgent > 0 && bUrgent > 0) {+ return new Date(a.lastMessage.createdAt) >+ new Date(b.lastMessage.createdAt)+ ? -1+ : 1;+ }++ // otherwise prioritize channel with urgent count+ if (aUrgent > 0 || bUrgent > 0) {+ return aUrgent > bUrgent ? -1 : 1;+ }++ // if both channels have unread threads, sort by last thread reply date+ if (aUnread > 0 && bUnread > 0) {+ return a.lastUnreadThreadDate > b.lastUnreadThreadDate ? -1 : 1;+ }++ // otherwise prioritize channel with unread thread count+ if (aUnread > 0 || bUnread > 0) {+ return aUnread > bUnread ? -1 : 1;+ }++ // read channels are sorted by last message datereturn new Date(a.lastMessage.createdAt) >new Date(b.lastMessage.createdAt)? -1: 1;- }-- // otherwise prioritize channel with urgent count- if (aUrgent > 0 || bUrgent > 0) {- return aUrgent > bUrgent ? -1 : 1;- }-- // if both channels have unread threads, sort by last thread reply date- if (aUnread > 0 && bUnread > 0) {- return a.lastUnreadThreadDate > b.lastUnreadThreadDate ? -1 : 1;- }-- // otherwise prioritize channel with unread thread count- if (aUnread > 0 || bUnread > 0) {- return aUnread > bUnread ? -1 : 1;- }-- // read channels are sorted by last message date- return new Date(a.lastMessage.createdAt) >- new Date(b.lastMessage.createdAt)- ? -1- : 1;- });+ })+ );}}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js b/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.jsindex 21ffd439955..f8d198fed5b 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js@@ -10,6 +10,7 @@ import ChatDrawerRoutesChannelThreads from "discourse/plugins/chat/discourse/comimport ChatDrawerRoutesChannels from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channels";import ChatDrawerRoutesDirectMessages from "discourse/plugins/chat/discourse/components/chat/drawer-routes/direct-messages";import ChatDrawerRoutesSearch from "discourse/plugins/chat/discourse/components/chat/drawer-routes/search";+import ChatDrawerRoutesStarredChannels from "discourse/plugins/chat/discourse/components/chat/drawer-routes/starred-channels";import ChatDrawerRoutesThreads from "discourse/plugins/chat/discourse/components/chat/drawer-routes/threads";const ROUTES = {@@ -157,6 +158,9 @@ const ROUTES = {"chat.direct-messages": {name: ChatDrawerRoutesDirectMessages,},+ "chat.starred-channels": {+ name: ChatDrawerRoutesStarredChannels,+ },"chat.threads": {name: ChatDrawerRoutesThreads,},diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat/starred-channels.gjs b/plugins/chat/assets/javascripts/discourse/templates/chat/starred-channels.gjsnew file mode 100644index 00000000000..7d76747b9b7--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/templates/chat/starred-channels.gjs@@ -0,0 +1,3 @@+import StarredChannels from "discourse/plugins/chat/discourse/components/chat/routes/starred-channels";++export default <template><StarredChannels /></template>diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-row.scss b/plugins/chat/assets/stylesheets/common/chat-channel-row.scssindex e5a42ba5c02..3d5df1a6a1b 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-row.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-row.scss@@ -75,6 +75,24 @@overflow: hidden;}+ &__name-container {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ overflow: hidden;+ }++ &__starred-icon {+ display: flex;+ align-items: center;+ color: var(--primary-low-mid);+ flex-shrink: 0;++ .d-icon {+ font-size: var(--font-down-2);+ }+ }+.chat-channel {&__user-info,&__channel-info {diff --git a/plugins/chat/assets/stylesheets/common/chat-footer.scss b/plugins/chat/assets/stylesheets/common/chat-footer.scssindex 1a964c32b12..44b62d94bf0 100644--- a/plugins/chat/assets/stylesheets/common/chat-footer.scss+++ b/plugins/chat/assets/stylesheets/common/chat-footer.scss@@ -21,8 +21,8 @@display: flex;flex-direction: column;align-items: center;- flex-basis: 33%;- flex-shrink: 0;+ flex-basis: auto;+ flex-shrink: 1;flex-grow: 1;padding-block: 0.75rem;height: 100%;diff --git a/plugins/chat/assets/stylesheets/common/chat-navbar.scss b/plugins/chat/assets/stylesheets/common/chat-navbar.scssindex 1d3de159adc..bf1ae11e476 100644--- a/plugins/chat/assets/stylesheets/common/chat-navbar.scss+++ b/plugins/chat/assets/stylesheets/common/chat-navbar.scss@@ -62,6 +62,25 @@align-items: center;}+.c-navbar__star-channel-button {+ height: var(--chat-header-offset);+ color: var(--primary-medium);++ &:hover,+ &:focus {+ color: var(--primary);+ }++ &.--starred {+ color: var(--tertiary);++ &:hover,+ &:focus {+ color: var(--tertiary-hover);+ }+ }+}+.c-navbar__title {display: flex;align-items: center;diff --git a/plugins/chat/assets/stylesheets/common/core-extensions.scss b/plugins/chat/assets/stylesheets/common/core-extensions.scssindex 13f423cc373..8f029ecf885 100644--- a/plugins/chat/assets/stylesheets/common/core-extensions.scss+++ b/plugins/chat/assets/stylesheets/common/core-extensions.scss@@ -25,3 +25,26 @@.user-main .collapsed-info .details .controls ul {flex-direction: row;}++.sidebar-section-link-suffix.icon.starred {+ color: var(--primary-low-mid);+ font-size: var(--font-down-2);+}++.sidebar-section-link-content-badge.icon {+ display: inline-flex;+ align-items: center;+ margin-left: 0.5em;++ svg {+ font-size: var(--font-down-2);+ }++ &.urgent svg {+ color: var(--success);+ }++ &.unread svg {+ color: var(--d-sidebar-suffix-color);+ }+}diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 22990def43b..1627110f99d 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -53,6 +53,9 @@ en:cancel: "Cancel"cancel_reply: "Cancel reply"chat_channels: "Channels"+ starred: "Starred"+ starred_channels: "Starred channels"+ starred_channels_empty: "You haven't starred any channels yet. Star channels to see them here for quick access."browse_all_channels: "Browse all channels"see_in: "See in"move_to_channel:@@ -69,6 +72,8 @@ en:title: "Channel settings"edit: "Edit"add: "Add"+ star_channel: "Star channel"+ unstar_channel: "Unstar channel"close_channel: "Close channel"open_channel: "Open channel"archive_channel: "Archive channel"diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.ymlindex 51c4cd9b3dd..50e12811168 100644--- a/plugins/chat/config/locales/server.en.yml+++ b/plugins/chat/config/locales/server.en.yml@@ -26,6 +26,7 @@ en:chat_preferred_index: "Preferred tab when loading /chat."allow_chat_in_anonymous_mode: "Enable this setting to allow users who are browsing your site anonymously to use chat. This setting requires the `allow anonymous mode` setting to be enabled."chat_search_enabled: "Enable this setting to allow users to search chat messages."+ star_chat_channels: "Enable starring of chat channels. Starred channels will be in their own dedicated section on the sidebar for quick access."errors:chat_default_channel: "The default chat channel must be a public channel."direct_message_enabled_groups_invalid: "You must specify at least one group for this setting. If you do not want anyone except staff to send direct messages, choose the staff group."diff --git a/plugins/chat/config/routes.rb b/plugins/chat/config/routes.rbindex 9bb582a0cf2..e507873c17c 100644--- a/plugins/chat/config/routes.rb+++ b/plugins/chat/config/routes.rb@@ -93,6 +93,7 @@ Chat::Engine.routes.draw doget "/new-message" => "chat#respond"get "/direct-messages" => "chat#respond"get "/channels" => "chat#respond"+ get "/starred-channels" => "chat#respond"get "/threads" => "chat#respond"get "/browse" => "chat#respond"get "/browse/all" => "chat#respond"diff --git a/plugins/chat/config/settings.yml b/plugins/chat/config/settings.ymlindex 6600a050f3a..793113e3443 100644--- a/plugins/chat/config/settings.yml+++ b/plugins/chat/config/settings.yml@@ -153,3 +153,10 @@ chat:validator: "Chat::AllowChatInAnonymousModeValidator"depends_on:- "allow_anonymous_mode"+ star_chat_channels:+ default: false+ hidden: true+ client: true+ upcoming_change:+ status: "pre_alpha"+ impact: "feature,all_members"diff --git a/plugins/chat/db/migrate/20251119100000_add_starred_to_user_chat_channel_memberships.rb b/plugins/chat/db/migrate/20251119100000_add_starred_to_user_chat_channel_memberships.rbnew file mode 100644index 00000000000..1b450cfba59--- /dev/null+++ b/plugins/chat/db/migrate/20251119100000_add_starred_to_user_chat_channel_memberships.rb@@ -0,0 +1,8 @@+# frozen_string_literal: true++class AddStarredToUserChatChannelMemberships < ActiveRecord::Migration[7.1]+ def change+ add_column :user_chat_channel_memberships, :starred, :boolean, default: false, null: false+ add_index :user_chat_channel_memberships, %i[user_id starred]+ end+enddiff --git a/plugins/chat/spec/requests/chat/api/channels_current_user_membership_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_current_user_membership_controller_spec.rbindex c41b3fa64b7..57bffc15d0c 100644--- a/plugins/chat/spec/requests/chat/api/channels_current_user_membership_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channels_current_user_membership_controller_spec.rb@@ -7,6 +7,7 @@ describe Chat::Api::ChannelsCurrentUserMembershipController dobefore doSiteSetting.chat_enabled = trueSiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ SiteSetting.star_chat_channels = truesign_in(current_user)end@@ -102,6 +103,57 @@ describe Chat::Api::ChannelsCurrentUserMembershipController doendend+ describe "#update" do+ let!(:membership) do+ Chat::UserChatChannelMembership.create!(+ chat_channel_id: channel_1.id,+ user_id: current_user.id,+ following: true,+ )+ end++ context "when starring a channel" do+ it "updates the starred status" do+ put "/chat/api/channels/#{channel_1.id}/memberships/me", params: { starred: true }++ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]["starred"]).to eq(true)+ expect(response.parsed_body["membership"]["chat_channel_id"]).to eq(channel_1.id)+ end+ end++ context "when unstarring a channel" do+ before { membership.update!(starred: true) }++ it "updates the starred status" do+ expect {+ put "/chat/api/channels/#{channel_1.id}/memberships/me", params: { starred: false }+ }.to change { membership.reload.starred }.from(true).to(false)++ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]["starred"]).to eq(false)+ end+ end++ context "when the user is not a member" do+ before { membership.destroy! }++ it "returns a 404" do+ put "/chat/api/channels/#{channel_1.id}/memberships/me", params: { starred: true }++ expect(response.status).to eq(404)+ end+ end++ context "when channel is not found" do+ it "returns a 404" do+ put "/chat/api/channels/-999/memberships/me", params: { starred: true }++ expect(response.status).to eq(404)+ end+ end+ end+describe "#destroy" dodescribe "success" doit "works" dodiff --git a/plugins/chat/spec/services/chat/update_user_channel_membership_spec.rb b/plugins/chat/spec/services/chat/update_user_channel_membership_spec.rbnew file mode 100644index 00000000000..12d0fc234d9--- /dev/null+++ b/plugins/chat/spec/services/chat/update_user_channel_membership_spec.rb@@ -0,0 +1,69 @@+# frozen_string_literal: true++RSpec.describe Chat::UpdateUserChannelMembership do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:channel_id) }+ it { is_expected.not_to allow_value(nil).for(:starred) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:current_user, :user)+ fab!(:channel, :category_channel)+ fab!(:membership) do+ Fabricate(+ :user_chat_channel_membership,+ user: current_user,+ chat_channel: channel,+ starred: false,+ )+ end++ let(:params) { { channel_id: channel.id, starred: true } }+ let(:dependencies) { { guardian: current_user.guardian } }++ before { SiteSetting.star_chat_channels = true }++ context "when contract is invalid" do+ let(:params) { { starred: true } }++ it { is_expected.to fail_a_contract }+ end++ context "when channel is not found" do+ let(:params) { { channel_id: -999, starred: true } }++ it { is_expected.to fail_to_find_a_model(:channel) }+ end++ context "when membership is not found" do+ before { membership.destroy! }++ it { is_expected.to fail_to_find_a_model(:membership) }+ end++ context "when user cannot access channel" do+ fab!(:private_channel, :private_category_channel)+ fab!(:private_membership) do+ Fabricate(+ :user_chat_channel_membership,+ user: current_user,+ chat_channel: private_channel,+ starred: false,+ )+ end+ let(:params) { { channel_id: private_channel.id, starred: true } }++ it { is_expected.to fail_a_policy(:can_access_channel) }+ end++ context "when everything is ok" do+ it { is_expected.to run_successfully }++ it "updates the starred status" do+ expect { result }.to change { membership.reload.starred }.from(false).to(true)+ end+ end+ end+enddiff --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 700c3c3da0d..48b77132a51 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@@ -14,6 +14,7 @@"muted": { "type": "boolean" },"notification_level": { "type": "string" },"following": { "type": "boolean" },+ "starred": { "type": "boolean" },"user": {"type": ["object", "null"],"required": ["id", "name", "avatar_template", "username"],diff --git a/plugins/chat/spec/system/drawer/starred_channels_spec.rb b/plugins/chat/spec/system/drawer/starred_channels_spec.rbnew file mode 100644index 00000000000..b6a1705ead8--- /dev/null+++ b/plugins/chat/spec/system/drawer/starred_channels_spec.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++RSpec.describe "Drawer - starred channels", type: :system do+ fab!(:current_user, :user)+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel A") }+ fab!(:channel_2) { Fabricate(:category_channel, name: "Channel B") }++ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:drawer_page) { PageObjects::Pages::ChatDrawer.new }++ before do+ chat_system_bootstrap+ SiteSetting.star_chat_channels = true+ channel_1.add(current_user)+ channel_2.add(current_user)+ sign_in(current_user)+ chat_page.prefers_drawer+ end++ context "when user has starred channels" do+ before { channel_1.membership_for(current_user).update!(starred: true) }++ it "shows starred tab in footer" do+ visit("/")+ chat_page.open_from_header++ expect(page).to have_css("#c-footer-starred")+ end++ it "navigates to starred channels when clicking footer tab" do+ visit("/")+ chat_page.open_from_header+ drawer_page.click_starred_channels++ expect(drawer_page).to have_open_starred_channels+ expect(page).to have_css("#c-footer-starred.--active")+ end++ it "shows the starred channel in the list" do+ visit("/")+ chat_page.open_from_header+ drawer_page.click_starred_channels++ expect(page).to have_css(".chat-channel-row[data-chat-channel-id='#{channel_1.id}']")+ end++ it "can open a starred channel" do+ visit("/")+ chat_page.open_from_header+ drawer_page.click_starred_channels+ find(".chat-channel-row[data-chat-channel-id='#{channel_1.id}']").click++ expect(drawer_page).to have_open_channel(channel_1)+ end+ end++ context "when user has no starred channels" do+ it "does not show starred tab in footer" do+ visit("/")+ chat_page.open_from_header++ expect(page).to have_no_css("#c-footer-starred")+ end+ end++ context "when star_chat_channels setting is disabled" do+ before do+ channel_1.membership_for(current_user).update!(starred: true)+ SiteSetting.star_chat_channels = false+ end++ it "does not show starred tab in footer" do+ visit("/")+ chat_page.open_from_header++ expect(page).to have_no_css("#c-footer-starred")+ end+ end+enddiff --git a/plugins/chat/spec/system/page_objects/chat/components/sidebar.rb b/plugins/chat/spec/system/page_objects/chat/components/sidebar.rbindex ad0a28f414f..cc73075cf3d 100644--- a/plugins/chat/spec/system/page_objects/chat/components/sidebar.rb+++ b/plugins/chat/spec/system/page_objects/chat/components/sidebar.rb@@ -18,13 +18,17 @@ module PageObjectsif args[:unread]predicate &&- component.has_css?("#{channel_selector} .sidebar-section-link-suffix.icon.unread")+ component.has_css?(+ "#{channel_selector} .sidebar-section-link-content-badge.icon.unread",+ )elsif args[:mention]predicate &&- component.has_css?("#{channel_selector} .sidebar-section-link-suffix.icon.urgent")+ component.has_css?(+ "#{channel_selector} .sidebar-section-link-content-badge.icon.urgent",+ )elsepredicate &&- component.has_no_css?("#{channel_selector} .sidebar-section-link-suffix.icon")+ component.has_no_css?("#{channel_selector} .sidebar-section-link-content-badge.icon")endenddiff --git a/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb b/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rbindex 28a353e730e..f9f2c7d275c 100644--- a/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb+++ b/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb@@ -116,6 +116,10 @@ module PageObjectsfind("#c-footer-threads").clickend+ def click_starred_channels+ find("#c-footer-starred").click+ end+def maximizemouseoutfind("#{VISIBLE_DRAWER} .c-navbar__full-page-button").click@@ -151,6 +155,11 @@ module PageObjectshas_css?("#{VISIBLE_DRAWER} .public-channels")end+ def has_open_starred_channels?+ has_css?("html.has-drawer-chat")+ has_css?("#{VISIBLE_DRAWER} .starred-channels")+ end+def has_open_direct_messages?has_css?("html.has-drawer-chat")has_css?("#{VISIBLE_DRAWER} .direct-message-channels")diff --git a/plugins/chat/spec/system/page_objects/sidebar/sidebar.rb b/plugins/chat/spec/system/page_objects/sidebar/sidebar.rbindex f1ae291fcf1..d5368e3d56e 100644--- a/plugins/chat/spec/system/page_objects/sidebar/sidebar.rb+++ b/plugins/chat/spec/system/page_objects/sidebar/sidebar.rb@@ -53,25 +53,25 @@ module PageObjectsdef has_unread_user_threads?has_css?(- ".sidebar-section-link[data-link-name='user-threads'] .sidebar-section-link-suffix.icon.unread",+ ".sidebar-section-link[data-link-name='user-threads'] .sidebar-section-link-content-badge.icon.unread",)enddef has_no_unread_user_threads?has_no_css?(- ".sidebar-section-link[data-link-name='user-threads'] .sidebar-section-link-suffix.icon.unread",+ ".sidebar-section-link[data-link-name='user-threads'] .sidebar-section-link-content-badge.icon.unread",)enddef has_unread_channel?(channel)has_css?(- ".sidebar-section-link.channel-#{channel.id} .sidebar-section-link-suffix:is(.unread, .urgent)",+ ".sidebar-section-link.channel-#{channel.id} .sidebar-section-link-content-badge:is(.unread, .urgent)",)enddef has_no_unread_channel?(channel)has_no_css?(- ".sidebar-section-link.channel-#{channel.id} .sidebar-section-link-suffix:is(.unread, .urgent)",+ ".sidebar-section-link.channel-#{channel.id} .sidebar-section-link-content-badge:is(.unread, .urgent)",)enddiff --git a/plugins/chat/spec/system/shortcuts/mark_all_read_spec.rb b/plugins/chat/spec/system/shortcuts/mark_all_read_spec.rbindex d04f720d8ce..b2cf955ab44 100644--- a/plugins/chat/spec/system/shortcuts/mark_all_read_spec.rb+++ b/plugins/chat/spec/system/shortcuts/mark_all_read_spec.rb@@ -32,17 +32,17 @@ RSpec.describe "Shortcuts | mark all read", type: :system docontext "when pressing shift+esc" doit "marks all channels read" doexpect(page).to have_css(- ".sidebar-section-link.channel-#{channel_1.id} .sidebar-section-link-suffix.unread",+ ".sidebar-section-link.channel-#{channel_1.id} .sidebar-section-link-content-badge.unread",)expect(page).to have_css(- ".sidebar-section-link.channel-#{channel_2.id} .sidebar-section-link-suffix.unread",+ ".sidebar-section-link.channel-#{channel_2.id} .sidebar-section-link-content-badge.unread",)find("body").send_keys(%i[shift escape])expect(page).not_to have_css(- ".sidebar-section-link.channel-#{channel_1.id} .sidebar-section-link-suffix.unread",+ ".sidebar-section-link.channel-#{channel_1.id} .sidebar-section-link-content-badge.unread",)expect(page).not_to have_css(- ".sidebar-section-link.channel-#{channel_2.id} .sidebar-section-link-suffix.unread",+ ".sidebar-section-link.channel-#{channel_2.id} .sidebar-section-link-content-badge.unread",)chat_sidebar.open_channel(channel_2)expect(page).to have_content("all read message 9")diff --git a/plugins/chat/spec/system/single_thread_spec.rb b/plugins/chat/spec/system/single_thread_spec.rbindex 8f98eefa5df..3dcab16b1c7 100644--- a/plugins/chat/spec/system/single_thread_spec.rb+++ b/plugins/chat/spec/system/single_thread_spec.rb@@ -233,7 +233,7 @@ describe "Single thread in side panel", type: :system dosign_in(current_user)chat_page.visit_channel(channel)expect(page).not_to have_css(- ".sidebar-section-link.channel-#{channel.id} .sidebar-section-link-suffix.unread",+ ".sidebar-section-link.channel-#{channel.id} .sidebar-section-link-content-badge.unread",)endenddiff --git a/plugins/chat/spec/system/starred_channels_spec.rb b/plugins/chat/spec/system/starred_channels_spec.rbnew file mode 100644index 00000000000..8b49f99cf2e--- /dev/null+++ b/plugins/chat/spec/system/starred_channels_spec.rb@@ -0,0 +1,371 @@+# frozen_string_literal: true++RSpec.describe "Starred channels", type: :system do+ fab!(:current_user, :user)++ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:sidebar) { PageObjects::Pages::Sidebar.new }++ before do+ chat_system_bootstrap+ SiteSetting.navigation_menu = "sidebar"+ SiteSetting.star_chat_channels = true+ sign_in(current_user)+ end++ context "when starring a channel" do+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel A") }+ fab!(:channel_2) { Fabricate(:category_channel, name: "Channel B") }++ before do+ channel_1.add(current_user)+ channel_2.add(current_user)+ end++ it "shows the starred channel in the Starred Channels section" do+ visit("/")++ expect(page).to have_no_css("#sidebar-section-content-chat-starred-channels")++ chat_page.visit_channel(channel_1)++ membership = channel_1.membership_for(current_user)++ expect(page).to have_css(".c-navbar__star-channel-button .d-icon-far-star")+ find(".c-navbar__star-channel-button").click+ expect(page).to have_css(".c-navbar__star-channel-button.--starred .d-icon-star")+ expect(membership.reload.starred).to eq(true)++ visit("/")++ expect(page).to have_css("#sidebar-section-content-chat-starred-channels")+ expect(+ page.find("#sidebar-section-content-chat-starred-channels li:nth-child(1)"),+ ).to have_css(".channel-#{channel_1.id}")+ end++ it "removes the starred channel from the regular Channels section" do+ visit("/")++ expect(page.find("#sidebar-section-content-chat-channels li:nth-child(1)")).to have_css(+ ".channel-#{channel_1.id}",+ )++ chat_page.visit_channel(channel_1)++ find(".c-navbar__star-channel-button").click+ expect(page).to have_css(".c-navbar__star-channel-button.--starred .d-icon-star")++ visit("/")++ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{channel_1.id}",+ )+ expect(page.find("#sidebar-section-content-chat-channels")).to have_no_css(+ ".channel-#{channel_1.id}",+ )+ expect(page.find("#sidebar-section-content-chat-channels")).to have_css(+ ".channel-#{channel_2.id}",+ )+ end+ end++ context "when starring multiple channels" do+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel C") }+ fab!(:channel_2) { Fabricate(:category_channel, name: "Channel A") }+ fab!(:channel_3) { Fabricate(:category_channel, name: "Channel B") }++ before do+ channel_1.add(current_user)+ channel_2.add(current_user)+ channel_3.add(current_user)+ end++ it "sorts starred channels alphabetically by slug in the Starred Channels section" do+ channel_1.membership_for(current_user).update!(starred: true)+ channel_2.membership_for(current_user).update!(starred: true)+ channel_3.membership_for(current_user).update!(starred: true)++ visit("/")++ expect(+ page.find("#sidebar-section-content-chat-starred-channels li:nth-child(1)"),+ ).to have_css(".channel-#{channel_2.id}")+ expect(+ page.find("#sidebar-section-content-chat-starred-channels li:nth-child(2)"),+ ).to have_css(".channel-#{channel_3.id}")+ expect(+ page.find("#sidebar-section-content-chat-starred-channels li:nth-child(3)"),+ ).to have_css(".channel-#{channel_1.id}")+ end++ it "shows unstarred channels in the regular Channels section" do+ channel_1.membership_for(current_user).update!(starred: true)++ visit("/")++ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{channel_1.id}",+ )++ expect(page.find("#sidebar-section-content-chat-channels")).to have_no_css(+ ".channel-#{channel_1.id}",+ )+ expect(page.find("#sidebar-section-content-chat-channels li:nth-child(1)")).to have_css(+ ".channel-#{channel_2.id}",+ )+ expect(page.find("#sidebar-section-content-chat-channels li:nth-child(2)")).to have_css(+ ".channel-#{channel_3.id}",+ )+ end+ end++ context "when unstarring a channel" do+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel A") }+ fab!(:channel_2) { Fabricate(:category_channel, name: "Channel B") }++ before do+ channel_1.add(current_user)+ channel_2.add(current_user)++ channel_1.membership_for(current_user).update!(starred: true)+ end++ it "moves the channel from Starred Channels to regular Channels section" do+ visit("/")++ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{channel_1.id}",+ )+ expect(page.find("#sidebar-section-content-chat-channels")).to have_no_css(+ ".channel-#{channel_1.id}",+ )++ chat_page.visit_channel(channel_1)++ membership = channel_1.membership_for(current_user)++ expect(page).to have_css(".c-navbar__star-channel-button.--starred .d-icon-star")+ find(".c-navbar__star-channel-button").click+ expect(page).to have_css(".c-navbar__star-channel-button .d-icon-far-star")+ expect(page).to have_no_css(".c-navbar__star-channel-button.--starred")+ expect(membership.reload.starred).to eq(false)++ visit("/")++ expect(page).to have_no_css("#sidebar-section-content-chat-starred-channels")+ expect(page.find("#sidebar-section-content-chat-channels li:nth-child(1)")).to have_css(+ ".channel-#{channel_1.id}",+ )+ end+ end++ context "when all channels are starred" do+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel A") }+ fab!(:channel_2) { Fabricate(:category_channel, name: "Channel B") }++ before do+ channel_1.add(current_user)+ channel_2.add(current_user)++ channel_1.membership_for(current_user).update!(starred: true)+ channel_2.membership_for(current_user).update!(starred: true)+ end++ it "shows only the Starred Channels section" do+ visit("/")++ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{channel_1.id}",+ )+ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{channel_2.id}",+ )+ end+ end++ context "when starring direct message channels" do+ fab!(:user_1, :user)+ fab!(:user_2, :user)+ fab!(:user_3, :user)+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }+ fab!(:dm_channel_2) { Fabricate(:direct_message_channel, users: [current_user, user_2]) }+ fab!(:dm_channel_3) { Fabricate(:direct_message_channel, users: [current_user, user_3]) }++ before do+ user_1.update!(username: "charlie")+ user_2.update!(username: "alice")+ user_3.update!(username: "bob")+ end++ it "shows the starred DM channel in the Starred Channels section" do+ visit("/")++ chat_page.visit_channel(dm_channel_1)++ membership = dm_channel_1.membership_for(current_user)++ expect(page).to have_css(".c-navbar__star-channel-button .d-icon-far-star")+ find(".c-navbar__star-channel-button").click+ expect(page).to have_css(".c-navbar__star-channel-button.--starred .d-icon-star")+ expect(membership.reload.starred).to eq(true)++ visit("/")++ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{dm_channel_1.id}",+ )+ end++ it "removes the starred DM from the regular Direct Messages section" do+ dm_channel_1.membership_for(current_user).update!(starred: true)++ visit("/")++ expect(page.find("#sidebar-section-content-chat-starred-channels")).to have_css(+ ".channel-#{dm_channel_1.id}",+ )+ expect(page.find("#sidebar-section-content-chat-dms")).to have_no_css(+ ".channel-#{dm_channel_1.id}",+ )+ end++ it "sorts starred DM channels alphabetically by title in Starred Channels section" do+ dm_channel_1.membership_for(current_user).update!(starred: true)+ dm_channel_2.membership_for(current_user).update!(starred: true)+ dm_channel_3.membership_for(current_user).update!(starred: true)++ visit("/")++ starred_section = page.find("#sidebar-section-content-chat-starred-channels")+ expect(starred_section.find("li:nth-child(1)")).to have_css(".channel-#{dm_channel_2.id}")+ expect(starred_section.find("li:nth-child(2)")).to have_css(".channel-#{dm_channel_3.id}")+ expect(starred_section.find("li:nth-child(3)")).to have_css(".channel-#{dm_channel_1.id}")+ end+ end++ context "when starring both public channels and DMs" do+ fab!(:user_1, :user)+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel B") }+ fab!(:channel_2) { Fabricate(:category_channel, name: "Channel A") }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }++ before do+ user_1.update!(username: "alice")+ channel_1.add(current_user)+ channel_2.add(current_user)++ channel_1.membership_for(current_user).update!(starred: true)+ channel_2.membership_for(current_user).update!(starred: true)+ dm_channel_1.membership_for(current_user).update!(starred: true)+ end++ it "shows public channels first, then DMs in the Starred Channels section" do+ visit("/")++ starred_section = page.find("#sidebar-section-content-chat-starred-channels")+ expect(starred_section.find("li:nth-child(1)")).to have_css(".channel-#{channel_2.id}")+ expect(starred_section.find("li:nth-child(2)")).to have_css(".channel-#{channel_1.id}")+ expect(starred_section.find("li:nth-child(3)")).to have_css(".channel-#{dm_channel_1.id}")+ end+ end++ context "when the star_chat_channels setting is disabled" do+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel A") }++ before do+ channel_1.add(current_user)+ channel_1.membership_for(current_user).update!(starred: true)+ SiteSetting.star_chat_channels = false+ end++ it "does not show the Starred Channels section" do+ visit("/")++ expect(page).to have_no_css("#sidebar-section-content-chat-starred-channels")+ expect(page.find("#sidebar-section-content-chat-channels")).to have_css(+ ".channel-#{channel_1.id}",+ )+ end++ it "does not show the star button in the channel navbar" do+ chat_page.visit_channel(channel_1)++ expect(page).to have_no_css(".c-navbar__star-channel-button")+ end+ end++ context "when using the navbar star button" do+ fab!(:channel_1) { Fabricate(:category_channel, name: "Channel A") }++ before { channel_1.add(current_user) }++ it "can star a channel from the navbar" do+ chat_page.visit_channel(channel_1)++ expect(page).to have_css(".c-navbar__star-channel-button .d-icon-far-star")++ find(".c-navbar__star-channel-button").click++ expect(page).to have_css(".c-navbar__star-channel-button.--starred .d-icon-star")+ expect(channel_1.membership_for(current_user).reload.starred).to eq(true)+ end++ it "can unstar a channel from the navbar" do+ channel_1.membership_for(current_user).update!(starred: true)++ chat_page.visit_channel(channel_1)++ expect(page).to have_css(".c-navbar__star-channel-button.--starred .d-icon-star")++ find(".c-navbar__star-channel-button").click++ expect(page).to have_css(".c-navbar__star-channel-button .d-icon-far-star")+ expect(page).to have_no_css(".c-navbar__star-channel-button.--starred")+ expect(channel_1.membership_for(current_user).reload.starred).to eq(false)+ end++ it "shows the correct tooltip when hovering over the star button" do+ chat_page.visit_channel(channel_1)++ find(".c-navbar__star-channel-button").hover++ expect(page).to have_css(+ ".fk-d-tooltip__content",+ text: I18n.t("js.chat.channel_settings.star_channel"),+ )+ end++ it "shows the correct tooltip when channel is already starred" do+ channel_1.membership_for(current_user).update!(starred: true)++ chat_page.visit_channel(channel_1)++ find(".c-navbar__star-channel-button").hover++ expect(page).to have_css(+ ".fk-d-tooltip__content",+ text: I18n.t("js.chat.channel_settings.unstar_channel"),+ )+ end++ it "updates tooltip after toggling starred state" do+ chat_page.visit_channel(channel_1)++ find(".c-navbar__star-channel-button").hover+ expect(page).to have_css(+ ".fk-d-tooltip__content",+ text: I18n.t("js.chat.channel_settings.star_channel"),+ )++ find(".c-navbar__star-channel-button").click+ expect(page).to have_css(".c-navbar__star-channel-button.--starred")++ find(".c-navbar__star-channel-button").hover+ expect(page).to have_css(+ ".fk-d-tooltip__content",+ text: I18n.t("js.chat.channel_settings.unstar_channel"),+ )+ end+ end+enddiff --git a/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.js b/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.jsnew file mode 100644index 00000000000..2eed04967fc--- /dev/null+++ b/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.js@@ -0,0 +1,273 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";+import UserChatChannelMembership from "discourse/plugins/chat/discourse/models/user-chat-channel-membership";++module(+ "Discourse Chat | Unit | Service | chat-channels-manager",+ function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.subject = getOwner(this).lookup("service:chat-channels-manager");+ this.fabricators = new ChatFabricators(getOwner(this));+ this.siteSettings = getOwner(this).lookup("service:site-settings");+ this.siteSettings.star_chat_channels = true;+ });++ module("#sortChannelsByActivity with starred channels", function () {+ test("prioritizes starred channels over unstarred", function (assert) {+ const channelA = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "channel-a",+ }),+ });+ const channelB = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "channel-b",+ }),+ });++ channelA.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ channelB.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: false,+ });++ this.subject.store(channelA);+ this.subject.store(channelB);++ const result = this.subject.publicMessageChannels;++ assert.strictEqual(+ result[0].id,+ channelA.id,+ "starred channel comes first"+ );+ assert.strictEqual(+ result[1].id,+ channelB.id,+ "unstarred channel comes second"+ );+ });++ test("sorts starred channels alphabetically by slug", function (assert) {+ const channelC = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "channel-c",+ }),+ });+ const channelA = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "channel-a",+ }),+ });+ const channelB = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "channel-b",+ }),+ });++ channelC.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ channelA.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ channelB.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });++ this.subject.store(channelC);+ this.subject.store(channelA);+ this.subject.store(channelB);++ const result = this.subject.publicMessageChannels;++ assert.strictEqual(+ result[0].slug,+ "channel-a",+ "first starred channel is A"+ );+ assert.strictEqual(+ result[1].slug,+ "channel-b",+ "second starred channel is B"+ );+ assert.strictEqual(+ result[2].slug,+ "channel-c",+ "third starred channel is C"+ );+ });++ test("keeps unstarred channels sorted by activity after starred ones", function (assert) {+ const starredChannel = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "starred-channel",+ }),+ });+ const unstarredChannel = this.fabricators.channel({+ chatable: this.fabricators.coreFabricators.category({+ slug: "unstarred-channel",+ }),+ });++ starredChannel.currentUserMembership = UserChatChannelMembership.create(+ {+ following: true,+ starred: true,+ }+ );+ unstarredChannel.currentUserMembership =+ UserChatChannelMembership.create({+ following: true,+ starred: false,+ });++ this.subject.store(unstarredChannel);+ this.subject.store(starredChannel);++ const result = this.subject.publicMessageChannels;++ assert.strictEqual(+ result[0].id,+ starredChannel.id,+ "starred channel is first"+ );+ assert.strictEqual(+ result[1].id,+ unstarredChannel.id,+ "unstarred channel is after starred"+ );+ });+ });++ module("#sortDirectMessageChannels with starred channels", function () {+ test("prioritizes starred DM channels over unstarred", function (assert) {+ const dmA = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Alice",+ });+ const dmB = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Bob",+ });++ dmA.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ dmB.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: false,+ });++ this.subject.store(dmA);+ this.subject.store(dmB);++ const result = this.subject.directMessageChannels;++ assert.strictEqual(+ result[0].id,+ dmA.id,+ "starred DM channel comes first"+ );+ assert.strictEqual(+ result[1].id,+ dmB.id,+ "unstarred DM channel comes second"+ );+ });++ test("sorts starred DM channels alphabetically by title", function (assert) {+ const dmCharlie = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Charlie",+ });+ const dmAlice = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Alice",+ });+ const dmBob = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Bob",+ });++ dmCharlie.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ dmAlice.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ dmBob.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });++ this.subject.store(dmCharlie);+ this.subject.store(dmAlice);+ this.subject.store(dmBob);++ const result = this.subject.directMessageChannels;++ assert.strictEqual(+ result[0].title,+ "Alice",+ "first starred DM is Alice"+ );+ assert.strictEqual(result[1].title, "Bob", "second starred DM is Bob");+ assert.strictEqual(+ result[2].title,+ "Charlie",+ "third starred DM is Charlie"+ );+ });++ test("keeps unstarred DM channels sorted by activity after starred ones", function (assert) {+ const starredDM = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Starred User",+ });+ const unstarredDM = this.fabricators.channel({+ chatable: this.fabricators.directMessage(),+ title: "Unstarred User",+ });++ starredDM.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: true,+ });+ unstarredDM.currentUserMembership = UserChatChannelMembership.create({+ following: true,+ starred: false,+ });++ this.subject.store(unstarredDM);+ this.subject.store(starredDM);++ const result = this.subject.directMessageChannels;++ assert.strictEqual(+ result[0].id,+ starredDM.id,+ "starred DM channel is first"+ );+ assert.strictEqual(+ result[1].id,+ unstarredDM.id,+ "unstarred DM channel is after starred"+ );+ });+ });+ }+);diff --git a/public/images/upcoming_changes/star_chat_channels.png b/public/images/upcoming_changes/star_chat_channels.pngnew file mode 100644index 00000000000..c740673d9c6Binary files /dev/null and b/public/images/upcoming_changes/star_chat_channels.png differ