Skip to content

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

FEATURE: Chat channel list in category UI (#37750)

Martin Brennane768f0c3cd59
diff --git a/app/models/category.rb b/app/models/category.rb
index ef19f5d5374..fa84c0b239c 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -963,6 +963,10 @@ class Category < ActiveRecord::Base
end
end
+ def slug_url_without_id
+ "#{Discourse.base_path}/c/#{slug_path.join("/")}"
+ end
+
alias_method :relative_url, :url
# If the name changes, try and update the category definition topic too if it's an exact match
diff --git a/frontend/discourse/admin/components/edit-category-tab.gjs b/frontend/discourse/admin/components/edit-category-tab.gjs
index ee55f27647a..2dfd68a41f5 100644
--- a/frontend/discourse/admin/components/edit-category-tab.gjs
+++ b/frontend/discourse/admin/components/edit-category-tab.gjs
@@ -24,9 +24,9 @@ export default class EditCategoryTab extends Component {
return "edit-category-" + tab;
}
- @discourseComputed("tab")
- title(tab) {
- return i18n(`category.${underscore(tab)}`);
+ @discourseComputed("tab", "tabTitle")
+ title(tab, tabTitle) {
+ return tabTitle ?? i18n(`category.${underscore(tab)}`);
}
didInsertElement() {
diff --git a/frontend/discourse/admin/templates/edit-category/tabs-horizontal.gjs b/frontend/discourse/admin/templates/edit-category/tabs-horizontal.gjs
index 6f0fa779dbc..aaf76c1d77e 100644
--- a/frontend/discourse/admin/templates/edit-category/tabs-horizontal.gjs
+++ b/frontend/discourse/admin/templates/edit-category/tabs-horizontal.gjs
@@ -1,3 +1,4 @@
+import Component from "@glimmer/component";
import { concat } from "@ember/helper";
import { on } from "@ember/modifier";
import EditCategoryTab from "discourse/admin/components/edit-category-tab";
@@ -5,92 +6,116 @@ import BackButton from "discourse/components/back-button";
import BreadCrumbs from "discourse/components/bread-crumbs";
import DPageHeader from "discourse/components/d-page-header";
import DToggleSwitch from "discourse/components/d-toggle-switch";
+import { registeredEditCategoryTabs } from "discourse/lib/edit-category-tabs";
import { and } from "discourse/truth-helpers";
-const EditCategoryTabsHorizontalTemplate = <template>
- {{#if (and @controller.site.desktopView @controller.model.id)}}
- <BackButton
- @route="discovery.category"
- @model={{concat @controller.parentParams.slug "/" @controller.model.id}}
- @label="category.back"
- />
- {{/if}}
- <DPageHeader
- @titleLabel={{@controller.baseTitle}}
- @showDrawer={{true}}
- @collapseActionsOnMobile={{false}}
- >
+export default class EditCategoryTabsHorizontalTemplate extends Component {
+ evaluateTabCondition(tab, controller) {
+ if (!tab.condition) {
+ return true;
+ }
+ return tab.condition({
+ category: controller.model,
+ siteSettings: controller.siteSettings,
+ });
+ }
- <:actions>
- <DToggleSwitch
- @label="category.show_advanced"
- @state={{@controller.showAdvancedTabs}}
- {{on "click" @controller.toggleAdvancedTabs}}
+ <template>
+ {{#if (and @controller.site.desktopView @controller.model.id)}}
+ <BackButton
+ @route="discovery.category"
+ @model={{concat @controller.parentParams.slug "/" @controller.model.id}}
+ @label="category.back"
/>
- </:actions>
- <:tabs>
- {{#if @controller.showAdvancedTabs}}
- <EditCategoryTab
- @panels={{@controller.panels}}
- @selectedTab={{@controller.selectedTab}}
- @params={{@controller.parentParams}}
- @tab="general"
- />
- <EditCategoryTab
- @panels={{@controller.panels}}
- @selectedTab={{@controller.selectedTab}}
- @params={{@controller.parentParams}}
- @tab="security"
- />
- <EditCategoryTab
- @panels={{@controller.panels}}
- @selectedTab={{@controller.selectedTab}}
- @params={{@controller.parentParams}}
- @tab="settings"
- />
- <EditCategoryTab
- @panels={{@controller.panels}}
- @selectedTab={{@controller.selectedTab}}
- @params={{@controller.parentParams}}
- @tab="images"
- />
- <EditCategoryTab
- @panels={{@controller.panels}}
- @selectedTab={{@controller.selectedTab}}
- @params={{@controller.parentParams}}
- @tab="topic-template"
+ {{/if}}
+ <DPageHeader
+ @titleLabel={{@controller.baseTitle}}
+ @showDrawer={{true}}
+ @collapseActionsOnMobile={{false}}
+ >
+
+ <:actions>
+ <DToggleSwitch
+ class="category-show-advanced-tabs-toggle"
+ @label="category.show_advanced"
+ @state={{@controller.showAdvancedTabs}}
+ {{on "click" @controller.toggleAdvancedTabs}}
/>
- {{#if @controller.siteSettings.tagging_enabled}}
+ </:actions>
+ <:tabs>
+ {{#if @controller.showAdvancedTabs}}
<EditCategoryTab
@panels={{@controller.panels}}
@selectedTab={{@controller.selectedTab}}
@params={{@controller.parentParams}}
- @tab="tags"
+ @tab="general"
/>
- {{/if}}
-
- {{#if @controller.siteSettings.content_localization_enabled}}
<EditCategoryTab
@panels={{@controller.panels}}
@selectedTab={{@controller.selectedTab}}
@params={{@controller.parentParams}}
- @tab="localizations"
+ @tab="security"
/>
- {{/if}}
- {{/if}}
- </:tabs>
- <:drawer>
- {{#if @controller.model.id}}
- <BreadCrumbs
- @categories={{@controller.breadcrumbCategories}}
- @category={{@controller.model}}
- @noSubcategories={{@controller.model.noSubcategories}}
- @editingCategory={{true}}
- @editingCategoryTab={{@controller.selectedTab}}
- />
- {{/if}}
- </:drawer>
- </DPageHeader>
-</template>;
+ <EditCategoryTab
+ @panels={{@controller.panels}}
+ @selectedTab={{@controller.selectedTab}}
+ @params={{@controller.parentParams}}
+ @tab="settings"
+ />
+ <EditCategoryTab
+ @panels={{@controller.panels}}
+ @selectedTab={{@controller.selectedTab}}
+ @params={{@controller.parentParams}}
+ @tab="images"
+ />
+ <EditCategoryTab
+ @panels={{@controller.panels}}
+ @selectedTab={{@controller.selectedTab}}
+ @params={{@controller.parentParams}}
+ @tab="topic-template"
+ />
+ {{#if @controller.siteSettings.tagging_enabled}}
+ <EditCategoryTab
+ @panels={{@controller.panels}}
+ @selectedTab={{@controller.selectedTab}}
+ @params={{@controller.parentParams}}
+ @tab="tags"
+ />
+ {{/if}}
+
+ {{#if @controller.siteSettings.content_localization_enabled}}
+ <EditCategoryTab
+ @panels={{@controller.panels}}
+ @selectedTab={{@controller.selectedTab}}
+ @params={{@controller.parentParams}}
+ @tab="localizations"
+ />
+ {{/if}}
-export default EditCategoryTabsHorizontalTemplate;
+ {{#each registeredEditCategoryTabs as |pluginTab|}}
+ {{#if (this.evaluateTabCondition pluginTab @controller)}}
+ <EditCategoryTab
+ @panels={{@controller.panels}}
+ @selectedTab={{@controller.selectedTab}}
+ @params={{@controller.parentParams}}
+ @tab={{pluginTab.id}}
+ @tabTitle={{pluginTab.name}}
+ />
+ {{/if}}
+ {{/each}}
+ {{/if}}
+ </:tabs>
+ <:drawer>
+ {{#if @controller.model.id}}
+ <BreadCrumbs
+ @categories={{@controller.breadcrumbCategories}}
+ @category={{@controller.model}}
+ @noSubcategories={{@controller.model.noSubcategories}}
+ @editingCategory={{true}}
+ @editingCategoryTab={{@controller.selectedTab}}
+ />
+ {{/if}}
+ </:drawer>
+ </DPageHeader>
+ </template>
+}
diff --git a/frontend/discourse/admin/templates/edit-category/tabs.gjs b/frontend/discourse/admin/templates/edit-category/tabs.gjs
index 0ac30b21d40..f156ed64aa8 100644
--- a/frontend/discourse/admin/templates/edit-category/tabs.gjs
+++ b/frontend/discourse/admin/templates/edit-category/tabs.gjs
@@ -15,6 +15,7 @@ import UpsertCategoryTags from "discourse/admin/components/upsert-category/tags"
import EditCategoryTabsHorizontal from "discourse/admin/templates/edit-category/tabs-horizontal";
import EditCategoryTabsVertical from "discourse/admin/templates/edit-category/tabs-vertical";
import Form from "discourse/components/form";
+import { registeredEditCategoryTabs } from "discourse/lib/edit-category-tabs";
const TAB_COMPONENTS = {
general: EditCategoryGeneral,
@@ -41,10 +42,16 @@ function componentFor(name, useSimplified) {
name = name.replace("edit-category-", "");
const components = useSimplified ? TAB_COMPONENTS_V2 : TAB_COMPONENTS;
- if (!components[name]) {
- throw new Error(`No category-tab component found for tab name: ${name}`);
+ if (components[name]) {
+ return components[name];
}
- return components[name];
+
+ const pluginTab = registeredEditCategoryTabs.find((tab) => tab.id === name);
+ if (pluginTab) {
+ return pluginTab.component;
+ }
+
+ throw new Error(`No category-tab component found for tab name: ${name}`);
}
export default <template>
diff --git a/frontend/discourse/app/lib/edit-category-tabs.js b/frontend/discourse/app/lib/edit-category-tabs.js
new file mode 100644
index 00000000000..45bddda8608
--- /dev/null
+++ b/frontend/discourse/app/lib/edit-category-tabs.js
@@ -0,0 +1,5 @@
+export let registeredEditCategoryTabs = [];
+
+export function clearRegisteredEditCategoryTabs() {
+ registeredEditCategoryTabs.length = 0;
+}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 3d5e8872d5a..09933abd729 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -63,6 +63,7 @@ import { registerRichEditorExtension } from "discourse/lib/composer/rich-editor-
import deprecated from "discourse/lib/deprecated";
import { registerDesktopNotificationHandler } from "discourse/lib/desktop-notifications";
import { downloadCalendar } from "discourse/lib/download-calendar";
+import { registeredEditCategoryTabs } from "discourse/lib/edit-category-tabs";
import { isDevelopment, isTesting } from "discourse/lib/environment";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import { registerHashtagType } from "discourse/lib/hashtag-type-registry";
@@ -3315,6 +3316,31 @@ class _PluginApi {
_addCategoryPropertyForSave(property);
}
+ /**
+ * Registers a custom tab for the category edit page.
+ * Only available when the `enable_simplified_category_creation`
+ * site setting is enabled, this will not work for the legacy
+ * category edit page.
+ *
+ * ```
+ * api.registerEditCategoryTab({
+ * id: "chat",
+ * name: "Chat",
+ * component: MyChatComponent,
+ * condition: ({ category, siteSettings }) => siteSettings.chat_enabled,
+ * });
+ * ```
+ *
+ * @param {Object} tab
+ * @param {string} tab.id - unique identifier for the tab, used in URL routing
+ * @param {string} tab.name - display name shown on the tab
+ * @param {Class} tab.component - Glimmer component to render as tab content
+ * @param {Function} [tab.condition] - optional callback returning boolean to conditionally show the tab
+ */
+ registerEditCategoryTab(tab) {
+ registeredEditCategoryTabs.push(tab);
+ }
+
// eslint-disable-next-line no-unused-vars
#deprecateModifyClass(className) {
// display notification messages for deprecated classes
diff --git a/frontend/discourse/tests/acceptance/edit-category-plugin-api-test.gjs b/frontend/discourse/tests/acceptance/edit-category-plugin-api-test.gjs
new file mode 100644
index 00000000000..b07cdf85d58
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/edit-category-plugin-api-test.gjs
@@ -0,0 +1,56 @@
+import { visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+const DummyTabComponent = <template>
+ {{#if (eq @selectedTab "custom-test")}}
+ <div class="custom-test-tab-content">Custom tab content</div>
+ {{/if}}
+</template>;
+
+import { eq } from "discourse/truth-helpers";
+
+acceptance("Edit Category - Plugin Tab API", function (needs) {
+ needs.user();
+ needs.settings({ enable_simplified_category_creation: true });
+
+ test("registerEditCategoryTab adds a tab that renders", async function (assert) {
+ withPluginApi((api) => {
+ api.registerEditCategoryTab({
+ id: "custom-test",
+ name: "Custom Test",
+ component: DummyTabComponent,
+ });
+ });
+
+ await visit("/c/bug/edit/custom-test");
+
+ assert
+ .dom(".edit-category-custom-test")
+ .exists("the plugin tab is rendered in the nav");
+ assert
+ .dom(".edit-category-custom-test a")
+ .hasText("Custom Test", "the tab has the correct title");
+ assert
+ .dom(".custom-test-tab-content")
+ .exists("the plugin tab component is rendered");
+ });
+
+ test("registerEditCategoryTab respects condition", async function (assert) {
+ withPluginApi((api) => {
+ api.registerEditCategoryTab({
+ id: "hidden-tab",
+ name: "Hidden Tab",
+ component: DummyTabComponent,
+ condition: () => false,
+ });
+ });
+
+ await visit("/c/bug/edit/general");
+
+ assert
+ .dom(".edit-category-hidden-tab")
+ .doesNotExist("the tab is not shown when condition returns false");
+ });
+});
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 48dffa97e72..b9c8a595c12 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -45,6 +45,7 @@ import { rollbackAllPrepends } from "discourse/lib/class-prepend";
import { clearPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";
import deprecated from "discourse/lib/deprecated";
import { clearDesktopNotificationHandlers } from "discourse/lib/desktop-notifications";
+import { clearRegisteredEditCategoryTabs } from "discourse/lib/edit-category-tabs";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import { restoreBaseUri } from "discourse/lib/get-url";
import { cleanUpHashtagTypeClasses } from "discourse/lib/hashtag-type-registry";
@@ -265,6 +266,7 @@ export function testCleanup(container, app) {
clearAboutPageActivities();
clearPluginHeaderActionComponents();
clearRegisteredTabs();
+ clearRegisteredEditCategoryTabs();
clearAddedTrackedPostProperties();
resetGroupPostSmallActionCodes();
enableClearA11yAnnouncementsInTests();
diff --git a/plugins/chat/app/controllers/chat/api/channels_controller.rb b/plugins/chat/app/controllers/chat/api/channels_controller.rb
index 0cc7612c9dd..30772dd5590 100644
--- a/plugins/chat/app/controllers/chat/api/channels_controller.rb
+++ b/plugins/chat/app/controllers/chat/api/channels_controller.rb
@@ -5,11 +5,13 @@ class Chat::Api::ChannelsController < Chat::ApiController
CATEGORY_CHANNEL_EDITABLE_PARAMS = %i[auto_join_users allow_channel_wide_mentions]
def index
- permitted = params.permit(:filter, :limit, :offset, :status)
+ permitted = params.permit(:filter, :limit, :offset, :status, :chatable_id, :chatable_type)
options = { filter: permitted[:filter], limit: (permitted[:limit] || 25).to_i }
options[:offset] = permitted[:offset].to_i
options[:status] = Chat::Channel.statuses[permitted[:status]] ? permitted[:status] : nil
+ options[:chatable_id] = permitted[:chatable_id]
+ options[:chatable_type] = permitted[:chatable_type]
memberships = Chat::ChannelMembershipManager.all_for_user(current_user)
channels = Chat::ChannelFetcher.secured_public_channels(guardian, options)
diff --git a/plugins/chat/assets/javascripts/discourse/components/upsert-category/chat.gjs b/plugins/chat/assets/javascripts/discourse/components/upsert-category/chat.gjs
new file mode 100644
index 00000000000..c440cf323fe
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/upsert-category/chat.gjs
@@ -0,0 +1,111 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { htmlSafe } from "@ember/template";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import EmptyState from "discourse/components/empty-state";
+import icon from "discourse/helpers/d-icon";
+import replaceEmoji from "discourse/helpers/replace-emoji";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import getURL from "discourse/lib/get-url";
+import { i18n } from "discourse-i18n";
+
+function channelSettingsUrl(channel) {
+ return getURL(`/chat/c/${channel.slug || "-"}/${channel.id}/info/settings`);
+}
+
+function channelColorStyle(channel) {
+ return htmlSafe(`color: #${channel.chatable?.color || "000"}`);
+}
+
+function channelIcon(channel) {
+ return channel.emoji ? replaceEmoji(`:${channel.emoji}:`) : icon("d-chat");
+}
+
+export default class EditCategoryChat extends Component {
+ @tracked channels = null;
+ @tracked loading = true;
+
+ @action
+ async loadChannels() {
+ try {
+ this.loading = true;
+ const result = await ajax(
+ `/chat/api/channels?chatable_id=${this.args.category.id}&chatable_type=Category`
+ );
+ this.channels = (result.channels || []).sort((a, b) =>
+ (a.title || "").localeCompare(b.title || "")
+ );
+ } catch (err) {
+ popupAjaxError(err);
+ this.channels = [];
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ <template>
+ <section class="edit-category-chat" {{didInsert this.loadChannels}}>
+ <ConditionalLoadingSpinner @condition={{this.loading}}>
+ {{#if this.channels.length}}
+ <table class="d-table edit-category-chat__table">
+ <thead class="d-table__header">
+ <tr class="d-table__row">
+ <th class="d-table__header-cell">{{i18n
+ "chat.edit_category.channel"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "chat.edit_category.description"
+ }}</th>
+ <th class="d-table__header-cell"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.channels as |channel|}}
+ <tr class="d-table__row" data-channel-id={{channel.id}}>
+ <td class="d-table__cell edit-category-chat__channel-name">
+ <span
+ class="chat-channel-icon --icon"
+ style={{channelColorStyle channel}}
+ >
+ {{channelIcon channel}}
+ </span>
+ <span>{{channel.title}}</span>
+ </td>
+ <td
+ class="d-table__cell edit-category-chat__channel-description"
+ >
+ {{if channel.description channel.description "-"}}
+ </td>
+ <td
+ class="d-table__cell edit-category-chat__channel-actions d-table__cell-actions"
+ >
+ <a
+ href={{channelSettingsUrl channel}}
+ class="btn btn-default btn-small"
+ >
+ {{icon "gear"}}
+ {{i18n "chat.edit_category.settings"}}
+ </a>
+ </td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ {{else}}
+ <EmptyState
+ @title={{i18n "chat.edit_category.no_channels"}}
+ @body={{htmlSafe
+ (i18n
+ "chat.edit_category.no_channels_body"
+ chatBrowseUrl=(getURL "/chat/browse/open")
+ )
+ }}
+ />
+ {{/if}}
+ </ConditionalLoadingSpinner>
+ </section>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-category-tab.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-category-tab.js
new file mode 100644
index 00000000000..d203f1b6b37
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-category-tab.js
@@ -0,0 +1,19 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { i18n } from "discourse-i18n";
+import CategoryChat from "discourse/plugins/chat/discourse/components/upsert-category/chat";
+
+export default {
+ name: "chat-category-tab",
+
+ initialize() {
+ withPluginApi((api) => {
+ api.registerEditCategoryTab({
+ id: "chat",
+ name: i18n("chat.edit_category.tab_title"),
+ component: CategoryChat,
+ condition: ({ category, siteSettings }) =>
+ siteSettings.chat_enabled && category.id,
+ });
+ });
+ },
+};
diff --git a/plugins/chat/assets/stylesheets/common/edit-category-chat.scss b/plugins/chat/assets/stylesheets/common/edit-category-chat.scss
new file mode 100644
index 00000000000..20b96360fc4
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/common/edit-category-chat.scss
@@ -0,0 +1,12 @@
+.edit-category-chat {
+ &__channel-name {
+ .chat-channel-icon {
+ font-size: var(--font-up-1);
+ display: inline;
+ }
+ }
+
+ &__empty {
+ color: var(--primary-medium);
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/common/index.scss b/plugins/chat/assets/stylesheets/common/index.scss
index b760a963508..b479caac3e0 100644
--- a/plugins/chat/assets/stylesheets/common/index.scss
+++ b/plugins/chat/assets/stylesheets/common/index.scss
@@ -74,3 +74,4 @@
@import "chat-message-search-entry";
@import "chat-channel-filter-bar";
@import "chat-search";
+@import "edit-category-chat";
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index 9c7e67d05b8..be412a4ee0d 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -39,6 +39,14 @@ en:
other: "%{formatted_number} chat messages"
chat:
+ edit_category:
+ tab_title: "Chat"
+ channel: "Channel"
+ description: "Description"
+ actions: "Actions"
+ settings: "Settings"
+ no_channels: "There are no chat channels associated with this category"
+ no_channels_body: "You can have multiple channels per category, accessible to the same members based on the category’s Security settings. <a href='%{chatBrowseUrl}'>Create a chat channel</a>."
text_copied: Text copied to clipboard
link_copied: Link copied to clipboard
back_to_forum: "Forum"
diff --git a/plugins/chat/lib/chat/category_extension.rb b/plugins/chat/lib/chat/category_extension.rb
index 185cec5e83b..b5b31b869e8 100644
--- a/plugins/chat/lib/chat/category_extension.rb
+++ b/plugins/chat/lib/chat/category_extension.rb
@@ -11,6 +11,11 @@ module Chat
as: :chatable,
class_name: "Chat::CategoryChannel",
dependent: :destroy
+ has_many :category_channels,
+ class_name: "Chat::CategoryChannel",
+ dependent: :destroy,
+ foreign_key: %i[chatable_id chatable_type],
+ inverse_of: :chatable
end
def cannot_delete_reason
diff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rb
index 9585dfec8c6..153733de2c5 100644
--- a/plugins/chat/lib/chat/channel_fetcher.rb
+++ b/plugins/chat/lib/chat/channel_fetcher.rb
@@ -111,6 +111,17 @@ module Chat
channels = channels.where(status: options[:status]) if options[:status].present?
+ if options[:chatable_id].present? && options[:chatable_type].present?
+ filter_chatable = options[:chatable_type].constantize&.find_by_id(options[:chatable_id])
+ if filter_chatable.present? && guardian.can_see_chatable?(filter_chatable)
+ channels =
+ channels.where(
+ chatable_id: options[:chatable_id],
+ chatable_type: options[:chatable_type],
+ )
+ end
+ end
+
if options[:filter].present?
category_filter =
(options[:filter_on_category_name] ? "OR categories.name ILIKE :filter" : "")
diff --git a/plugins/chat/lib/chat/guardian_extensions.rb b/plugins/chat/lib/chat/guardian_extensions.rb
index 6fdd7486294..8754bb01cde 100644
--- a/plugins/chat/lib/chat/guardian_extensions.rb
+++ b/plugins/chat/lib/chat/guardian_extensions.rb
@@ -133,18 +133,22 @@ module Chat
is_staff? || @user.has_trust_level?(TrustLevel[4])
end
- def can_preview_chat_channel?(chat_channel)
- return false if !chat_channel&.chatable
-
- if chat_channel.direct_message_channel?
- chat_channel.chatable.user_can_access?(@user)
- elsif chat_channel.category_channel?
- can_see_category?(chat_channel.chatable)
+ def can_see_chatable?(chatable)
+ case chatable
+ when Category
+ can_see_category?(chatable)
+ when Chat::DirectMessage
+ chatable.user_can_access?(@user)
else
true
end
end
+ def can_preview_chat_channel?(chat_channel)
+ return false if !chat_channel&.chatable
+ can_see_chatable?(chat_channel.chatable)
+ end
+
def can_join_chat_channel?(chat_channel, post_allowed_category_ids: nil)
return false if anonymous?
return false unless can_chat?
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 2e0bd6773d2..59b6474a1fb 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -289,6 +289,12 @@ after_initialize do
object.chat_quick_reactions_custom
end
+ add_to_serializer(
+ :category,
+ :has_chat_channels,
+ include_condition: -> { SiteSetting.chat_enabled },
+ ) { object.category_channels.exists? }
+
on(:site_setting_changed) do |name, old_value, new_value|
user_option_field = Chat::RETENTION_SETTINGS_TO_USER_OPTION_FIELDS[name.to_sym]
begin
diff --git a/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb b/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb
index 287680ee110..54467a88104 100644
--- a/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb
+++ b/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb
@@ -296,6 +296,46 @@ describe Chat::ChannelFetcher do
).to be_empty
end
+ context "when filtering by chatable (Category)" do
+ fab!(:other_category, :category)
+ fab!(:other_channel) { Fabricate(:category_channel, chatable: other_category) }
+
+ it "returns only channels for the given category when user can see the category" do
+ expect(
+ described_class.secured_public_channels(
+ guardian,
+ following: following,
+ chatable_id: category.id,
+ chatable_type: "Category",
+ ).map(&:id),
+ ).to eq([category_channel.id])
+ end
+
+ it "does not filter when chatable type and id are not found" do
+ expect(
+ described_class.secured_public_channels(
+ guardian,
+ following: following,
+ chatable_id: -999,
+ chatable_type: "Category",
+ ).map(&:id),
+ ).to contain_exactly(category_channel.id, other_channel.id)
+ end
+
+ it "does not filter when user cannot access the chatable" do
+ Fabricate(:category_channel, chatable: private_category)
+
+ expect(
+ described_class.secured_public_channels(
+ guardian,
+ following: following,
+ chatable_id: private_category.id,
+ chatable_type: "Category",
+ ).map(&:id),
+ ).to contain_exactly(category_channel.id, other_channel.id)
+ end
+ end
+
context "when scoping to the user's channel memberships" do
let(:following) { true }
diff --git a/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb
index 84ee026b124..abebd5a2b9c 100644
--- a/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb
+++ b/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb
@@ -109,6 +109,64 @@ RSpec.describe Chat::Api::ChannelsController do
expect(response.parsed_body["channels"]).to be_blank
end
end
+
+ context "when filtering by chatable_id and chatable_type (Category)" do
+ fab!(:category_1, :category)
+ fab!(:category_2, :category)
+ fab!(:channel_1) { Fabricate(:category_channel, chatable: category_1) }
+ fab!(:channel_2) { Fabricate(:category_channel, chatable: category_2) }
+
+ it "returns only channels for the given category" do
+ get "/chat/api/channels",
+ params: {
+ chatable_id: category_1.id,
+ chatable_type: "Category",
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["channels"].map { |c| c["id"] }).to eq([channel_1.id])
+ end
+
+ it "returns empty when the category has no channels" do
+ category_without_channel = Fabricate(:category)
+
+ get "/chat/api/channels",
+ params: {
+ chatable_id: category_without_channel.id,
+ chatable_type: "Category",
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["channels"]).to be_blank
+ end
+
+ it "does not filter when chatable type and id are not found" do
+ get "/chat/api/channels", params: { chatable_id: -999, chatable_type: "Category" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["channels"].map { |c| c["id"] }).to contain_exactly(
+ channel_1.id,
+ channel_2.id,
+ )
+ end
+
+ it "does not filter when user cannot access the chatable" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ Fabricate(:category_channel, chatable: private_category)
+
+ get "/chat/api/channels",
+ params: {
+ chatable_id: private_category.id,
+ chatable_type: "Category",
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["channels"].map { |c| c["id"] }).to contain_exactly(
+ channel_1.id,
+ channel_2.id,
+ )
+ end
+ end
end
end
diff --git a/plugins/chat/spec/system/admin/category_channel_list_spec.rb b/plugins/chat/spec/system/admin/category_channel_list_spec.rb
new file mode 100644
index 00000000000..31557f5d508
--- /dev/null
+++ b/plugins/chat/spec/system/admin/category_channel_list_spec.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+RSpec.describe "Admin category channels list", type: :system do
+ fab!(:current_user, :admin)
+ fab!(:category)
+ fab!(:channel_1) { Fabricate(:chat_channel, chatable: category, emoji: "goat") }
+ fab!(:channel_2) { Fabricate(:chat_channel, chatable: category) }
+ fab!(:channel_3, :chat_channel)
+
+ before do
+ # We are only showing the Chat tab on the new category UI, not the old one
+ SiteSetting.enable_simplified_category_creation = true
+ chat_system_bootstrap
+ sign_in(current_user)
+ end
+
+ context "when a category has no chat channels" do
+ fab!(:category_2, :category)
+
+ it "shows a message saying that there are no chat channels" do
+ visit "#{category_2.slug_url_without_id}/edit/chat"
+ expect(page).to have_content(
+ html_translation_to_text(
+ I18n.t(
+ "js.chat.edit_category.no_channels_body",
+ chatBrowseUrl: "#{Discourse.base_path}/chat/browse/open",
+ ),
+ ),
+ )
+ end
+ end
+
+ context "when a category has chat channels" do
+ it "shows a list of chat channels and opens the channel settings" do
+ visit "#{category.slug_url_without_id}/edit/general"
+ PageObjects::Components::DToggleSwitch.new(".category-show-advanced-tabs-toggle").toggle
+ page.find(".edit-category-chat").click
+
+ expect(page.find(".d-table__row[data-channel-id='#{channel_1.id}']")).to have_content(
+ channel_1.title,
+ )
+ expect(page.find(".d-table__row[data-channel-id='#{channel_2.id}']")).to have_content(
+ channel_2.title,
+ )
+ expect(page).to have_no_css(".d-table__row[data-channel-id='#{channel_3.id}']")
+ expect(page.find(".d-table__row[data-channel-id='#{channel_1.id}']")).to have_css(
+ "img.emoji[title='goat']",
+ )
+
+ page.find(
+ ".d-table__row[data-channel-id='#{channel_1.id}'] .d-table__cell-actions .btn",
+ ).click
+
+ expect(page).to have_css(".c-channel-settings")
+ end
+ end
+end
diff --git a/spec/support/system_helpers.rb b/spec/support/system_helpers.rb
index 1abe661e60e..48981619f3b 100644
--- a/spec/support/system_helpers.rb
+++ b/spec/support/system_helpers.rb
@@ -380,4 +380,8 @@ module SystemHelpers
def tap_screen_at(x, y)
page.driver.with_playwright_page { |pw_page| pw_page.touchscreen.tap_point(x, y) }
end
+
+ def html_translation_to_text(html_translation)
+ Nokogiri.HTML5(html_translation).at("body").inner_text
+ end
end