Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add chat channel sort and filter options (#43249)

Sam3dfc739016f9
diff --git a/app/assets/stylesheets/common/float-kit/d-menu.scss b/app/assets/stylesheets/common/float-kit/d-menu.scss
index 64d240d12d1..6ce7d583217 100644
--- a/app/assets/stylesheets/common/float-kit/d-menu.scss
+++ b/app/assets/stylesheets/common/float-kit/d-menu.scss
@@ -5,7 +5,7 @@
max-width: 600px;
display: flex;
padding: 0;
- z-index: z("dropdown");
+ z-index: calc(z("composer", "dropdown") + 1);
&__trigger {
.touch & {
diff --git a/app/models/user_option.rb b/app/models/user_option.rb
index acb62720971..1c05ce17053 100644
--- a/app/models/user_option.rb
+++ b/app/models/user_option.rb
@@ -293,6 +293,12 @@ end
# automatically_unpin_topics :boolean default(TRUE), not null
# bookmark_auto_delete_preference :integer default(3), not null
# chat_announce_new_messages :boolean default(TRUE), not null
+# chat_channel_list_filter :integer default("all"), not null
+# chat_channel_list_filter_dms :integer default("all"), not null
+# chat_channel_list_filter_starred :integer default("all"), not null
+# chat_channel_list_sort :integer default("alphabetical"), not null
+# chat_channel_list_sort_dms :integer default("priority"), not null
+# chat_channel_list_sort_starred :integer default("alphabetical"), not null
# chat_email_frequency :integer default("when_away"), not null
# chat_enabled :boolean default(TRUE), not null
# chat_header_indicator_preference :integer default("all_new"), not null
diff --git a/db/structure.sql b/db/structure.sql
index e6e596491c7..b98132f04b7 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -12211,7 +12211,13 @@ CREATE TABLE public.user_options (
automatically_translate boolean DEFAULT true NOT NULL,
understood_languages character varying[] DEFAULT '{}'::character varying[] NOT NULL,
send_shortcut integer DEFAULT 0 NOT NULL,
- ai_ask_ai_default boolean DEFAULT true NOT NULL
+ ai_ask_ai_default boolean DEFAULT true NOT NULL,
+ chat_channel_list_filter integer DEFAULT 0 NOT NULL,
+ chat_channel_list_sort integer DEFAULT 0 NOT NULL,
+ chat_channel_list_sort_starred integer DEFAULT 0 NOT NULL,
+ chat_channel_list_sort_dms integer DEFAULT 2 NOT NULL,
+ chat_channel_list_filter_starred integer DEFAULT 0 NOT NULL,
+ chat_channel_list_filter_dms integer DEFAULT 0 NOT NULL
);
@@ -24481,9 +24487,12 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20260908160656'),
+('20260908153158'),
('20260908112615'),
('20260904065041'),
('20260904063128'),
+('20260904000537'),
('20260903195501'),
('20260903065141'),
('20260902150024'),
diff --git a/frontend/discourse/app/components/sidebar/section-link.gjs b/frontend/discourse/app/components/sidebar/section-link.gjs
index 0b2a6d34cbb..1399ead2905 100644
--- a/frontend/discourse/app/components/sidebar/section-link.gjs
+++ b/frontend/discourse/app/components/sidebar/section-link.gjs
@@ -43,6 +43,7 @@ export default class SectionLink extends Component {
@service capabilities;
@service currentUser;
@service router;
+ @service sidebarState;
@tracked hovering = false;
@tracked hoverActionActive = false;
@@ -196,11 +197,43 @@ export default class SectionLink extends Component {
@bind
maybeScrollIntoView(element) {
+ this.#revealLink(element);
+ }
+
+ @bind
+ revealActiveLink(element) {
+ this.#revealLink(element, { force: true });
+ }
+
+ #revealLink(element, { force = false } = {}) {
if (!this.args.scrollIntoView) {
return;
}
schedule("afterRender", () => {
+ if (
+ this.isDestroying ||
+ !element.isConnected ||
+ !this.args.scrollIntoView
+ ) {
+ return;
+ }
+
+ const container = element.closest(".sidebar-sections");
+ const destination = element.querySelector("a")?.href;
+
+ // Reinserting the same destination in another section is not navigation.
+ if (
+ container &&
+ destination &&
+ !this.sidebarState.shouldRevealLink(container, destination, {
+ force,
+ linkRoute: this.args.route,
+ })
+ ) {
+ return;
+ }
+
if (isFullyScrolledIntoView(element)) {
return;
}
@@ -219,7 +252,7 @@ export default class SectionLink extends Component {
data-list-item-name={{@linkName}}
...attributes
{{didInsert this.maybeScrollIntoView}}
- {{didUpdate this.maybeScrollIntoView @scrollIntoView}}
+ {{didUpdate this.revealActiveLink @scrollIntoView}}
{{on "mouseenter" this.hoveringSectionLink}}
{{on "mouseleave" this.stopHoveringSectionLink}}
>
diff --git a/frontend/discourse/app/components/sidebar/section.gjs b/frontend/discourse/app/components/sidebar/section.gjs
index fc4bdf8f73b..d93a638f36c 100644
--- a/frontend/discourse/app/components/sidebar/section.gjs
+++ b/frontend/discourse/app/components/sidebar/section.gjs
@@ -165,6 +165,9 @@ export default class SidebarSection extends Component {
if (this.displaySectionContent) {
this.sidebarState.collapseSection(this.args.sectionName);
} else {
+ this.sidebarState.resetLinkReveal(
+ event.target.closest(".sidebar-sections")
+ );
this.sidebarState.expandSection(this.args.sectionName);
}
diff --git a/frontend/discourse/app/services/sidebar-state.js b/frontend/discourse/app/services/sidebar-state.js
index 5357072f667..03df2f624a3 100644
--- a/frontend/discourse/app/services/sidebar-state.js
+++ b/frontend/discourse/app/services/sidebar-state.js
@@ -18,6 +18,7 @@ import {
@disableImplicitInjections
export default class SidebarState extends Service {
@service keyValueStore;
+ @service router;
@tracked currentPanelKey = currentPanelKey;
@tracked mode = COMBINED_MODE;
@@ -31,6 +32,7 @@ export default class SidebarState extends Service {
collapsedSections = trackedSet();
previousState = {};
#hiders = trackedSet();
+ #revealedLinks = new WeakMap();
get sidebarHidden() {
return this.#hiders.size > 0;
@@ -52,6 +54,37 @@ export default class SidebarState extends Service {
return escapeRegExp(this.filter.toLowerCase().trim());
}
+ resetLinkReveal(container) {
+ this.#revealedLinks.delete(container);
+ }
+
+ shouldRevealLink(container, destination, { force = false, linkRoute } = {}) {
+ let state = this.#revealedLinks.get(container);
+ const route = this.router.currentRoute;
+ const panel = this.currentPanelKey;
+
+ if (
+ !state ||
+ state.route !== route ||
+ state.panel !== panel ||
+ state.mode !== this.mode ||
+ state.filter !== this.filter
+ ) {
+ state = {
+ route,
+ panel,
+ mode: this.mode,
+ filter: this.filter,
+ destinations: new Map(),
+ };
+ this.#revealedLinks.set(container, state);
+ }
+
+ const revealed = state.destinations.get(linkRoute) === destination;
+ state.destinations.set(linkRoute, destination);
+ return force || !revealed;
+ }
+
registerHider(ref) {
this.#hiders.add(ref);
diff --git a/frontend/discourse/tests/integration/components/sidebar/section-link-test.gjs b/frontend/discourse/tests/integration/components/sidebar/section-link-test.gjs
index 18d23f99ba5..db4696fc2a3 100644
--- a/frontend/discourse/tests/integration/components/sidebar/section-link-test.gjs
+++ b/frontend/discourse/tests/integration/components/sidebar/section-link-test.gjs
@@ -1,6 +1,14 @@
-import { render, triggerEvent } from "@ember/test-helpers";
+import { trackedObject } from "@ember/reactive/collections";
+import {
+ click,
+ find,
+ render,
+ rerender,
+ triggerEvent,
+} from "@ember/test-helpers";
import { module, test } from "qunit";
import sinon from "sinon";
+import Section from "discourse/components/sidebar/section";
import SectionLink from "discourse/components/sidebar/section-link";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
@@ -255,4 +263,148 @@ module("Integration | Component | Sidebar | SectionLink", function (hooks) {
"no scrolling happens when the link is already fully in view"
);
});
+ test("moving an active destination between sections preserves the current scroll position", async function (assert) {
+ this.state = trackedObject({ moved: false });
+
+ await render(
+ <template>
+ <div
+ class="sidebar-sections"
+ style="height: 200px; overflow-y: auto; display: block"
+ >
+ <ul style="height: 600px; margin: 0">
+ {{#unless this.state.moved}}
+ <SectionLink
+ @href="/latest"
+ @linkName="original"
+ @scrollIntoView={{true}}
+ />
+ {{/unless}}
+ </ul>
+ <ul style="height: 600px; margin: 0">
+ {{#if this.state.moved}}
+ <SectionLink
+ @href="/latest"
+ @linkName="moved"
+ @scrollIntoView={{true}}
+ />
+ {{/if}}
+ </ul>
+ </div>
+ </template>
+ );
+ const scroller = find(".sidebar-sections");
+ scroller.scrollTop = 100;
+
+ this.state.moved = true;
+ await rerender();
+
+ assert
+ .dom('[data-list-item-name="moved"]')
+ .exists("the destination moved into the other section");
+ assert.strictEqual(
+ scroller.scrollTop,
+ 100,
+ "reinsertion does not reveal the moved link"
+ );
+
+ scroller.scrollTop = 300;
+ this.state.moved = false;
+ await rerender();
+
+ assert.strictEqual(
+ scroller.scrollTop,
+ 300,
+ "rollback respects scrolling since the initial move"
+ );
+ });
+
+ test("new destinations and reactivated links are still revealed", async function (assert) {
+ this.state = trackedObject({ destinations: ["/latest"], active: true });
+
+ await render(
+ <template>
+ <div
+ class="sidebar-sections"
+ style="height: 200px; overflow-y: auto; display: block"
+ >
+ <div style="height: 600px"></div>
+ <ul>
+ {{#each this.state.destinations as |destination|}}
+ <SectionLink
+ @href={{destination}}
+ @linkName="destination"
+ @scrollIntoView={{this.state.active}}
+ />
+ {{/each}}
+ </ul>
+ <div style="height: 600px"></div>
+ </div>
+ </template>
+ );
+ const scroller = find(".sidebar-sections");
+ assert.true(scroller.scrollTop > 0, "the initial active link is revealed");
+
+ scroller.scrollTop = 0;
+ this.state.destinations = ["/top"];
+ await rerender();
+ assert.true(scroller.scrollTop > 0, "a different destination is revealed");
+
+ scroller.scrollTop = 0;
+ this.state.destinations = ["/latest"];
+ await rerender();
+ assert.true(
+ scroller.scrollTop > 0,
+ "returning to a previous destination reveals it again"
+ );
+
+ this.state.active = false;
+ await rerender();
+ scroller.scrollTop = 0;
+ this.state.active = true;
+ await rerender();
+ assert.true(
+ scroller.scrollTop > 0,
+ "reactivating an existing link reveals it"
+ );
+ });
+
+ test("expanding a section reveals its previously revealed active link", async function (assert) {
+ await render(
+ <template>
+ <div
+ class="sidebar-sections"
+ style="height: 200px; overflow-y: auto; display: block"
+ >
+ <Section
+ @collapsable={{true}}
+ @headerLinkText="Test"
+ @sectionName="reveal-test"
+ >
+ <li style="height: 600px"></li>
+ <SectionLink
+ @href="/latest"
+ @linkName="destination"
+ @scrollIntoView={{true}}
+ />
+ </Section>
+ <div style="height: 600px"></div>
+ </div>
+ </template>
+ );
+ const scroller = find(".sidebar-sections");
+ assert.true(scroller.scrollTop > 0, "the initial link is revealed");
+
+ await click(".sidebar-section-header-collapsable");
+ assert
+ .dom('[data-list-item-name="destination"]')
+ .doesNotExist("collapsing removes the link");
+ scroller.scrollTop = 0;
+ await click(".sidebar-section-header-collapsable");
+
+ assert.true(
+ scroller.scrollTop > 0,
+ "explicit expansion reveals the link again"
+ );
+ });
});
diff --git a/migrations/tooling/config/schema/plugin_manifest.yml b/migrations/tooling/config/schema/plugin_manifest.yml
index 58415e2053f..be110c77ac7 100644
--- a/migrations/tooling/config/schema/plugin_manifest.yml
+++ b/migrations/tooling/config/schema/plugin_manifest.yml
@@ -44,6 +44,8 @@ plugins:
columns:
user_options:
- chat_announce_new_messages
+ - chat_channel_list_filter
+ - chat_channel_list_sort
- chat_email_frequency
- chat_enabled
- chat_header_indicator_preference
@@ -245,7 +247,7 @@ plugins:
plugin_checksums:
automation: e69972690991bc04d92b2d161aac8921
boards: 3f7be99d5aaac4cf66318ef036e231a2
- chat: 3324ff0e829d9282accc917503038f18
+ chat: ab866e1148b3ab93d658a44dc4417951
discourse-adplugin: 9e52419decf1099c5bc301a90e6cc91a
discourse-affiliate: '08c6e1a851441a082e9be9ddddc63910'
discourse-ai: 1dbe6a6155758187d0a34e7fb0b24181
diff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list-direct.gjs b/plugins/chat/assets/javascripts/discourse/components/channels-list-direct.gjs
index 9b8d571a322..6f12095414e 100644
--- a/plugins/chat/assets/javascripts/discourse/components/channels-list-direct.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list-direct.gjs
@@ -6,13 +6,14 @@ import { service } from "@ember/service";
import PluginOutlet from "discourse/components/plugin-outlet";
import lazyHash from "discourse/helpers/lazy-hash";
import { and, not, or } from "discourse/truth-helpers";
-import DButton from "discourse/ui-kit/d-button";
import DEmptyState from "discourse/ui-kit/d-empty-state";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
import ChatModalNewMessage from "discourse/plugins/chat/discourse/components/chat/modal/new-message";
+import ChatChannelListOptionsButton from "./chat-channel-list-options-button";
import ChatChannelRow from "./chat-channel-row";
+import ChatSidebarChannelListFilterEmptyState from "./chat-sidebar-channel-list-filter-empty-state";
import ChatZero from "./svg/chat-zero";
export default class ChannelsListDirect extends Component {
@@ -25,14 +26,6 @@ export default class ChannelsListDirect extends Component {
return this.args.inSidebar ?? false;
}
- get createDirectMessageChannelLabel() {
- if (!this.canCreateDirectMessageChannel) {
- return "chat.direct_messages.cannot_create";
- }
-
- return "chat.direct_messages.new";
- }
-
get showDirectMessageChannels() {
return (
this.canCreateDirectMessageChannel || !this.directMessageChannelsEmpty
@@ -49,10 +42,10 @@ export default class ChannelsListDirect extends Component {
get channelList() {
if (this.inSidebar) {
- return this.chatChannelsManager.truncatedUnstarredDirectMessageChannels;
+ return this.chatChannelsManager.sidebarDirectMessageChannels;
}
- // In mobile/drawer, show all channels including starred, sorted by activity
- return this.chatChannelsManager.truncatedDirectMessageChannelsByActivity;
+ // In mobile/drawer, show all channels including starred, sorted by preference
+ return this.chatChannelsManager.truncatedDirectMessageChannelsByPreference;
}
@action
@@ -94,13 +87,10 @@ export default class ChannelsListDirect extends Component {
<span class="channel-title">{{i18n "chat.direct_messages.title"}}</span>
- {{#if this.canCreateDirectMessageChannel}}
- <DButton
- class="no-text btn-flat open-new-message-btn"
- title={{i18n this.createDirectMessageChannelLabel}}
- @action={{this.openNewMessageModal}}
- @icon="plus"
- />
+ {{#if this.site.desktopView}}
+ <div class="chat-channel-divider__actions">
+ <ChatChannelListOptionsButton @section="dms" />
+ </div>
{{/if}}
</div>
{{/if}}
@@ -131,6 +121,13 @@ export default class ChannelsListDirect extends Component {
@channel={{channel}}
@options={{hash leaveButton=true}}
/>
+ {{else}}
+ {{#unless this.inSidebar}}
+ <ChatSidebarChannelListFilterEmptyState
+ @layout="empty-state"
+ @section="dms"
+ />
+ {{/unless}}
{{/each}}
{{/if}}
</div>
diff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs b/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs
index cca1175196d..c6d6ecf7cec 100644
--- a/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs
@@ -11,7 +11,9 @@ import DEmptyState from "discourse/ui-kit/d-empty-state";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import ChatChannelListOptionsButton from "./chat-channel-list-options-button";
import ChatChannelRow from "./chat-channel-row";
+import ChatSidebarChannelListFilterEmptyState from "./chat-sidebar-channel-list-filter-empty-state";
import ChatZero from "./svg/chat-zero";
export default class ChannelsListPublic extends Component {
@@ -41,8 +43,8 @@ export default class ChannelsListPublic extends Component {
if (this.inSidebar) {
return this.chatChannelsManager.unstarredPublicMessageChannelsByActivity;
}
- // In mobile/drawer, show all channels including starred, sorted by activity
- return this.chatChannelsManager.allPublicChannelsByActivity;
+ // In mobile/drawer, show all channels including starred, sorted by preference
+ return this.chatChannelsManager.publicMessageChannelsByPreference;
}
@action
@@ -90,13 +92,9 @@ export default class ChannelsListPublic extends Component {
<span class="channel-title">{{i18n "chat.chat_channels"}}</span>
{{#if this.canBrowseChannels}}
- <LinkTo
- class="btn no-text btn-flat open-browse-page-btn title-action"
- title={{i18n "chat.channels_list_popup.browse"}}
- @route="chat.browse"
- >
- {{dIcon "pencil"}}
- </LinkTo>
+ <div class="chat-channel-divider__actions">
+ <ChatChannelListOptionsButton @section="channels" />
+ </div>
{{/if}}
</div>
{{/if}}
@@ -129,6 +127,13 @@ export default class ChannelsListPublic extends Component {
@channel={{channel}}
@options={{hash settingsButton=true}}
/>
+ {{else}}
+ {{#unless this.inSidebar}}
+ <ChatSidebarChannelListFilterEmptyState
+ @layout="empty-state"
+ @section="channels"
+ />
+ {{/unless}}
{{/each}}
{{/if}}
</div>
diff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjs b/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjs
index 69bd1811956..d7941072d4b 100644
--- a/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list-starred.gjs
@@ -1,11 +1,15 @@
import Component from "@glimmer/component";
import { hash } from "@ember/helper";
import { service } from "@ember/service";
+import { or } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
+import ChatChannelListOptionsButton from "./chat-channel-list-options-button";
import ChatChannelRow from "./chat-channel-row";
+import ChatSidebarChannelListFilterEmptyState from "./chat-sidebar-channel-list-filter-empty-state";
export default class ChannelsListStarred extends Component {
@service chatChannelsManager;
+ @service site;
get inSidebar() {
return this.args.inSidebar ?? false;
@@ -16,12 +20,22 @@ export default class ChannelsListStarred extends Component {
return this.args.channels;
}
if (!this.inSidebar) {
- return this.chatChannelsManager.starredChannelsByActivity;
+ return this.chatChannelsManager.starredChannelsByPreference;
}
return this.chatChannelsManager.starredChannels;
}
<template>
+ {{#unless (or this.inSidebar this.site.mobileView)}}
+ <div class="chat-channel-divider starred-channels-section">
+ <span class="channel-title">{{i18n "chat.starred_channels"}}</span>
+
+ <div class="chat-channel-divider__actions">
+ <ChatChannelListOptionsButton @section="starred" />
+ </div>
+ </div>
+ {{/unless}}
+
<div class="channels-list-container starred-channels">
{{#each this.channelList as |channel|}}
<ChatChannelRow
@@ -29,11 +43,20 @@ export default class ChannelsListStarred extends Component {
@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>
+ {{#if this.chatChannelsManager.starredChannels.length}}
+ {{#unless this.inSidebar}}
+ <ChatSidebarChannelListFilterEmptyState
+ @layout="empty-state"
+ @section="starred"
+ />
+ {{/unless}}
+ {{else}}
+ <div class="chat-channel-list__empty">
+ <span class="chat-channel-list__empty-message">
+ {{i18n "chat.starred_channels_empty"}}
+ </span>
+ </div>
+ {{/if}}
{{/each}}
</div>
</template>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-filter-menu.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-filter-menu.gjs
new file mode 100644
index 00000000000..866b54f2329
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-filter-menu.gjs
@@ -0,0 +1,135 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import {
+ CHAT_CHANNEL_LIST_ACTIVE_DAYS,
+ CHAT_CHANNEL_LIST_FILTERS,
+} from "discourse/plugins/chat/discourse/lib/chat-constants";
+
+export default class ChatChannelListFilterMenu extends Component {
+ @service chatChannelListPreferences;
+
+ get section() {
+ return this.args.section ?? "channels";
+ }
+
+ get currentFilter() {
+ return this.chatChannelListPreferences.filterFor(this.section);
+ }
+
+ get isSaving() {
+ return this.chatChannelListPreferences.isSavingFilterFor(this.section);
+ }
+
+ @action
+ async selectFilter(filter) {
+ const preferences = this.chatChannelListPreferences;
+ const { closeParent, closeSubmenu } = this.args;
+ const section = this.section;
+
+ await closeSubmenu?.();
+ await closeParent?.();
+ await preferences.setFilter(section, filter);
+ }
+
+ <template>
+ <DDropdownMenu
+ aria-label={{i18n "chat.channel_list.filter.title"}}
+ class="chat-channel-list-filter-menu"
+ role="group"
+ ...attributes
+ as |dropdown|
+ >
+ <dropdown.subheader role="presentation">
+ {{i18n "chat.channel_list.filter.title"}}
+ </dropdown.subheader>
+
+ <dropdown.item role="none">
+ <DButton
+ aria-checked={{if
+ (eq this.currentFilter CHAT_CHANNEL_LIST_FILTERS.ALL)
+ "true"
+ "false"
+ }}
+ class="chat-channel-list-filter-menu__all"
+ data-menu-option-id="all"
+ role="menuitemradio"
+ @action={{this.selectFilter}}
+ @actionParam={{CHAT_CHANNEL_LIST_FILTERS.ALL}}
+ @disabled={{this.isSaving}}
+ @icon="check"
+ @label="chat.channel_list.filter.all"
+ />
+ </dropdown.item>
+
+ <dropdown.item role="none">
+ <DButton
+ aria-checked={{if
+ (eq this.currentFilter CHAT_CHANNEL_LIST_FILTERS.ACTIVE)
+ "true"
+ "false"
+ }}
+ class="chat-channel-list-filter-menu__active --with-description"
+ data-menu-option-id="active"
+ role="menuitemradio"
+ @action={{this.selectFilter}}
+ @actionParam={{CHAT_CHANNEL_LIST_FILTERS.ACTIVE}}
+ @disabled={{this.isSaving}}
+ @icon="check"
+ >
+ <span class="chat-channel-list-filter-menu__label">
+ <span class="chat-channel-list-filter-menu__label-title">
+ {{i18n "chat.channel_list.filter.active"}}
+ </span>
+ <span class="chat-channel-list-filter-menu__label-description">
+ {{i18n
+ "chat.channel_list.filter.active_description"
+ days=CHAT_CHANNEL_LIST_ACTIVE_DAYS
+ }}
+ </span>
+ </span>
+ </DButton>
+ </dropdown.item>
+
+ <dropdown.item role="none">
+ <DButton
+ aria-checked={{if
+ (eq this.currentFilter CHAT_CHANNEL_LIST_FILTERS.UNREAD)
+ "true"
+ "false"
+ }}
+ class="chat-channel-list-filter-menu__unread"
+ data-menu-option-id="unread"
+ role="menuitemradio"
+ @action={{this.selectFilter}}
+ @actionParam={{CHAT_CHANNEL_LIST_FILTERS.UNREAD}}
+ @disabled={{this.isSaving}}
+ @icon="check"
+ @label="chat.channel_list.filter.unread"
+ />
+ </dropdown.item>
+
+ <dropdown.item role="none">
+ <DButton
+ aria-checked={{if
+ (eq this.currentFilter CHAT_CHANNEL_LIST_FILTERS.MENTIONS)
+ "true"
+ "false"
+ }}
+ class="chat-channel-list-filter-menu__mentions"
+ data-menu-option-id="mentions"
+ role="menuitemradio"
+ @action={{this.selectFilter}}
+ @actionParam={{CHAT_CHANNEL_LIST_FILTERS.MENTIONS}}
+ @disabled={{this.isSaving}}
+ @icon="check"
+ @label="chat.channel_list.filter.mentions"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-options-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-options-button.gjs
new file mode 100644
index 00000000000..8c817e2e193
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-options-button.gjs
@@ -0,0 +1,46 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import { CHANNEL_LIST_SECTION_OPTIONS } from "discourse/plugins/chat/discourse/lib/chat-channel-list-options";
+import ChatChannelListSidebarMenu from "./chat-channel-list-sidebar-menu";
+
+/**
+ * Divider/section header action that opens the shared channel list menu
+ * (filter/sort/browse/create) for the given section. Used in the drawer,
+ * mobile, and full-page channel lists, where a section header can't rely on
+ * the cover sidebar's `actions` API.
+ */
+export default class ChatChannelListOptionsButton extends Component {
+ @service menu;
+
+ get section() {
+ return this.args.section ?? "channels";
+ }
+
+ @action
+ openMenu(_actionParam, event) {
+ this.menu.show(event.target.closest("button"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ modalForMobile: true,
+ placement: "right-start",
+ data: {
+ section: this.section,
+ ...CHANNEL_LIST_SECTION_OPTIONS[this.section],
+ },
+ });
+ }
+
+ <template>
+ <DButton
+ class="chat-channel-list-options-button title-action"
+ ...attributes
+ @action={{this.openMenu}}
+ @forwardEvent={{true}}
+ @icon="ellipsis-vertical"
+ @title="chat.channel_list.options.title"
+ />
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sidebar-menu.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sidebar-menu.gjs
new file mode 100644
index 00000000000..bc9c24e4e69
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sidebar-menu.gjs
@@ -0,0 +1,233 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import ChatModalCreateChannel from "discourse/plugins/chat/discourse/components/chat/modal/create-channel";
+import ChatModalNewMessage from "discourse/plugins/chat/discourse/components/chat/modal/new-message";
+import {
+ CHAT_CHANNEL_LIST_FILTERS,
+ CHAT_CHANNEL_LIST_SORTS,
+} from "discourse/plugins/chat/discourse/lib/chat-constants";
+import ChatChannelListFilterMenu from "./chat-channel-list-filter-menu";
+import ChatChannelListSortMenu from "./chat-channel-list-sort-menu";
+
+const FILTER_LABEL_KEYS = {
+ [CHAT_CHANNEL_LIST_FILTERS.ALL]: "chat.channel_list.filter.all",
+ [CHAT_CHANNEL_LIST_FILTERS.ACTIVE]: "chat.channel_list.filter.active",
+ [CHAT_CHANNEL_LIST_FILTERS.UNREAD]: "chat.channel_list.filter.unread",
+ [CHAT_CHANNEL_LIST_FILTERS.MENTIONS]: "chat.channel_list.filter.mentions",
+};
+
+const SORT_LABEL_KEYS = {
+ [CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL]: "chat.channel_list.sort.alphabetical",
+ [CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY]:
+ "chat.channel_list.sort.recent_activity",
+ [CHAT_CHANNEL_LIST_SORTS.PRIORITY]: "chat.channel_list.sort.priority",
+};
+
+/**
+ * Shared menu for the chat sidebar section header cog buttons. Each section
+ * passes the options it supports via `data`:
+ *
+ * - Channels: `{ showCreateChannel: true, showBrowse: true, showFilter: true, showSort: true }`
+ * - Starred: `{ showFilter: true, showSort: true }`
+ * - Direct messages: `{ showNewMessage: true, showFilter: true, showSort: true }`
+ */
+export default class ChatChannelListSidebarMenu extends Component {
+ @service chat;
+ @service chatChannelListPreferences;
+ @service currentUser;
+ @service modal;
+ @service router;
+
+ get showCreateChannel() {
+ return this.args.data?.showCreateChannel && this.currentUser?.staff;
+ }
+
+ get showBrowse() {
+ return this.args.data?.showBrowse;
+ }
+
+ get showFilter() {
+ return this.args.data?.showFilter;
+ }
+
+ get showSort() {
+ return this.args.data?.showSort;
+ }
+
+ get showNewMessage() {
+ return this.args.data?.showNewMessage && this.chat.userCanDirectMessage;
+ }
+
+ get hasTopLevelActions() {
+ return this.showCreateChannel || this.showBrowse || this.showNewMessage;
+ }
+
+ get currentFilterLabel() {
+ return i18n(
+ FILTER_LABEL_KEYS[this.chatChannelListPreferences.filterFor(this.section)]
+ );
+ }
+
+ get currentFilterAriaLabel() {
+ return i18n("chat.channel_list.options.current_filter", {
+ filter: this.currentFilterLabel,
+ });
+ }
+
+ get section() {
+ return this.args.data?.section ?? "channels";
+ }
+
+ get currentSortLabel() {
+ return i18n(
+ SORT_LABEL_KEYS[this.chatChannelListPreferences.sortFor(this.section)]
+ );
+ }
+
+ get currentSortAriaLabel() {
+ return i18n("chat.channel_list.options.current_sort", {
+ sort: this.currentSortLabel,
+ });
+ }
+
+ @action
+ openCreateChannel() {
+ this.modal.show(ChatModalCreateChannel);
+ this.args.close?.();
+ }
+
+ @action
+ openNewMessage() {
+ this.modal.show(ChatModalNewMessage);
+ this.args.close?.();
+ }
+
+ @action
+ async browseChannels() {
+ await this.args.close?.();
+ await this.router.transitionTo("chat.browse.open");
+ }
+
+ <template>
+ <DDropdownMenu
+ class="chat-channel-list-options-menu"
+ role="none"
+ ...attributes
+ as |dropdown|
+ >
+ {{#if this.showCreateChannel}}
+ <dropdown.item role="none">
+ <DButton
+ data-menu-option-id="createChannel"
+ role="menuitem"
+ @action={{this.openCreateChannel}}
+ @label="chat.channels_list_popup.create"
+ @suffixIcon="plus"
+ />
+ </dropdown.item>
+ {{/if}}
+
+ {{#if this.showBrowse}}
+ <dropdown.item role="none">
+ <DButton
+ data-menu-option-id="browseChannels"
+ role="menuitem"
+ @action={{this.browseChannels}}
+ @label="chat.channels_list_popup.browse"
+ />
+ </dropdown.item>
+ {{/if}}
+
+ {{#if this.showNewMessage}}
+ <dropdown.item role="none">
+ <DButton
+ data-menu-option-id="startDm"
+ role="menuitem"
+ @action={{this.openNewMessage}}
+ @label="chat.direct_messages.new"
+ @suffixIcon="plus"
+ />
+ </dropdown.item>
+ {{/if}}
+
+ {{#if this.hasTopLevelActions}}
+ <dropdown.divider role="none" />
+ {{/if}}
+
+ {{#if this.showFilter}}
+ <dropdown.subheader role="presentation">
+ {{i18n "chat.channel_list.options.filter"}}
+ </dropdown.subheader>
+
+ <dropdown.item role="none">
+ <DMenu
+ aria-haspopup="menu"
+ data-menu-option-id="filterChannels"
+ role="menuitem"
+ @ariaLabel={{this.currentFilterAriaLabel}}
+ @contentRole="menu"
+ @groupIdentifier="chat-channel-list-options-submenu"
+ @identifier="chat-channel-list-filter-menu"
+ @label={{this.currentFilterLabel}}
+ @modalForMobile={{true}}
+ @offset={{hash mainAxis=10 crossAxis=-5}}
+ @placement="right-start"
+ >
+ <:trigger>
+ <span class="d-button__suffix-icon">{{dIcon "angle-right"}}</span>
+ </:trigger>
+ <:content as |submenu|>
+ <ChatChannelListFilterMenu
+ @closeParent={{@close}}
+ @closeSubmenu={{submenu.close}}
+ @section={{this.section}}
+ />
+ </:content>
+ </DMenu>
+ </dropdown.item>
+ {{/if}}
+
+ {{#if this.showSort}}
+ <dropdown.subheader role="presentation">
+ {{i18n "chat.channel_list.options.sort"}}
+ </dropdown.subheader>
+
+ <dropdown.item role="none">
+ <DMenu
+ aria-haspopup="menu"
+ data-menu-option-id="sortChannels"
+ role="menuitem"
+ @ariaLabel={{this.currentSortAriaLabel}}
+ @contentRole="menu"
+ @groupIdentifier="chat-channel-list-options-submenu"
+ @identifier="chat-channel-list-sort-menu"
+ @label={{this.currentSortLabel}}
+ @modalForMobile={{true}}
+ @offset={{hash mainAxis=10 crossAxis=-5}}
+ @placement="right-start"
+ >
+ <:trigger>
+ <span class="d-button__suffix-icon">
+ {{dIcon "angle-right"}}
+ </span>
+ </:trigger>
+ <:content as |submenu|>
+ <ChatChannelListSortMenu
+ @closeParent={{@close}}
+ @closeSubmenu={{submenu.close}}
+ @section={{this.section}}
+ />
+ </:content>
+ </DMenu>
+ </dropdown.item>
+ {{/if}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sort-choice.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sort-choice.gjs
new file mode 100644
index 00000000000..2e4e8978179
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sort-choice.gjs
@@ -0,0 +1,85 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+import { CHAT_CHANNEL_LIST_SORTS } from "discourse/plugins/chat/discourse/lib/chat-constants";
+
+export const SORT_OPTIONS = [
+ {
+ value: CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL,
+ className: "chat-channel-list-sort-menu__alphabetical",
+ dataOptionId: "alphabetical",
+ labelKey: "chat.channel_list.sort.alphabetical",
+ },
+ {
+ value: CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY,
+ className: "chat-channel-list-sort-menu__recent-activity",
+ dataOptionId: "recent_activity",
+ labelKey: "chat.channel_list.sort.recent_activity",
+ },
+ {
+ value: CHAT_CHANNEL_LIST_SORTS.PRIORITY,
+ className: "chat-channel-list-sort-menu__priority --with-description",
+ dataOptionId: "priority",
+ descriptionKey: "chat.channel_list.sort.priority_description",
+ labelKey: "chat.channel_list.sort.priority",
+ },
+];
+
+/**
+ * A single sort radio row for the channel list menus. Rendered either inside
+ * the standalone sort menu (drawer, mobile, fly-out submenus) or inline in a
+ * section header menu that has no other list options to fly out.
+ */
+export default class ChatChannelListSortChoice extends Component {
+ @service chatChannelListPreferences;
+
+ get isCurrentSort() {
+ return (
+ this.chatChannelListPreferences.sortFor(this.args.section) ===
+ this.args.choice.value
+ );
+ }
+
+ get isSavingSort() {
+ return this.chatChannelListPreferences.isSavingSortFor(this.args.section);
+ }
+
+ @action
+ async selectSort(sort) {
+ const section = this.args.section;
+ const preferences = this.chatChannelListPreferences;
+
+ await this.args.closeSubmenu?.();
+ await this.args.close?.();
+ await this.args.closeParent?.();
+ await preferences.setSort(section, sort);
+ }
+
+ <template>
+ <li class="dropdown-menu__item chat-channel-list-sort-choice" role="none">
+ <DButton
+ aria-checked={{if this.isCurrentSort "true" "false"}}
+ class={{@choice.className}}
+ data-menu-option-id={{@choice.dataOptionId}}
+ role="menuitemradio"
+ @action={{this.selectSort}}
+ @actionParam={{@choice.value}}
+ @disabled={{this.isSavingSort}}
+ @icon="check"
+ >
+ <span class="chat-channel-list-sort-menu__label">
+ <span class="chat-channel-list-sort-menu__label-title">
+ {{i18n @choice.labelKey}}
+ </span>
+ {{#if @choice.descriptionKey}}
+ <span class="chat-channel-list-sort-menu__label-description">
+ {{i18n @choice.descriptionKey}}
+ </span>
+ {{/if}}
+ </span>
+ </DButton>
+ </li>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sort-menu.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sort-menu.gjs
new file mode 100644
index 00000000000..bb3b99b25d5
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-list-sort-menu.gjs
@@ -0,0 +1,29 @@
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import ChatChannelListSortChoice, {
+ SORT_OPTIONS,
+} from "./chat-channel-list-sort-choice";
+
+export default <template>
+ <DDropdownMenu
+ aria-label={{i18n "chat.channel_list.sort.title"}}
+ class="chat-channel-list-sort-menu"
+ role="group"
+ ...attributes
+ as |dropdown|
+ >
+ <dropdown.subheader role="presentation">
+ {{i18n "chat.channel_list.sort.title"}}
+ </dropdown.subheader>
+
+ {{#each SORT_OPTIONS as |choice|}}
+ <ChatChannelListSortChoice
+ @choice={{choice}}
+ @close={{@close}}
+ @closeParent={{@closeParent}}
+ @closeSubmenu={{@closeSubmenu}}
+ @section={{@section}}
+ />
+ {{/each}}
+ </DDropdownMenu>
+</template>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-sidebar-context-menu.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-sidebar-context-menu.gjs
index 0639a40d25a..2c8ad355086 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-sidebar-context-menu.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-sidebar-context-menu.gjs
@@ -1,5 +1,4 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import { service } from "@ember/service";
import { popupAjaxError } from "discourse/lib/ajax-error";
@@ -15,8 +14,6 @@ export default class ChatChannelSidebarContextMenu extends Component {
@service chatChannelsManager;
@service currentUser;
- @tracked isTogglingStarred;
-
get channel() {
return this.args.data.channel;
}
@@ -25,6 +22,10 @@ export default class ChatChannelSidebarContextMenu extends Component {
return this.channel?.currentUserMembership;
}
+ get isTogglingStarred() {
+ return this.chatChannelsManager.isUpdatingStarred(this.channel);
+ }
+
get starIcon() {
return this.currentUserMembership?.starred ? "star" : "far-star";
}
@@ -43,27 +44,15 @@ export default class ChatChannelSidebarContextMenu extends Component {
@action
async toggleStarred() {
- if (!this.currentUserMembership || this.isTogglingStarred) {
- return;
- }
-
- this.isTogglingStarred = true;
- const previousValue = this.currentUserMembership.starred;
- const newValue = !previousValue;
-
- this.currentUserMembership.starred = newValue;
-
- try {
- await this.chatApi.updateCurrentUserChannelMembership(this.channel.id, {
- starred: newValue,
- });
- this.args.close();
- } catch (err) {
- this.currentUserMembership.starred = previousValue;
- popupAjaxError(err);
- } finally {
- this.isTogglingStarred = false;
- }
+ const channel = this.channel;
+ const menuIdentifier = channel.isDirectMessageChannel
+ ? "chat-direct-message-channel-menu"
+ : "chat-channel-menu";
+ const menu = this.menu;
+
+ await this.chatChannelsManager.toggleStarred(channel, {
+ beforeUpdate: () => menu.close(menuIdentifier),
+ });
}
@action
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-channel-list-filter-empty-state.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-channel-list-filter-empty-state.gjs
new file mode 100644
index 00000000000..b3a542e831e
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-channel-list-filter-empty-state.gjs
@@ -0,0 +1,67 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import DEmptyState from "discourse/ui-kit/d-empty-state";
+import { i18n } from "discourse-i18n";
+import { CHAT_CHANNEL_LIST_FILTERS } from "discourse/plugins/chat/discourse/lib/chat-constants";
+import ChatZero from "./svg/chat-zero";
+
+/**
+ * Shown when a chat channel list section is empty because its filter is
+ * hiding every row. `@section` (`"channels"`, `"starred"`, or `"dms"`) picks
+ * which section's filter the "show all" button resets. In the cover sidebar
+ * the state is a slim section-list item; with `@layout="empty-state"` (used
+ * by the drawer and mobile channel lists) it renders the same illustrated
+ * empty state as the "no channels" DEmptyState so the two look alike.
+ */
+export default class ChatSidebarChannelListFilterEmptyState extends Component {
+ @service chatChannelListPreferences;
+ @service sidebarState;
+
+ get section() {
+ return this.args.section ?? "channels";
+ }
+
+ get isSaving() {
+ return this.chatChannelListPreferences.isSavingFilterFor(this.section);
+ }
+
+ get isEmptyStateLayout() {
+ return this.args.layout === "empty-state";
+ }
+
+ @action
+ showAll() {
+ return this.chatChannelListPreferences.setFilter(
+ this.section,
+ CHAT_CHANNEL_LIST_FILTERS.ALL
+ );
+ }
+
+ <template>
+ {{#unless this.sidebarState.filter}}
+ {{#if this.isEmptyStateLayout}}
+ <DEmptyState
+ @ctaAction={{this.showAll}}
+ @ctaLabel={{i18n "chat.channel_list.empty.show_all"}}
+ @identifier="empty-channels-list"
+ @svgContent={{ChatZero}}
+ @title={{i18n "chat.channel_list.empty.filtered"}}
+ />
+ {{else}}
+ <li class="chat-sidebar-channels-filter-empty-state" ...attributes>
+ <span class="chat-sidebar-channels-filter-empty-state__text">
+ {{i18n "chat.channel_list.empty.filtered"}}
+ </span>
+ <DButton
+ class="btn-transparent chat-sidebar-channels-filter-empty-state__reset"
+ @action={{this.showAll}}
+ @disabled={{this.isSaving}}
+ @label="chat.channel_list.empty.show_all"
+ />
+ </li>
+ {{/if}}
+ {{/unless}}
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-dms-filter-empty-state.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-dms-filter-empty-state.gjs
new file mode 100644
index 00000000000..c3c64826d04
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-dms-filter-empty-state.gjs
@@ -0,0 +1,5 @@
+import ChatSidebarChannelListFilterEmptyState from "discourse/plugins/chat/discourse/components/chat-sidebar-channel-list-filter-empty-state";
+
+export default <template>
+ <ChatSidebarChannelListFilterEmptyState @section="dms" />
+</template>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-starred-filter-empty-state.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-starred-filter-empty-state.gjs
new file mode 100644
index 00000000000..d43e00a27b3
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-sidebar-starred-filter-empty-state.gjs
@@ -0,0 +1,5 @@
+import ChatSidebarChannelListFilterEmptyState from "discourse/plugins/chat/discourse/components/chat-sidebar-channel-list-filter-empty-state";
+
+export default <template>
+ <ChatSidebarChannelListFilterEmptyState @section="starred" />
+</template>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
index e4fbce851c7..dc31784b95e 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
@@ -1,5 +1,4 @@
import { hash } from "@ember/helper";
-import BrowseChannelsButton from "./browse-channels-button";
import CloseDrawerButton from "./close-drawer-button";
import ClosePinsButton from "./close-pins-button";
import CloseThreadButton from "./close-thread-button";
@@ -7,7 +6,6 @@ import CloseThreadsButton from "./close-threads-button";
import Filter from "./filter";
import FullPageButton from "./full-page-button";
import NewChannelButton from "./new-channel-button";
-import NewDirectMessageButton from "./new-direct-message-button";
import OpenDrawerButton from "./open-drawer-button";
import PinnedMessagesButton from "./pinned-messages-button";
import ThreadSettingsButton from "./thread-settings-button";
@@ -20,8 +18,6 @@ const ChatNavbarActions = <template>
{{yield
(hash
OpenDrawerButton=OpenDrawerButton
- BrowseChannelsButton=BrowseChannelsButton
- NewDirectMessageButton=NewDirectMessageButton
NewChannelButton=NewChannelButton
ThreadTrackingDropdown=ThreadTrackingDropdown
CloseThreadButton=CloseThreadButton
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjs
deleted file mode 100644
index 5be0f8c4a2a..00000000000
--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjs
+++ /dev/null
@@ -1,30 +0,0 @@
-import Component from "@glimmer/component";
-import { LinkTo } from "@ember/routing";
-import { service } from "@ember/service";
-import dIcon from "discourse/ui-kit/helpers/d-icon";
-import { i18n } from "discourse-i18n";
-
-export default class ChatNavbarBrowseChannelsButton extends Component {
- @service router;
- @service currentUser;
-
- browseChannelsLabel = i18n("chat.channels_list_popup.browse");
-
- get showBrowseChannelsButton() {
- return (
- this.currentUser && this.router.currentRoute.name === "chat.channels"
- );
- }
-
- <template>
- {{#if this.showBrowseChannelsButton}}
- <LinkTo
- class="btn no-text btn-flat c-navbar__browse-button"
- title={{this.browseChannelsLabel}}
- @route="chat.browse"
- >
- {{dIcon "pencil"}}
- </LinkTo>
- {{/if}}
- </template>
-}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-list-options-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-list-options-button.gjs
new file mode 100644
index 00000000000..25a3d641ab9
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-list-options-button.gjs
@@ -0,0 +1,23 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import ChatChannelListOptionsButton from "../../chat-channel-list-options-button";
+
+/**
+ * Mobile navbar action that opens the shared channel list menu
+ * (filter/sort/browse/create) for a section. On mobile the channel lists hide
+ * their in-list section divider (the cover sidebar and desktop drawer are not
+ * available), so the options menu lives in the route navbar instead.
+ */
+export default class ChatNavbarChannelListOptionsButton extends Component {
+ @service site;
+
+ get showButton() {
+ return this.site.mobileView;
+ }
+
+ <template>
+ {{#if this.showButton}}
+ <ChatChannelListOptionsButton @section={{@section}} />
+ {{/if}}
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/new-direct-message-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/new-direct-message-button.gjs
deleted file mode 100644
index 2a08ba6d61c..00000000000
--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/new-direct-message-button.gjs
+++ /dev/null
@@ -1,41 +0,0 @@
-import Component from "@glimmer/component";
-import { action } from "@ember/object";
-import { service } from "@ember/service";
-import DButton from "discourse/ui-kit/d-button";
-import { i18n } from "discourse-i18n";
-import ChatModalNewMessage from "discourse/plugins/chat/discourse/components/chat/modal/new-message";
-
-export default class ChatNavbarNewDirectMessageButton extends Component {
- @service router;
- @service modal;
- @service chat;
-
- buttonLabel = i18n("chat.channels_list_popup.browse");
-
- get showButtonComponent() {
- return (
- this.router.currentRoute.name === "chat.direct-messages" &&
- this.canCreateDirectMessageChannel
- );
- }
-
- get canCreateDirectMessageChannel() {
- return this.chat.userCanDirectMessage;
- }
-
- @action
- openNewMessageModal() {
- this.modal.show(ChatModalNewMessage);
- }
-
- <template>
- {{#if this.showButtonComponent}}
- <DButton
- class="btn no-text btn-flat c-navbar__new-dm-button"
- title={{this.buttonLabel}}
- @action={{this.openNewMessageModal}}
- @icon="plus"
- />
- {{/if}}
- </template>
-}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs
index df4eb3c57bc..5c51293ac3e 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs
@@ -1,6 +1,7 @@
import { i18n } from "discourse-i18n";
import ChannelsListPublic from "../../channels-list-public";
import Navbar from "../navbar";
+import ChannelListOptionsButton from "../navbar/channel-list-options-button";
const ChatRoutesChannels = <template>
<div class="c-routes --channels">
@@ -8,7 +9,7 @@ const ChatRoutesChannels = <template>
<navbar.Title @title={{i18n "chat.chat_channels"}} />
<navbar.Actions as |action|>
<action.OpenDrawerButton />
- <action.BrowseChannelsButton />
+ <ChannelListOptionsButton @section="channels" />
</navbar.Actions>
</Navbar>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/direct-messages.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/direct-messages.gjs
index 4c0a05f32e6..460344a79cc 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/direct-messages.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/direct-messages.gjs
@@ -1,6 +1,7 @@
import { i18n } from "discourse-i18n";
import ChannelsListDirect from "../../channels-list-direct";
import Navbar from "../navbar";
+import ChannelListOptionsButton from "../navbar/channel-list-options-button";
const ChatRoutesDirectMessages = <template>
<div class="c-routes --direct-messages">
@@ -8,7 +9,7 @@ const ChatRoutesDirectMessages = <template>
<navbar.Title @title={{i18n "chat.direct_messages.title"}} />
<navbar.Actions as |action|>
<action.OpenDrawerButton />
- <action.NewDirectMessageButton />
+ <ChannelListOptionsButton @section="dms" />
</navbar.Actions>
</Navbar>
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.gjs
index b4aee5fef24..bd43d6d089d 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/starred-channels.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/starred-channels.gjs
@@ -1,14 +1,15 @@
import { i18n } from "discourse-i18n";
import ChannelsListStarred from "../../channels-list-starred";
import Navbar from "../navbar";
+import ChannelListOptionsButton from "../navbar/channel-list-options-button";
const ChatRoutesStarredChannels = <template>
<div class="c-routes --starred-channels">
<Navbar as |navbar|>
<navbar.Title @title={{i18n "chat.starred"}} />
<navbar.Actions as |action|>
-
<action.OpenDrawerButton />
+ <ChannelListOptionsButton @section="starred" />
</navbar.Actions>
</Navbar>
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js
index ffe5f666eb2..1d1bec96958 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js
@@ -11,9 +11,13 @@ import { withPluginApi } from "discourse/lib/plugin-api";
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 ChatChannelListSidebarMenu from "discourse/plugins/chat/discourse/components/chat-channel-list-sidebar-menu";
import ChatChannelSidebarContextMenu from "discourse/plugins/chat/discourse/components/chat-channel-sidebar-context-menu";
+import ChatSidebarChannelListFilterEmptyState from "discourse/plugins/chat/discourse/components/chat-sidebar-channel-list-filter-empty-state";
+import ChatSidebarDmsFilterEmptyState from "discourse/plugins/chat/discourse/components/chat-sidebar-dms-filter-empty-state";
import ChatSidebarIndicators from "discourse/plugins/chat/discourse/components/chat-sidebar-indicators";
+import ChatSidebarStarredFilterEmptyState from "discourse/plugins/chat/discourse/components/chat-sidebar-starred-filter-empty-state";
+import { CHANNEL_LIST_SECTION_OPTIONS } from "discourse/plugins/chat/discourse/lib/chat-channel-list-options";
import {
CHAT_PANEL,
initSidebarState,
@@ -240,6 +244,23 @@ function createChannelLink(BaseCustomSidebarSectionLink, options = {}) {
};
}
+function channelListOptionsAction(section, menuService) {
+ return {
+ id: "channelListOptions",
+ title: i18n("chat.channel_list.options.title"),
+ action: (event) => {
+ menuService.show(event.currentTarget, {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ modalForMobile: true,
+ placement: "right-start",
+ data: { section, ...CHANNEL_LIST_SECTION_OPTIONS[section] },
+ });
+ },
+ };
+}
+
export default {
name: "chat-sidebar",
initialize(container) {
@@ -440,11 +461,14 @@ export default {
this.chatChannelsManager = container.lookup(
"service:chat-channels-manager"
);
+ this.chatChannelListPreferences = container.lookup(
+ "service:chat-channel-list-preferences"
+ );
this.menuService = container.lookup("service:menu");
}
get sectionLinks() {
- return this.chatChannelsManager.starredChannels.map(
+ return this.chatChannelsManager.starredChannelsByPreference.map(
(channel) =>
new SidebarChatStarredChannelLink({
channel,
@@ -473,12 +497,33 @@ export default {
return this.sectionLinks;
}
+ get emptyStateComponent() {
+ if (
+ !this.chatChannelListPreferences.isDefaultFilterFor("starred")
+ ) {
+ return ChatSidebarStarredFilterEmptyState;
+ }
+ }
+
get displaySection() {
return (
this.chatStateManager.hasPreloadedChannels &&
- this.chatChannelsManager.hasStarredChannels
+ (this.chatChannelsManager.starredChannelsByPreference.length >
+ 0 ||
+ (this.chatChannelsManager.hasStarredChannels &&
+ !this.chatChannelListPreferences.isDefaultFilterFor(
+ "starred"
+ )))
);
}
+
+ get actions() {
+ return [channelListOptionsAction("starred", this.menuService)];
+ }
+
+ get actionsIcon() {
+ return "ellipsis-vertical";
+ }
};
return SidebarChatStarredChannelsSection;
@@ -636,12 +681,14 @@ export default {
this.chatChannelsManager = container.lookup(
"service:chat-channels-manager"
);
- this.router = container.lookup("service:router");
+ this.chatChannelListPreferences = container.lookup(
+ "service:chat-channel-list-preferences"
+ );
this.menuService = container.lookup("service:menu");
}
get sectionLinks() {
- return this.chatChannelsManager.unstarredPublicMessageChannels.map(
+ return this.chatChannelsManager.sidebarPublicMessageChannels.map(
(channel) =>
new SidebarChatChannelsSectionLink({
channel,
@@ -653,6 +700,16 @@ export default {
);
}
+ get emptyStateComponent() {
+ if (
+ !this.chatChannelListPreferences.isDefaultFilterFor(
+ "channels"
+ )
+ ) {
+ return ChatSidebarChannelListFilterEmptyState;
+ }
+ }
+
get name() {
return "chat-channels";
}
@@ -670,17 +727,11 @@ export default {
return [];
}
- return [
- {
- id: "browseChannels",
- title: i18n("chat.channels_list_popup.browse"),
- action: () => this.router.transitionTo("chat.browse.open"),
- },
- ];
+ return [channelListOptionsAction("channels", this.menuService)];
}
get actionsIcon() {
- return "pencil";
+ return "ellipsis-vertical";
}
get links() {
@@ -690,8 +741,12 @@ export default {
get displaySection() {
return (
this.chatStateManager.hasPreloadedChannels &&
- (this.sectionLinks.length > 0 ||
- this.currentUserCanJoinPublicChannels)
+ (this.chatChannelsManager.unstarredPublicMessageChannels
+ .length > 0 ||
+ this.currentUserCanJoinPublicChannels ||
+ !this.chatChannelListPreferences.isDefaultFilterFor(
+ "channels"
+ ))
);
}
};
@@ -900,7 +955,6 @@ export default {
const SidebarChatDirectMessagesSection = class extends BaseCustomSidebarSection {
@service site;
- @service modal;
@service router;
@service currentUser;
@service chatStateManager;
@@ -917,20 +971,22 @@ export default {
this.chatChannelsManager = container.lookup(
"service:chat-channels-manager"
);
+ this.chatChannelListPreferences = container.lookup(
+ "service:chat-channel-list-preferences"
+ );
this.menuService = container.lookup("service:menu");
}
get hideSectionHeader() {
return (
- this.chatChannelsManager
- .truncatedUnstarredDirectMessageChannels.length === 0
+ this.chatChannelsManager.unstarredDirectMessageChannels
+ .length === 0
);
}
get sectionLinks() {
const channels =
- this.chatChannelsManager
- .truncatedUnstarredDirectMessageChannels;
+ this.chatChannelsManager.sidebarDirectMessageChannels;
if (channels.length > 0) {
return channels.map(
@@ -943,9 +999,14 @@ export default {
siteSettings: this.siteSettings,
})
);
- } else {
+ } else if (
+ this.chatChannelsManager.unstarredDirectMessageChannels
+ .length === 0
+ ) {
return [new SidebarChatNewDirectMessagesSectionLink()];
}
+
+ return [];
}
get name() {
@@ -961,29 +1022,33 @@ export default {
}
get actions() {
- return [
- {
- id: "startDm",
- title: i18n("chat.direct_messages.new"),
- action: () => {
- this.modal.show(ChatModalNewMessage);
- },
- },
- ];
+ return [channelListOptionsAction("dms", this.menuService)];
}
get actionsIcon() {
- return "plus";
+ return "ellipsis-vertical";
}
get links() {
return this.sectionLinks;
}
+ get emptyStateComponent() {
+ if (
+ !this.chatChannelListPreferences.isDefaultFilterFor("dms")
+ ) {
+ return ChatSidebarDmsFilterEmptyState;
+ }
+ }
+
get displaySection() {
return (
this.chatStateManager.hasPreloadedChannels &&
- this.sectionLinks?.length > 0
+ (this.chatChannelsManager.sidebarDirectMessageChannels
+ .length > 0 ||
+ this.chatChannelsManager.unstarredDirectMessageChannels
+ .length === 0 ||
+ !this.chatChannelListPreferences.isDefaultFilterFor("dms"))
);
}
};
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js
index 5598ad49921..9514e4cc219 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js
@@ -10,6 +10,12 @@ export default {
if (chat_enabled) {
// Chat settings
api.addSaveableUserOption("chat_announce_new_messages");
+ api.addSaveableUserOption("chat_channel_list_filter");
+ api.addSaveableUserOption("chat_channel_list_filter_starred");
+ api.addSaveableUserOption("chat_channel_list_filter_dms");
+ api.addSaveableUserOption("chat_channel_list_sort");
+ api.addSaveableUserOption("chat_channel_list_sort_starred");
+ api.addSaveableUserOption("chat_channel_list_sort_dms");
api.addSaveableUserOption("chat_new_message_sound");
api.addSaveableUserOption("chat_enabled");
api.addSaveableUserOption("chat_quick_reaction_type");
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-list-options.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-list-options.js
new file mode 100644
index 00000000000..64a96098dff
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-list-options.js
@@ -0,0 +1,15 @@
+/**
+ * Options exposed by the shared chat channel list menu for each sidebar /
+ * drawer / mobile section. Used by the cover sidebar section headers and by
+ * the non-sidebar list headers so both stay in sync.
+ */
+export const CHANNEL_LIST_SECTION_OPTIONS = {
+ channels: {
+ showCreateChannel: true,
+ showBrowse: true,
+ showFilter: true,
+ showSort: true,
+ },
+ starred: { showFilter: true, showSort: true },
+ dms: { showNewMessage: true, showFilter: true, showSort: true },
+};
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js
index 6846f8c2fe8..9e63cc7663f 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js
@@ -27,6 +27,18 @@ export const CHAT_ATTRS = [
"chat_quick_reactions_custom",
];
+export const CHAT_CHANNEL_LIST_FILTERS = Object.freeze({
+ ALL: "all",
+ ACTIVE: "active",
+ UNREAD: "unread",
+ MENTIONS: "mentions",
+});
+export const CHAT_CHANNEL_LIST_SORTS = Object.freeze({
+ ALPHABETICAL: "alphabetical",
+ RECENT_ACTIVITY: "recent_activity",
+ PRIORITY: "priority",
+});
+export const CHAT_CHANNEL_LIST_ACTIVE_DAYS = 30;
export const CHAT_QUICK_REACTIONS_CUSTOM_DEFAULT = "heart|+1|smile";
export const HEADER_INDICATOR_PREFERENCE_NEVER = "never";
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-channel-list-preferences.js b/plugins/chat/assets/javascripts/discourse/services/chat-channel-list-preferences.js
new file mode 100644
index 00000000000..0edf633d691
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-channel-list-preferences.js
@@ -0,0 +1,178 @@
+import { tracked } from "@glimmer/tracking";
+import Service, { service } from "@ember/service";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import {
+ CHAT_CHANNEL_LIST_FILTERS,
+ CHAT_CHANNEL_LIST_SORTS,
+} from "discourse/plugins/chat/discourse/lib/chat-constants";
+
+const VALID_FILTERS = new Set(Object.values(CHAT_CHANNEL_LIST_FILTERS));
+const VALID_SORTS = new Set(Object.values(CHAT_CHANNEL_LIST_SORTS));
+
+const SECTIONS = {
+ channels: {
+ filter: {
+ field: "chat_channel_list_filter",
+ value: "channelsFilter",
+ saving: "isSavingChannelsFilter",
+ },
+ sort: {
+ field: "chat_channel_list_sort",
+ value: "channelsSort",
+ saving: "isSavingChannelsSort",
+ },
+ },
+ starred: {
+ filter: {
+ field: "chat_channel_list_filter_starred",
+ value: "starredFilter",
+ saving: "isSavingStarredFilter",
+ },
+ sort: {
+ field: "chat_channel_list_sort_starred",
+ value: "starredSort",
+ saving: "isSavingStarredSort",
+ },
+ },
+ dms: {
+ filter: {
+ field: "chat_channel_list_filter_dms",
+ value: "dmsFilter",
+ saving: "isSavingDmsFilter",
+ },
+ sort: {
+ field: "chat_channel_list_sort_dms",
+ value: "dmsSort",
+ saving: "isSavingDmsSort",
+ },
+ },
+};
+
+export default class ChatChannelListPreferences extends Service {
+ @service currentUser;
+
+ @tracked channelsFilter;
+ @tracked starredFilter;
+ @tracked dmsFilter;
+ @tracked channelsSort;
+ @tracked starredSort;
+ @tracked dmsSort;
+ @tracked isSavingChannelsFilter = false;
+ @tracked isSavingStarredFilter = false;
+ @tracked isSavingDmsFilter = false;
+ @tracked isSavingChannelsSort = false;
+ @tracked isSavingStarredSort = false;
+ @tracked isSavingDmsSort = false;
+
+ constructor() {
+ super(...arguments);
+
+ const userOption = this.currentUser?.user_option;
+ this.channelsFilter = this.#validFilter(
+ userOption?.chat_channel_list_filter
+ );
+ this.starredFilter = this.#validFilter(
+ userOption?.chat_channel_list_filter_starred
+ );
+ this.dmsFilter = this.#validFilter(
+ userOption?.chat_channel_list_filter_dms
+ );
+ this.channelsSort = this.#validSort(userOption?.chat_channel_list_sort);
+ this.starredSort = this.#validSort(
+ userOption?.chat_channel_list_sort_starred
+ );
+ this.dmsSort = this.#validSort(userOption?.chat_channel_list_sort_dms);
+ }
+
+ /** The filter preference for a section: `"channels"`, `"starred"`, or `"dms"`. */
+ filterFor(section) {
+ return (
+ this[this.#section(section).filter.value] ?? CHAT_CHANNEL_LIST_FILTERS.ALL
+ );
+ }
+
+ isDefaultFilterFor(section) {
+ return this.filterFor(section) === CHAT_CHANNEL_LIST_FILTERS.ALL;
+ }
+
+ isSavingFilterFor(section) {
+ return this[this.#section(section).filter.saving];
+ }
+
+ /** The sort preference for a section: `"channels"`, `"starred"`, or `"dms"`. */
+ sortFor(section) {
+ return (
+ this[this.#section(section).sort.value] ??
+ CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL
+ );
+ }
+
+ isSavingSortFor(section) {
+ return this[this.#section(section).sort.saving];
+ }
+
+ async setFilter(section, filter) {
+ if (!SECTIONS[section]) {
+ return false;
+ }
+ if (!VALID_FILTERS.has(filter)) {
+ return false;
+ }
+
+ const { field, value, saving } = SECTIONS[section].filter;
+ return await this.#save(field, value, saving, filter);
+ }
+
+ async setSort(section, sort) {
+ if (!SECTIONS[section]) {
+ return false;
+ }
+ if (!VALID_SORTS.has(sort)) {
+ return false;
+ }
+
+ const { field, value, saving } = SECTIONS[section].sort;
+ return await this.#save(field, value, saving, sort);
+ }
+
+ #section(section) {
+ return SECTIONS[section] ?? SECTIONS.channels;
+ }
+
+ #validFilter(value) {
+ return VALID_FILTERS.has(value) ? value : CHAT_CHANNEL_LIST_FILTERS.ALL;
+ }
+
+ #validSort(value) {
+ return VALID_SORTS.has(value)
+ ? value
+ : CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL;
+ }
+
+ async #save(fieldName, propertyName, savingPropertyName, value) {
+ if (!this.currentUser || this[savingPropertyName]) {
+ return false;
+ }
+
+ if (this[propertyName] === value) {
+ return true;
+ }
+
+ const previousValue = this[propertyName];
+ this[propertyName] = value;
+ this.currentUser.set(`user_option.${fieldName}`, value);
+ this[savingPropertyName] = true;
+
+ try {
+ await this.currentUser.save([fieldName]);
+ return true;
+ } catch (error) {
+ this[propertyName] = previousValue;
+ this.currentUser.set(`user_option.${fieldName}`, previousValue);
+ popupAjaxError(error);
+ return false;
+ } finally {
+ this[savingPropertyName] = false;
+ }
+ }
+}
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js
index a2648afe4c5..57b6758571e 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js
@@ -1,10 +1,15 @@
import { cached, tracked } from "@glimmer/tracking";
-import { trackedObject } from "@ember/reactive/collections";
+import { trackedObject, trackedSet } from "@ember/reactive/collections";
import Service, { service } from "@ember/service";
import Promise from "rsvp";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { AUTO_GROUPS } from "discourse/lib/constants";
import { debounce } from "discourse/lib/decorators";
+import {
+ CHAT_CHANNEL_LIST_ACTIVE_DAYS,
+ CHAT_CHANNEL_LIST_FILTERS,
+ CHAT_CHANNEL_LIST_SORTS,
+} from "discourse/plugins/chat/discourse/lib/chat-constants";
import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";
import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";
@@ -17,7 +22,9 @@ const DIRECT_MESSAGE_CHANNELS_LIMIT = 50;
*/
export default class ChatChannelsManager extends Service {
+ @service chat;
@service chatApi;
+ @service chatChannelListPreferences;
@service chatSubscriptionsManager;
@service chatStateManager;
@service currentUser;
@@ -25,6 +32,7 @@ export default class ChatChannelsManager extends Service {
@service siteSettings;
@tracked userHasThreads = false;
+ #pendingStarredUpdates = trackedSet();
@tracked _cached = trackedObject();
@cached
@@ -85,15 +93,17 @@ export default class ChatChannelsManager extends Service {
}
/**
- * Returns all public message channels sorted by activity (unreads first).
- * Used in mobile/drawer mode where starred channels appear in both tabs.
+ * Returns all public message channels filtered and sorted by the user's
+ * channel list preferences. Used in mobile/drawer mode where starred
+ * channels also appear in the channels tab.
*
- * @returns {ChatChannel[]} Array of public channels sorted by activity
+ * @returns {ChatChannel[]} Array of public channels sorted by preference
*/
- get allPublicChannelsByActivity() {
- return this.#sortChannelsByActivityUnreadsFirst([
- ...this.publicMessageChannels,
- ]);
+ get publicMessageChannelsByPreference() {
+ return this.#filterAndSortSidebarChannels(
+ this.publicMessageChannels,
+ "channels"
+ );
}
/**
@@ -134,22 +144,26 @@ export default class ChatChannelsManager extends Service {
}
/**
- * Returns all direct message channels sorted by activity (unreads first).
- * Used in mobile/drawer mode where starred channels appear in both tabs.
+ * Returns all direct message channels filtered and sorted by the user's
+ * channel list preferences. Used in mobile/drawer mode where starred
+ * channels also appear in the DM tab.
*
- * @returns {ChatChannel[]} Array of DM channels sorted by activity
+ * @returns {ChatChannel[]} Array of DM channels sorted by preference
*/
- get directMessageChannelsByActivity() {
- return this.#sortDirectMessageChannelsByActivity(
+ get directMessageChannelsByPreference() {
+ // Not `directMessageChannels`: its comparator dereferences `lastMessage.id`
+ // unguarded, so a channel with no messages throws before this re-sorts.
+ return this.#filterAndSortSidebarChannels(
this.channels.filter((channel) => {
const membership = channel.currentUserMembership;
return channel.isDirectMessageChannel && membership?.following;
- })
+ }),
+ "dms"
);
}
- get truncatedDirectMessageChannelsByActivity() {
- return this.directMessageChannelsByActivity.slice(
+ get truncatedDirectMessageChannelsByPreference() {
+ return this.directMessageChannelsByPreference.slice(
0,
DIRECT_MESSAGE_CHANNELS_LIMIT
);
@@ -192,64 +206,6 @@ export default class ChatChannelsManager extends Service {
return this.starredChannels.length > 0;
}
- /**
- * Returns all starred channels sorted by activity (unreads first).
- * Prioritizes unread status over channel type:
- * 1. Unread public channels (sorted by activity)
- * 2. Unread DMs/Groups (sorted by activity)
- * 3. Read public channels (sorted by activity)
- * 4. Read DMs/Groups (sorted by activity)
- *
- * @returns {ChatChannel[]} Array of starred channels sorted by activity
- */
- get starredChannelsByActivity() {
- const starredChannels = this.channels.filter(
- (channel) =>
- channel.currentUserMembership?.following &&
- channel.currentUserMembership?.starred
- );
-
- return starredChannels.sort((a, b) => {
- const aUrgent = this.#getChannelUrgentCount(a);
- const bUrgent = this.#getChannelUrgentCount(b);
- const aUnread = this.#getChannelUnreadCount(a);
- const bUnread = this.#getChannelUnreadCount(b);
-
- const aHasActivity = aUrgent > 0 || aUnread > 0;
- const bHasActivity = bUrgent > 0 || bUnread > 0;
-
- // First: prioritize channels with activity over those without
- if (aHasActivity !== bHasActivity) {
- return aHasActivity ? -1 : 1;
- }
-
- // Within the same activity state, sort by channel type (public first)
- if (a.isDirectMessageChannel !== b.isDirectMessageChannel) {
- return a.isDirectMessageChannel ? 1 : -1;
- }
-
- // Within the same channel type and activity state:
- // If both have activity, prioritize by urgent then unread
- if (aHasActivity && bHasActivity) {
- if (aUrgent > 0 && bUrgent > 0) {
- return this.#compareByLastActivity(a, b);
- }
- if (aUrgent > 0 || bUrgent > 0) {
- return aUrgent > bUrgent ? -1 : 1;
- }
- if (aUnread > 0 && bUnread > 0) {
- return this.#compareByLastActivity(a, b);
- }
- if (aUnread > 0 || bUnread > 0) {
- return aUnread > bUnread ? -1 : 1;
- }
- }
-
- // Sort remaining by last activity
- return this.#compareByLastActivity(a, b);
- });
- }
-
/**
* Returns public message channels that are not starred.
* Falls back to all public channels if starring is disabled.
@@ -270,6 +226,48 @@ export default class ChatChannelsManager extends Service {
);
}
+ get sidebarPublicMessageChannels() {
+ return this.#filterAndSortSidebarChannels(
+ this.unstarredPublicMessageChannels,
+ "channels"
+ );
+ }
+
+ get sidebarDirectMessageChannels() {
+ return this.#limitSidebarChannels(
+ this.#filterAndSortSidebarChannels(
+ this.unstarredDirectMessageChannels,
+ "dms"
+ ),
+ DIRECT_MESSAGE_CHANNELS_LIMIT
+ );
+ }
+
+ /**
+ * Returns all starred channels filtered and sorted by the user's channel
+ * list preferences. Alphabetical sorting keeps the public-then-DM grouping
+ * of `starredChannels`; other sorts order across both types.
+ *
+ * @returns {ChatChannel[]} Array of starred channels sorted by preference
+ */
+ get starredChannelsByPreference() {
+ const channels = this.#filterSidebarChannels(
+ this.starredChannels,
+ "starred"
+ );
+
+ if (
+ this.chatChannelListPreferences.sortFor("starred") ===
+ CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL
+ ) {
+ return channels;
+ }
+
+ return channels.sort((channelA, channelB) => {
+ return this.#compareSidebarChannels(channelA, channelB, "starred");
+ });
+ }
+
/**
* Returns direct message channels that are not starred.
* Falls back to all DM channels if starring is disabled.
@@ -290,13 +288,6 @@ export default class ChatChannelsManager extends Service {
);
}
- get truncatedUnstarredDirectMessageChannels() {
- return this.unstarredDirectMessageChannels.slice(
- 0,
- DIRECT_MESSAGE_CHANNELS_LIMIT
- );
- }
-
get publicMessageChannelsEmpty() {
return (
this.publicMessageChannels?.length === 0 &&
@@ -380,6 +371,39 @@ export default class ChatChannelsManager extends Service {
}
}
+ isUpdatingStarred(channel) {
+ return this.#pendingStarredUpdates.has(channel.currentUserMembership);
+ }
+
+ async toggleStarred(channel, { beforeUpdate } = {}) {
+ const membership = channel.currentUserMembership;
+
+ if (!membership || this.#pendingStarredUpdates.has(membership)) {
+ return;
+ }
+
+ this.#pendingStarredUpdates.add(membership);
+ const previousValue = membership.starred;
+ let updated = false;
+
+ try {
+ await beforeUpdate?.();
+ membership.starred = !previousValue;
+ updated = true;
+
+ await this.chatApi.updateCurrentUserChannelMembership(channel.id, {
+ starred: membership.starred,
+ });
+ } catch (error) {
+ if (updated) {
+ membership.starred = previousValue;
+ }
+ popupAjaxError(error);
+ } finally {
+ this.#pendingStarredUpdates.delete(membership);
+ }
+ }
+
async unfollow(model) {
try {
this.chatSubscriptionsManager.stopChannelSubscription(model);
@@ -442,25 +466,6 @@ export default class ChatChannelsManager extends Service {
});
}
- #getChannelUrgentCount(channel) {
- if (channel.isDirectMessageChannel) {
- return (
- channel.tracking.unreadCount +
- channel.tracking.mentionCount +
- channel.tracking.watchedThreadsUnreadCount
- );
- }
- return (
- channel.tracking.mentionCount + channel.tracking.watchedThreadsUnreadCount
- );
- }
-
- #getChannelUnreadCount(channel) {
- return (
- channel.tracking.unreadCount + channel.unreadThreadsCountSinceLastViewed
- );
- }
-
#compareByLastActivity(a, b) {
const aDate = a.lastMessage?.createdAt
? new Date(a.lastMessage.createdAt)
@@ -480,6 +485,156 @@ export default class ChatChannelsManager extends Service {
}
}
+ #channelMatchesSidebarFilter(channel, filter, activeCutoff) {
+ if (filter === CHAT_CHANNEL_LIST_FILTERS.ALL) {
+ return true;
+ }
+
+ if (filter === CHAT_CHANNEL_LIST_FILTERS.ACTIVE) {
+ if (!channel.lastMessage?.id || !channel.lastMessage.createdAt) {
+ return false;
+ }
+
+ return new Date(channel.lastMessage.createdAt).getTime() >= activeCutoff;
+ }
+
+ if (channel.currentUserMembership?.muted) {
+ return false;
+ }
+
+ if (filter === CHAT_CHANNEL_LIST_FILTERS.UNREAD) {
+ return this.#sidebarUnreadCount(channel) > 0;
+ }
+
+ if (filter === CHAT_CHANNEL_LIST_FILTERS.MENTIONS) {
+ return this.#sidebarUrgentCount(channel) > 0;
+ }
+
+ return true;
+ }
+
+ #filterAndSortSidebarChannels(channels, section) {
+ return this.#filterSidebarChannels(channels, section).sort(
+ (channelA, channelB) => {
+ return this.#compareSidebarChannels(channelA, channelB, section);
+ }
+ );
+ }
+
+ #filterSidebarChannels(channels, section) {
+ const filter = this.chatChannelListPreferences.filterFor(section);
+ const activeCutoff =
+ filter === CHAT_CHANNEL_LIST_FILTERS.ACTIVE
+ ? Date.now() - CHAT_CHANNEL_LIST_ACTIVE_DAYS * 24 * 60 * 60 * 1000
+ : undefined;
+
+ return channels.filter((channel) => {
+ return (
+ this.#channelMatchesSidebarFilter(channel, filter, activeCutoff) ||
+ this.#isActiveSidebarChannel(channel)
+ );
+ });
+ }
+
+ #limitSidebarChannels(channels, limit) {
+ const limitedChannels = channels.slice(0, limit);
+ const activeChannel = channels.find((channel) => {
+ return this.#isActiveSidebarChannel(channel);
+ });
+
+ if (!activeChannel || limitedChannels.includes(activeChannel)) {
+ return limitedChannels;
+ }
+
+ return [...limitedChannels.slice(0, -1), activeChannel];
+ }
+
+ #compareChannelsAlphabetically(channelA, channelB) {
+ const channelAName = channelA.isDirectMessageChannel
+ ? channelA.title
+ : channelA.slug;
+ const channelBName = channelB.isDirectMessageChannel
+ ? channelB.title
+ : channelB.slug;
+ const alphabetical = (channelAName || "").localeCompare(channelBName || "");
+ return alphabetical || channelA.id - channelB.id;
+ }
+
+ #compareSidebarChannels(channelA, channelB, section) {
+ const sort = this.chatChannelListPreferences.sortFor(section);
+
+ if (sort === CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL) {
+ return this.#compareChannelsAlphabetically(channelA, channelB);
+ }
+
+ if (sort === CHAT_CHANNEL_LIST_SORTS.PRIORITY) {
+ const priority =
+ this.#sidebarChannelPriority(channelA) -
+ this.#sidebarChannelPriority(channelB);
+ if (priority) {
+ return priority;
+ }
+ }
+
+ return (
+ this.#compareChannelsByRecency(channelA, channelB) ||
+ this.#compareChannelsAlphabetically(channelA, channelB)
+ );
+ }
+
+ #compareChannelsByRecency(channelA, channelB) {
+ const channelAHasActivity =
+ channelA.lastMessage?.id && channelA.lastMessage.createdAt;
+ const channelBHasActivity =
+ channelB.lastMessage?.id && channelB.lastMessage.createdAt;
+
+ if (!!channelAHasActivity !== !!channelBHasActivity) {
+ return channelAHasActivity ? -1 : 1;
+ }
+
+ if (!channelAHasActivity) {
+ return 0;
+ }
+
+ return this.#compareByLastActivity(channelA, channelB);
+ }
+
+ #isActiveSidebarChannel(channel) {
+ return (
+ channel.id === this.chat.activeChannel?.id &&
+ (this.chatStateManager.isDrawerExpanded ||
+ this.chatStateManager.isFullPageActive)
+ );
+ }
+
+ #sidebarChannelPriority(channel) {
+ if (channel.currentUserMembership?.muted) {
+ return 2;
+ }
+
+ if (this.#sidebarUrgentCount(channel) > 0) {
+ return 0;
+ }
+
+ return this.#sidebarUnreadCount(channel) > 0 ? 1 : 2;
+ }
+
+ #sidebarUnreadCount(channel) {
+ return (
+ (channel.tracking?.unreadCount ?? 0) +
+ (channel.tracking?.mentionCount ?? 0) +
+ (channel.tracking?.watchedThreadsUnreadCount ?? 0) +
+ (channel.unreadThreadsCountSinceLastViewed ?? 0)
+ );
+ }
+
+ #sidebarUrgentCount(channel) {
+ return (
+ (channel.tracking?.mentionCount ?? 0) +
+ (channel.tracking?.watchedThreadsUnreadCount ?? 0)
+ );
+ }
+
#cache(channel) {
if (!channel) {
return;
@@ -548,16 +703,6 @@ export default class ChatChannelsManager extends Service {
);
}
- /**
- * Sorts public channels by activity without starred priority.
- * Unreads come first regardless of starred status.
- */
- #sortChannelsByActivityUnreadsFirst(channels) {
- return channels.sort((a, b) => {
- return this.#compareChannelsByActivity(a, b);
- });
- }
-
#compareChannelsByActivity(a, b) {
const stats = {
a: {
@@ -609,16 +754,6 @@ export default class ChatChannelsManager extends Service {
);
}
- /**
- * Sorts DM channels by activity without starred priority.
- * Unreads come first regardless of starred status.
- */
- #sortDirectMessageChannelsByActivity(channels) {
- return channels.sort((a, b) => {
- return this.#compareDirectMessageChannelsByActivity(a, b);
- });
- }
-
#compareDirectMessageChannelsByActivity(a, b) {
if (!a.lastMessage.id) {
return 1;
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat.js b/plugins/chat/assets/javascripts/discourse/services/chat.js
index 71640a61690..ce01890a1c6 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat.js
@@ -427,9 +427,9 @@ export default class Chat extends Service {
const manager = this.chatChannelsManager;
return [
- ...manager.starredChannels,
- ...manager.unstarredPublicMessageChannels,
- ...manager.truncatedUnstarredDirectMessageChannels,
+ ...manager.starredChannelsByPreference,
+ ...manager.sidebarPublicMessageChannels,
+ ...manager.sidebarDirectMessageChannels,
];
}
@@ -445,16 +445,15 @@ export default class Chat extends Service {
const manager = this.chatChannelsManager;
// Filter each section for channels with activity
- const starredWithActivity = manager.starredChannels.filter(
+ const starredWithActivity = manager.starredChannelsByPreference.filter(
(c) => c.hasUnread
);
- const publicWithActivity = manager.unstarredPublicMessageChannels.filter(
+ const publicWithActivity = manager.sidebarPublicMessageChannels.filter(
+ (c) => c.hasUnread
+ );
+ const dmsWithActivity = manager.sidebarDirectMessageChannels.filter(
(c) => c.hasUnread
);
- const dmsWithActivity =
- manager.truncatedUnstarredDirectMessageChannels.filter(
- (c) => c.hasUnread
- );
const allChannels = [
...starredWithActivity,
diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-list-options.scss b/plugins/chat/assets/stylesheets/common/chat-channel-list-options.scss
new file mode 100644
index 00000000000..79076706024
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/common/chat-channel-list-options.scss
@@ -0,0 +1,84 @@
+.chat-channel-divider__actions {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+}
+
+.chat-channel-list-options-button {
+ padding: 0;
+ background: transparent;
+ color: var(--primary-medium);
+ font-size: var(--font-0-rem);
+
+ &:hover {
+ background: transparent;
+ }
+}
+
+.chat-channel-list-options-menu,
+.chat-channel-list-filter-menu,
+.chat-channel-list-sort-menu {
+ min-width: 17rem;
+}
+
+.chat-channel-list-filter-menu .dropdown-menu__item,
+.chat-channel-list-sort-menu .dropdown-menu__item,
+.chat-channel-list-sort-choice {
+ > .btn {
+ height: auto;
+ min-height: var(--d-sidebar-row-height);
+
+ > .d-icon {
+ visibility: hidden;
+ }
+
+ &[aria-checked="true"] > .d-icon {
+ visibility: visible;
+ }
+
+ &.--with-description {
+ padding-top: var(--space-2);
+ padding-bottom: var(--space-2);
+ }
+ }
+}
+
+.chat-channel-list-filter-menu__label,
+.chat-channel-list-sort-menu__label {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+}
+
+.chat-channel-list-filter-menu__label-description,
+.chat-channel-list-sort-menu__label-description {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ padding-inline-end: var(--space-2);
+}
+
+.chat-sidebar-channels-filter-empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: var(--space-1);
+ padding: var(--space-1) 0 var(--space-1) var(--space-9);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ line-height: var(--line-height-medium);
+
+ &__reset {
+ padding: 0;
+ color: var(--tertiary);
+ }
+}
+
+.fk-d-menu-modal.chat-channel-list-options-menu-content {
+ .dropdown-menu__subheader {
+ padding-inline: var(--space-4);
+ }
+
+ .dropdown-menu__divider {
+ margin-block: var(--space-2);
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/common/index.scss b/plugins/chat/assets/stylesheets/common/index.scss
index 18807183d6d..c089f892296 100644
--- a/plugins/chat/assets/stylesheets/common/index.scss
+++ b/plugins/chat/assets/stylesheets/common/index.scss
@@ -11,6 +11,7 @@
@import "chat-channel-empty-state";
@import "chat-channel-icon";
@import "chat-channel-info";
+@import "chat-channel-list-options";
@import "chat-channel-name";
@import "chat-channel-preview-card";
@import "chat-channel-title";
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index 947f6e68c0a..9a0f07f64b1 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -136,7 +136,7 @@ en:
process_started: "The process to delete the channel has started. This modal will close shortly, you will no longer see the deleted channel anywhere."
channels_list_popup:
browse: "Browse channels"
- create: "New channel"
+ create: "New channel..."
close: "Close"
remove: "Remove"
@@ -153,8 +153,8 @@ en:
muted: "muted"
joined: "joined"
empty_state:
- direct_message_cta: "Start a personal Chat"
- direct_message: "You can also start a personal chat with one or more users."
+ direct_message_cta: "Start a direct message or group chat"
+ direct_message: "You can also start a direct message or group chat with one or more users."
title: "No channels found"
my_threads: "You don't have any threads yet. Threads you participate in will be displayed here."
email_frequency:
@@ -637,15 +637,37 @@ en:
direct_messages:
title: "DMs"
aria_label: "Switch to direct messages"
- new: "Create a personal chat"
+ new: "New direct message or group chat..."
create: "Go"
- leave: "Leave this personal chat"
- close: "Close this personal chat"
+ leave: "Leave channel"
+ close: "Close channel"
cannot_create: "Sorry, you cannot send direct messages."
channel_list:
title: "Channels"
aria_label: "Switch to channels list"
+ options:
+ title: "Channel list options"
+ filter: "Filter"
+ sort: "Sort"
+ current_filter: "Filter: %{filter}"
+ current_sort: "Sort: %{sort}"
+ filter:
+ title: "Filter channels by:"
+ all: "All channels"
+ active: "Active only"
+ active_description: "New activity in last %{days} days"
+ unread: "Unreads"
+ mentions: "Mentions"
+ sort:
+ title: "Sort channels by:"
+ alphabetical: "Alphabetically"
+ recent_activity: "Recent activity"
+ priority: "Priority"
+ priority_description: "Mentions, then unreads, then recent activity"
+ empty:
+ filtered: "No channels match this filter."
+ show_all: "Show all channels"
incoming_webhooks:
back: "Back"
@@ -812,11 +834,11 @@ en:
# %{identifier} is either @here or @all
other_html: '<span>%{username}</span> <span>mentioned %{identifier} in "%{channel}"</span>'
direct_message_chat_mention:
- direct: "mentioned you in personal chat"
- direct_html: "<span>%{username}</span> <span>mentioned you in personal chat</span>"
- other_plain: "mentioned %{identifier} in personal chat"
+ direct: "mentioned you in a direct message"
+ direct_html: "<span>%{username}</span> <span>mentioned you in a direct message</span>"
+ other_plain: "mentioned %{identifier} in a direct message"
# %{identifier} is either @here or @all
- other_html: "<span>%{username}</span> <span>mentioned %{identifier} in personal chat</span>"
+ other_html: "<span>%{username}</span> <span>mentioned %{identifier} in a direct message</span>"
chat_message: "New chat message"
chat_quoted: "%{username} quoted your chat message"
@@ -892,8 +914,8 @@ en:
sidebar:
start_new_dm:
- text: Start new DM
- title: Create a personal chat
+ text: Start DM or group chat
+ title: New direct message or group chat
panels:
chat:
label: "Chat"
diff --git a/plugins/chat/db/migrate/20260904000537_add_chat_channel_list_preferences_to_user_options.rb b/plugins/chat/db/migrate/20260904000537_add_chat_channel_list_preferences_to_user_options.rb
new file mode 100644
index 00000000000..7bc5043fb8c
--- /dev/null
+++ b/plugins/chat/db/migrate/20260904000537_add_chat_channel_list_preferences_to_user_options.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+class AddChatChannelListPreferencesToUserOptions < ActiveRecord::Migration[8.0]
+ def change
+ add_column :user_options, :chat_channel_list_filter, :integer, default: 0, null: false
+ add_column :user_options, :chat_channel_list_sort, :integer, default: 0, null: false
+ end
+end
diff --git a/plugins/chat/db/migrate/20260908153158_add_chat_channel_list_section_sorts_to_user_options.rb b/plugins/chat/db/migrate/20260908153158_add_chat_channel_list_section_sorts_to_user_options.rb
new file mode 100644
index 00000000000..bf158a6204e
--- /dev/null
+++ b/plugins/chat/db/migrate/20260908153158_add_chat_channel_list_section_sorts_to_user_options.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+class AddChatChannelListSectionSortsToUserOptions < ActiveRecord::Migration[8.0]
+ def change
+ add_column :user_options, :chat_channel_list_sort_starred, :integer, default: 0, null: false
+ add_column :user_options, :chat_channel_list_sort_dms, :integer, default: 2, null: false
+ end
+end
diff --git a/plugins/chat/db/migrate/20260908160656_add_chat_channel_list_section_filters_to_user_options.rb b/plugins/chat/db/migrate/20260908160656_add_chat_channel_list_section_filters_to_user_options.rb
new file mode 100644
index 00000000000..5724de3c3e2
--- /dev/null
+++ b/plugins/chat/db/migrate/20260908160656_add_chat_channel_list_section_filters_to_user_options.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+class AddChatChannelListSectionFiltersToUserOptions < ActiveRecord::Migration[8.0]
+ def change
+ add_column :user_options, :chat_channel_list_filter_starred, :integer, default: 0, null: false
+ add_column :user_options, :chat_channel_list_filter_dms, :integer, default: 0, null: false
+ end
+end
diff --git a/plugins/chat/lib/chat/user_option_extension.rb b/plugins/chat/lib/chat/user_option_extension.rb
index 105da9947c0..ebe4b27bc48 100644
--- a/plugins/chat/lib/chat/user_option_extension.rb
+++ b/plugins/chat/lib/chat/user_option_extension.rb
@@ -55,6 +55,62 @@ module Chat
base.enum :chat_quick_reaction_type, { frequent: 0, custom: 1 }, prefix: true
end
+ def base.chat_channel_list_filters
+ @chat_channel_list_filters ||= { all: 0, active: 1, unread: 2, mentions: 3 }
+ end
+
+ if !base.method_defined?(:chat_channel_list_filter_all?)
+ base.enum :chat_channel_list_filter,
+ base.chat_channel_list_filters,
+ prefix: true,
+ scopes: false,
+ validate: true
+ end
+
+ if !base.method_defined?(:chat_channel_list_filter_starred_all?)
+ base.enum :chat_channel_list_filter_starred,
+ base.chat_channel_list_filters,
+ prefix: true,
+ scopes: false,
+ validate: true
+ end
+
+ if !base.method_defined?(:chat_channel_list_filter_dms_all?)
+ base.enum :chat_channel_list_filter_dms,
+ base.chat_channel_list_filters,
+ prefix: true,
+ scopes: false,
+ validate: true
+ end
+
+ def base.chat_channel_list_sorts
+ @chat_channel_list_sorts ||= { alphabetical: 0, recent_activity: 1, priority: 2 }
+ end
+
+ if !base.method_defined?(:chat_channel_list_sort_alphabetical?)
+ base.enum :chat_channel_list_sort,
+ base.chat_channel_list_sorts,
+ prefix: true,
+ scopes: false,
+ validate: true
+ end
+
+ if !base.method_defined?(:chat_channel_list_sort_starred_alphabetical?)
+ base.enum :chat_channel_list_sort_starred,
+ base.chat_channel_list_sorts,
+ prefix: true,
+ scopes: false,
+ validate: true
+ end
+
+ if !base.method_defined?(:chat_channel_list_sort_dms_alphabetical?)
+ base.enum :chat_channel_list_sort_dms,
+ base.chat_channel_list_sorts,
+ prefix: true,
+ scopes: false,
+ validate: true
+ end
+
if !base.method_defined?(:chat_send_shortcut)
base.define_method(:chat_send_shortcut) { send_shortcut }
base.define_method(:chat_send_shortcut=) { |value| self.send_shortcut = value }
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index e8db23b28ae..d40208e2cd5 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -91,6 +91,12 @@ after_initialize do
UserUpdater::OPTION_ATTR.push(:ignore_channel_wide_mention)
UserUpdater::OPTION_ATTR.push(:show_thread_title_prompts)
UserUpdater::OPTION_ATTR.push(:chat_announce_new_messages)
+ UserUpdater::OPTION_ATTR.push(:chat_channel_list_filter)
+ UserUpdater::OPTION_ATTR.push(:chat_channel_list_filter_starred)
+ UserUpdater::OPTION_ATTR.push(:chat_channel_list_filter_dms)
+ UserUpdater::OPTION_ATTR.push(:chat_channel_list_sort)
+ UserUpdater::OPTION_ATTR.push(:chat_channel_list_sort_starred)
+ UserUpdater::OPTION_ATTR.push(:chat_channel_list_sort_dms)
UserUpdater::OPTION_ATTR.push(:chat_new_message_sound)
UserUpdater::OPTION_ATTR.push(:chat_email_frequency)
UserUpdater::OPTION_ATTR.push(:chat_header_indicator_preference)
@@ -310,6 +316,46 @@ after_initialize do
add_to_serializer(:user_option, :chat_announce_new_messages) { object.chat_announce_new_messages }
+ add_to_serializer(:user_option, :chat_channel_list_filter) { object.chat_channel_list_filter }
+
+ add_to_serializer(:current_user_option, :chat_channel_list_filter) do
+ object.chat_channel_list_filter
+ end
+
+ add_to_serializer(:user_option, :chat_channel_list_sort) { object.chat_channel_list_sort }
+
+ add_to_serializer(:current_user_option, :chat_channel_list_sort) { object.chat_channel_list_sort }
+
+ add_to_serializer(:user_option, :chat_channel_list_sort_starred) do
+ object.chat_channel_list_sort_starred
+ end
+
+ add_to_serializer(:current_user_option, :chat_channel_list_sort_starred) do
+ object.chat_channel_list_sort_starred
+ end
+
+ add_to_serializer(:user_option, :chat_channel_list_sort_dms) { object.chat_channel_list_sort_dms }
+
+ add_to_serializer(:current_user_option, :chat_channel_list_sort_dms) do
+ object.chat_channel_list_sort_dms
+ end
+
+ add_to_serializer(:user_option, :chat_channel_list_filter_starred) do
+ object.chat_channel_list_filter_starred
+ end
+
+ add_to_serializer(:current_user_option, :chat_channel_list_filter_starred) do
+ object.chat_channel_list_filter_starred
+ end
+
+ add_to_serializer(:user_option, :chat_channel_list_filter_dms) do
+ object.chat_channel_list_filter_dms
+ end
+
+ add_to_serializer(:current_user_option, :chat_channel_list_filter_dms) do
+ object.chat_channel_list_filter_dms
+ end
+
add_to_serializer(:current_user_option, :chat_announce_new_messages) do
object.chat_announce_new_messages
end
diff --git a/plugins/chat/spec/models/user_option_spec.rb b/plugins/chat/spec/models/user_option_spec.rb
index 2502d457760..f6bc5f80a5c 100644
--- a/plugins/chat/spec/models/user_option_spec.rb
+++ b/plugins/chat/spec/models/user_option_spec.rb
@@ -31,6 +31,32 @@ RSpec.describe UserOption do
end
end
+ describe "#chat_channel_list_filter" do
+ it "defaults to all" do
+ expect(described_class.new.chat_channel_list_filter).to eq("all")
+ end
+
+ it "validates assigned values" do
+ user_option = described_class.new(chat_channel_list_filter: "invalid")
+
+ expect(user_option).not_to be_valid
+ expect(user_option.errors[:chat_channel_list_filter]).to be_present
+ end
+ end
+
+ describe "#chat_channel_list_sort" do
+ it "defaults to alphabetical" do
+ expect(described_class.new.chat_channel_list_sort).to eq("alphabetical")
+ end
+
+ it "validates assigned values" do
+ user_option = described_class.new(chat_channel_list_sort: "invalid")
+
+ expect(user_option).not_to be_valid
+ expect(user_option.errors[:chat_channel_list_sort]).to be_present
+ end
+ end
+
describe "#chat_send_shortcut" do
fab!(:user)
diff --git a/plugins/chat/spec/requests/core_ext/users_controller_spec.rb b/plugins/chat/spec/requests/core_ext/users_controller_spec.rb
index b1667ad1e68..a0b432d94b8 100644
--- a/plugins/chat/spec/requests/core_ext/users_controller_spec.rb
+++ b/plugins/chat/spec/requests/core_ext/users_controller_spec.rb
@@ -54,6 +54,57 @@ describe UsersController do
end
end
+ describe "#update" do
+ fab!(:user)
+ fab!(:other_user, :user)
+
+ before { sign_in(user) }
+
+ it "persists chat channel list preferences while chat is disabled" do
+ SiteSetting.chat_enabled = false
+
+ put "/u/#{user.username}.json",
+ params: {
+ chat_channel_list_filter: "unread",
+ chat_channel_list_sort: "priority",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(user.user_option.reload).to have_attributes(
+ chat_channel_list_filter: "unread",
+ chat_channel_list_sort: "priority",
+ )
+ end
+
+ it "rejects invalid chat channel list preferences" do
+ put "/u/#{user.username}.json",
+ params: {
+ chat_channel_list_filter: "invalid",
+ chat_channel_list_sort: "priority",
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(user.user_option.reload).to have_attributes(
+ chat_channel_list_filter: "all",
+ chat_channel_list_sort: "alphabetical",
+ )
+ end
+
+ it "rejects an invalid sort preference" do
+ put "/u/#{user.username}.json", params: { chat_channel_list_sort: "invalid" }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(user.user_option.reload.chat_channel_list_sort).to eq("alphabetical")
+ end
+
+ it "does not allow another user to update the preferences" do
+ put "/u/#{other_user.username}.json", params: { chat_channel_list_filter: "unread" }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(other_user.user_option.reload.chat_channel_list_filter).to eq("all")
+ end
+ end
+
describe "#show_card" do
fab!(:user)
fab!(:another_user, :user)
diff --git a/plugins/chat/spec/serializer/current_user_serializer_spec.rb b/plugins/chat/spec/serializer/current_user_serializer_spec.rb
index a3340520f6f..231ba1f0ec7 100644
--- a/plugins/chat/spec/serializer/current_user_serializer_spec.rb
+++ b/plugins/chat/spec/serializer/current_user_serializer_spec.rb
@@ -39,6 +39,27 @@ RSpec.describe CurrentUserSerializer do
end
end
+ describe "#chat_channel_list_preferences" do
+ it "includes default values" do
+ expect(serializer.as_json[:user_option]).to include(
+ chat_channel_list_filter: "all",
+ chat_channel_list_sort: "alphabetical",
+ )
+ end
+
+ it "includes changed values" do
+ current_user.user_option.update!(
+ chat_channel_list_filter: "mentions",
+ chat_channel_list_sort: "priority",
+ )
+
+ expect(serializer.as_json[:user_option]).to include(
+ chat_channel_list_filter: "mentions",
+ chat_channel_list_sort: "priority",
+ )
+ end
+ end
+
describe "#chat_drafts" do
context "when user can't chat" do
before { SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff] }
diff --git a/plugins/chat/spec/serializer/user_serializer_spec.rb b/plugins/chat/spec/serializer/user_serializer_spec.rb
index 78667489b0a..e277f1f82e0 100644
--- a/plugins/chat/spec/serializer/user_serializer_spec.rb
+++ b/plugins/chat/spec/serializer/user_serializer_spec.rb
@@ -11,6 +11,27 @@ RSpec.describe UserSerializer do
end
end
+ describe "#chat_channel_list_preferences" do
+ it "includes default values" do
+ expect(serializer.as_json[:user_option]).to include(
+ chat_channel_list_filter: "all",
+ chat_channel_list_sort: "alphabetical",
+ )
+ end
+
+ it "includes changed values" do
+ user.user_option.update!(
+ chat_channel_list_filter: "mentions",
+ chat_channel_list_sort: "priority",
+ )
+
+ expect(serializer.as_json[:user_option]).to include(
+ chat_channel_list_filter: "mentions",
+ chat_channel_list_sort: "priority",
+ )
+ end
+ end
+
describe "#chat_quick_reaction_type" do
it "is present with default enum string" do
expect(serializer.as_json[:user_option][:chat_quick_reaction_type]).to eq("frequent")
diff --git a/plugins/chat/spec/system/anonymous_public_channels_spec.rb b/plugins/chat/spec/system/anonymous_public_channels_spec.rb
index e89656efde1..8f9b01b96d1 100644
--- a/plugins/chat/spec/system/anonymous_public_channels_spec.rb
+++ b/plugins/chat/spec/system/anonymous_public_channels_spec.rb
@@ -30,7 +30,7 @@ RSpec.describe "Anonymous public chat channels" do
expect(chat_page).to have_public_channel(public_channel)
expect(chat_page).to have_no_public_channel(private_channel)
- expect(chat_page).to have_no_browse_page_button
+ expect(chat_page).to have_no_channel_list_options_button
chat_page.open_public_channel(public_channel)
diff --git a/plugins/chat/spec/system/drawer/starred_channels_spec.rb b/plugins/chat/spec/system/drawer/starred_channels_spec.rb
index e2f887342b9..ff19884801d 100644
--- a/plugins/chat/spec/system/drawer/starred_channels_spec.rb
+++ b/plugins/chat/spec/system/drawer/starred_channels_spec.rb
@@ -53,7 +53,8 @@ RSpec.describe "Drawer - starred channels" do
dm_channel_2.membership_for(current_user).update!(starred: true)
end
- it "sorts by activity: unread public, unread DMs, read public, read DMs" do
+ it "sorts by priority with unread channels before read ones" do
+ current_user.user_option.update!(chat_channel_list_sort_starred: "priority")
Fabricate(:chat_message, chat_channel: channel_2, user: user_1)
Fabricate(:chat_message, chat_channel: dm_channel_1, user: user_1)
channel_2.membership_for(current_user).update!(last_viewed_at: 1.minute.ago)
@@ -63,10 +64,10 @@ RSpec.describe "Drawer - starred channels" do
chat_page.open_from_header
drawer_page.click_starred_channels
- channels = page.all(".chat-channel-row")
- expect(channels.map { |c| c["data-chat-channel-id"] }).to eq(
- [channel_2.id, dm_channel_1.id, channel_1.id, dm_channel_2.id].map(&:to_s),
- )
+ channels = page.all(".chat-channel-row").map { |c| c["data-chat-channel-id"] }
+
+ expect(channels.first(2).sort).to eq([channel_2.id, dm_channel_1.id].map(&:to_s).sort)
+ expect(channels.last(2).sort).to eq([channel_1.id, dm_channel_2.id].map(&:to_s).sort)
end
end
diff --git a/plugins/chat/spec/system/list_channels/drawer_spec.rb b/plugins/chat/spec/system/list_channels/drawer_spec.rb
index 6cb0579af78..075d780422e 100644
--- a/plugins/chat/spec/system/list_channels/drawer_spec.rb
+++ b/plugins/chat/spec/system/list_channels/drawer_spec.rb
@@ -58,7 +58,16 @@ RSpec.describe "List channels | Drawer" do
channel_4.add(current_user)
end
- it "sorts them by urgent, unread messages or threads, then by slug" do
+ it "shows the channel list sort toggle" do
+ drawer_page.visit_index
+
+ expect(drawer_page.channels_index.component).to have_css(
+ ".chat-channel-list-options-button",
+ )
+ end
+
+ it "sorts by urgent, unread messages or threads first when priority is selected" do
+ current_user.user_option.update!(chat_channel_list_sort: "priority")
drawer_page.visit_index
Fabricate(
@@ -74,15 +83,71 @@ RSpec.describe "List channels | Drawer" do
expect(drawer_page).to have_channel_at_position(channel_2, 4)
end
- it "sorts by slug when multiple channels have the same unread count" do
+ it "sorts channels alphabetically by default even with unreads" do
drawer_page.visit_index
Fabricate(:chat_message, chat_channel: channel_2, use_service: true)
Fabricate(:chat_message, chat_channel: channel_4, use_service: true)
- expect(drawer_page).to have_channel_at_position(channel_2, 1)
- expect(drawer_page).to have_channel_at_position(channel_3, 2)
- expect(drawer_page).to have_channel_at_position(channel_4, 3)
- expect(drawer_page).to have_channel_at_position(channel_1, 4)
+ expect(drawer_page).to have_channel_at_position(channel_1, 1)
+ expect(drawer_page).to have_channel_at_position(channel_2, 2)
+ expect(drawer_page).to have_channel_at_position(channel_3, 3)
+ expect(drawer_page).to have_channel_at_position(channel_4, 4)
+ end
+
+ it "sorts by recent activity from the sort menu and persists the choice" do
+ older_message =
+ Fabricate(
+ :chat_message,
+ chat_channel: channel_1,
+ user: current_user,
+ use_service: true,
+ created_at: 3.days.ago,
+ )
+ channel_1.update!(last_message: older_message, messages_count: 1)
+ recent_message =
+ Fabricate(
+ :chat_message,
+ chat_channel: channel_2,
+ user: current_user,
+ use_service: true,
+ created_at: 1.hour.ago,
+ )
+ channel_2.update!(last_message: recent_message, messages_count: 1)
+
+ drawer_page.visit_index
+
+ ids = page.all(".chat-channel-row").map { |c| c["data-chat-channel-id"] }
+ expect(ids.index(channel_1.id.to_s)).to be < ids.index(channel_2.id.to_s)
+
+ drawer_page.channels_index.set_channel_sort("recent_activity")
+
+ try_until_success do
+ ids = page.all(".chat-channel-row").map { |c| c["data-chat-channel-id"] }
+ expect(ids.index(channel_2.id.to_s)).to be < ids.index(channel_1.id.to_s)
+ end
+ try_until_success do
+ expect(current_user.user_option.reload.chat_channel_list_sort).to eq("recent_activity")
+ end
+ end
+
+ it "filters the channel list from the shared options menu" do
+ unread_channel = Fabricate(:category_channel, name: "unread channel")
+ unread_channel.add(current_user)
+ Fabricate(
+ :chat_message,
+ chat_channel: unread_channel,
+ user: Fabricate(:user),
+ use_service: true,
+ )
+
+ drawer_page.visit_index
+
+ drawer_page.channels_index.set_channel_filter("unread")
+
+ try_until_success do
+ expect(drawer_page).to have_channel(unread_channel)
+ expect(drawer_page).to have_no_channel(channel_1)
+ end
end
end
end
@@ -131,6 +196,8 @@ RSpec.describe "List channels | Drawer" do
end
it "sorts them by latest activity" do
+ current_user.user_option.update!(chat_channel_list_sort_dms: "priority")
+
Fabricate(
:chat_message,
chat_channel: dm_channel_2,
@@ -153,8 +220,6 @@ RSpec.describe "List channels | Drawer" do
expect(drawer_page).to have_channel_at_position(dm_channel_2, 1)
expect(drawer_page).to have_urgent_channel(dm_channel_2)
expect(drawer_page).to have_channel_at_position(dm_channel_4, 2)
- expect(drawer_page).to have_channel_at_position(dm_channel_1, 3)
- expect(drawer_page).to have_channel_at_position(dm_channel_3, 4)
end
context "with unread threads" do
@@ -194,14 +259,24 @@ RSpec.describe "List channels | Drawer" do
before do
dm_channel_3.membership_for(current_user).mark_read!(message_1.id)
dm_channel_4.membership_for(current_user).mark_read!(message_2.id)
+ end
+
+ it "sorts channels with unread threads by last reply" do
+ current_user.user_option.update!(chat_channel_list_sort_dms: "recent_activity")
drawer_page.visit_index
drawer_page.click_direct_messages
- end
- it "sorts channels with unread threads by last reply" do
- Fabricate(:chat_message, thread: thread_1, user: user_2, use_service: true)
- Fabricate(:chat_message, thread: thread_2, user: user_3, use_service: true)
+ # Distinct timestamps: `use_service: true` stamps its own `created_at`
+ # and the serializer truncates to whole seconds, so back-to-back
+ # replies tie on recency and fall through to title order. They must
+ # also land after the `mark_read!` above to still count as unread.
+ freeze_time(1.minute.from_now) do
+ Fabricate(:chat_message, thread: thread_1, user: user_2, use_service: true)
+ end
+ freeze_time(2.minutes.from_now) do
+ Fabricate(:chat_message, thread: thread_2, user: user_3, use_service: true)
+ end
expect(drawer_page).to have_channel_at_position(dm_channel_4, 1)
expect(drawer_page).to have_unread_channel(dm_channel_4)
@@ -211,6 +286,11 @@ RSpec.describe "List channels | Drawer" do
end
it "sorts channels with unread threads by importance" do
+ current_user.user_option.update!(chat_channel_list_sort_dms: "priority")
+
+ drawer_page.visit_index
+ drawer_page.click_direct_messages
+
thread_1.membership_for(current_user).update!(
notification_level: ::Chat::NotificationLevels.all[:watching],
)
diff --git a/plugins/chat/spec/system/list_channels/mobile_spec.rb b/plugins/chat/spec/system/list_channels/mobile_spec.rb
index 229bcb8f2bc..e19f1d3242b 100644
--- a/plugins/chat/spec/system/list_channels/mobile_spec.rb
+++ b/plugins/chat/spec/system/list_channels/mobile_spec.rb
@@ -62,7 +62,7 @@ RSpec.describe "List channels | mobile", mobile: true do
channel_4.add(current_user)
end
- it "sorts them by mentions, unread, then by slug" do
+ it "sorts channels alphabetically by default even with mentions and unreads" do
Jobs.run_immediately!
Fabricate(
@@ -88,16 +88,17 @@ RSpec.describe "List channels | mobile", mobile: true do
visit("/chat/channels")
- # channel with mentions should be first
expect(page.find("#public-channels a:nth-child(1)")["data-chat-channel-id"]).to eq(
- channel_4.id.to_s,
+ channel_1.id.to_s,
)
- # channels with unread messages are next
expect(page.find("#public-channels a:nth-child(2)")["data-chat-channel-id"]).to eq(
- channel_1.id.to_s,
+ channel_2.id.to_s,
)
expect(page.find("#public-channels a:nth-child(3)")["data-chat-channel-id"]).to eq(
- channel_2.id.to_s,
+ channel_3.id.to_s,
+ )
+ expect(page.find("#public-channels a:nth-child(4)")["data-chat-channel-id"]).to eq(
+ channel_4.id.to_s,
)
end
@@ -327,9 +328,10 @@ RSpec.describe "List channels | mobile", mobile: true do
end
end
- it "has a new dm channel button" do
+ it "has a new dm channel option in the options menu" do
visit("/chat/direct-messages")
- find(".c-navbar__new-dm-button").click
+ find(".chat-channel-list-options-button").click
+ find('[data-menu-option-id="startDm"]').click
expect(chat.message_creator).to be_opened
end
diff --git a/plugins/chat/spec/system/list_channels/sidebar_spec.rb b/plugins/chat/spec/system/list_channels/sidebar_spec.rb
index b31f051a6cf..3a8e6890cc1 100644
--- a/plugins/chat/spec/system/list_channels/sidebar_spec.rb
+++ b/plugins/chat/spec/system/list_channels/sidebar_spec.rb
@@ -87,7 +87,7 @@ RSpec.describe "List channels | sidebar" do
drawer_page.visit_index
drawer_page.click_channels
- expect(drawer_page).to have_channel_at_position(channel_1, 1)
+ expect(drawer_page).to have_channel_at_position(channel_2, 1)
expect(page.find("#sidebar-section-content-chat-channels li:nth-child(1)")).to have_css(
".channel-#{channel_2.id}",
diff --git a/plugins/chat/spec/system/page_objects/chat/chat.rb b/plugins/chat/spec/system/page_objects/chat/chat.rb
index 6c068063ac1..556519b5ba8 100644
--- a/plugins/chat/spec/system/page_objects/chat/chat.rb
+++ b/plugins/chat/spec/system/page_objects/chat/chat.rb
@@ -166,8 +166,8 @@ module PageObjects
has_no_css?(public_channel_selector(channel))
end
- def has_no_browse_page_button?
- has_no_css?(".open-browse-page-btn")
+ def has_no_channel_list_options_button?
+ has_no_css?(".chat-channel-list-options-button")
end
def has_add_member_button?
diff --git a/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb b/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb
index edaa17cd964..064205f662c 100644
--- a/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb
+++ b/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb
@@ -18,7 +18,30 @@ module PageObjects
end
def open_browse
- component.find(".open-browse-page-btn").click
+ open_channel_list_options.option('[data-menu-option-id="browseChannels"]').click
+ end
+
+ def open_channel_list_options
+ trigger = component.find(".chat-channel-list-options-button")
+ trigger.click
+ PageObjects::Components::DMenu.new(trigger, "chat-channel-list-options-menu")
+ end
+
+ def set_channel_sort(sort)
+ menu = open_channel_list_options
+ sort_trigger = menu.option('[data-menu-option-id="sortChannels"]')
+ sort_trigger.click
+ submenu = PageObjects::Components::DMenu.new(sort_trigger, "chat-channel-list-sort-menu")
+ submenu.option(%([data-menu-option-id="#{sort}"])).click
+ end
+
+ def set_channel_filter(filter)
+ menu = open_channel_list_options
+ filter_trigger = menu.option('[data-menu-option-id="filterChannels"]')
+ filter_trigger.click
+ submenu =
+ PageObjects::Components::DMenu.new(filter_trigger, "chat-channel-list-filter-menu")
+ submenu.option(%([data-menu-option-id="#{filter}"])).click
end
def open_channel(channel)
@@ -37,8 +60,8 @@ module PageObjects
has_no_css?(channel_row_selector(channel))
end
- def has_no_browse_page_button?
- has_no_css?(".open-browse-page-btn")
+ def has_no_channel_list_options_button?
+ has_no_css?(".chat-channel-list-options-button")
end
def has_unread_channel?(
diff --git a/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb b/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb
index 8dc405afbd2..031cb688fc2 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
@@ -19,7 +19,7 @@ module PageObjects
def open_browse
mouseout
- find("#{VISIBLE_DRAWER} .open-browse-page-btn").click
+ channels_index.open_browse
end
def close
@@ -122,8 +122,8 @@ module PageObjects
channels_index.has_no_channel?(channel)
end
- def has_no_browse_page_button?
- channels_index.has_no_browse_page_button?
+ def has_no_channel_list_options_button?
+ channels_index.has_no_channel_list_options_button?
end
def has_channel_at_position?(channel, position)
diff --git a/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb b/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb
index 40421246ca1..cddf04ba082 100644
--- a/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb
+++ b/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb
@@ -33,7 +33,55 @@ module PageObjects
end
def open_browse
- channels_section.find(".sidebar-section-header-button", visible: false).click
+ open_channel_list_options.option('[data-menu-option-id="browseChannels"]').click
+ end
+
+ def open_channel_list_options
+ open_list_options(PUBLIC_CHANNELS_SECTION_SELECTOR)
+ end
+
+ def open_list_options(selector)
+ find(selector).hover
+ menu =
+ PageObjects::Components::DMenu.new(
+ "#{selector} .sidebar-section-header-button",
+ "chat-channel-list-options-menu",
+ )
+ menu.expand
+ menu
+ end
+
+ def set_channel_filter(filter)
+ set_list_filter(PUBLIC_CHANNELS_SECTION_SELECTOR, filter)
+ end
+
+ def set_starred_filter(filter)
+ set_list_filter(STARRED_CHANNELS_SECTION_SELECTOR, filter)
+ end
+
+ def set_dm_filter(filter)
+ set_list_filter(DM_CHANNELS_SECTION_SELECTOR, filter)
+ end
+
+ def set_list_filter(selector, filter)
+ menu = open_list_options(selector)
+ filter_trigger = menu.option('[data-menu-option-id="filterChannels"]')
+ filter_trigger.click
+ submenu =
+ PageObjects::Components::DMenu.new(filter_trigger, "chat-channel-list-filter-menu")
+ submenu.option(%([data-menu-option-id="#{filter}"])).click
+ end
+
+ def set_channel_sort(sort)
+ menu = open_channel_list_options
+ sort_trigger = menu.option('[data-menu-option-id="sortChannels"]')
+ sort_trigger.click
+ submenu = PageObjects::Components::DMenu.new(sort_trigger, "chat-channel-list-sort-menu")
+ submenu.option(%([data-menu-option-id="#{sort}"])).click
+ end
+
+ def show_all_channels
+ find(".chat-sidebar-channels-filter-empty-state__reset").click
end
def open_channel(channel)
@@ -89,6 +137,10 @@ module PageObjects
has_no_css?(".sidebar-section-link.channel-#{channel.id}")
end
+ def channel_names
+ within(channels_section) { all(".sidebar-section-link-content-text").map(&:text) }
+ end
+
def has_user_threads_section?
has_css?(
".sidebar-section-link[data-link-name='user-threads'][href='/chat/threads']",
diff --git a/plugins/chat/spec/system/sidebar_channel_list_options_spec.rb b/plugins/chat/spec/system/sidebar_channel_list_options_spec.rb
new file mode 100644
index 00000000000..dfd4eb8ff18
--- /dev/null
+++ b/plugins/chat/spec/system/sidebar_channel_list_options_spec.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+RSpec.describe "Chat sidebar channel list options" do
+ fab!(:current_user, :user)
+ fab!(:read_channel) { Fabricate(:category_channel, name: "Alpha channel") }
+ fab!(:unread_channel) { Fabricate(:category_channel, name: "Zulu channel") }
+ fab!(:message_author, :user)
+
+ let(:chat_sidebar) { PageObjects::Pages::ChatSidebar.new }
+
+ before do
+ read_message =
+ Fabricate(
+ :chat_message,
+ chat_channel: read_channel,
+ user: message_author,
+ created_at: 2.days.ago,
+ )
+ read_channel.update!(last_message: read_message, messages_count: 1)
+
+ chat_system_bootstrap(current_user, [read_channel, unread_channel])
+
+ unread_message =
+ Fabricate(
+ :chat_message,
+ chat_channel: unread_channel,
+ user: message_author,
+ created_at: 1.hour.ago,
+ )
+ unread_channel.update!(last_message: unread_message, messages_count: 1)
+
+ SiteSetting.navigation_menu = "sidebar"
+ sign_in(current_user)
+ end
+
+ it "sorts, filters, and persists the user's choices" do
+ visit("/")
+
+ expect(chat_sidebar.channel_names).to eq(["Alpha channel", "Zulu channel"])
+
+ chat_sidebar.set_channel_sort("recent_activity")
+
+ try_until_success(reason: "channel list re-sorts after the menu closes") do
+ expect(chat_sidebar.channel_names).to eq(["Zulu channel", "Alpha channel"])
+ end
+ try_until_success(reason: "channel sort preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_sort).to eq("recent_activity")
+ end
+
+ chat_sidebar.set_channel_filter("unread")
+
+ expect(chat_sidebar).to have_channel(unread_channel)
+ expect(chat_sidebar).to have_no_channel(read_channel)
+ try_until_success(reason: "channel filter preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_filter).to eq("unread")
+ end
+
+ page.refresh
+
+ expect(chat_sidebar).to have_channel(unread_channel)
+ expect(chat_sidebar).to have_no_channel(read_channel)
+ expect(chat_sidebar.channel_names).to eq(["Zulu channel"])
+
+ chat_sidebar.set_channel_filter("mentions")
+
+ expect(page).to have_css(
+ ".chat-sidebar-channels-filter-empty-state",
+ text: "No channels match this filter.",
+ )
+
+ chat_sidebar.show_all_channels
+
+ expect(chat_sidebar).to have_channel(unread_channel)
+ expect(chat_sidebar).to have_channel(read_channel)
+ try_until_success(reason: "reset channel filter preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_filter).to eq("all")
+ end
+ end
+
+ it "opens the new channel modal for staff from the channels options menu" do
+ current_user.update!(admin: true)
+ visit("/")
+
+ menu = chat_sidebar.open_channel_list_options
+ menu.option('[data-menu-option-id="createChannel"]').click
+
+ expect(page).to have_css(".chat-modal-create-channel")
+ end
+
+ it "keeps the starred section visible when the starred filter hides its channels" do
+ read_channel.membership_for(current_user).update!(starred: true)
+
+ visit("/")
+
+ within(chat_sidebar.starred_section) { expect(page).to have_css(".channel-#{read_channel.id}") }
+
+ chat_sidebar.set_starred_filter("unread")
+
+ within(chat_sidebar.starred_section) do
+ expect(page).to have_no_css(".channel-#{read_channel.id}")
+ end
+ expect(page).to have_css(
+ ".sidebar-section[data-section-name='chat-starred-channels']",
+ text: "No channels match this filter.",
+ )
+ try_until_success(reason: "starred filter preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_filter_starred).to eq("unread")
+ end
+
+ chat_sidebar.show_all_channels
+
+ within(chat_sidebar.starred_section) { expect(page).to have_css(".channel-#{read_channel.id}") }
+ try_until_success(reason: "reset starred filter preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_filter_starred).to eq("all")
+ end
+ end
+
+ it "hides the starred section when a filter is set but nothing is starred" do
+ current_user.user_option.update!(chat_channel_list_filter_starred: "unread")
+
+ visit("/")
+
+ expect(chat_sidebar).to have_no_starred_channels_section
+ end
+
+ it "keeps the DM section visible when the DM filter hides its channels" do
+ dm_channel = Fabricate(:direct_message_channel, users: [current_user, message_author])
+
+ visit("/")
+
+ within(chat_sidebar.dms_section) { expect(page).to have_css(".channel-#{dm_channel.id}") }
+
+ chat_sidebar.set_dm_filter("unread")
+
+ within(chat_sidebar.dms_section) { expect(page).to have_no_css(".channel-#{dm_channel.id}") }
+ expect(page).to have_css(
+ ".sidebar-section[data-section-name='chat-dms']",
+ text: "No channels match this filter.",
+ )
+ try_until_success(reason: "DM filter preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_filter_dms).to eq("unread")
+ end
+
+ chat_sidebar.show_all_channels
+
+ within(chat_sidebar.dms_section) { expect(page).to have_css(".channel-#{dm_channel.id}") }
+ try_until_success(reason: "reset DM filter preference saves asynchronously") do
+ expect(current_user.user_option.reload.chat_channel_list_filter_dms).to eq("all")
+ end
+ end
+end
diff --git a/plugins/chat/test/javascripts/components/channels-list-starred-test.gjs b/plugins/chat/test/javascripts/components/channels-list-starred-test.gjs
new file mode 100644
index 00000000000..06c059b8bdb
--- /dev/null
+++ b/plugins/chat/test/javascripts/components/channels-list-starred-test.gjs
@@ -0,0 +1,64 @@
+import { getOwner } from "@ember/owner";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { i18n } from "discourse-i18n";
+import ChannelsListStarred from "discourse/plugins/chat/discourse/components/channels-list-starred";
+import { CHAT_CHANNEL_LIST_FILTERS } from "discourse/plugins/chat/discourse/lib/chat-constants";
+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";
+import UserChatChannelMembership from "discourse/plugins/chat/discourse/models/user-chat-channel-membership";
+
+module("Integration | Component | ChannelsListStarred", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.manager = getOwner(this).lookup("service:chat-channels-manager");
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.fabricators = new ChatFabricators(getOwner(this));
+ });
+
+ test("shows the filtered empty state when the starred filter hides every channel", async function (assert) {
+ const setFilter = sinon.stub(this.preferences, "setFilter").resolves(true);
+ this.preferences.starredFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+
+ const channel = this.fabricators.channel({
+ id: 1,
+ chatable: this.fabricators.coreFabricators.category({ slug: "alpha" }),
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: true,
+ });
+ this.manager.store(channel);
+
+ await render(<template><ChannelsListStarred /></template>);
+
+ assert
+ .dom(".empty-state .empty-state__title")
+ .hasText(
+ i18n("chat.channel_list.empty.filtered"),
+ "the filtered empty state explains the filter"
+ );
+
+ await click(".empty-state__cta .btn");
+
+ assert.true(
+ setFilter.calledWith("starred", "all"),
+ "the show all action resets the starred filter"
+ );
+ });
+
+ test("keeps the plain empty message when there are no starred channels", async function (assert) {
+ await render(<template><ChannelsListStarred /></template>);
+
+ assert
+ .dom(".chat-channel-list__empty-message")
+ .exists("the no-starred-channels message is shown");
+ assert
+ .dom(".empty-state")
+ .doesNotExist("the filtered empty state is not shown without channels");
+ });
+});
diff --git a/plugins/chat/test/javascripts/components/chat-channel-list-sidebar-menu-test.gjs b/plugins/chat/test/javascripts/components/chat-channel-list-sidebar-menu-test.gjs
new file mode 100644
index 00000000000..5bf1c13e91e
--- /dev/null
+++ b/plugins/chat/test/javascripts/components/chat-channel-list-sidebar-menu-test.gjs
@@ -0,0 +1,814 @@
+import { getOwner } from "@ember/owner";
+import {
+ click,
+ find,
+ focus,
+ render,
+ settled,
+ triggerEvent,
+ triggerKeyEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import ModalContainer from "discourse/components/modal-container";
+import DMenus from "discourse/float-kit/components/d-menus";
+import { forceMobile } from "discourse/lib/mobile";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { i18n } from "discourse-i18n";
+import ChatChannelListFilterMenu from "discourse/plugins/chat/discourse/components/chat-channel-list-filter-menu";
+import ChatChannelListOptionsButton from "discourse/plugins/chat/discourse/components/chat-channel-list-options-button";
+import ChatChannelListSidebarMenu from "discourse/plugins/chat/discourse/components/chat-channel-list-sidebar-menu";
+import ChatChannelListSortMenu from "discourse/plugins/chat/discourse/components/chat-channel-list-sort-menu";
+import ChatSidebarChannelListFilterEmptyState from "discourse/plugins/chat/discourse/components/chat-sidebar-channel-list-filter-empty-state";
+import { CHANNEL_LIST_SECTION_OPTIONS } from "discourse/plugins/chat/discourse/lib/chat-channel-list-options";
+
+const sectionData = (section) => ({
+ section,
+ ...CHANNEL_LIST_SECTION_OPTIONS[section],
+});
+
+const CHANNELS_DATA = sectionData("channels");
+const STARRED_DATA = sectionData("starred");
+const DMS_DATA = sectionData("dms");
+
+module(
+ "Integration | Component | ChatChannelListSidebarMenu",
+ function (hooks) {
+ setupRenderingTest(hooks, { stubRouter: true });
+
+ test("shows browse and the current filter and sort", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ preferences.channelsFilter = "unread";
+ preferences.channelsSort = "priority";
+
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{CHANNELS_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom('[data-menu-option-id="browseChannels"]')
+ .hasText(
+ i18n("chat.channels_list_popup.browse"),
+ "the browse action is shown"
+ );
+ assert
+ .dom('[data-menu-option-id="filterChannels"]')
+ .hasAttribute("aria-expanded", "false", "the filter submenu is closed")
+ .hasAttribute("aria-haspopup", "menu", "the filter exposes its submenu")
+ .hasAttribute(
+ "aria-label",
+ i18n("chat.channel_list.options.current_filter", {
+ filter: i18n("chat.channel_list.filter.unread"),
+ })
+ )
+ .hasText(
+ i18n("chat.channel_list.filter.unread"),
+ "the current filter is shown"
+ );
+ assert
+ .dom('[data-menu-option-id="sortChannels"]')
+ .hasAttribute("aria-expanded", "false", "the sort submenu is closed")
+ .hasAttribute("aria-haspopup", "menu", "the sort exposes its submenu")
+ .hasAttribute(
+ "aria-label",
+ i18n("chat.channel_list.options.current_sort", {
+ sort: i18n("chat.channel_list.sort.priority"),
+ })
+ )
+ .hasText(
+ i18n("chat.channel_list.sort.priority"),
+ "the current sort is shown"
+ );
+ });
+
+ test("opens the filter submenu", async function (assert) {
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{CHANNELS_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ await click('[data-menu-option-id="filterChannels"]');
+
+ assert
+ .dom('[data-menu-option-id="filterChannels"]')
+ .hasAttribute(
+ "aria-expanded",
+ "true",
+ "the trigger reports its submenu"
+ );
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-filter-menu"]')
+ .hasAttribute("role", "menu", "the filter submenu has menu semantics");
+ assert
+ .dom(".chat-channel-list-filter-menu__all")
+ .hasAttribute("aria-checked", "true", "the default filter is selected");
+ });
+
+ test("opens the sort submenu", async function (assert) {
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{CHANNELS_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ await click('[data-menu-option-id="sortChannels"]');
+
+ assert
+ .dom('[data-menu-option-id="sortChannels"]')
+ .hasAttribute(
+ "aria-expanded",
+ "true",
+ "the trigger reports its submenu"
+ );
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-sort-menu"]')
+ .hasAttribute("role", "menu", "the sort submenu has menu semantics");
+ assert
+ .dom(".chat-channel-list-sort-menu__alphabetical")
+ .hasAttribute("aria-checked", "true", "the default sort is selected");
+ });
+
+ test("shows the filter, sort, and no top-level actions for the starred header", async function (assert) {
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{STARRED_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom('[data-menu-option-id="browseChannels"]')
+ .doesNotExist("the browse option is hidden");
+ assert
+ .dom('[data-menu-option-id="startDm"]')
+ .doesNotExist("the new message action is hidden");
+ assert
+ .dom('[data-menu-option-id="filterChannels"]')
+ .exists("the filter option is shown");
+ assert
+ .dom('[data-menu-option-id="sortChannels"]')
+ .exists("the sort option is shown behind a fly-out submenu");
+ });
+
+ test("shows the new message, filter, and sort options for the direct messages header", async function (assert) {
+ sinon
+ .stub(getOwner(this).lookup("service:chat"), "userCanDirectMessage")
+ .value(true);
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ preferences.dmsSort = "recent_activity";
+
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{DMS_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom('[data-menu-option-id="startDm"]')
+ .hasText(
+ i18n("chat.direct_messages.new"),
+ "the new message action is shown"
+ );
+ assert
+ .dom('[data-menu-option-id="browseChannels"]')
+ .doesNotExist("the browse option is hidden");
+ assert
+ .dom('[data-menu-option-id="filterChannels"]')
+ .exists("the filter option is shown");
+ assert
+ .dom('[data-menu-option-id="sortChannels"]')
+ .exists("the sort option is shown behind a fly-out submenu");
+
+ await click('[data-menu-option-id="sortChannels"]');
+
+ assert
+ .dom(".chat-channel-list-sort-menu__recent-activity")
+ .hasAttribute(
+ "aria-checked",
+ "true",
+ "the current sort choice is selected"
+ );
+ assert
+ .dom('.chat-channel-list-options-menu [aria-checked="true"]')
+ .exists({ count: 1 }, "exactly one sort choice is checked");
+ });
+
+ test("starts a personal chat from the direct messages header menu", async function (assert) {
+ sinon
+ .stub(getOwner(this).lookup("service:chat"), "userCanDirectMessage")
+ .value(true);
+
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ <ModalContainer />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: DMS_DATA,
+ });
+
+ await click('[data-menu-option-id="startDm"]');
+
+ assert
+ .dom(".chat-modal-new-message")
+ .exists("the new message modal opens");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .doesNotExist("the menu closes");
+ });
+
+ test("hides the new message option when the user cannot send direct messages", async function (assert) {
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{DMS_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom('[data-menu-option-id="startDm"]')
+ .doesNotExist("the new message action is hidden without permission");
+ assert
+ .dom(".dropdown-menu__divider")
+ .doesNotExist(
+ "the top-level divider is dropped with no actions above it"
+ );
+ assert
+ .dom('[data-menu-option-id="filterChannels"]')
+ .exists("the filter option is still shown");
+ });
+
+ test("hides the create channel option for non-staff", async function (assert) {
+ await render(
+ <template>
+ <ChatChannelListSidebarMenu @data={{CHANNELS_DATA}} />
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom('[data-menu-option-id="createChannel"]')
+ .doesNotExist("create channel is hidden for non-staff");
+ });
+
+ test("creates a channel from the channels header menu", async function (assert) {
+ getOwner(this).lookup("service:current-user").set("admin", true);
+
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ <ModalContainer />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: CHANNELS_DATA,
+ });
+
+ assert
+ .dom('[data-menu-option-id="createChannel"]')
+ .hasText(
+ i18n("chat.channels_list_popup.create"),
+ "the create channel action is shown for staff"
+ );
+
+ await click('[data-menu-option-id="createChannel"]');
+
+ assert
+ .dom(".chat-modal-create-channel")
+ .exists("the create channel modal opens");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .doesNotExist("the menu closes");
+ });
+
+ test("selecting a sort choice from the sort fly-out saves it", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setSort = sinon.stub(preferences, "setSort").resolves(true);
+
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: STARRED_DATA,
+ });
+
+ await click('[data-menu-option-id="sortChannels"]');
+ await click(".chat-channel-list-sort-menu__priority");
+
+ assert.true(
+ setSort.calledWith("starred", "priority"),
+ "the selected sort is saved for the starred section"
+ );
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .doesNotExist("the header menu closes after selection");
+ assert
+ .dom(".menu-trigger")
+ .isFocused("focus returns to the trigger after selection");
+ });
+
+ test("switches between submenus without closing the parent", async function (assert) {
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: CHANNELS_DATA,
+ });
+
+ await click('[data-menu-option-id="filterChannels"]');
+ await click('[data-menu-option-id="sortChannels"]');
+
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .exists("the parent menu remains open");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-filter-menu"]')
+ .doesNotExist("the previous submenu closes");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-sort-menu"]')
+ .exists("the selected submenu opens");
+ });
+
+ test("closes both menus before saving a selection", async function (assert) {
+ let resolveSave;
+ const savePromise = new Promise((resolve) => {
+ resolveSave = resolve;
+ });
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setSort = sinon.stub(preferences, "setSort").returns(savePromise);
+
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: CHANNELS_DATA,
+ });
+ await click('[data-menu-option-id="sortChannels"]');
+
+ await click(".chat-channel-list-sort-menu__priority");
+
+ assert.true(setSort.calledOnce, "the selection starts saving");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .doesNotExist("the parent menu closes while the save is pending");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-sort-menu"]')
+ .doesNotExist("the submenu closes while the save is pending");
+ assert
+ .dom(".menu-trigger")
+ .isFocused("the menu restores focus to its trigger after selection");
+
+ resolveSave(true);
+ await settled();
+ });
+
+ test("closes mobile modals and restores focus after selection", async function (assert) {
+ forceMobile();
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ sinon.stub(preferences, "setFilter").resolves(true);
+
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ <ModalContainer />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ modalForMobile: true,
+ data: CHANNELS_DATA,
+ });
+ await click('[data-menu-option-id="filterChannels"]');
+
+ assert
+ .dom(
+ '.fk-d-menu-modal[data-identifier="chat-channel-list-filter-menu"]'
+ )
+ .exists("the submenu renders as a mobile modal");
+ await click(".chat-channel-list-filter-menu__mentions");
+ assert.dom(".fk-d-menu-modal").doesNotExist("both modal menus close");
+
+ assert
+ .dom(".menu-trigger")
+ .isFocused("focus returns to the trigger after the modals close");
+ });
+
+ test("Escape and keyboard selection close the menu tree", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setFilter = sinon.stub(preferences, "setFilter").resolves(true);
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: CHANNELS_DATA,
+ });
+ await click('[data-menu-option-id="filterChannels"]');
+ await focus(".chat-channel-list-filter-menu__mentions");
+ await triggerKeyEvent(document.activeElement, "keydown", "Escape");
+
+ assert
+ .dom(".chat-channel-list-filter-menu")
+ .doesNotExist("Escape dismisses the submenu");
+ assert
+ .dom(".chat-channel-list-options-menu")
+ .doesNotExist("Escape dismisses the parent menu too");
+ assert
+ .dom(".menu-trigger")
+ .isFocused("focus returns to the outer trigger");
+
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: CHANNELS_DATA,
+ });
+ await focus('[data-menu-option-id="filterChannels"]');
+ // Key events from test helpers do not synthesize the native button click.
+ await triggerEvent(document.activeElement, "click", { detail: 0 });
+ await focus(".chat-channel-list-filter-menu__mentions");
+ await triggerKeyEvent(document.activeElement, "keydown", "Enter");
+
+ assert.true(
+ setFilter.calledWith("channels", "mentions"),
+ "keyboard selection saves the filter"
+ );
+ assert
+ .dom(".chat-channel-list-options-menu")
+ .doesNotExist("selection closes the parent");
+ assert
+ .dom(".chat-channel-list-filter-menu")
+ .doesNotExist("selection closes the submenu");
+ assert
+ .dom(".menu-trigger")
+ .isFocused("focus returns to the sidebar trigger");
+ });
+
+ test("closes the submenu before browsing channels", async function (assert) {
+ await render(
+ <template>
+ <button class="menu-trigger" type="button">Open</button>
+ <DMenus />
+ </template>
+ );
+ const menu = getOwner(this).lookup("service:menu");
+ const router = getOwner(this).lookup("service:router");
+ router.transitionTo = sinon.spy();
+ await menu.show(find(".menu-trigger"), {
+ component: ChatChannelListSidebarMenu,
+ contentRole: "menu",
+ identifier: "chat-channel-list-options-menu",
+ data: CHANNELS_DATA,
+ });
+ await click('[data-menu-option-id="sortChannels"]');
+
+ await click('[data-menu-option-id="browseChannels"]');
+
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .doesNotExist("the parent menu closes");
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-sort-menu"]')
+ .doesNotExist("the submenu closes");
+ assert.true(
+ router.transitionTo.calledWith("chat.browse.open"),
+ "the browse page opens"
+ );
+ });
+ }
+);
+
+module("Integration | Component | ChatChannelListFilterMenu", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("shows and changes the selected filter", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ preferences.channelsFilter = "unread";
+ const setFilter = sinon.stub(preferences, "setFilter").resolves(true);
+
+ await render(<template><ChatChannelListFilterMenu /></template>);
+
+ assert
+ .dom(".chat-channel-list-filter-menu__unread")
+ .hasAttribute(
+ "role",
+ "menuitemradio",
+ "filter choices have radio semantics"
+ )
+ .hasAttribute("aria-checked", "true", "the current filter is selected");
+
+ await click(".chat-channel-list-filter-menu__mentions");
+
+ assert.true(
+ setFilter.calledWith("channels", "mentions"),
+ "the selected filter is saved for the channels section"
+ );
+ });
+
+ test("marks only the active filter as selected", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ preferences.channelsFilter = "active";
+
+ await render(<template><ChatChannelListFilterMenu /></template>);
+
+ assert
+ .dom(".chat-channel-list-filter-menu__active")
+ .hasAttribute("aria-checked", "true", "active is selected")
+ .includesText(i18n("chat.channel_list.filter.active"))
+ .includesText(
+ i18n("chat.channel_list.filter.active_description", { days: 30 })
+ );
+ assert
+ .dom(".chat-channel-list-filter-menu__active .d-icon")
+ .exists("the selected option has a checkmark");
+ assert
+ .dom(".chat-channel-list-filter-menu__all")
+ .hasAttribute("aria-checked", "false", "all is not selected");
+ assert
+ .dom(".chat-channel-list-filter-menu__all .d-icon")
+ .exists("unselected options retain a checkmark gutter");
+ assert
+ .dom('.chat-channel-list-filter-menu [aria-checked="true"]')
+ .exists({ count: 1 }, "only one filter is selected");
+ });
+});
+
+module("Integration | Component | ChatChannelListSortMenu", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("shows and changes the selected sort", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ preferences.channelsSort = "priority";
+ const setSort = sinon.stub(preferences, "setSort").resolves(true);
+
+ await render(
+ <template><ChatChannelListSortMenu @section="channels" /></template>
+ );
+
+ assert
+ .dom(".chat-channel-list-sort-menu__priority")
+ .hasAttribute(
+ "role",
+ "menuitemradio",
+ "sort choices have radio semantics"
+ )
+ .hasAttribute("aria-checked", "true", "the current sort is selected")
+ .includesText(i18n("chat.channel_list.sort.priority"))
+ .includesText(i18n("chat.channel_list.sort.priority_description"));
+
+ await click(".chat-channel-list-sort-menu__recent-activity");
+
+ assert.true(
+ setSort.calledWith("channels", "recent_activity"),
+ "the selected sort is saved"
+ );
+ });
+});
+
+module(
+ "Integration | Component | ChatSidebarChannelListFilterEmptyState",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("does not compete with the sidebar text-search empty state", async function (assert) {
+ const sidebarState = getOwner(this).lookup("service:sidebar-state");
+ sidebarState.filter = "missing";
+
+ await render(
+ <template>
+ <ul>
+ <ChatSidebarChannelListFilterEmptyState />
+ </ul>
+ </template>
+ );
+
+ assert
+ .dom(".chat-sidebar-channels-filter-empty-state")
+ .doesNotExist("the channel-filter reset is hidden during text search");
+ });
+
+ test("resets the channels filter by default", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setFilter = sinon.stub(preferences, "setFilter").resolves(true);
+
+ await render(
+ <template>
+ <ul>
+ <ChatSidebarChannelListFilterEmptyState />
+ </ul>
+ </template>
+ );
+
+ assert
+ .dom(".chat-sidebar-channels-filter-empty-state")
+ .hasTagName("li", "the state is valid section-list content")
+ .includesText(
+ i18n("chat.channel_list.empty.filtered"),
+ "the empty state explains the filter"
+ );
+
+ await click(".chat-sidebar-channels-filter-empty-state__reset");
+
+ assert.true(
+ setFilter.calledWith("channels", "all"),
+ "the channels filter is reset"
+ );
+ });
+
+ test("resets the filter of the section it is rendered for", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setFilter = sinon.stub(preferences, "setFilter").resolves(true);
+
+ await render(
+ <template>
+ <ul>
+ <ChatSidebarChannelListFilterEmptyState @section="starred" />
+ <ChatSidebarChannelListFilterEmptyState @section="dms" />
+ </ul>
+ </template>
+ );
+
+ await click(".chat-sidebar-channels-filter-empty-state__reset");
+
+ assert.true(
+ setFilter.calledWith("starred", "all"),
+ "the starred filter is reset"
+ );
+
+ const resets = document.querySelectorAll(
+ ".chat-sidebar-channels-filter-empty-state__reset"
+ );
+ await click(resets[1]);
+
+ assert.true(
+ setFilter.calledWith("dms", "all"),
+ "the dms filter is reset"
+ );
+ });
+
+ test("renders an illustrated state matching the no-channels layout", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setFilter = sinon.stub(preferences, "setFilter").resolves(true);
+
+ await render(
+ <template>
+ <ChatSidebarChannelListFilterEmptyState
+ @layout="empty-state"
+ @section="dms"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".empty-state__image")
+ .exists("the same illustration as the no-channels state is shown");
+ assert
+ .dom(".empty-state__title")
+ .hasText(
+ i18n("chat.channel_list.empty.filtered"),
+ "the title explains the filter"
+ );
+
+ await click(".empty-state__cta .btn");
+
+ assert.true(
+ setFilter.calledWith("dms", "all"),
+ "the show all action resets the dms filter"
+ );
+ });
+ }
+);
+
+module(
+ "Integration | Component | ChatChannelListOptionsButton",
+ function (hooks) {
+ setupRenderingTest(hooks, { stubRouter: true });
+
+ test("opens the shared channel list menu for its section", async function (assert) {
+ sinon
+ .stub(getOwner(this).lookup("service:chat"), "userCanDirectMessage")
+ .value(true);
+
+ await render(
+ <template>
+ <ChatChannelListOptionsButton @section="dms" />
+ <DMenus />
+ </template>
+ );
+
+ await click(".chat-channel-list-options-button");
+
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .hasAttribute("role", "menu", "the shared channel list menu opens");
+ assert
+ .dom('[data-menu-option-id="startDm"]')
+ .exists("the new message action is exposed");
+ assert
+ .dom('[data-menu-option-id="filterChannels"]')
+ .exists("the filter action is exposed");
+ assert
+ .dom('[data-menu-option-id="sortChannels"]')
+ .exists("the sort action is exposed");
+ });
+
+ test("saves a sort from the shared menu for the trigger's section", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const setSort = sinon.stub(preferences, "setSort").resolves(true);
+
+ await render(
+ <template>
+ <ChatChannelListOptionsButton @section="dms" />
+ <DMenus />
+ </template>
+ );
+
+ await click(".chat-channel-list-options-button");
+ await click('[data-menu-option-id="sortChannels"]');
+ await click(".chat-channel-list-sort-menu__recent-activity");
+
+ assert.true(
+ setSort.calledWith("dms", "recent_activity"),
+ "the selected sort is saved for the section"
+ );
+ assert
+ .dom('.fk-d-menu[data-identifier="chat-channel-list-options-menu"]')
+ .doesNotExist("the menu closes after selection");
+ });
+ }
+);
diff --git a/plugins/chat/test/javascripts/components/chat-navbar-channel-list-options-button-test.gjs b/plugins/chat/test/javascripts/components/chat-navbar-channel-list-options-button-test.gjs
new file mode 100644
index 00000000000..cb2fe2eb6c2
--- /dev/null
+++ b/plugins/chat/test/javascripts/components/chat-navbar-channel-list-options-button-test.gjs
@@ -0,0 +1,58 @@
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import ModalContainer from "discourse/components/modal-container";
+import DMenus from "discourse/float-kit/components/d-menus";
+import { forceMobile, resetMobile } from "discourse/lib/mobile";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { i18n } from "discourse-i18n";
+import ChatNavbarChannelListOptionsButton from "discourse/plugins/chat/discourse/components/chat/navbar/channel-list-options-button";
+
+module(
+ "Integration | Component | ChatNavbarChannelListOptionsButton",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ resetMobile();
+ });
+
+ test("is hidden on desktop because the in-list divider shows the menu", async function (assert) {
+ await render(
+ <template>
+ <ChatNavbarChannelListOptionsButton @section="channels" />
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom(".chat-channel-list-options-button")
+ .doesNotExist("the navbar options button is desktop-hidden");
+ });
+
+ test("opens the section's shared options menu on mobile", async function (assert) {
+ forceMobile();
+
+ await render(
+ <template>
+ <ChatNavbarChannelListOptionsButton @section="channels" />
+ <DMenus />
+ <ModalContainer />
+ </template>
+ );
+
+ await click(".chat-channel-list-options-button");
+
+ assert
+ .dom(
+ '.fk-d-menu-modal[data-identifier="chat-channel-list-options-menu"]'
+ )
+ .exists("the shared options menu opens from the mobile navbar");
+ assert
+ .dom(".chat-channel-list-options-menu")
+ .includesText(
+ i18n("chat.channels_list_popup.browse"),
+ "the channels options are shown for the channels section"
+ );
+ });
+ }
+);
diff --git a/plugins/chat/test/javascripts/unit/services/chat-channel-list-preferences-test.js b/plugins/chat/test/javascripts/unit/services/chat-channel-list-preferences-test.js
new file mode 100644
index 00000000000..d4addd30896
--- /dev/null
+++ b/plugins/chat/test/javascripts/unit/services/chat-channel-list-preferences-test.js
@@ -0,0 +1,371 @@
+import { getOwner } from "@ember/owner";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { logIn } from "discourse/tests/helpers/qunit-helpers";
+import {
+ CHAT_CHANNEL_LIST_FILTERS,
+ CHAT_CHANNEL_LIST_SORTS,
+} from "discourse/plugins/chat/discourse/lib/chat-constants";
+
+module("Unit | Service | chat-channel-list-preferences", function (hooks) {
+ setupTest(hooks);
+
+ test("initializes from the current user", function (assert) {
+ const currentUser = logIn(this.owner);
+ currentUser.set("user_option.chat_channel_list_filter", "mentions");
+ currentUser.set("user_option.chat_channel_list_filter_starred", "active");
+ currentUser.set("user_option.chat_channel_list_filter_dms", "unread");
+ currentUser.set("user_option.chat_channel_list_sort", "priority");
+ currentUser.set(
+ "user_option.chat_channel_list_sort_starred",
+ "recent_activity"
+ );
+ currentUser.set("user_option.chat_channel_list_sort_dms", "priority");
+
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+
+ assert.strictEqual(
+ preferences.filterFor("channels"),
+ CHAT_CHANNEL_LIST_FILTERS.MENTIONS,
+ "it initializes the channels filter"
+ );
+ assert.strictEqual(
+ preferences.filterFor("starred"),
+ CHAT_CHANNEL_LIST_FILTERS.ACTIVE,
+ "it initializes the starred filter"
+ );
+ assert.strictEqual(
+ preferences.filterFor("dms"),
+ CHAT_CHANNEL_LIST_FILTERS.UNREAD,
+ "it initializes the dms filter"
+ );
+ assert.strictEqual(
+ preferences.sortFor("channels"),
+ CHAT_CHANNEL_LIST_SORTS.PRIORITY,
+ "it initializes the channels sort"
+ );
+ assert.strictEqual(
+ preferences.sortFor("starred"),
+ CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY,
+ "it initializes the starred sort"
+ );
+ assert.strictEqual(
+ preferences.sortFor("dms"),
+ CHAT_CHANNEL_LIST_SORTS.PRIORITY,
+ "it initializes the dms sort"
+ );
+ });
+
+ test("uses defaults without a signed-in user", async function (assert) {
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+
+ assert.strictEqual(
+ preferences.filterFor("channels"),
+ "all",
+ "the channels filter defaults to all"
+ );
+ assert.strictEqual(
+ preferences.filterFor("starred"),
+ "all",
+ "the starred filter defaults to all"
+ );
+ assert.strictEqual(
+ preferences.filterFor("dms"),
+ "all",
+ "the dms filter defaults to all"
+ );
+ assert.strictEqual(
+ preferences.sortFor("channels"),
+ "alphabetical",
+ "the channels sort defaults to alphabetical"
+ );
+ assert.strictEqual(
+ preferences.sortFor("starred"),
+ "alphabetical",
+ "the starred sort defaults to alphabetical"
+ );
+ assert.strictEqual(
+ preferences.sortFor("dms"),
+ "alphabetical",
+ "the dms sort defaults to alphabetical"
+ );
+ assert.false(
+ await preferences.setFilter("channels", CHAT_CHANNEL_LIST_FILTERS.UNREAD),
+ "anonymous filter changes are refused"
+ );
+ assert.false(
+ await preferences.setSort("channels", CHAT_CHANNEL_LIST_SORTS.PRIORITY),
+ "anonymous sort changes are refused"
+ );
+ });
+
+ test("saves filter and sort changes per section independently", async function (assert) {
+ const currentUser = logIn(this.owner);
+ currentUser.set("user_option.chat_channel_list_filter", "all");
+ currentUser.set("user_option.chat_channel_list_sort", "alphabetical");
+ currentUser.set(
+ "user_option.chat_channel_list_sort_starred",
+ "alphabetical"
+ );
+ currentUser.set("user_option.chat_channel_list_sort_dms", "alphabetical");
+ const pendingSaves = [];
+ currentUser.save = (fields) =>
+ new Promise((resolve) => {
+ pendingSaves.push({ fields, resolve });
+ });
+
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ const channelsFilterSave = preferences.setFilter(
+ "channels",
+ CHAT_CHANNEL_LIST_FILTERS.UNREAD
+ );
+ const dmsFilterSave = preferences.setFilter(
+ "dms",
+ CHAT_CHANNEL_LIST_FILTERS.MENTIONS
+ );
+ const channelsSave = preferences.setSort(
+ "channels",
+ CHAT_CHANNEL_LIST_SORTS.PRIORITY
+ );
+ const starredSave = preferences.setSort(
+ "starred",
+ CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY
+ );
+
+ assert.strictEqual(
+ preferences.filterFor("channels"),
+ "unread",
+ "the channels filter is optimistic"
+ );
+ assert.strictEqual(
+ preferences.filterFor("dms"),
+ "mentions",
+ "the dms filter is optimistic"
+ );
+ assert.strictEqual(
+ preferences.filterFor("starred"),
+ "all",
+ "the starred filter is untouched"
+ );
+ assert.strictEqual(
+ preferences.sortFor("channels"),
+ "priority",
+ "the channels sort is optimistic"
+ );
+ assert.strictEqual(
+ preferences.sortFor("starred"),
+ "recent_activity",
+ "the starred sort is optimistic"
+ );
+ assert.strictEqual(
+ preferences.sortFor("dms"),
+ "alphabetical",
+ "the dms sort is untouched"
+ );
+ assert.true(
+ preferences.isSavingFilterFor("channels"),
+ "channels filter is saving"
+ );
+ assert.true(preferences.isSavingFilterFor("dms"), "dms filter is saving");
+ assert.false(
+ preferences.isSavingFilterFor("starred"),
+ "starred filter is not saving"
+ );
+ assert.true(
+ preferences.isSavingSortFor("channels"),
+ "channels sort is saving"
+ );
+ assert.true(
+ preferences.isSavingSortFor("starred"),
+ "starred sort is saving"
+ );
+ assert.false(preferences.isSavingSortFor("dms"), "dms sort is not saving");
+ assert.deepEqual(
+ pendingSaves.map(({ fields }) => fields),
+ [
+ ["chat_channel_list_filter"],
+ ["chat_channel_list_filter_dms"],
+ ["chat_channel_list_sort"],
+ ["chat_channel_list_sort_starred"],
+ ],
+ "each preference saves without blocking the others"
+ );
+
+ pendingSaves.forEach(({ resolve }) => resolve());
+ assert.true(await channelsFilterSave, "the channels filter completes");
+ assert.true(await dmsFilterSave, "the dms filter completes");
+ assert.true(await channelsSave, "the channels sort completes");
+ assert.true(await starredSave, "the starred sort completes");
+ ["channels", "starred", "dms"].forEach((section) => {
+ assert.false(
+ preferences.isSavingFilterFor(section),
+ `the ${section} filter pending state clears`
+ );
+ assert.false(
+ preferences.isSavingSortFor(section),
+ `the ${section} sort pending state clears`
+ );
+ });
+ });
+
+ test("persists changed preferences", async function (assert) {
+ const currentUser = logIn(this.owner);
+ currentUser.set("user_option.chat_channel_list_filter", "all");
+ currentUser.set("user_option.chat_channel_list_filter_dms", "all");
+ currentUser.set("user_option.chat_channel_list_sort", "alphabetical");
+ currentUser.set("user_option.chat_channel_list_sort_dms", "alphabetical");
+ const requests = [];
+ pretender.put("/u/eviltrout.json", (request) => {
+ requests.push(new URLSearchParams(request.requestBody));
+ return response(200, { user: {} });
+ });
+
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+
+ assert.true(
+ await preferences.setFilter("channels", CHAT_CHANNEL_LIST_FILTERS.UNREAD),
+ "the channels filter saves"
+ );
+ assert.true(
+ await preferences.setFilter("dms", CHAT_CHANNEL_LIST_FILTERS.MENTIONS),
+ "the dms filter saves"
+ );
+ assert.true(
+ await preferences.setSort(
+ "channels",
+ CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY
+ ),
+ "the channels sort saves"
+ );
+ assert.true(
+ await preferences.setSort("dms", CHAT_CHANNEL_LIST_SORTS.PRIORITY),
+ "the dms sort saves"
+ );
+
+ assert.strictEqual(requests.length, 4, "each changed preference is saved");
+ assert.strictEqual(
+ requests[0].get("chat_channel_list_filter"),
+ "unread",
+ "only the changed channels filter is sent"
+ );
+ assert.strictEqual(
+ requests[0].get("chat_channel_list_sort"),
+ null,
+ "the sort is omitted from the filter request"
+ );
+ assert.strictEqual(
+ requests[1].get("chat_channel_list_filter_dms"),
+ "mentions",
+ "only the changed dms filter is sent"
+ );
+ assert.strictEqual(
+ requests[1].get("chat_channel_list_filter"),
+ null,
+ "the channels filter is omitted"
+ );
+ assert.strictEqual(
+ requests[2].get("chat_channel_list_sort"),
+ "recent_activity",
+ "only the changed channels sort is sent"
+ );
+ assert.strictEqual(
+ requests[2].get("chat_channel_list_filter"),
+ null,
+ "the filter is omitted from the sort request"
+ );
+ assert.strictEqual(
+ requests[3].get("chat_channel_list_sort_dms"),
+ "priority",
+ "only the changed dms sort is sent"
+ );
+ });
+
+ test("does not save unchanged or invalid values", async function (assert) {
+ const currentUser = logIn(this.owner);
+ currentUser.set("user_option.chat_channel_list_filter", "all");
+ let requestsCount = 0;
+ pretender.put("/u/eviltrout.json", () => {
+ requestsCount += 1;
+ return response(200, { user: {} });
+ });
+
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+
+ assert.true(
+ await preferences.setFilter("channels", CHAT_CHANNEL_LIST_FILTERS.ALL),
+ "an unchanged value succeeds"
+ );
+ assert.false(
+ await preferences.setFilter("channels", "invalid"),
+ "an invalid value fails"
+ );
+ assert.true(
+ await preferences.setSort(
+ "channels",
+ CHAT_CHANNEL_LIST_SORTS.ALPHABETICAL
+ ),
+ "an unchanged sort succeeds"
+ );
+ assert.false(
+ await preferences.setSort("channels", "invalid"),
+ "an invalid sort fails"
+ );
+ assert.false(
+ await preferences.setFilter(
+ "unknown-section",
+ CHAT_CHANNEL_LIST_FILTERS.UNREAD
+ ),
+ "an unknown section fails"
+ );
+ assert.false(
+ await preferences.setSort(
+ "unknown-section",
+ CHAT_CHANNEL_LIST_SORTS.PRIORITY
+ ),
+ "an unknown sort section fails"
+ );
+ assert.strictEqual(requestsCount, 0, "no request is sent");
+ });
+
+ test("rolls back a failed save", async function (assert) {
+ const currentUser = logIn(this.owner);
+ currentUser.set("user_option.chat_channel_list_filter", "all");
+ pretender.put("/u/eviltrout.json", () => {
+ return response(422, { errors: ["Unable to save"] });
+ });
+
+ const preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+
+ assert.false(
+ await preferences.setFilter("channels", CHAT_CHANNEL_LIST_FILTERS.UNREAD),
+ "the failed request is reported"
+ );
+ assert.strictEqual(
+ preferences.filterFor("channels"),
+ "all",
+ "the service value is restored"
+ );
+ assert.strictEqual(
+ currentUser.user_option.chat_channel_list_filter,
+ "all",
+ "the user option is restored"
+ );
+ assert.false(
+ preferences.isSavingFilterFor("channels"),
+ "the saving state is cleared"
+ );
+ });
+});
diff --git a/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.js b/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.js
index ab75ce00145..6ffb7d02cfd 100644
--- a/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.js
+++ b/plugins/chat/test/javascripts/unit/services/chat-channels-manager-test.js
@@ -1,6 +1,12 @@
import { getOwner } from "@ember/owner";
import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
+import sinon from "sinon";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import {
+ CHAT_CHANNEL_LIST_FILTERS,
+ CHAT_CHANNEL_LIST_SORTS,
+} from "discourse/plugins/chat/discourse/lib/chat-constants";
import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";
import UserChatChannelMembership from "discourse/plugins/chat/discourse/models/user-chat-channel-membership";
@@ -12,6 +18,134 @@ module("Unit | Service | chat-channels-manager", function (hooks) {
this.fabricators = new ChatFabricators(getOwner(this));
});
+ module("#toggleStarred", function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.channel = this.fabricators.channel();
+ this.channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: false,
+ });
+ });
+
+ test("guards pending changes and persists the optimistic value", async function (assert) {
+ const channel = this.channel;
+ const membership = channel.currentUserMembership;
+ const requests = [];
+ pretender.put(
+ `/chat/api/channels/${channel.id}/memberships/me`,
+ (request) => {
+ requests.push(
+ new URLSearchParams(request.requestBody).get("starred")
+ );
+ return response(200, {});
+ }
+ );
+ let finishClosing;
+ const closing = new Promise((resolve) => {
+ finishClosing = resolve;
+ });
+
+ const update = this.subject.toggleStarred(channel, {
+ beforeUpdate: () => closing,
+ });
+
+ assert.true(
+ this.subject.isUpdatingStarred(channel),
+ "closing the menu is guarded"
+ );
+ assert.false(
+ membership.starred,
+ "the row stays in place until the menu closes"
+ );
+ await this.subject.toggleStarred(channel);
+ assert.strictEqual(
+ requests.length,
+ 0,
+ "a second caller cannot start another update"
+ );
+
+ finishClosing();
+ await closing;
+ assert.true(
+ membership.starred,
+ "the membership updates before the request completes"
+ );
+ await update;
+
+ assert.deepEqual(requests, ["true"], "one starred update is persisted");
+ assert.false(
+ this.subject.isUpdatingStarred(channel),
+ "the guard clears after saving"
+ );
+
+ await this.subject.toggleStarred(channel);
+ assert.false(
+ membership.starred,
+ "the channel can subsequently be unstarred"
+ );
+ assert.deepEqual(
+ requests,
+ ["true", "false"],
+ "the second change is persisted"
+ );
+ });
+
+ test("rolls back failed saves and permits retrying", async function (assert) {
+ const channel = this.channel;
+ pretender.put(`/chat/api/channels/${channel.id}/memberships/me`, () =>
+ response(422, { errors: ["Unable to star channel"] })
+ );
+
+ await this.subject.toggleStarred(channel);
+
+ assert.false(
+ channel.currentUserMembership.starred,
+ "the previous membership is restored"
+ );
+ assert.false(
+ this.subject.isUpdatingStarred(channel),
+ "the failed request releases the guard"
+ );
+
+ pretender.put(`/chat/api/channels/${channel.id}/memberships/me`, () =>
+ response(200, {})
+ );
+ await this.subject.toggleStarred(channel);
+ assert.true(channel.currentUserMembership.starred, "retrying succeeds");
+ });
+
+ test("releases the guard when closing the menu fails", async function (assert) {
+ const channel = this.channel;
+ let requests = 0;
+ pretender.put(`/chat/api/channels/${channel.id}/memberships/me`, () => {
+ requests++;
+ return response(200, {});
+ });
+
+ await this.subject.toggleStarred(channel, {
+ beforeUpdate: () =>
+ Promise.reject({ errors: ["Unable to close menu"] }),
+ });
+
+ assert.false(
+ channel.currentUserMembership.starred,
+ "the membership was not changed"
+ );
+ assert.strictEqual(requests, 0, "no request was sent");
+ assert.false(
+ this.subject.isUpdatingStarred(channel),
+ "the close failure releases the guard"
+ );
+
+ await this.subject.toggleStarred(channel);
+ assert.true(
+ channel.currentUserMembership.starred,
+ "a later attempt succeeds"
+ );
+ assert.strictEqual(requests, 1, "the later attempt is persisted");
+ });
+ });
+
module("#sortChannelsByActivity with starred channels", function () {
test("prioritizes starred channels over unstarred", function (assert) {
const channelA = this.fabricators.channel({
@@ -225,380 +359,1080 @@ module("Unit | Service | chat-channels-manager", function (hooks) {
});
});
- module("#starredChannelsByActivity", function () {
- test("sorts starred channels with unreads first", function (assert) {
- const channelWithUnread = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "channel-with-unread",
- }),
+ 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 channelNoUnread = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "channel-no-unread",
- }),
+ const dmB = this.fabricators.channel({
+ chatable: this.fabricators.directMessage(),
+ title: "Bob",
});
- channelWithUnread.currentUserMembership =
- UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
- channelNoUnread.currentUserMembership = UserChatChannelMembership.create({
+ dmA.currentUserMembership = UserChatChannelMembership.create({
following: true,
starred: true,
});
+ dmB.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: false,
+ });
- channelWithUnread.tracking.unreadCount = 5;
- channelNoUnread.tracking.unreadCount = 0;
-
- this.subject.store(channelNoUnread);
- this.subject.store(channelWithUnread);
+ this.subject.store(dmA);
+ this.subject.store(dmB);
- const result = this.subject.starredChannelsByActivity;
+ const result = this.subject.directMessageChannels;
assert.strictEqual(
result[0].id,
- channelWithUnread.id,
- "channel with unreads comes first"
+ dmA.id,
+ "starred DM channel comes first"
);
assert.strictEqual(
result[1].id,
- channelNoUnread.id,
- "channel without unreads comes second"
+ dmB.id,
+ "unstarred DM channel comes second"
);
});
- test("includes both public and DM starred channels", function (assert) {
- const publicChannel = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "public",
- }),
+ 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 dmChannel = this.fabricators.channel({
+ const dmBob = this.fabricators.channel({
chatable: this.fabricators.directMessage(),
- title: "DM User",
+ title: "Bob",
});
- publicChannel.currentUserMembership = UserChatChannelMembership.create({
+ dmCharlie.currentUserMembership = UserChatChannelMembership.create({
following: true,
starred: true,
});
- dmChannel.currentUserMembership = UserChatChannelMembership.create({
+ dmAlice.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: true,
+ });
+ dmBob.currentUserMembership = UserChatChannelMembership.create({
following: true,
starred: true,
});
- this.subject.store(publicChannel);
- this.subject.store(dmChannel);
+ this.subject.store(dmCharlie);
+ this.subject.store(dmAlice);
+ this.subject.store(dmBob);
- const result = this.subject.starredChannelsByActivity;
+ const result = this.subject.directMessageChannels;
- assert.strictEqual(result.length, 2, "returns both channels");
+ 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("prioritizes unread status over channel type", function (assert) {
- const readPublicChannel = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "read-public",
- }),
+ 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 unreadDmChannel = this.fabricators.channel({
+ const unstarredDM = this.fabricators.channel({
chatable: this.fabricators.directMessage(),
- title: "Unread DM",
+ title: "Unstarred User",
});
- readPublicChannel.currentUserMembership =
- UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
- unreadDmChannel.currentUserMembership = UserChatChannelMembership.create({
+ starredDM.currentUserMembership = UserChatChannelMembership.create({
following: true,
starred: true,
});
+ unstarredDM.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: false,
+ });
- readPublicChannel.tracking.unreadCount = 0;
- unreadDmChannel.tracking.unreadCount = 3;
-
- this.subject.store(readPublicChannel);
- this.subject.store(unreadDmChannel);
+ this.subject.store(unstarredDM);
+ this.subject.store(starredDM);
- const result = this.subject.starredChannelsByActivity;
+ const result = this.subject.directMessageChannels;
assert.strictEqual(
result[0].id,
- unreadDmChannel.id,
- "unread DM comes before read public channel"
+ starredDM.id,
+ "starred DM channel is first"
);
assert.strictEqual(
result[1].id,
- readPublicChannel.id,
- "read public channel comes after unread DM"
+ unstarredDM.id,
+ "unstarred DM channel is after starred"
);
});
+ });
- test("sorts unread public channels before unread DMs", function (assert) {
- const unreadPublicChannel = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "unread-public",
- }),
- });
- const unreadDmChannel = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Unread DM",
- });
-
- unreadPublicChannel.currentUserMembership =
- UserChatChannelMembership.create({
+ module("#sidebarPublicMessageChannels", function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.buildChannel = ({
+ id,
+ slug,
+ createdAt,
+ unreadCount = 0,
+ mentionCount = 0,
+ watchedThreadsUnreadCount = 0,
+ muted = false,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.coreFabricators.category({ slug }),
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
following: true,
- starred: true,
+ starred: false,
+ muted,
});
- unreadDmChannel.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
-
- unreadPublicChannel.tracking.unreadCount = 2;
- unreadDmChannel.tracking.unreadCount = 5;
-
- this.subject.store(unreadDmChannel);
- this.subject.store(unreadPublicChannel);
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ channel.tracking.unreadCount = unreadCount;
+ channel.tracking.mentionCount = mentionCount;
+ channel.tracking.watchedThreadsUnreadCount = watchedThreadsUnreadCount;
+ this.subject.store(channel);
+ return channel;
+ };
+ });
- const result = this.subject.starredChannelsByActivity;
+ test("sorts channels alphabetically by default", function (assert) {
+ this.buildChannel({ id: 1, slug: "zulu", createdAt: "2026-09-03" });
+ this.buildChannel({ id: 2, slug: "alpha", createdAt: "2026-09-01" });
- assert.strictEqual(
- result[0].id,
- unreadPublicChannel.id,
- "unread public channel comes first"
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["alpha", "zulu"],
+ "channels are sorted by slug"
);
- assert.strictEqual(
- result[1].id,
- unreadDmChannel.id,
- "unread DM comes second"
+ });
+
+ test("sorts channels by recent activity", function (assert) {
+ this.preferences.channelsSort = CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY;
+ this.buildChannel({ id: 1, slug: "older", createdAt: "2026-09-01" });
+ this.buildChannel({ id: 2, slug: "newer", createdAt: "2026-09-03" });
+ const emptyChannel = this.buildChannel({
+ id: 3,
+ slug: "empty",
+ createdAt: "2026-09-04",
+ });
+ emptyChannel.lastMessage = null;
+
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["newer", "older", "empty"],
+ "newer channels are first and empty channels are last"
);
});
- test("sorts read public channels before read DMs", function (assert) {
- const readPublicChannel = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "read-public",
- }),
+ test("sorts urgent, unread, and read channels by priority", function (assert) {
+ this.preferences.channelsSort = CHAT_CHANNEL_LIST_SORTS.PRIORITY;
+ this.buildChannel({ id: 1, slug: "read", createdAt: "2026-09-03" });
+ this.buildChannel({
+ id: 2,
+ slug: "unread",
+ createdAt: "2026-09-01",
+ unreadCount: 1,
});
- const readDmChannel = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Read DM",
+ this.buildChannel({
+ id: 3,
+ slug: "urgent",
+ createdAt: "2026-08-30",
+ mentionCount: 1,
});
- readPublicChannel.currentUserMembership =
- UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
- readDmChannel.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["urgent", "unread", "read"],
+ "priority groups are ordered"
+ );
+ });
- readPublicChannel.tracking.unreadCount = 0;
- readDmChannel.tracking.unreadCount = 0;
+ test("filters channels by recent activity", function (assert) {
+ const clock = sinon.useFakeTimers(new Date("2026-09-03T12:00:00Z"));
- this.subject.store(readDmChannel);
- this.subject.store(readPublicChannel);
+ try {
+ this.preferences.channelsFilter = CHAT_CHANNEL_LIST_FILTERS.ACTIVE;
+ this.buildChannel({
+ id: 1,
+ slug: "active",
+ createdAt: "2026-08-05T12:00:00Z",
+ });
+ this.buildChannel({
+ id: 2,
+ slug: "boundary",
+ createdAt: "2026-08-04T12:00:00Z",
+ });
+ this.buildChannel({
+ id: 3,
+ slug: "inactive",
+ createdAt: "2026-08-03T11:59:59Z",
+ });
- const result = this.subject.starredChannelsByActivity;
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["active", "boundary"],
+ "the 30-day boundary is inclusive"
+ );
+ } finally {
+ clock.restore();
+ }
+ });
- assert.strictEqual(
- result[0].id,
- readPublicChannel.id,
- "read public channel comes first"
+ test("keeps the active channel visible when it does not match", function (assert) {
+ this.preferences.channelsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+ const activeChannel = this.buildChannel({
+ id: 1,
+ slug: "active",
+ createdAt: "2026-09-03",
+ });
+ const chat = getOwner(this).lookup("service:chat");
+ const chatStateManager = getOwner(this).lookup(
+ "service:chat-state-manager"
);
- assert.strictEqual(
- result[1].id,
- readDmChannel.id,
- "read DM comes second"
+ chat.activeChannel = activeChannel;
+ chatStateManager.isDrawerExpanded = true;
+
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["active"],
+ "the channel being viewed remains available"
);
});
- test("complete ordering: unread public, unread DM, read public, read DM", function (assert) {
- const readPublicChannel = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "read-public",
- }),
- });
- const unreadPublicChannel = this.fabricators.channel({
- chatable: this.fabricators.coreFabricators.category({
- slug: "unread-public",
- }),
+ test("filters unread and mention channels and excludes muted activity", function (assert) {
+ this.buildChannel({ id: 1, slug: "read", createdAt: "2026-09-03" });
+ this.buildChannel({
+ id: 2,
+ slug: "unread",
+ createdAt: "2026-09-02",
+ unreadCount: 1,
});
- const readDmChannel = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Read DM",
+ this.buildChannel({
+ id: 3,
+ slug: "mention",
+ createdAt: "2026-09-01",
+ mentionCount: 1,
});
- const unreadDmChannel = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Unread DM",
+ this.buildChannel({
+ id: 4,
+ slug: "muted",
+ createdAt: "2026-09-03",
+ mentionCount: 1,
+ muted: true,
});
- readPublicChannel.currentUserMembership =
- UserChatChannelMembership.create({
- following: true,
- starred: true,
+ this.preferences.channelsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["mention", "unread"],
+ "all visible unread activity is included"
+ );
+
+ this.preferences.channelsFilter = CHAT_CHANNEL_LIST_FILTERS.MENTIONS;
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["mention"],
+ "only non-muted urgent activity is included"
+ );
+ });
+
+ test("falls back to showing channels for an unknown filter", function (assert) {
+ this.preferences.channelsFilter = "unknown";
+ this.buildChannel({ id: 1, slug: "read", createdAt: "2026-09-03" });
+
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map(
+ (channel) => channel.slug
+ ),
+ ["read"],
+ "an invalid persisted value does not hide the channel list"
+ );
+ });
+ });
+
+ module("#sidebarDirectMessageChannels", function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.buildDirectMessageChannel = ({
+ id,
+ title,
+ createdAt = "2026-09-03",
+ unreadCount = 0,
+ mentionCount = 0,
+ muted = false,
+ starred = false,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.directMessage(),
+ title,
});
- unreadPublicChannel.currentUserMembership =
- UserChatChannelMembership.create({
+ channel.currentUserMembership = UserChatChannelMembership.create({
following: true,
- starred: true,
+ muted,
+ starred,
});
- readDmChannel.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
- unreadDmChannel.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
- });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ channel.tracking.unreadCount = unreadCount;
+ channel.tracking.mentionCount = mentionCount;
+ this.subject.store(channel);
+ return channel;
+ };
+ });
- readPublicChannel.tracking.unreadCount = 0;
- unreadPublicChannel.tracking.unreadCount = 2;
- readDmChannel.tracking.unreadCount = 0;
- unreadDmChannel.tracking.unreadCount = 3;
+ test("sorts direct messages alphabetically by title", function (assert) {
+ this.buildDirectMessageChannel({ id: 1, title: "Zulu" });
+ this.buildDirectMessageChannel({ id: 2, title: "Alpha" });
- this.subject.store(readDmChannel);
- this.subject.store(unreadDmChannel);
- this.subject.store(readPublicChannel);
- this.subject.store(unreadPublicChannel);
+ assert.deepEqual(
+ this.subject.sidebarDirectMessageChannels.map(
+ (channel) => channel.title
+ ),
+ ["Alpha", "Zulu"],
+ "direct messages use their titles for alphabetical sorting"
+ );
+ });
- const result = this.subject.starredChannelsByActivity;
+ test("keeps an active direct message within the sidebar limit", function (assert) {
+ for (let index = 0; index < 50; index++) {
+ this.buildDirectMessageChannel({
+ id: index + 1,
+ title: `Channel ${String(index).padStart(2, "0")}`,
+ });
+ }
+ const activeChannel = this.buildDirectMessageChannel({
+ id: 51,
+ title: "Zulu",
+ });
+ const chat = getOwner(this).lookup("service:chat");
+ const chatStateManager = getOwner(this).lookup(
+ "service:chat-state-manager"
+ );
+ chat.activeChannel = activeChannel;
+ chatStateManager.isDrawerExpanded = true;
- assert.strictEqual(result.length, 4, "returns all 4 channels");
assert.strictEqual(
- result[0].id,
- unreadPublicChannel.id,
- "1st: unread public channel"
+ this.subject.sidebarDirectMessageChannels.length,
+ 50,
+ "the sidebar limit remains enforced"
);
- assert.strictEqual(result[1].id, unreadDmChannel.id, "2nd: unread DM");
- assert.strictEqual(
- result[2].id,
- readPublicChannel.id,
- "3rd: read public channel"
+ assert.true(
+ this.subject.sidebarDirectMessageChannels.includes(activeChannel),
+ "the direct message being viewed remains available"
);
- assert.strictEqual(result[3].id, readDmChannel.id, "4th: read DM");
});
- });
- 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",
+ test("applies non-default sorting to starred channels", function (assert) {
+ this.buildDirectMessageChannel({
+ id: 1,
+ title: "Older",
+ createdAt: "2026-09-01",
+ starred: true,
});
- const dmB = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Bob",
+ this.buildDirectMessageChannel({
+ id: 2,
+ title: "Newer",
+ createdAt: "2026-09-03",
+ starred: true,
});
+ this.preferences.dmsSort = CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY;
+
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map(
+ (channel) => channel.title
+ ),
+ ["Newer", "Older"],
+ "starred channels honor the selected activity sort"
+ );
+ });
- dmA.currentUserMembership = UserChatChannelMembership.create({
- following: true,
+ test("filters unstarred and starred direct messages by unread activity", function (assert) {
+ this.buildDirectMessageChannel({ id: 1, title: "Read" });
+ this.buildDirectMessageChannel({
+ id: 2,
+ title: "Unread",
+ unreadCount: 1,
+ });
+ this.buildDirectMessageChannel({
+ id: 3,
+ title: "Muted",
+ unreadCount: 1,
+ muted: true,
+ });
+ this.buildDirectMessageChannel({
+ id: 4,
+ title: "Starred read",
starred: true,
});
- dmB.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: false,
+ this.buildDirectMessageChannel({
+ id: 5,
+ title: "Starred unread",
+ mentionCount: 1,
+ starred: true,
});
+ this.preferences.dmsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+
+ assert.deepEqual(
+ this.subject.sidebarDirectMessageChannels.map(
+ (channel) => channel.title
+ ),
+ ["Unread"],
+ "only non-muted unstarred direct messages with activity remain"
+ );
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map(
+ (channel) => channel.title
+ ),
+ ["Starred read", "Starred unread"],
+ "the dms unread filter does not leak into the starred list"
+ );
+ });
+ });
- this.subject.store(dmA);
- this.subject.store(dmB);
+ module("#publicMessageChannelsByPreference", function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.buildChannel = ({
+ id,
+ slug,
+ createdAt,
+ starred = false,
+ unreadCount = 0,
+ mentionCount = 0,
+ muted = false,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.coreFabricators.category({ slug }),
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred,
+ muted,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ channel.tracking.unreadCount = unreadCount;
+ channel.tracking.mentionCount = mentionCount;
+ this.subject.store(channel);
+ return channel;
+ };
+ });
- const result = this.subject.directMessageChannels;
+ test("includes starred channels and sorts alphabetically by default", function (assert) {
+ this.buildChannel({ id: 1, slug: "zulu", createdAt: "2026-09-01" });
+ this.buildChannel({ id: 2, slug: "alpha", createdAt: "2026-09-03" });
+ this.buildChannel({
+ id: 3,
+ slug: "beta",
+ createdAt: "2026-09-02",
+ starred: true,
+ });
- assert.strictEqual(
- result[0].id,
- dmA.id,
- "starred DM channel comes first"
+ assert.deepEqual(
+ this.subject.publicMessageChannelsByPreference.map(
+ (channel) => channel.slug
+ ),
+ ["alpha", "beta", "zulu"],
+ "starred channels stay in the channels list and sort by slug"
);
- assert.strictEqual(
- result[1].id,
- dmB.id,
- "unstarred DM channel comes second"
+ });
+
+ test("sorts by recent activity", function (assert) {
+ this.preferences.channelsSort = CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY;
+ this.buildChannel({ id: 1, slug: "older", createdAt: "2026-09-01" });
+ this.buildChannel({ id: 2, slug: "newer", createdAt: "2026-09-03" });
+
+ assert.deepEqual(
+ this.subject.publicMessageChannelsByPreference.map(
+ (channel) => channel.slug
+ ),
+ ["newer", "older"],
+ "channels with newer activity sort first"
);
});
- test("sorts starred DM channels alphabetically by title", function (assert) {
- const dmCharlie = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Charlie",
+ test("sorts urgent, unread, and read channels by priority", function (assert) {
+ this.preferences.channelsSort = CHAT_CHANNEL_LIST_SORTS.PRIORITY;
+ this.buildChannel({ id: 1, slug: "read", createdAt: "2026-09-03" });
+ this.buildChannel({
+ id: 2,
+ slug: "unread",
+ createdAt: "2026-09-01",
+ unreadCount: 1,
});
- const dmAlice = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Alice",
+ this.buildChannel({
+ id: 3,
+ slug: "urgent",
+ createdAt: "2026-08-30",
+ mentionCount: 1,
});
- const dmBob = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Bob",
+
+ assert.deepEqual(
+ this.subject.publicMessageChannelsByPreference.map(
+ (channel) => channel.slug
+ ),
+ ["urgent", "unread", "read"],
+ "priority places urgent, then unread, then read channels"
+ );
+ });
+
+ test("applies the channels filter", function (assert) {
+ this.preferences.channelsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+ this.buildChannel({ id: 1, slug: "read", createdAt: "2026-09-03" });
+ this.buildChannel({
+ id: 2,
+ slug: "unreaded",
+ createdAt: "2026-09-01",
+ unreadCount: 1,
});
- dmCharlie.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
+ assert.deepEqual(
+ this.subject.publicMessageChannelsByPreference.map(
+ (channel) => channel.slug
+ ),
+ ["unreaded"],
+ "read channels are hidden by the unread filter"
+ );
+ });
+ });
+
+ module("#directMessageChannelsByPreference", function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.buildDirectMessageChannel = ({
+ id,
+ title,
+ createdAt = "2026-09-03",
+ starred = false,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.directMessage(),
+ title,
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ this.subject.store(channel);
+ return channel;
+ };
+ });
+
+ test("includes starred channels and sorts alphabetically by title", function (assert) {
+ this.buildDirectMessageChannel({ id: 1, title: "Zulu" });
+ this.buildDirectMessageChannel({ id: 2, title: "Alpha" });
+ this.buildDirectMessageChannel({ id: 3, title: "Beta", starred: true });
+
+ assert.deepEqual(
+ this.subject.directMessageChannelsByPreference.map(
+ (channel) => channel.title
+ ),
+ ["Alpha", "Beta", "Zulu"],
+ "starred DMs stay in the DM list and sort by title"
+ );
+ });
+
+ test("sorts by recent activity with empty channels last", function (assert) {
+ this.preferences.dmsSort = CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY;
+ this.buildDirectMessageChannel({
+ id: 1,
+ title: "Older",
+ createdAt: "2026-09-01",
});
- dmAlice.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
+ this.buildDirectMessageChannel({
+ id: 2,
+ title: "Newer",
+ createdAt: "2026-09-02",
});
- dmBob.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
+ const emptyChannel = this.buildDirectMessageChannel({
+ id: 3,
+ title: "Empty",
+ createdAt: "2026-09-04",
});
+ emptyChannel.lastMessage = null;
- this.subject.store(dmCharlie);
- this.subject.store(dmAlice);
- this.subject.store(dmBob);
+ const result = this.subject.directMessageChannelsByPreference;
+ assert.deepEqual(
+ result.map((channel) => channel.title),
+ ["Newer", "Older", "Empty"],
+ "channels without a last message sort after those with activity"
+ );
+ });
- const result = this.subject.directMessageChannels;
+ test("applies the dms filter", function (assert) {
+ this.preferences.dmsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+ const unreadDm = this.buildDirectMessageChannel({
+ id: 1,
+ title: "Unreaded",
+ });
+ unreadDm.tracking.unreadCount = 1;
+ this.buildDirectMessageChannel({ id: 2, title: "Read" });
+
+ assert.deepEqual(
+ this.subject.directMessageChannelsByPreference.map(
+ (channel) => channel.title
+ ),
+ ["Unreaded"],
+ "read DMs are hidden by the unread filter"
+ );
+ });
+ });
- 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"
+ module("#starredChannelsByPreference", function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
);
+ this.buildPublic = ({ id, slug, createdAt }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.coreFabricators.category({ slug }),
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: true,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ this.subject.store(channel);
+ return channel;
+ };
+ this.buildDirectMessage = ({
+ id,
+ title,
+ createdAt,
+ mentionCount = 0,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.directMessage(),
+ title,
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ starred: true,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ channel.tracking.mentionCount = mentionCount;
+ this.subject.store(channel);
+ return channel;
+ };
+ this.channelName = (channel) =>
+ channel.isDirectMessageChannel ? channel.title : channel.slug;
});
- 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",
+ test("sorts public channels then direct messages alphabetically", function (assert) {
+ this.buildDirectMessage({ id: 4, title: "A dm" });
+ this.buildPublic({
+ id: 1,
+ slug: "zulu",
+ createdAt: "2026-09-03",
});
- const unstarredDM = this.fabricators.channel({
- chatable: this.fabricators.directMessage(),
- title: "Unstarred User",
+ this.buildPublic({
+ id: 2,
+ slug: "alpha",
+ createdAt: "2026-09-01",
});
- starredDM.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: true,
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map(this.channelName),
+ ["alpha", "zulu", "A dm"],
+ "public channels precede direct messages and each group sorts by name"
+ );
+ });
+
+ test("sorts by recent activity across public and direct messages", function (assert) {
+ this.preferences.starredSort = CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY;
+ this.buildPublic({
+ id: 1,
+ slug: "oldpub",
+ createdAt: "2026-09-01",
});
- unstarredDM.currentUserMembership = UserChatChannelMembership.create({
- following: true,
- starred: false,
+ this.buildDirectMessage({
+ id: 2,
+ title: "New dm",
+ createdAt: "2026-09-03",
});
- this.subject.store(unstarredDM);
- this.subject.store(starredDM);
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map(this.channelName),
+ ["New dm", "oldpub"],
+ "the most recently active starred channel sorts first"
+ );
+ });
- const result = this.subject.directMessageChannels;
+ test("sorts by priority with mentions first", function (assert) {
+ this.preferences.starredSort = CHAT_CHANNEL_LIST_SORTS.PRIORITY;
+ this.buildDirectMessage({
+ id: 1,
+ title: "Read dm",
+ createdAt: "2026-09-03",
+ });
+ this.buildDirectMessage({
+ id: 2,
+ title: "Mentioned dm",
+ createdAt: "2026-09-01",
+ mentionCount: 1,
+ });
- assert.strictEqual(
- result[0].id,
- starredDM.id,
- "starred DM channel is first"
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map(this.channelName),
+ ["Mentioned dm", "Read dm"],
+ "starred channels with mentions sort first"
);
- assert.strictEqual(
- result[1].id,
- unstarredDM.id,
- "unstarred DM channel is after starred"
+ });
+
+ test("applies the starred filter across public and direct messages", function (assert) {
+ this.preferences.starredFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+ const unreadPublic = this.buildPublic({
+ id: 1,
+ slug: "unreaded",
+ createdAt: "2026-09-01",
+ });
+ unreadPublic.tracking.unreadCount = 1;
+ this.buildDirectMessage({
+ id: 2,
+ title: "Read dm",
+ createdAt: "2026-09-03",
+ });
+
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map(this.channelName),
+ ["unreaded"],
+ "read starred channels are hidden by the unread filter"
);
});
});
+ module(
+ "per-section filter preferences are independent",
+ function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.buildPublicChannel = ({
+ id,
+ slug,
+ createdAt,
+ unreadCount = 0,
+ mentionCount = 0,
+ muted = false,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.coreFabricators.category({ slug }),
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ muted,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ channel.tracking.unreadCount = unreadCount;
+ channel.tracking.mentionCount = mentionCount;
+ this.subject.store(channel);
+ return channel;
+ };
+ this.buildStarred = (args) => {
+ const channel = this.buildPublicChannel(args);
+ channel.currentUserMembership.starred = true;
+ return channel;
+ };
+ this.buildDirectMessage = ({
+ id,
+ title,
+ createdAt,
+ unreadCount = 0,
+ mentionCount = 0,
+ }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.directMessage(),
+ title,
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ channel.tracking.unreadCount = unreadCount;
+ channel.tracking.mentionCount = mentionCount;
+ this.subject.store(channel);
+ return channel;
+ };
+ });
+
+ test("changing the channels filter does not change starred or dms lists", function (assert) {
+ this.buildPublicChannel({
+ id: 1,
+ slug: "read",
+ createdAt: "2026-09-03",
+ });
+ this.buildPublicChannel({
+ id: 2,
+ slug: "unread",
+ createdAt: "2026-09-03",
+ unreadCount: 1,
+ });
+ this.buildStarred({
+ id: 3,
+ slug: "zulu",
+ createdAt: "2026-09-04",
+ unreadCount: 1,
+ });
+ this.buildStarred({ id: 4, slug: "alpha", createdAt: "2026-09-02" });
+ this.buildDirectMessage({
+ id: 5,
+ title: "Zulu dm",
+ createdAt: "2026-09-04",
+ unreadCount: 1,
+ });
+ this.buildDirectMessage({
+ id: 6,
+ title: "Alpha dm",
+ createdAt: "2026-09-02",
+ });
+
+ this.preferences.channelsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map((c) => c.slug),
+ ["unread"],
+ "channels honor their own unread filter"
+ );
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map((c) => c.slug),
+ ["alpha", "zulu"],
+ "starred shows all channels, unaffected by the channels filter"
+ );
+ assert.deepEqual(
+ this.subject.sidebarDirectMessageChannels.map((c) => c.title),
+ ["Alpha dm", "Zulu dm"],
+ "dms show all direct messages, unaffected by the channels filter"
+ );
+ });
+
+ test("changing the dms filter only affects the direct messages list", function (assert) {
+ this.buildPublicChannel({
+ id: 1,
+ slug: "read",
+ createdAt: "2026-09-03",
+ });
+ this.buildPublicChannel({
+ id: 2,
+ slug: "unread",
+ createdAt: "2026-09-03",
+ unreadCount: 1,
+ });
+ this.buildDirectMessage({
+ id: 5,
+ title: "Read dm",
+ createdAt: "2026-09-04",
+ });
+ this.buildDirectMessage({
+ id: 6,
+ title: "Unread dm",
+ createdAt: "2026-09-02",
+ unreadCount: 1,
+ });
+
+ this.preferences.dmsFilter = CHAT_CHANNEL_LIST_FILTERS.UNREAD;
+
+ assert.deepEqual(
+ this.subject.sidebarDirectMessageChannels.map((c) => c.title),
+ ["Unread dm"],
+ "dms honor their own unread filter"
+ );
+ assert.deepEqual(
+ this.subject.sidebarPublicMessageChannels.map((c) => c.slug),
+ ["read", "unread"],
+ "channels show all channels, unaffected by the dms filter"
+ );
+ });
+ }
+ );
+ module(
+ "per-section sort preferences are independent",
+ function (nestedHooks) {
+ nestedHooks.beforeEach(function () {
+ this.preferences = getOwner(this).lookup(
+ "service:chat-channel-list-preferences"
+ );
+ this.buildPublicChannel = ({ id, slug, createdAt }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.coreFabricators.category({ slug }),
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ this.subject.store(channel);
+ return channel;
+ };
+ this.buildStarred = ({ id, slug, createdAt }) => {
+ const channel = this.buildPublicChannel({ id, slug, createdAt });
+ channel.currentUserMembership.starred = true;
+ return channel;
+ };
+ this.buildDirectMessage = ({ id, title, createdAt }) => {
+ const channel = this.fabricators.channel({
+ id,
+ chatable: this.fabricators.directMessage(),
+ title,
+ });
+ channel.currentUserMembership = UserChatChannelMembership.create({
+ following: true,
+ });
+ channel.lastMessage = this.fabricators.message({
+ id: id * 10,
+ channel,
+ created_at: createdAt,
+ });
+ this.subject.store(channel);
+ return channel;
+ };
+ });
+
+ test("changing the channels sort does not change starred or dms sorting", function (assert) {
+ this.buildPublicChannel({
+ id: 1,
+ slug: "older",
+ createdAt: "2026-09-01",
+ });
+ this.buildPublicChannel({
+ id: 2,
+ slug: "newer",
+ createdAt: "2026-09-03",
+ });
+ this.buildStarred({ id: 3, slug: "zulu", createdAt: "2026-09-04" });
+ this.buildStarred({ id: 4, slug: "alpha", createdAt: "2026-09-02" });
+ this.buildDirectMessage({
+ id: 5,
+ title: "Zulu dm",
+ createdAt: "2026-09-04",
+ });
+ this.buildDirectMessage({
+ id: 6,
+ title: "Alpha dm",
+ createdAt: "2026-09-02",
+ });
+
+ // Channels: recent activity first (starred channels stay in the list).
+ this.preferences.channelsSort = CHAT_CHANNEL_LIST_SORTS.RECENT_ACTIVITY;
+
+ assert.deepEqual(
+ this.subject.publicMessageChannelsByPreference.map((c) => c.slug),
+ ["zulu", "newer", "alpha", "older"],
+ "channels use the channels sort"
+ );
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map((c) => c.slug),
+ ["alpha", "zulu"],
+ "starred still sorts by its own default, alphabetical"
+ );
+ assert.deepEqual(
+ this.subject.directMessageChannelsByPreference.map((c) => c.title),
+ ["Alpha dm", "Zulu dm"],
+ "dms still sorts by its own default, alphabetical"
+ );
+ });
+
+ test("changing the starred sort only affects the starred section", function (assert) {
+ this.buildPublicChannel({
+ id: 1,
+ slug: "older",
+ createdAt: "2026-09-01",
+ });
+ this.buildPublicChannel({
+ id: 2,
+ slug: "newer",
+ createdAt: "2026-09-03",
+ });
+ this.buildStarred({ id: 3, slug: "zulu", createdAt: "2026-09-04" });
+ this.buildStarred({ id: 4, slug: "alpha", createdAt: "2026-09-02" });
+
+ // Starred: priority, then recency (all read → newest first).
+ this.preferences.starredSort = CHAT_CHANNEL_LIST_SORTS.PRIORITY;
+
+ assert.deepEqual(
+ this.subject.starredChannelsByPreference.map((c) => c.slug),
+ ["zulu", "alpha"],
+ "starred honors its own priority sort"
+ );
+ assert.deepEqual(
+ this.subject.publicMessageChannelsByPreference.map((c) => c.slug),
+ ["alpha", "newer", "older", "zulu"],
+ "channels keeps its own alphabetical sort, not affected by starred"
+ );
+ });
+ }
+ );
});