A platform for community discussion. Free, open, simple.
FEATURE: allow a chat channel as a default homepage (#44202)
Kris0a264785d1d1
diff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rbindex 4af784d9eef..02ef269b8c2 100644--- a/app/serializers/site_serializer.rb+++ b/app/serializers/site_serializer.rb@@ -236,7 +236,13 @@ class SiteSerializer < ApplicationSerializerenddef homepage_options- DiscoursePluginRegistry.homepage_options.map { |option| option.slice(:id, :path, :server_side) }+ DiscoursePluginRegistry.homepage_options.map do |option|+ {+ id: option[:id],+ path: HomepageHelper.option_path(option, scope),+ server_side: option[:server_side],+ }+ endenddef periodsdiff --git a/frontend/discourse/admin/components/site-setting.gjs b/frontend/discourse/admin/components/site-setting.gjsindex 0141a1f4cb4..f4b3d415a20 100644--- a/frontend/discourse/admin/components/site-setting.gjs+++ b/frontend/discourse/admin/components/site-setting.gjs@@ -193,7 +193,8 @@ export default class SiteSettingComponent extends Component {}get showDependsOnNotice() {- return this.setting.depends_on?.length > 0;+ // Inline dependents only appear under their parent once it is satisfied.+ return !this.args.inline && this.setting.depends_on?.length > 0;}get dependsOnNoticeText() {diff --git a/frontend/discourse/admin/lib/site-setting-filter.js b/frontend/discourse/admin/lib/site-setting-filter.jsindex ae33b43d866..a700c9a5573 100644--- a/frontend/discourse/admin/lib/site-setting-filter.js+++ b/frontend/discourse/admin/lib/site-setting-filter.js@@ -127,9 +127,13 @@ export default class SiteSettingFilter {return false;});+ // An inline dependent is displayed as its parent, which may belong to an+ // earlier category that already lists it.const siteSettings = opts.dependsOn? matchedSiteSettings- : this.displaySettingsFor(matchedSiteSettings);+ : this.displaySettingsFor(matchedSiteSettings).filter(+ (setting) => !matches.includes(setting)+ );if (siteSettings.length > 0) {matches.push(...siteSettings);diff --git a/frontend/discourse/app/lib/homepage-router-overrides.js b/frontend/discourse/app/lib/homepage-router-overrides.jsindex 8ace1ed6ad4..b46b22c12ae 100644--- a/frontend/discourse/app/lib/homepage-router-overrides.js+++ b/frontend/discourse/app/lib/homepage-router-overrides.js@@ -90,6 +90,21 @@ export function discoveryHomepageRoute() {return `discovery.${item ?? "latest"}`;}+/**+ * Whether the transition is rendering the homepage at `/`.+ *+ * @param {Transition} transition+ * @returns {boolean}+ */+export function isHomepageTransition(transition) {+ const intent = transition?.intent;++ return Boolean(+ intent?.queryParams?.[homepageRewriteParam] ||+ intent?.url?.includes(`${homepageRewriteParam}=`)+ );+}+export function serverSideHomepage() {return registeredHomepageOption()?.server_side === true;}diff --git a/frontend/discourse/tests/acceptance/admin-site-settings-test.js b/frontend/discourse/tests/acceptance/admin-site-settings-test.jsindex 7d4f7e59ab9..f744520bddd 100644--- a/frontend/discourse/tests/acceptance/admin-site-settings-test.js+++ b/frontend/discourse/tests/acceptance/admin-site-settings-test.js@@ -201,10 +201,7 @@ acceptance("Admin - Site Settings", function (needs) {.hasValue("default", "parent controls reset the dependent setting");assert.dom(".setting-depends-on-notice")- .includesText(- "This setting only applies when Highlight scope is set to a compatible value.",- "value-based dependencies do not use enabled copy"- );+ .doesNotExist("the parent already shows the dependency");});test("filtering by an inline dependent site setting shows its parent setting", async function (assert) {diff --git a/frontend/discourse/tests/integration/components/site-setting-test.gjs b/frontend/discourse/tests/integration/components/site-setting-test.gjsindex 95efff11f3b..36c6ec7b932 100644--- a/frontend/discourse/tests/integration/components/site-setting-test.gjs+++ b/frontend/discourse/tests/integration/components/site-setting-test.gjs@@ -688,6 +688,23 @@ module(.hasText("Parent setting");});+ test("uses value-based copy for settings that depend on another setting's value", async function (assert) {+ await renderSetting({+ setting: "dependent_setting",+ value: "1",+ type: "integer",+ depends_on: ["parent_setting"],+ depends_on_humanized_names: ["Parent setting"],+ depends_on_values: { parent_setting: ["include"] },+ });++ assert+ .dom(".setting-depends-on-notice__text")+ .includesText(+ "This setting only applies when Parent setting is set to a compatible value."+ );+ });+test("does not show the depends_on notice when setting has no dependencies", async function (assert) {await renderSetting({setting: "plain_setting",diff --git a/frontend/discourse/tests/unit/lib/homepage-router-overrides-test.js b/frontend/discourse/tests/unit/lib/homepage-router-overrides-test.jsindex 306335fd9c5..875b7669ee4 100644--- a/frontend/discourse/tests/unit/lib/homepage-router-overrides-test.js+++ b/frontend/discourse/tests/unit/lib/homepage-router-overrides-test.js@@ -6,6 +6,7 @@ import applyRouterHomepageOverrides, {homepageNavigationDestination,homepagePath,homepagePreviewDestination,+ isHomepageTransition,} from "discourse/lib/homepage-router-overrides";import { setDefaultHomepage } from "discourse/lib/utilities";import Site from "discourse/models/site";@@ -107,4 +108,19 @@ module("Unit | Lib | homepage-router-overrides", function (hooks) {assert.deepEqual(updatedURLs, ["/?sort=name", "/directory"]);});++ test("detects transitions that render the homepage", function (assert) {+ assert.true(+ isHomepageTransition({+ intent: { url: "/directory?_discourse_homepage_rewrite=1" },+ })+ );+ assert.true(+ isHomepageTransition({+ intent: { queryParams: { _discourse_homepage_rewrite: "1" } },+ })+ );+ assert.false(isHomepageTransition({ intent: { url: "/directory" } }));+ assert.false(isHomepageTransition(undefined));+ });});diff --git a/frontend/discourse/tests/unit/lib/site-setting-filter-test.js b/frontend/discourse/tests/unit/lib/site-setting-filter-test.jsnew file mode 100644index 00000000000..968f95a3744--- /dev/null+++ b/frontend/discourse/tests/unit/lib/site-setting-filter-test.js@@ -0,0 +1,40 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import SiteSettingFilter from "discourse/admin/lib/site-setting-filter";+import SiteSetting from "discourse/admin/models/site-setting";++module("Unit | Lib | SiteSettingFilter", function (hooks) {+ setupTest(hooks);++ test("lists an inline dependent's parent once when they are in different categories", function (assert) {+ const parent = SiteSetting.create({+ setting: "highlight_scope",+ description: "Choose a scope.",+ value: "include",+ });+ const dependent = SiteSetting.create({+ setting: "highlight_categories",+ description: "Choose categories.",+ value: "",+ depends_on: ["highlight_scope"],+ depends_on_values: { highlight_scope: ["include"] },+ depends_behavior: "hidden",+ dependent_setting_display: "inline",+ });+ const filter = new SiteSettingFilter([+ { nameKey: "basic", siteSettings: [parent] },+ { nameKey: "plugins", siteSettings: [dependent] },+ ]);++ const [all, ...categories] = filter.filterSettings("highlight");++ assert.deepEqual(+ all.siteSettings.map((setting) => setting.setting),+ ["highlight_scope"]+ );+ assert.deepEqual(+ categories.map((category) => category.nameKey),+ ["basic"]+ );+ });+});diff --git a/lib/homepage_helper.rb b/lib/homepage_helper.rbindex 9d3d7a92f40..bf8b0d90bcf 100644--- a/lib/homepage_helper.rb+++ b/lib/homepage_helper.rb@@ -26,6 +26,20 @@ class HomepageHelpertop_menu_homepage(current_user)end+ def self.option_path(option, guardian)+ path = option[:path]+ return path if !path.respond_to?(:call)++ effective_homepage = guardian.anonymous? ? SiteSetting.anonymous_homepage : SiteSetting.homepage+ return if !option[:server_side] && option[:id] != effective_homepage+ return if !option_available?(option[:id], nil, guardian.user)++ path.call+ rescue StandardError => e+ Discourse.warn_exception(e, message: "Homepage path failed for '#{option[:id]}'")+ nil+ end+def self.custom_homepage_route(request)if CrawlerDetection.crawler_layout_request?(request)return SiteSetting.custom_homepage_crawler_routediff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex 170168fd4e1..a9eb1b28531 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -1173,7 +1173,11 @@ class Plugin::Instance## @param id [String, Symbol] stable identifier stored in the site setting# @param name [String] client-side translation key used in the admin setting- # @param path [String] application path for the homepage+ # @param path [String, Proc] application path for the homepage, excluding any+ # subfolder, or a lambda returning one when it depends on settings. A lambda+ # is resolved when the site data is built; anonymous site data is cached+ # until a site setting changes, so call `Site.clear_anon_cache!` if the path+ # depends on anything else.# @param route [String] Rails controller action, in `controller#action` form# @param anonymous [Boolean] whether logged-out visitors may use this homepage# @param server_side [Boolean] whether navigation requires a full page request@@ -1182,7 +1186,7 @@ class Plugin::Instance# back to the top menu homepage# @param available [Proc, nil] called with `guardian:` and `request:` (which# may be nil); when it returns false the visitor gets the regular top menu- # homepage instead. It runs whenever the homepage is resolved, including on+ # homepage instead, and a lambda `path` is not sent to them. It runs whenever the homepage is resolved, including on# page loads and topic list requests, so keep it cheap.def register_homepage(id,@@ -1201,7 +1205,9 @@ class Plugin::Instance"homepage id must contain only lowercase letters, numbers, underscores, and hyphens"endraise ArgumentError, "homepage name must be present" if name.blank?- raise ArgumentError, "homepage path must start with /" if !path.to_s.start_with?("/")+ if !path.respond_to?(:call) && !path.to_s.start_with?("/")+ raise ArgumentError, "homepage path must start with /"+ endif !route.to_s.match?(/\A[^#]+#[^#]+\z/)raise ArgumentError, "homepage route must use controller#action format"end@@ -1230,7 +1236,7 @@ class Plugin::Instance{id: id,name: name,- path: path.to_s,+ path: path.respond_to?(:call) ? path : path.to_s,route: route.to_s,anonymous: anonymous,server_side: server_side,diff --git a/plugins/chat/app/models/chat/channel.rb b/plugins/chat/app/models/chat/channel.rbindex b1ec9d91258..3e255216e2a 100644--- a/plugins/chat/app/models/chat/channel.rb+++ b/plugins/chat/app/models/chat/channel.rb@@ -47,6 +47,9 @@ module Chatvalidate :ensure_slug_ok, if: :slug_changed?before_validation :generate_auto_slugafter_update :enqueue_channel_hashtag_remap, if: :saved_change_to_slug?+ after_commit :clear_homepage_anon_cache,+ on: :update,+ if: -> { saved_change_to_slug? || saved_change_to_status? }scope :with_categories,-> do@@ -119,6 +122,12 @@ module ChatHashtagRemapper.enqueue([{ type: Chat::ChannelHashtagDataSource.type, id:, old_ref: }])end+ # The anonymous site data caches the homepage path, which depends on the+ # slug and on the channel being available.+ def clear_homepage_anon_cache+ Site.clear_anon_cache! if SiteSetting.chat_homepage_channel.to_s == id.to_s+ end+def ensure_slug_okif self.slug.present?# if we don't unescape it first we strip the % from the encoded versiondiff --git a/plugins/chat/app/models/chat/homepage_channel_site_setting.rb b/plugins/chat/app/models/chat/homepage_channel_site_setting.rbnew file mode 100644index 00000000000..328479ad0d9--- /dev/null+++ b/plugins/chat/app/models/chat/homepage_channel_site_setting.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++require "enum_site_setting"++module Chat+ class HomepageChannelSiteSetting < ::EnumSiteSetting+ def self.valid_value?(val)+ val.blank? || selectable_channels.exists?(id: val)+ end++ def self.values+ selectable_channels+ .includes(:chatable)+ .order(:id)+ .map { |channel| { name: channel.title, value: channel.id } }+ end++ def self.translate_names?+ false+ end++ def self.selectable_channels+ Chat::Channel.public_channels.where.not(status: :archived)+ end++ private_class_method :selectable_channels+ end+enddiff --git a/plugins/chat/assets/javascripts/discourse/routes/chat.js b/plugins/chat/assets/javascripts/discourse/routes/chat.jsindex 39702674714..599e1afa28a 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat.js@@ -1,5 +1,8 @@import { service } from "@ember/service";-import { discoveryHomepageRoute } from "discourse/lib/homepage-router-overrides";+import {+ discoveryHomepageRoute,+ isHomepageTransition,+} from "discourse/lib/homepage-router-overrides";import { withPluginApi } from "discourse/lib/plugin-api";import Session from "discourse/models/session";import DiscourseRoute from "discourse/routes/discourse";@@ -47,9 +50,12 @@ export default class ChatRoute extends DiscourseRoute {// This preserves the original behavior: if someone directly types /chat in// the address bar, show them full page chat (they explicitly chose it).// But if requiresRefresh caused a reload mid-session, respect drawer preference.+ // The homepage always opens full page: there is no page beneath for the+ // drawer to open over.if (isDrawerPreferred &&canHandleInDrawer &&+ !isHomepageTransition(transition) &&(!fullPageReload || requiresRefresh)) {transition.abort();diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 28718c6811c..260292cfdee 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -39,6 +39,7 @@ en:other: "%{formatted_number} chat messages"chat:+ homepage_option: "Chat channel"edit_category:tab_title: "Chat"channel: "Channel"diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.ymlindex fb5eb79ded8..820b7c7b93a 100644--- a/plugins/chat/config/locales/server.en.yml+++ b/plugins/chat/config/locales/server.en.yml@@ -22,6 +22,7 @@ en:chat_pinning_messages_allowed_groups: "Users in these groups are allowed to pin chat messages in channels that they can access. Note that admins and moderators can always pin chat messages. Any member of a group chat or DM can pin messages there."max_mentions_per_chat_message: "Maximum number of @name notifications a user can use in a chat message."chat_max_direct_message_users: "Users cannot add more than this number of other users when creating a new direct message. Set to 0 to only allow messages to oneself. Staff are exempt from this setting."+ chat_homepage_channel: "The channel people land on when {{setting:default_homepage}} is set to a chat channel. People who cannot access the channel see the first item in {{setting:top_menu}} instead, including anonymous visitors, unless {{setting:chat_allowed_groups}} includes anonymous users."chat_allow_archiving_channels: "Allow staff to archive messages to a topic when closing a channel."chat_editing_grace_period: "For (n) seconds after sending a chat, editing will not display the (edited) tag by the chat message."chat_editing_grace_period_max_diff_low_trust: "Maximum number of character changes allowed in chat editing grace period, if more changed display the (edited) tag by the chat message (trust level 0 and 1)."diff --git a/plugins/chat/config/settings.yml b/plugins/chat/config/settings.ymlindex 31c50d1663a..a1861ca19c8 100644--- a/plugins/chat/config/settings.yml+++ b/plugins/chat/config/settings.yml@@ -67,6 +67,19 @@ chat:default: 60min: 0area: "flags"+ chat_homepage_channel:+ refresh: true+ type: enum+ default: ""+ enum: "Chat::HomepageChannelSiteSetting"+ area: "interface"+ depends_on:+ - default_homepage+ depends_on_values:+ default_homepage:+ - chat+ depends_behavior: "hidden"+ dependent_setting_display: "inline"chat_allow_archiving_channels:default: falseclient: truediff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rbindex 835f54042eb..4c71c2f307f 100644--- a/plugins/chat/plugin.rb+++ b/plugins/chat/plugin.rb@@ -442,6 +442,29 @@ after_initialize doChat::AutoLeaveChannels.call(params: { group_id: group.id, event: :group_destroyed })end+ homepage_channel = -> { Chat::Channel.find_by(id: SiteSetting.chat_homepage_channel.presence) }++ register_homepage(+ "chat",+ name: "chat.homepage_option",+ path: -> { homepage_channel.call&.relative_url&.delete_prefix(Discourse.base_path) || "/chat" },+ route: "chat/chat#respond",+ anonymous: true,+ enabled: -> { SiteSetting.enable_public_channels },+ available: ->(guardian:, request:) do+ channel = homepage_channel.call+ next false if channel.nil? || channel.archived? || !channel.public_channel?+ next false if CrawlerDetection.crawler_layout_request?(request)++ if guardian.anonymous?+ guardian.can_preview_anonymous_public_chat_channel?(channel)+ else+ guardian.can_chat? && guardian.user.user_option&.chat_enabled &&+ guardian.can_preview_chat_channel?(channel)+ end+ end,+ )+register_presence_channel_prefix("chat") do |channel_name|next if channel_name != "/chat/online"PresenceChannel::Config.new.tap { |config| config.allowed_group_ids = Chat.allowed_group_ids }diff --git a/plugins/chat/spec/models/chat/homepage_channel_site_setting_spec.rb b/plugins/chat/spec/models/chat/homepage_channel_site_setting_spec.rbnew file mode 100644index 00000000000..ea58756d783--- /dev/null+++ b/plugins/chat/spec/models/chat/homepage_channel_site_setting_spec.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++RSpec.describe Chat::HomepageChannelSiteSetting do+ fab!(:channel_1) { Fabricate(:category_channel, name: "General") }++ it "offers public channels" do+ expect(described_class.values).to include({ name: "General", value: channel_1.id })+ expect(described_class.translate_names?).to eq(false)+ end++ it "does not offer direct message channels" do+ dm_channel = Fabricate(:direct_message_channel)++ expect(described_class.values.map { |v| v[:value] }).not_to include(dm_channel.id)+ end++ it "does not offer archived channels" do+ channel_1.update!(status: :archived)++ expect(described_class.values).to be_empty+ end++ it "validates values" do+ expect(described_class.valid_value?("")).to eq(true)+ expect(described_class.valid_value?(channel_1.id)).to eq(true)+ expect(described_class.valid_value?(-1)).to eq(false)+ end++ it "does not validate archived channels" do+ channel_1.update!(status: :archived)++ expect(described_class.valid_value?(channel_1.id)).to eq(false)+ end++ it "loads channel categories without a query per channel" do+ described_class.values+ initial_count = track_sql_queries { described_class.values }.size++ Fabricate(:category_channel)++ expect(track_sql_queries { described_class.values }.size).to eq(initial_count)+ end+enddiff --git a/plugins/chat/spec/requests/homepage_spec.rb b/plugins/chat/spec/requests/homepage_spec.rbnew file mode 100644index 00000000000..48a01a96957--- /dev/null+++ b/plugins/chat/spec/requests/homepage_spec.rb@@ -0,0 +1,191 @@+# frozen_string_literal: true++RSpec.describe "Chat channel homepage" do+ fab!(:chatters, :group)+ fab!(:user) { Fabricate(:user, group_ids: [chatters.id], refresh_auto_groups: true) }+ fab!(:channel_1) { Fabricate(:category_channel, name: "General") }++ let(:crawler_request) { ActionDispatch::TestRequest.create("HTTP_USER_AGENT" => "Googlebot") }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = chatters.id+ SiteSetting.top_menu = "latest|new|top|categories"+ SiteSetting.default_homepage = "chat"+ SiteSetting.chat_homepage_channel = channel_1.id+ end++ it "resolves to chat" do+ expect(HomepageHelper.resolve(nil, user)).to eq("chat")+ end++ it "points the homepage at the channel" do+ serialized = SiteSerializer.new(Site.new(user.guardian), scope: user.guardian, root: false)++ expect(serialized.as_json[:homepage_options]).to include(+ id: "chat",+ path: channel_1.relative_url,+ server_side: false,+ )+ end++ it "leaves the subfolder out of the homepage path" do+ set_subfolder "/forum"++ serialized = SiteSerializer.new(Site.new(user.guardian), scope: user.guardian, root: false)++ expect(serialized.as_json[:homepage_options]).to include(+ id: "chat",+ path: "/chat/c/#{channel_1.slug}/#{channel_1.id}",+ server_side: false,+ )+ end++ it "asks open clients to refresh when the channel changes" do+ channel_2 = Fabricate(:category_channel)++ messages =+ MessageBus.track_publish("/global/asset-version") do+ SiteSetting.set("chat_homepage_channel", channel_2.id)+ end++ expect(messages.map(&:data)).to eq(["clobber"])+ end++ it "renders the app at the root path" do+ SiteSetting.has_login_hint = false+ sign_in(user)++ get "/"++ expect(response.status).to eq(200)+ expect(response.body).to include('<meta name="discourse_current_homepage" content="chat">')+ end++ it "is not offered as a homepage choice when public channels are disabled" do+ expect(HomepageSiteSetting.choices).to include("chat")++ SiteSetting.enable_public_channels = false++ expect(HomepageSiteSetting.choices).not_to include("chat")+ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when no channel is chosen" do+ SiteSetting.chat_homepage_channel = ""++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when chat is disabled" do+ SiteSetting.chat_enabled = false++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when the channel no longer exists" do+ channel_1.destroy!++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when the channel is archived" do+ channel_1.update!(status: :archived)++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when chat_allowed_groups excludes the user" do+ SiteSetting.chat_allowed_groups = Fabricate(:group).id++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when the user has disabled chat in their preferences" do+ user.user_option.update!(chat_enabled: false)++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")+ end++ it "falls back when the user cannot see the channel's category" do+ channel_1.chatable.update!(read_restricted: true)++ expect(HomepageHelper.resolve(nil, user)).to eq("latest")++ serialized = SiteSerializer.new(Site.new(user.guardian), scope: user.guardian, root: false)+ expect(serialized.as_json[:homepage_options]).to include(+ id: "chat",+ path: nil,+ server_side: false,+ )+ end++ it "falls back for crawlers" do+ expect(HomepageHelper.resolve(crawler_request, user)).to eq("latest")+ end++ context "with an anonymous visitor" do+ it "falls back when anonymous chat access is not allowed" do+ expect(HomepageHelper.resolve).to eq("latest")+ end++ it "resolves to chat when anonymous chat access is allowed" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:anonymous_users]++ expect(HomepageHelper.resolve).to eq("chat")+ end++ it "renders the app at the root path when anonymous chat access is allowed" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:anonymous_users]+ SiteSetting.has_login_hint = false++ get "/"++ expect(response.status).to eq(200)+ expect(response.body).to include('<meta name="discourse_current_homepage" content="chat">')+ end++ it "serves the new homepage path after the channel slug changes" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:anonymous_users]+ Site.json_for(Guardian.new)++ channel_1.update!(slug: "new-slug")++ homepage =+ JSON.parse(Site.json_for(Guardian.new))["homepage_options"].find { _1["id"] == "chat" }+ expect(homepage["path"]).to eq("/chat/c/new-slug/#{channel_1.id}")+ end++ it "stops serving the homepage path after the channel is archived" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:anonymous_users]+ Site.json_for(Guardian.new)++ channel_1.update!(status: :archived)++ homepage =+ JSON.parse(Site.json_for(Guardian.new))["homepage_options"].find { _1["id"] == "chat" }+ expect(homepage["path"]).to be_nil+ end++ it "stops serving the homepage path after the channel is trashed" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:anonymous_users]+ admin = Fabricate(:admin)+ Site.json_for(Guardian.new)++ Chat::TrashChannel.call(params: { channel_id: channel_1.id }, guardian: admin.guardian)++ homepage =+ JSON.parse(Site.json_for(Guardian.new))["homepage_options"].find { _1["id"] == "chat" }+ expect(homepage["path"]).to be_nil+ end++ it "keeps the anonymous site cache when another channel's slug changes" do+ channel_2 = Fabricate(:category_channel)++ messages =+ MessageBus.track_publish(Site::SITE_JSON_CHANNEL) { channel_2.update!(slug: "other") }++ expect(messages).to be_empty+ end+ end+enddiff --git a/plugins/chat/spec/system/admin_homepage_channel_setting_spec.rb b/plugins/chat/spec/system/admin_homepage_channel_setting_spec.rbnew file mode 100644index 00000000000..22d4f12f130--- /dev/null+++ b/plugins/chat/spec/system/admin_homepage_channel_setting_spec.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++describe "Admin chat homepage channel setting" do+ fab!(:admin)+ fab!(:channel_1) { Fabricate(:category_channel, name: "General") }++ let(:settings_page) { PageObjects::Pages::AdminSiteSettings.new }+ let(:changes_banner) { PageObjects::Components::AdminChangesBanner.new }++ before do+ chat_system_bootstrap+ sign_in(admin)+ end++ it "reveals the channel picker only once the homepage is set to chat" do+ settings_page.visit("default_homepage")++ expect(page).to have_no_css("[data-setting='chat_homepage_channel']")++ settings_page.select_enum_value("default_homepage", "chat")+ settings_page.save_setting("default_homepage")++ expect(settings_page.find_setting("default_homepage")).to have_css(+ "[data-setting='chat_homepage_channel']",+ )++ settings_page.select_enum_value("chat_homepage_channel", channel_1.id.to_s)+ changes_banner.click_save+ page.refresh++ expect(settings_page.enum_setting("chat_homepage_channel").value).to eq(channel_1.id.to_s)+ end+enddiff --git a/plugins/chat/spec/system/homepage_channel_spec.rb b/plugins/chat/spec/system/homepage_channel_spec.rbnew file mode 100644index 00000000000..86748027ae1--- /dev/null+++ b/plugins/chat/spec/system/homepage_channel_spec.rb@@ -0,0 +1,81 @@+# frozen_string_literal: true++RSpec.describe "Chat channel as the homepage" do+ fab!(:current_user, :user)+ fab!(:channel_1, :category_channel)+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1) }++ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }++ before do+ chat_system_bootstrap+ SiteSetting.top_menu = "latest|new|top|categories"+ SiteSetting.default_homepage = "chat"+ SiteSetting.chat_homepage_channel = channel_1.id+ sign_in(current_user)+ end++ it "renders the channel at the root path" do+ visit("/")++ expect(channel_page.messages).to have_message(id: message_1.id)+ expect(page).to have_current_path("/")+ end++ it "returns to the root path from the logo" do+ visit("/categories")+ find("#site-logo").click++ expect(channel_page.messages).to have_message(id: message_1.id)+ expect(page).to have_current_path("/")+ end++ it "keeps the channel's own path when visited directly" do+ visit(channel_1.relative_url)++ expect(channel_page.messages).to have_message(id: message_1.id)+ expect(page).to have_current_path(channel_1.relative_url)+ end++ it "shows the usual homepage when the user cannot chat" do+ SiteSetting.chat_allowed_groups = Fabricate(:group).id++ visit("/")++ # the fallback is still served at / like any other homepage+ expect(page).to have_css(".navigation-container .nav-item_latest.active")+ expect(page).to have_no_css(".chat-channel")+ expect(page).to have_current_path("/")+ end++ it "shows the usual homepage when the user has disabled chat" do+ current_user.user_option.update!(chat_enabled: false)++ visit("/")++ expect(page).to have_css(".navigation-container .nav-item_latest.active")+ expect(page).to have_no_css(".chat-channel")+ expect(page).to have_current_path("/")+ end++ it "leaves an individual homepage preference alone" do+ current_user.user_option.update!(homepage_id: UserOption::HOMEPAGES.key("categories"))++ visit("/")++ expect(page).to have_css(".navigation-container .nav-item_categories.active")+ expect(page).to have_no_css(".chat-channel")+ end++ context "when the user prefers the drawer" do+ it "still opens full page from the homepage" do+ visit("/categories")+ chat_page.prefers_drawer+ find("#site-logo").click++ expect(channel_page.messages).to have_message(id: message_1.id)+ expect(page).to have_current_path("/")+ end+ end+enddiff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rbindex ac19b00eedc..2dfb7adc91a 100644--- a/spec/lib/plugin/instance_spec.rb+++ b/spec/lib/plugin/instance_spec.rb@@ -1276,6 +1276,15 @@ TEXT)end.to raise_error(ArgumentError, /server_side/)+ expect do+ plugin_instance.register_homepage(+ "other_homepage",+ name: "plugin.other_homepage",+ path: "other",+ route: "plugin#other",+ )+ end.to raise_error(ArgumentError, /path/)+expect doplugin_instance.register_homepage("other_homepage",diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rbindex 02841a606aa..becab985bf2 100644--- a/spec/serializers/site_serializer_spec.rb+++ b/spec/serializers/site_serializer_spec.rb@@ -70,6 +70,143 @@ RSpec.describe SiteSerializer doserver_side: false,)end++ it "only resolves a callable homepage path for the homepage in use" do+ calls = 0+ plugin = Plugin::Instance.new+ plugin.stubs(:enabled?).returns(true)+ plugin.register_homepage(+ "dynamic",+ name: "plugin.dynamic",+ path: -> { calls += 1 and "/dynamic" },+ route: "plugin#index",+ anonymous: true,+ )+ SiteSetting.top_menu = "latest|categories"+ SiteSetting.default_homepage = "latest"++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(calls).to eq(0)+ expect(serialized[:homepage_options]).to include(id: "dynamic", path: nil, server_side: false)++ SiteSetting.default_homepage = "dynamic"+ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(calls).to eq(1)+ expect(serialized[:homepage_options]).to include(+ id: "dynamic",+ path: "/dynamic",+ server_side: false,+ )+ end++ it "omits a callable homepage path when the homepage is unavailable to the visitor" do+ plugin = Plugin::Instance.new+ plugin.stubs(:enabled?).returns(true)+ plugin.register_homepage(+ "dynamic",+ name: "plugin.dynamic",+ path: -> { "/dynamic/private" },+ route: "plugin#index",+ available: ->(guardian:, request:) { guardian.is_admin? },+ )+ SiteSetting.default_homepage = "dynamic"++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json+ expect(serialized[:homepage_options]).to include(id: "dynamic", path: nil, server_side: false)++ admin_guardian = Fabricate(:admin).guardian+ serialized =+ described_class.new(Site.new(admin_guardian), scope: admin_guardian, root: false).as_json+ expect(serialized[:homepage_options]).to include(+ id: "dynamic",+ path: "/dynamic/private",+ server_side: false,+ )+ end++ it "omits a member-only callable homepage path for anonymous visitors" do+ plugin = Plugin::Instance.new+ plugin.stubs(:enabled?).returns(true)+ plugin.register_homepage(+ "dynamic",+ name: "plugin.dynamic",+ path: -> { "/private/secret-slug" },+ route: "plugin#index",+ )+ SiteSetting.top_menu = "latest|categories"+ SiteSetting.default_homepage = "dynamic"++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json+ expect(serialized[:homepage_options]).to include(id: "dynamic", path: nil, server_side: false)++ member_guardian = Fabricate(:user).guardian+ serialized =+ described_class.new(Site.new(member_guardian), scope: member_guardian, root: false).as_json+ expect(serialized[:homepage_options]).to include(+ id: "dynamic",+ path: "/private/secret-slug",+ server_side: false,+ )+ end++ it "omits a server side callable homepage path when it is unavailable to the visitor" do+ plugin = Plugin::Instance.new+ plugin.stubs(:enabled?).returns(true)+ plugin.register_homepage(+ "dynamic",+ name: "plugin.dynamic",+ path: -> { "/dynamic/private" },+ route: "plugin#index",+ server_side: true,+ available: ->(guardian:, request:) { false },+ )++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(serialized[:homepage_options]).to include(id: "dynamic", path: nil, server_side: true)+ end++ it "omits a callable homepage path that raises" do+ plugin = Plugin::Instance.new+ plugin.stubs(:enabled?).returns(true)+ plugin.register_homepage(+ "dynamic",+ name: "plugin.dynamic",+ path: -> { raise "boom" },+ route: "plugin#index",+ anonymous: true,+ )+ SiteSetting.default_homepage = "dynamic"+ Discourse.expects(:warn_exception).once++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(serialized[:homepage_options]).to include(id: "dynamic", path: nil, server_side: false)+ end++ it "resolves a registered homepage path that depends on settings" do+ plugin = Plugin::Instance.new+ plugin.stubs(:enabled?).returns(true)+ plugin.register_homepage(+ "dynamic",+ name: "plugin.dynamic",+ path: -> { "/dynamic/#{SiteSetting.title.parameterize}" },+ route: "plugin#index",+ anonymous: true,+ )+ SiteSetting.title = "Great Site"+ SiteSetting.default_homepage = "dynamic"++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(serialized[:homepage_options]).to include(+ id: "dynamic",+ path: "/dynamic/great-site",+ server_side: false,+ )+ endenddescribe "#anonymous_list_filters" do