A platform for community discussion. Free, open, simple.
UX: Hide empty notification filters in the user menu (#45046)
Keegan Georgeeafa0d1225af
diff --git a/app/models/user.rb b/app/models/user.rbindex f9927848a6f..db8dbad6e7b 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -737,6 +737,10 @@ class User < ActiveRecord::BaseDB.query_single(sql, user_id: id, high_priority: high_priority)[0].to_iend+ def available_notification_types+ notifications.visible.distinct.pluck(:notification_type)+ end+MAX_UNREAD_BACKLOG = 400def grouped_unread_notificationsresults = DB.query(<<~SQL, user_id: id, limit: MAX_UNREAD_BACKLOG)@@ -934,6 +938,7 @@ class User < ActiveRecord::Basepayload[:all_unread_notifications_count] = all_unread_notifications_countpayload[:grouped_unread_notifications] = grouped_unread_notifications+ payload[:available_notification_types] = available_notification_typespayload[:new_personal_messages_notifications_count] = new_personal_messages_notifications_countMessageBus.publish("/notification/#{id}", payload, user_ids: [id])diff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rbindex db76a1626e9..21bcac963d1 100644--- a/app/serializers/current_user_serializer.rb+++ b/app/serializers/current_user_serializer.rb@@ -71,6 +71,7 @@ class CurrentUserSerializer < BasicUserSerializer:draft_count,:pending_posts_count,:grouped_unread_notifications,+ :available_notification_types,:display_sidebar_tags,:sidebar_tags,:sidebar_category_ids,diff --git a/frontend/discourse/app/components/user-menu/menu.gjs b/frontend/discourse/app/components/user-menu/menu.gjsindex 10905e120e8..eb0ee7268e6 100644--- a/frontend/discourse/app/components/user-menu/menu.gjs+++ b/frontend/discourse/app/components/user-menu/menu.gjs@@ -29,6 +29,12 @@ const DEFAULT_TAB_ID = "all-notifications";const DEFAULT_PANEL_COMPONENT = UserMenuNotificationsList;const REVIEW_QUEUE_TAB_ID = "review-queue";+const PROGRESSIVE_TAB_IDS = new Set([+ "replies",+ "mentions",+ "likes",+ "other-notifications",+]);const CORE_TOP_TABS = [class extends UserMenuTab {@@ -221,8 +227,15 @@ export default class UserMenu extends Component {@tracked currentPanelComponent = DEFAULT_PANEL_COMPONENT;@tracked currentNotificationTypes;+ #availableNotificationTypes;+constructor() {super(...arguments);+ // Snapshot visibility so notifications cannot move tabs while the menu is open.+ const availableTypes = this.currentUser.available_notification_types;+ this.#availableNotificationTypes = availableTypes+ ? new Set(availableTypes)+ : null;this.router.on("routeDidChange", this.onRouteChange);}@@ -275,10 +288,12 @@ export default class UserMenu extends Component {));- return tabs.map((tab, index) => {- tab.position = index;- return tab;- });+ return tabs+ .filter((tab) => this.#hasNotifications(tab))+ .map((tab, index) => {+ tab.position = index;+ return tab;+ });}@cached@@ -337,6 +352,19 @@ export default class UserMenu extends Component {topTabsContainerElement.querySelector(".btn.active")?.focus();}+ #hasNotifications(tab) {+ if (+ !PROGRESSIVE_TAB_IDS.has(tab.id) ||+ this.#availableNotificationTypes === null+ ) {+ return true;+ }++ return tab.notificationTypes.some((type) =>+ this.#availableNotificationTypes.has(this.site.notification_types[type])+ );+ }+#notificationTypesForTheOtherTab(tabs) {const usedNotificationTypes = tabs.filter((tab) => tab.notificationTypes)diff --git a/frontend/discourse/app/instance-initializers/subscribe-user-notifications.js b/frontend/discourse/app/instance-initializers/subscribe-user-notifications.jsindex 40aae16cf46..65dde8b5085 100644--- a/frontend/discourse/app/instance-initializers/subscribe-user-notifications.js+++ b/frontend/discourse/app/instance-initializers/subscribe-user-notifications.js@@ -144,6 +144,13 @@ class SubscribeUserNotificationsInit {const oldHighPriority = this.currentUser.unread_high_priority_notifications;const oldAllUnread = this.currentUser.all_unread_notifications_count;+ if ("available_notification_types" in data) {+ this.currentUser.set(+ "available_notification_types",+ data.available_notification_types+ );+ }+this.currentUser.setProperties({unread_notifications: data.unread_notifications,unread_high_priority_notifications:diff --git a/frontend/discourse/tests/acceptance/user-menu-test.js b/frontend/discourse/tests/acceptance/user-menu-test.jsindex cf5c0e28c3b..55cc172aa4d 100644--- a/frontend/discourse/tests/acceptance/user-menu-test.js+++ b/frontend/discourse/tests/acceptance/user-menu-test.js@@ -59,6 +59,110 @@ acceptance("User menu", function (needs) {requestHeaders = {};});+ test("plugin-owned notifications reveals no unrelated core filters", async function (assert) {+ updateCurrentUser({+ available_notification_types: [NOTIFICATION_TYPES.chat_mention],+ });+ withPluginApi((api) => {+ api.registerUserMenuTab((UserMenuTab) => {+ return class extends UserMenuTab {+ id = "plugin-notifications";+ icon = "comment";+ panelComponent = DButton;+ notificationTypes = ["chat_mention"];++ get title() {+ return "Plugin notifications";+ }+ };+ });+ });+ await visit("/");+ await click(".d-header-icons .current-user button");++ assert+ .dom("#user-menu-button-plugin-notifications")+ .exists("plugin visibility rules remain unchanged");+ assert+ .dom("#user-menu-button-other-notifications")+ .doesNotExist("an empty core filter remains hidden");+ });++ test("new notification filters appear on the next menu opening", async function (assert) {+ updateCurrentUser({ available_notification_types: [] });+ await visit("/");+ await click(".d-header-icons .current-user button");+ assert+ .dom("#user-menu-button-likes")+ .doesNotExist("a new user has no Likes tab");++ await publishToMessageBus(`/notification/${loggedInUser().id}`, {+ available_notification_types: [NOTIFICATION_TYPES.liked],+ grouped_unread_notifications: { [NOTIFICATION_TYPES.liked]: 1 },+ });+ assert+ .dom("#user-menu-button-likes")+ .doesNotExist("the open menu does not rearrange itself");++ await click(".d-header-icons .current-user button");+ await click(".d-header-icons .current-user button");+ assert+ .dom("#user-menu-button-likes")+ .exists("the first like reveals the tab on reopening");+ assert+ .dom("#user-menu-button-likes .badge-notification")+ .hasText("1", "the new tab shows its unread count");++ const tabIds = findAll(".user-menu-tab").map((tab) => tab.id);+ await publishToMessageBus(`/notification/${loggedInUser().id}`, {+ available_notification_types: [NOTIFICATION_TYPES.liked],+ grouped_unread_notifications: { [NOTIFICATION_TYPES.liked]: 2 },+ });+ assert+ .dom("#user-menu-button-likes .badge-notification")+ .hasText(+ "2",+ "an already-visible tab updates its badge without reopening"+ );+ assert+ .dom("#user-menu-button-all-notifications")+ .isFocused("a badge update preserves keyboard focus");+ assert.deepEqual(+ findAll(".user-menu-tab").map((tab) => tab.id),+ tabIds,+ "badge updates preserve tab order"+ );++ await publishToMessageBus(`/notification/${loggedInUser().id}`, {+ available_notification_types: [NOTIFICATION_TYPES.liked],+ grouped_unread_notifications: {},+ });+ assert+ .dom("#user-menu-button-likes .badge-notification")+ .doesNotExist("the unread badge clears while the menu is still open");+ await click(".d-header-icons .current-user button");+ await click(".d-header-icons .current-user button");+ assert+ .dom("#user-menu-button-likes")+ .exists("reading all likes does not hide the revealed tab");+ assert+ .dom("#user-menu-button-likes .badge-notification")+ .doesNotExist("the badge clears independently of visibility");++ await publishToMessageBus(`/notification/${loggedInUser().id}`, {+ available_notification_types: [],+ grouped_unread_notifications: {},+ });+ assert+ .dom("#user-menu-button-likes")+ .exists("deletion does not move open tabs");+ await click(".d-header-icons .current-user button");+ await click(".d-header-icons .current-user button");+ assert+ .dom("#user-menu-button-likes")+ .doesNotExist("deleting the last like hides its filter on reopening");+ });+test("notifications panel has a11y attributes", async function (assert) {await visit("/");await click(".d-header-icons .current-user button");diff --git a/frontend/discourse/tests/integration/components/user-menu/menu-test.gjs b/frontend/discourse/tests/integration/components/user-menu/menu-test.gjsindex b136334f10a..06343354b9f 100644--- a/frontend/discourse/tests/integration/components/user-menu/menu-test.gjs+++ b/frontend/discourse/tests/integration/components/user-menu/menu-test.gjs@@ -1,10 +1,12 @@import { click, findAll, render, settled } from "@ember/test-helpers";import { module, test } from "qunit";import Menu from "discourse/components/user-menu/menu";+import { registerUserMenuTab } from "discourse/lib/user-menu/tab";import { NOTIFICATION_TYPES } from "discourse/tests/fixtures/concerns/notification-types";import NotificationFixtures from "discourse/tests/fixtures/notification-fixtures";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender from "discourse/tests/helpers/create-pretender";+import DButton from "discourse/ui-kit/d-button";import { i18n } from "discourse-i18n";module("Integration | Component | UserMenu", function (hooks) {@@ -14,6 +16,170 @@ module("Integration | Component | UserMenu", function (hooks) {this.siteSettings.enable_user_menu_mentions_tab = true;});+ test("new users only see navigation tabs before receiving notifications", async function (assert) {+ this.currentUser.set("available_notification_types", []);+ this.currentUser.set("can_send_private_messages", true);+ await render(<template><Menu /></template>);++ assert.deepEqual(+ findAll(".user-menu-tab").map((tab) => tab.id),+ [+ "user-menu-button-all-notifications",+ "user-menu-button-messages",+ "user-menu-button-bookmarks",+ "user-menu-button-profile",+ ],+ "empty notification filters are hidden while navigation remains available"+ );+ assert.deepEqual(+ findAll(".user-menu-tab").map((tab) => tab.dataset.tabNumber),+ ["0", "1", "2", "3"],+ "keyboard tab positions remain consecutive"+ );+ });++ test("read notifications reveals filters without unread badges", async function (assert) {+ this.currentUser.set("available_notification_types", [+ NOTIFICATION_TYPES.mentioned,+ NOTIFICATION_TYPES.liked,+ NOTIFICATION_TYPES.edited,+ ]);+ this.currentUser.set("grouped_unread_notifications", {});+ await render(<template><Menu /></template>);++ assert+ .dom("#user-menu-button-mentions")+ .exists("a past direct mention reveals Mentions");+ assert.dom("#user-menu-button-likes").exists("a past like reveals Likes");+ assert+ .dom("#user-menu-button-other-notifications")+ .exists("a past edit reveals Other notifications");+ assert+ .dom("#user-menu-button-replies")+ .doesNotExist(+ "a direct mention does not reveal Replies when Mentions is enabled"+ );+ assert+ .dom(".user-menu .badge-notification")+ .doesNotExist("read history does not add unread badges");+ });++ test("direct mentions reveal Replies when the mentions feature is disabled", async function (assert) {+ this.siteSettings.enable_user_menu_mentions_tab = false;+ this.currentUser.set("available_notification_types", [+ NOTIFICATION_TYPES.mentioned,+ ]);+ await render(<template><Menu /></template>);++ assert+ .dom("#user-menu-button-replies")+ .exists("Replies is the applicable filter for direct mentions");+ assert+ .dom("#user-menu-button-mentions")+ .doesNotExist("the disabled feature stays hidden");+ assert+ .dom("#user-menu-button-other-notifications")+ .doesNotExist("mentions are not reassigned to Other");+ });++ test("hidden filters do not move their types into Other notifications", async function (assert) {+ let requestedTypes;+ pretender.get("/notifications", (request) => {+ requestedTypes = request.queryParams.filter_by_types;+ return [+ 200,+ { "Content-Type": "application/json" },+ { notifications: [] },+ ];+ });+ this.currentUser.set("available_notification_types", [+ NOTIFICATION_TYPES.edited,+ ]);+ await render(<template><Menu /></template>);+ await click("#user-menu-button-other-notifications");++ assert.false(+ requestedTypes.split(",").includes("liked"),+ "hidden Likes still owns like notifications"+ );+ assert.false(+ requestedTypes.split(",").includes("replied"),+ "hidden Replies still owns reply notifications"+ );+ assert.false(+ requestedTypes.split(",").includes("mentioned"),+ "hidden Mentions still owns direct mentions"+ );+ });++ test("Other excludes plugin-owned types while retaining its own notifications", async function (assert) {+ registerUserMenuTab(+ (UserMenuTab) =>+ class extends UserMenuTab {+ id = "plugin-notifications";+ icon = "comment";+ panelComponent = DButton;+ notificationTypes = ["chat_mention"];++ get title() {+ return "Plugin notifications";+ }+ }+ );+ this.currentUser.set("available_notification_types", [+ NOTIFICATION_TYPES.chat_mention,+ NOTIFICATION_TYPES.edited,+ ]);+ let requestedTypes;+ pretender.get("/notifications", (request) => {+ requestedTypes = request.queryParams.filter_by_types;+ return [+ 200,+ { "Content-Type": "application/json" },+ { notifications: [] },+ ];+ });+ await render(<template><Menu /></template>);+ assert+ .dom("#user-menu-button-plugin-notifications")+ .exists("plugin tab remains available");+ await click("#user-menu-button-other-notifications");+ assert.false(+ requestedTypes.split(",").includes("chat_mention"),+ "Other does not absorb the plugin-owned notification type"+ );+ assert.true(+ requestedTypes.split(",").includes("edited"),+ "Other still includes its own notification type"+ );+ });++ test("disabling Likes preserves its existing classification into Other", async function (assert) {+ this.currentUser.set("user_option.likes_notifications_disabled", true);+ this.currentUser.set("available_notification_types", [+ NOTIFICATION_TYPES.liked,+ ]);+ await render(<template><Menu /></template>);++ assert+ .dom("#user-menu-button-likes")+ .doesNotExist("the user preference still hides Likes");+ assert+ .dom("#user-menu-button-other-notifications")+ .exists("Other retains the disabled tab's notification types");+ });++ test("missing availability data preserves tabs for older servers", async function (assert) {+ this.currentUser.set("available_notification_types", null);+ await render(<template><Menu /></template>);++ for (const id of ["replies", "mentions", "likes", "other-notifications"]) {+ assert+ .dom(`#user-menu-button-${id}`)+ .exists("tabs remain usable without availability data");+ }+ });+test("mentions tab is hidden when the upcoming change is disabled", async function (assert) {this.siteSettings.enable_user_menu_mentions_tab = false;this.currentUser.set("grouped_unread_notifications", {diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rbindex 2f656a8ec60..078fe80ad85 100644--- a/spec/models/user_spec.rb+++ b/spec/models/user_spec.rb@@ -3,6 +3,53 @@RSpec.describe User dosubject(:user) { Fabricate(:user, last_seen_at: 1.day.ago) }+ describe "#available_notification_types" do+ fab!(:user)++ it "returns distinct types for this user's read and unread notifications" do+ expect(user.available_notification_types).to eq([])+ like =+ Fabricate(+ :notification,+ user: user,+ notification_type: Notification.types[:liked],+ read: true,+ )+ Fabricate(:notification, user: user, notification_type: Notification.types[:mentioned])+ Fabricate(:notification, user: user, notification_type: Notification.types[:mentioned])+ Fabricate(:notification, notification_type: Notification.types[:replied])++ expect(user.available_notification_types).to contain_exactly(+ Notification.types[:liked],+ Notification.types[:mentioned],+ )++ like.destroy!+ expect(user.available_notification_types).to eq([Notification.types[:mentioned]])+ end++ it "excludes notifications for deleted topics" do+ notification = Fabricate(:notification, user: user)+ notification.topic.update!(deleted_at: Time.current)++ expect(user.available_notification_types).to eq([])+ end++ it "publishes current availability after creating and deleting notifications" do+ user.update!(last_seen_at: 1.minute.ago)+ notification = nil+ messages =+ MessageBus.track_publish("/notification/#{user.id}") do+ notification =+ Fabricate(:notification, user: user, notification_type: Notification.types[:liked])+ end+ expect(messages.last.data[:available_notification_types]).to eq([Notification.types[:liked]])++ messages = MessageBus.track_publish("/notification/#{user.id}") { notification.destroy! }+ expect(messages.last.data[:available_notification_types]).to eq([])+ end+ end+it_behaves_like "it has custom fields"describe "#reload" dodiff --git a/spec/serializers/current_user_serializer_spec.rb b/spec/serializers/current_user_serializer_spec.rbindex 1bc1337136a..81b7bfcee5b 100644--- a/spec/serializers/current_user_serializer_spec.rb+++ b/spec/serializers/current_user_serializer_spec.rb@@ -6,6 +6,20 @@ RSpec.describe CurrentUserSerializer dolet(:guardian) { user.guardian }+ it "includes notification types with remaining read or unread notifications" do+ expect(serializer.as_json[:available_notification_types]).to eq([])+ notification =+ Fabricate(+ :notification,+ user: user,+ notification_type: Notification.types[:liked],+ read: true,+ )+ expect(serializer.as_json[:available_notification_types]).to eq([Notification.types[:liked]])+ notification.destroy!+ expect(serializer.as_json[:available_notification_types]).to eq([])+ end+context "when SSO is not enabled" doit "does not include external_id" dopayload = serializer.as_jsondiff --git a/spec/system/header_spec.rb b/spec/system/header_spec.rbindex d6851f56d3c..a47a94e4217 100644--- a/spec/system/header_spec.rb+++ b/spec/system/header_spec.rb@@ -3,6 +3,7 @@RSpec.describe "Glimmer Header" dolet(:header) { PageObjects::Pages::Header.new }let(:search) { PageObjects::Pages::Search.new }+ let(:user_menu) { PageObjects::Components::UserMenu.new }fab!(:current_user, :user)fab!(:topic)@@ -116,6 +117,9 @@ RSpec.describe "Glimmer Header" doendit "moves focus between tabs using arrow keys" do+ %i[replied mentioned liked edited].each do |type|+ Fabricate(:notification, user: current_user, notification_type: Notification.types[type])+ endSiteSetting.enable_user_menu_mentions_tab = truesign_in(current_user)@@ -139,6 +143,30 @@ RSpec.describe "Glimmer Header" doexpect(header.active_element_id).to eq("user-menu-button-profile")end+ [[], [Notification.types[:liked]]].each do |types|+ it "navigates the reduced menu with #{types.length} available notification types" do+ types.each { |type| Fabricate(:notification, user: current_user, notification_type: type) }+ sign_in(current_user)+ visit "/"+ user_menu.open++ expect(user_menu).to have_focused_tab("all-notifications")+ visible_tabs = types.empty? ? %w[bookmarks profile] : %w[likes bookmarks profile]+ visible_tabs.each do |tab|+ user_menu.press_key(:down)+ expect(user_menu).to have_focused_tab(tab)+ end+ user_menu.press_key(:down)+ expect(user_menu).to have_focused_tab("all-notifications")+ user_menu.press_key(:up)+ expect(user_menu).to have_focused_tab("profile")+ user_menu.press_key(:up)+ expect(user_menu).to have_focused_tab("bookmarks")+ user_menu.press_key(:enter)+ expect(user_menu).to have_selected_tab("bookmarks")+ end+ end+it "prioritizes new personal messages bubble over unseen reviewables and regular notifications bubbles" doFabricate(:private_message_notification, user: current_user)Fabricate(diff --git a/spec/system/page_objects/components/user_menu.rb b/spec/system/page_objects/components/user_menu.rbindex aa435522a5b..d6480777a65 100644--- a/spec/system/page_objects/components/user_menu.rb+++ b/spec/system/page_objects/components/user_menu.rb@@ -9,6 +9,19 @@ module PageObjectsselfend+ def press_key(key)+ find(".user-menu-tab:focus").send_keys(key)+ self+ end++ def has_focused_tab?(id)+ page.has_css?("#user-menu-button-#{id}:focus")+ end++ def has_selected_tab?(id)+ page.has_css?("#user-menu-button-#{id}[aria-selected='true']")+ end+def click_replies_notifications_tabclick_link("user-menu-button-replies")has_css?("#quick-access-replies")@@ -101,6 +114,14 @@ module PageObjectsexpect(find("#user-menu-button-replies").text).to eq(count.to_s)end+ def has_notification_tab?(id)+ page.has_css?("#user-menu-button-#{id}")+ end++ def has_no_notification_tab?(id)+ page.has_no_css?("#user-menu-button-#{id}")+ end+def has_no_direct_mentions?page.has_no_css?(".user-menu .notification.mentioned")enddiff --git a/spec/system/viewing_user_menu_spec.rb b/spec/system/viewing_user_menu_spec.rbindex 1e8e4ab5f77..1e8cf2ae2e7 100644--- a/spec/system/viewing_user_menu_spec.rb+++ b/spec/system/viewing_user_menu_spec.rb@@ -5,6 +5,41 @@ RSpec.describe "Viewing User Menu" dolet(:user_menu) { PageObjects::Components::UserMenu.new }+ it "shows filters for read notifications and hides them after their last notification is deleted" do+ sign_in(user)+ visit("/latest")+ user_menu.open++ expect(user_menu).to have_notification_tab("all-notifications")+ expect(user_menu).to have_notification_tab("bookmarks")+ expect(user_menu).to have_notification_tab("profile")+ expect(user_menu).to have_no_notification_tab("likes")+ expect(user_menu).to have_no_notification_tab("replies")+ expect(user_menu).to have_no_notification_tab("other-notifications")++ notification =+ Fabricate(+ :notification,+ user: user,+ notification_type: Notification.types[:liked],+ post: Fabricate(:post),+ )+ visit("/latest")+ user_menu.open+ expect(user_menu).to have_notification_tab("likes")++ notification.update!(read: true)+ visit("/latest")+ user_menu.open+ expect(user_menu).to have_notification_tab("likes")+ expect(user_menu).to have_no_notification_tab("replies")++ notification.destroy!+ visit("/latest")+ user_menu.open+ expect(user_menu).to have_no_notification_tab("likes")+ end+it "keeps the mentions tab hidden when the upcoming change is disabled" doSiteSetting.enable_user_menu_mentions_tab = false