A platform for community discussion. Free, open, simple.
UX: Add New tab and shortcut UX for filter route (#43341)
Martin Brennan224e31bc7570
diff --git a/app/assets/stylesheets/common/components/topic-query-filter.scss b/app/assets/stylesheets/common/components/topic-query-filter.scssindex c1ca179cade..cde715bdd71 100644--- a/app/assets/stylesheets/common/components/topic-query-filter.scss+++ b/app/assets/stylesheets/common/components/topic-query-filter.scss@@ -127,3 +127,12 @@}}}++.filter-new-navigation {+ flex-basis: 100%;+ min-width: 0;++ &__tabs {+ margin-bottom: 0;+ }+}diff --git a/app/controllers/list_controller.rb b/app/controllers/list_controller.rbindex b4216f9140d..88297f4a897 100644--- a/app/controllers/list_controller.rb+++ b/app/controllers/list_controller.rb@@ -132,7 +132,7 @@ class ListController < ApplicationControllerdef filtertopic_query_opts = { no_definitions: !SiteSetting.show_category_definitions_in_topic_lists }- %i[page q].each do |key|+ %i[page q subset].each do |key|if params.key?(key.to_s)value = params[key]raise Discourse::InvalidParameters.new(key) if !TopicQuery.validate?(key, value)diff --git a/app/models/topic_list.rb b/app/models/topic_list.rbindex f6222be384d..8f5beaa95cd 100644--- a/app/models/topic_list.rb+++ b/app/models/topic_list.rb@@ -47,6 +47,7 @@ class TopicList:category,:publish_read_state,:filter_option_info,+ :filter_new_topic_ids,)def initialize(filter, current_user, topics, opts = nil)diff --git a/app/serializers/topic_list_serializer.rb b/app/serializers/topic_list_serializer.rbindex 2e6c17541de..9ff88d21bd6 100644--- a/app/serializers/topic_list_serializer.rb+++ b/app/serializers/topic_list_serializer.rb@@ -9,7 +9,8 @@ class TopicListSerializer < ApplicationSerializer:top_tags,:tags,:shared_drafts,- :filter_option_info+ :filter_option_info,+ :filter_new_topic_idshas_many :topics, serializer: TopicListItemSerializer, embed: :objectshas_many :shared_drafts, serializer: TopicListItemSerializer, embed: :objects@@ -29,6 +30,10 @@ class TopicListSerializer < ApplicationSerializerobject.shared_drafts.present?end+ def include_filter_new_topic_ids?+ !object.filter_new_topic_ids.nil?+ end+def include_filter_option_info?object.filter_option_info.present?enddiff --git a/frontend/discourse/app/components/discovery/filter-navigation.gjs b/frontend/discourse/app/components/discovery/filter-navigation.gjsindex 2ce44a87280..e5c6df9bfff 100644--- a/frontend/discourse/app/components/discovery/filter-navigation.gjs+++ b/frontend/discourse/app/components/discovery/filter-navigation.gjs@@ -4,6 +4,7 @@ import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import BulkSelectToggle from "discourse/components/bulk-select-toggle";import FilterNavigationMenu from "discourse/components/discovery/filter-navigation-menu";+import FilterNewNavigation from "discourse/components/discovery/filter-new-navigation";import PluginOutlet from "discourse/components/plugin-outlet";import bodyClass from "discourse/helpers/body-class";import { bind } from "discourse/lib/decorators";@@ -13,6 +14,7 @@ import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";export default class DiscoveryFilterNavigation extends Component {+ @service currentUser;@service site;@resettableTracked filterQueryString = this.args.queryString;@@ -75,6 +77,9 @@ export default class DiscoveryFilterNavigation extends Component {<PluginOutlet @name="after-filter-navigation-menu" /></div>+ {{#if this.currentUser.unified_new_enabled}}+ <FilterNewNavigation @query={{@queryString}} @subset={{@subset}} />+ {{/if}}</section></template>}diff --git a/frontend/discourse/app/components/discovery/filter-new-navigation.gjs b/frontend/discourse/app/components/discovery/filter-new-navigation.gjsnew file mode 100644index 00000000000..c104e33f323--- /dev/null+++ b/frontend/discourse/app/components/discovery/filter-new-navigation.gjs@@ -0,0 +1,72 @@+import Component from "@glimmer/component";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import NewListHeaderControls from "discourse/components/topic-list/new-list-header-controls";+import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";+import { i18n } from "discourse-i18n";++export default class FilterNewNavigation extends Component {+ @service filterTopicTracking;+ @service router;++ get counts() {+ if (this.args.query === this.filterTopicTracking.query) {+ return this.filterTopicTracking;+ }+ }++ get newLabel() {+ const count = this.counts?.newTopicsCount + this.counts?.newRepliesCount;+ return count > 0+ ? i18n("filters.new.title_with_count", { count })+ : i18n("filters.new.title");+ }++ get selection() {+ return { new: "all", "new-topics": "topics", "new-replies": "replies" }[+ this.args.subset+ ];+ }++ @action+ changeSubset(subset) {+ this.router.transitionTo("discovery.filter", {+ queryParams: { subset: subset ? `new-${subset}` : "new" },+ });+ }++ <template>+ <div class="filter-new-navigation" ...attributes>+ <DHorizontalOverflowNav @className="filter-new-navigation__tabs">+ <li>+ <LinkTo+ data-filter-view="all"+ @current-when={{if this.selection false true}}+ @query={{hash subset=null}}+ @route="discovery.filter"+ >{{i18n "filters.new.all"}}</LinkTo>+ </li>+ <li>+ <LinkTo+ data-filter-view="new"+ @current-when={{if this.selection true false}}+ @query={{hash subset="new"}}+ @route="discovery.filter"+ >{{this.newLabel}}</LinkTo>+ </li>+ </DHorizontalOverflowNav>+ {{#if this.selection}}+ <div class="topic-replies-toggle-wrapper">+ <NewListHeaderControls+ @changeNewListSubset={{this.changeSubset}}+ @current={{this.selection}}+ @newRepliesCount={{this.counts.newRepliesCount}}+ @newTopicsCount={{this.counts.newTopicsCount}}+ />+ </div>+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/app/components/topic-list/new-list-header-controls.gjs b/frontend/discourse/app/components/topic-list/new-list-header-controls.gjsindex 572e13d7051..1ee6b6d234a 100644--- a/frontend/discourse/app/components/topic-list/new-list-header-controls.gjs+++ b/frontend/discourse/app/components/topic-list/new-list-header-controls.gjs@@ -39,6 +39,7 @@ export default class NewListHeaderControls extends Component {<template><button+ aria-pressed={{if this.allActive "true" "false"}}class={{dConcatClass"topics-replies-toggle --all"(if this.allActive "active")@@ -50,6 +51,7 @@ export default class NewListHeaderControls extends Component {</button><button+ aria-pressed={{if this.topicsActive "true" "false"}}class={{dConcatClass"topics-replies-toggle --topics"(if this.topicsActive "active")@@ -61,6 +63,7 @@ export default class NewListHeaderControls extends Component {</button><button+ aria-pressed={{if this.repliesActive "true" "false"}}class={{dConcatClass"topics-replies-toggle --replies"(if this.repliesActive "active")diff --git a/frontend/discourse/app/controllers/discovery/filter.js b/frontend/discourse/app/controllers/discovery/filter.jsindex f4d8a1e588d..eb542e55d15 100644--- a/frontend/discourse/app/controllers/discovery/filter.js+++ b/frontend/discourse/app/controllers/discovery/filter.js@@ -6,8 +6,9 @@ import BulkSelectHelper from "discourse/lib/bulk-select-helper";export default class extends Controller {@tracked q = "";@tracked query_label = "";+ @tracked subset = null;- queryParams = ["q", "query_label"];+ queryParams = ["q", "subset", "query_label"];bulkSelectHelper = new BulkSelectHelper(this);get canBulkSelect() {diff --git a/frontend/discourse/app/routes/discovery/filter.js b/frontend/discourse/app/routes/discovery/filter.jsindex 572a037345f..ac93ac52524 100644--- a/frontend/discourse/app/routes/discovery/filter.js+++ b/frontend/discourse/app/routes/discovery/filter.js@@ -1,24 +1,43 @@+import { service } from "@ember/service";import { setTopicList } from "discourse/lib/topic-list-tracker";import { escapeExpression } from "discourse/lib/utilities";import DiscourseRoute from "discourse/routes/discourse";import { i18n } from "discourse-i18n";export default class DiscoveryFilterRoute extends DiscourseRoute {+ @service filterTopicTracking;+ @service topicTrackingState;+queryParams = {q: { refreshModel: true },+ subset: { refreshModel: true },};async model(data) {const list = await this.store.findFiltered("topicList", {filter: "filter",- params: { q: data.q },+ params: { q: data.q, subset: data.subset },});+ this.topicTrackingState.sync(list, "filter", { q: data.q });setTopicList(list);return list;}+ setupController(controller, model) {+ super.setupController(controller, model);+ this.filterTopicTracking.update(+ this.paramsFor(this.routeName).q,+ model.topic_list.filter_new_topic_ids+ );+ }++ deactivate() {+ super.deactivate(...arguments);+ this.filterTopicTracking.stop();+ }+titleToken() {const { q, query_label } = this.paramsFor(this.routeName);const query = query_label?.trim() || q;diff --git a/frontend/discourse/app/services/filter-topic-tracking.js b/frontend/discourse/app/services/filter-topic-tracking.jsnew file mode 100644index 00000000000..58d58d73d7b--- /dev/null+++ b/frontend/discourse/app/services/filter-topic-tracking.js@@ -0,0 +1,37 @@+import { tracked } from "@glimmer/tracking";+import Service, { service } from "@ember/service";++export default class FilterTopicTracking extends Service {+ @service topicTrackingState;++ @tracked matches;+ @tracked query;++ get newRepliesCount() {+ this.topicTrackingState.get("messageCount");+ return this.matches+ ? this.topicTrackingState.countUnread({+ customFilterFn: (topic) => this.matches.has(topic.topic_id),+ })+ : undefined;+ }++ get newTopicsCount() {+ this.topicTrackingState.get("messageCount");+ return this.matches+ ? this.topicTrackingState.countNew({+ customFilterFn: (topic) => this.matches.has(topic.topic_id),+ })+ : undefined;+ }++ update(query, topicIds) {+ this.query = query;+ this.matches = topicIds ? new Set(topicIds) : undefined;+ }++ stop() {+ this.query = undefined;+ this.matches = undefined;+ }+}diff --git a/frontend/discourse/app/templates/discovery/filter.gjs b/frontend/discourse/app/templates/discovery/filter.gjsindex ff29871c40d..758fb50a75a 100644--- a/frontend/discourse/app/templates/discovery/filter.gjs+++ b/frontend/discourse/app/templates/discovery/filter.gjs@@ -10,6 +10,7 @@ export default <template>@canBulkSelect={{@controller.canBulkSelect}}@queryLabel={{@controller.query_label}}@queryString={{@controller.q}}+ @subset={{@controller.subset}}@tips={{@controller.model.topic_list.filter_option_info}}@updateTopicsListQueryParams={{@controller.updateTopicsListQueryParams}}/>diff --git a/frontend/discourse/tests/acceptance/filter-new-test.js b/frontend/discourse/tests/acceptance/filter-new-test.jsnew file mode 100644index 00000000000..64e4c623bb0--- /dev/null+++ b/frontend/discourse/tests/acceptance/filter-new-test.js@@ -0,0 +1,144 @@+import { click, currentURL, settled, visit } from "@ember/test-helpers";+import { test } from "qunit";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Filter unified New", function (needs) {+ needs.user({ unified_new_enabled: true });+ needs.pretender((server, helper) => {+ server.get("/filter.json", () =>+ helper.response({+ topic_list: {+ can_create_topic: true,+ topics: [],+ filter_option_info: [],+ filter_new_topic_ids: [90001, 90002],+ },+ })+ );+ });++ test("navigates All, New and subsets while preserving the filter", async function (assert) {+ await visit("/filter?q=category%3Abug%20status%3Aopen");+ const tracking = this.container.lookup("service:topic-tracking-state");+ tracking.states.clear();+ tracking.loadStates([+ {+ topic_id: 90001,+ category_id: 1,+ highest_post_number: 1,+ last_read_post_number: null,+ created_in_new_period: true,+ },+ {+ topic_id: 90002,+ category_id: 1,+ last_read_post_number: 1,+ highest_post_number: 2,+ notification_level: 2,+ },+ {+ topic_id: 90003,+ category_id: 1,+ highest_post_number: 1,+ last_read_post_number: null,+ created_in_new_period: true,+ },+ ]);+ await settled();+ assert+ .dom('[data-filter-view="all"]')+ .hasClass("active", "All is initially active");+ assert+ .dom('[data-filter-view="new"]')+ .hasText(+ "New (2)",+ "counts matching states beyond the empty loaded page"+ );+ assert+ .dom(".topics-replies-toggle")+ .doesNotExist("subsets are hidden in All");++ await click('[data-filter-view="new"]');+ assert.strictEqual(+ new URL(currentURL(), "https://example.com").searchParams.get("subset"),+ "new",+ "New uses its own parameter"+ );+ assert.strictEqual(+ new URL(currentURL(), "https://example.com").searchParams.get("q"),+ "category:bug status:open",+ "New preserves the base query"+ );+ assert+ .dom(".topics-replies-toggle.--all")+ .hasAttribute("aria-pressed", "true", "New All is selected");+ assert+ .dom(".topics-replies-toggle.--topics")+ .hasText("Topics (1)", "shows scoped new count");+ assert+ .dom(".topics-replies-toggle.--replies")+ .hasText("Replies (1)", "shows scoped unread count");++ await click(".topics-replies-toggle.--replies");+ assert.strictEqual(+ new URL(currentURL(), "https://example.com").searchParams.get("subset"),+ "new-replies",+ "Replies updates the subset"+ );+ assert.strictEqual(+ new URL(currentURL(), "https://example.com").searchParams.get("q"),+ "category:bug status:open",+ "Replies preserves the query"+ );+ assert+ .dom(".topics-replies-toggle.--replies")+ .hasClass("active", "Replies is selected even for an empty list");+ await click('[data-filter-view="all"]');+ assert.false(+ new URL(currentURL(), "https://example.com").searchParams.has("subset"),+ "All removes the subset"+ );+ assert.strictEqual(+ new URL(currentURL(), "https://example.com").searchParams.get("q"),+ "category:bug status:open",+ "All preserves the query"+ );+ });++ test("treats manually entered New conditions as query text", async function (assert) {+ await visit("/filter?q=in%3Anew-replies");+ assert+ .dom('[data-filter-view="all"]')+ .hasClass("active", "query text does not select a tab");+ await click('[data-filter-view="new"]');+ assert.strictEqual(+ new URL(currentURL(), "https://example.com").searchParams.get("q"),+ "in:new-replies",+ "tabs preserve manually entered conditions"+ );+ });++ test("recognizes a direct subset URL", async function (assert) {+ await visit("/filter?q=status%3Aopen&subset=new-topics");+ assert.dom('[data-filter-view="new"]').hasClass("active", "New is active");+ assert+ .dom(".topics-replies-toggle.--topics")+ .hasClass("active", "Topics is active");+ });+});++acceptance("Filter unified New disabled", function (needs) {+ needs.user({ unified_new_enabled: false });+ needs.pretender((server, helper) => {+ server.get("/filter.json", () =>+ helper.response({ topic_list: { topics: [] } })+ );+ });++ test("keeps the existing filter UI", async function (assert) {+ await visit("/filter?q=in%3Anew");+ assert+ .dom(".filter-new-navigation")+ .doesNotExist("navigation is gated by the user flag");+ });+});diff --git a/frontend/discourse/tests/unit/services/filter-topic-tracking-test.js b/frontend/discourse/tests/unit/services/filter-topic-tracking-test.jsnew file mode 100644index 00000000000..53e2b30a80a--- /dev/null+++ b/frontend/discourse/tests/unit/services/filter-topic-tracking-test.js@@ -0,0 +1,96 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { logIn } from "discourse/tests/helpers/qunit-helpers";++module("Unit | Service | filter-topic-tracking", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ logIn(this.owner);+ this.owner.lookup("service:current-user").set("unified_new_enabled", true);+ this.tracking = this.owner.lookup("service:topic-tracking-state");+ this.counts = this.owner.lookup("service:filter-topic-tracking");+ this.tracking.states.clear();+ this.tracking.loadStates([+ { topic_id: 1, last_read_post_number: null, created_in_new_period: true },+ {+ topic_id: 2,+ last_read_post_number: 1,+ highest_post_number: 3,+ notification_level: 2,+ },+ { topic_id: 3, last_read_post_number: null, created_in_new_period: true },+ ]);+ });++ test("counts response membership and reacts to reading", function (assert) {+ this.counts.update("status:open", [1, 2]);+ assert.strictEqual(+ this.counts.query,+ "status:open",+ "stores the submitted query"+ );+ assert.strictEqual(+ this.counts.newTopicsCount,+ 1,+ "counts matching new topics"+ );+ assert.strictEqual(+ this.counts.newRepliesCount,+ 1,+ "counts matching unread topics"+ );+ this.tracking.modifyStateProp(2, "last_read_post_number", 3);+ assert.strictEqual(+ this.counts.newRepliesCount,+ 0,+ "reading updates the count"+ );+ });++ test("replaces membership on the next list load", function (assert) {+ this.counts.update("status:open", [1, 2]);+ this.tracking.loadStates([+ { topic_id: 4, last_read_post_number: null, created_in_new_period: true },+ ]);+ assert.strictEqual(+ this.counts.newTopicsCount,+ 1,+ "new arrivals await a list load"+ );+ this.counts.update("status:closed", [3, 4]);+ assert.strictEqual(+ this.counts.newTopicsCount,+ 2,+ "uses the new response membership"+ );+ assert.strictEqual(+ this.counts.newRepliesCount,+ 0,+ "drops previous membership"+ );+ });++ test("distinguishes empty membership from omitted counts and clears on exit", function (assert) {+ this.counts.update("", []);+ assert.strictEqual(+ this.counts.newTopicsCount,+ 0,+ "empty membership is zero"+ );+ this.counts.update("");+ assert.strictEqual(+ this.counts.newTopicsCount,+ undefined,+ "omitted membership hides counts"+ );+ this.counts.update("", [1]);+ this.counts.stop();+ assert.strictEqual(+ this.counts.newTopicsCount,+ undefined,+ "exit clears counts"+ );+ assert.strictEqual(this.counts.query, undefined, "exit clears the query");+ });+});diff --git a/lib/topic_query.rb b/lib/topic_query.rbindex 2c952c145a3..6d5e82f4a8f 100644--- a/lib/topic_query.rb+++ b/lib/topic_query.rb@@ -307,30 +307,36 @@ class TopicQueryenddef list_filter- topics_filter =- TopicsFilter.new(- guardian: @guardian,- scope: latest_results(include_muted: false, skip_ordering: true),- loaded_topic_users_reference: @guardian.authenticated?,- )-- results = topics_filter.filter_from_query_string(@options[:q])+ query = @options[:q]+ if @user&.unified_new_enabled? && %w[new new-topics new-replies].include?(@options[:subset])+ query = "#{query} in:#{@options[:subset]}"+ end+ results, topics_filter = filter_results(query)@invalid_filters = topics_filter.invalid_filters+ results = apply_ordering(results) if results.order_values.empty?- if !topics_filter.topic_notification_levels.include?(NotificationLevels.all[:muted])- results = remove_muted_topics(results, @user)- end+ list =+ create_list(+ :filter,+ {+ include_filter_option_info: @options[:include_filter_option_info].to_s != "false",+ unordered: topics_filter.topic_ids.present?,+ },+ results,+ )- results = apply_ordering(results) if results.order_values.empty?+ if @user&.unified_new_enabled?+ candidate_ids = TopicTrackingState.report(@user).map(&:topic_id)+ list.filter_new_topic_ids =+ if candidate_ids.empty?+ []+ else+ matches, = filter_results+ matches.where(id: candidate_ids).except(:limit, :offset, :order).distinct.pluck(:id)+ end+ end- create_list(- :filter,- {- include_filter_option_info: @options[:include_filter_option_info].to_s != "false",- unordered: topics_filter.topic_ids.present?,- },- results,- )+ listenddef list_read@@ -1331,6 +1337,23 @@ class TopicQueryprivate+ def filter_results(query = @options[:q])+ topics_filter =+ TopicsFilter.new(+ guardian: @guardian,+ scope: latest_results(include_muted: false, skip_ordering: true),+ loaded_topic_users_reference: @guardian.authenticated?,+ )++ results = topics_filter.filter_from_query_string(query)++ if !topics_filter.topic_notification_levels.include?(NotificationLevels.all[:muted])+ results = remove_muted_topics(results, @user)+ end++ [results, topics_filter]+ end+def apply_max_age_limit(results, options)if @user# micro optimisation so we don't load up all of user stats which we do not needdiff --git a/spec/requests/list_controller_spec.rb b/spec/requests/list_controller_spec.rbindex 098b68b6721..cf3f4b22134 100644--- a/spec/requests/list_controller_spec.rb+++ b/spec/requests/list_controller_spec.rb@@ -11,6 +11,138 @@ RSpec.describe ListController doSiteSetting.top_menu = "latest|new|categories"end+ describe "#filter unified New membership" do+ before { SiteSetting.enable_unified_new = true }++ it "omits membership for anonymous and disabled users" do+ get "/filter.json", params: { q: "" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["topic_list"]).not_to have_key("filter_new_topic_ids")++ sign_in(user)+ SiteSetting.enable_unified_new = false+ get "/filter.json", params: { q: "" }+ expect(response.parsed_body["topic_list"]).not_to have_key("filter_new_topic_ids")+ end++ it "includes both subsets across pages while applying the full filter" do+ sign_in(user)+ category = Fabricate(:category)+ matches = Fabricate.times(31, :topic, category: category)+ unread = Fabricate(:topic, category: category, highest_post_number: 2)+ Fabricate(+ :topic_user,+ user: user,+ topic: unread,+ last_read_post_number: 1,+ notification_level: 2,+ )+ Fabricate(:topic, category: category, closed: true)+ Fabricate(:topic)++ %w[new new-topics new-replies].each do |subset|+ get "/filter.json", params: { q: "category:#{category.slug} status:open", subset: subset }++ expect(response.status).to eq(200)+ expect(response.parsed_body["topic_list"]["filter_new_topic_ids"]).to contain_exactly(+ *matches.map(&:id),+ unread.id,+ )+ end+ expect(response.parsed_body["topic_list"]["topics"].map { |entry| entry["id"] }).to eq(+ [unread.id],+ )+ end++ it "preserves the original query and subset in pagination links" do+ sign_in(user)+ category = Fabricate(:category)+ Fabricate.times(31, :topic, category: category)+ query = "category:#{category.slug}"++ get "/filter.json", params: { q: query, subset: "new-topics" }++ params =+ Rack::Utils.parse_query(+ URI.parse(response.parsed_body["topic_list"]["more_topics_url"]).query,+ )+ expect(params).to include("q" => query, "subset" => "new-topics", "page" => "1")+ end++ it "keeps manually entered New conditions in the membership query" do+ sign_in(user)+ unread = Fabricate(:topic, highest_post_number: 2)+ Fabricate(+ :topic_user,+ user: user,+ topic: unread,+ last_read_post_number: 1,+ notification_level: 2,+ )+ Fabricate(:topic)++ get "/filter.json", params: { q: "in:new-replies", subset: "new-topics" }++ expect(response.parsed_body["topic_list"]["topics"]).to be_empty+ expect(response.parsed_body["topic_list"]["filter_new_topic_ids"]).to eq([unread.id])+ end++ it "ignores unknown subsets and disables subset filtering with unified New" do+ sign_in(user)+ %w[unsupported new-replies].each do |subset|+ SiteSetting.enable_unified_new = subset == "unsupported"+ get "/filter.json", params: { q: "topic:#{topic.id}", subset: subset }+ expect(response.parsed_body["topic_list"]["topics"].map { |entry| entry["id"] }).to eq(+ [topic.id],+ )+ end+ end++ it "applies permissions, muting and custom plugin filters" do+ sign_in(user)+ allowed = Fabricate(:topic)+ private_topic = Fabricate(:topic, category: Fabricate(:private_category, group: group))+ muted = Fabricate(:topic)+ TopicUser.change(user.id, muted.id, notification_level: TopicUser.notification_levels[:muted])+ deleted = Fabricate(:topic, deleted_at: Time.zone.now)+ unlisted = Fabricate(:topic, visible: false)+ Plugin::Instance+ .new+ .add_filter_custom_filter("selected") do |scope, values, _guardian|+ scope.where(id: values.map(&:to_i))+ end+ ids = [allowed.id, private_topic.id, muted.id, deleted.id, unlisted.id]++ get "/filter.json", params: { q: "selected:#{ids.join(",")}" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["topic_list"]["filter_new_topic_ids"]).to eq([allowed.id])+ ensure+ DiscoursePluginRegistry.reset_register!(:custom_filter_mappings)+ end++ it "respects the user's upcoming change group membership" do+ Fabricate(:site_setting_group, name: :enable_unified_new, group_ids: group.id.to_s)+ sign_in(user)++ get "/filter.json", params: { q: "" }+ expect(response.parsed_body["topic_list"]).not_to have_key("filter_new_topic_ids")++ group.add(user)+ get "/filter.json", params: { q: "" }+ expect(response.parsed_body["topic_list"]).to have_key("filter_new_topic_ids")+ end++ it "returns an empty array when no tracked topics match" do+ sign_in(user)++ get "/filter.json", params: { q: "topic:0 in:new-replies" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["topic_list"]["filter_new_topic_ids"]).to eq([])+ end+ end+describe "#index" doit "does not expose the Klipy API key in anonymous preloaded site settings" doSiteSetting.klipy_api_key = "super-secret-klipy-key"diff --git a/spec/system/filter_new_topics_spec.rb b/spec/system/filter_new_topics_spec.rbnew file mode 100644index 00000000000..98a8303b340--- /dev/null+++ b/spec/system/filter_new_topics_spec.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++RSpec.describe "Filter new topics" do+ include ThemeScreenshotMarker++ fab!(:user)+ fab!(:category) { Fabricate(:category, name: "Announcements") }+ fab!(:new_topic) do+ Fabricate(:topic, category: category, title: "What is coming next for our community")+ end+ fab!(:unread_topic) do+ Fabricate(:topic, category: category, title: "Share your feedback on the latest release")+ end+ fab!(:closed_topic) { Fabricate(:topic, category: category, closed: true) }+ let(:navigation) { PageObjects::Components::FilterNewNavigation.new }+ let(:topic_list) { PageObjects::Components::TopicList.new }+ let(:query_filter) { PageObjects::Components::TopicQueryFilter.new }++ before do+ Fabricate(:post, topic: new_topic)+ Fabricate(:post, topic: unread_topic)+ Fabricate(:post, topic: unread_topic)+ Fabricate(:post, topic: closed_topic)+ TopicUser.change(+ user.id,+ unread_topic.id,+ last_read_post_number: 1,+ notification_level: TopicUser.notification_levels[:tracking],+ )+ user.user_option.update!(new_topic_duration_minutes: User::NewTopicDuration::ALWAYS)+ sign_in(user)+ end++ it "lets the user switch between all matches, new topics, and unread replies" do+ query = "category:#{category.slug} status:open"+ SiteSetting.enable_unified_new = false+ visit("/filter?q=#{CGI.escape(query)}")+ expect(navigation).to have_no_navigation+ expect(topic_list).to have_topic(new_topic)+ screenshot_marker(label: "filter-unified-new-before")++ SiteSetting.enable_unified_new = true+ page.refresh+ navigation.select_view("new")+ expect(navigation).to have_counts(topics: 1, replies: 1)+ expect(topic_list).to have_topic(new_topic)+ expect(topic_list).to have_topic(unread_topic)+ expect(topic_list).to have_no_topic(closed_topic)+ screenshot_marker(label: "filter-unified-new-after")++ navigation.select_subset("topics")+ expect(query_filter).to have_input_text(query)+ expect(topic_list).to have_topic(new_topic)+ expect(topic_list).to have_no_topic(unread_topic)++ navigation.select_subset("replies")+ expect(query_filter).to have_input_text(query)+ expect(topic_list).to have_topic(unread_topic)+ expect(topic_list).to have_no_topic(new_topic)++ page.go_back+ expect(query_filter).to have_input_text(query)+ expect(topic_list).to have_topic(new_topic)+ expect(topic_list).to have_no_topic(unread_topic)++ page.go_forward+ expect(query_filter).to have_input_text(query)+ page.refresh+ expect(query_filter).to have_input_text(query)+ expect(topic_list).to have_topic(unread_topic)+ expect(topic_list).to have_no_topic(new_topic)++ navigation.select_view("all")+ expect(query_filter).to have_input_text(query)+ expect(topic_list).to have_topic(new_topic)+ expect(topic_list).to have_topic(unread_topic)+ end+enddiff --git a/spec/system/page_objects/components/filter_new_navigation.rb b/spec/system/page_objects/components/filter_new_navigation.rbnew file mode 100644index 00000000000..77944af8245--- /dev/null+++ b/spec/system/page_objects/components/filter_new_navigation.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class FilterNewNavigation < PageObjects::Components::Base+ def select_view(view)+ find("[data-filter-view='#{view}']").click+ end++ def select_subset(subset)+ find(".filter-new-navigation .topics-replies-toggle.--#{subset}").click+ end++ def has_counts?(topics:, replies:)+ has_css?(+ "[data-filter-view='new']",+ text: I18n.t("js.filters.new.title_with_count", count: topics + replies),+ ) &&+ has_css?(+ ".filter-new-navigation .--topics",+ text: I18n.t("js.filters.new.topics_with_count", count: topics),+ ) &&+ has_css?(+ ".filter-new-navigation .--replies",+ text: I18n.t("js.filters.new.replies_with_count", count: replies),+ )+ end++ def has_no_navigation?+ has_no_css?(".filter-new-navigation")+ end+ end+ end+end