Skip to content

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

FEATURE: Admin filter controls now support URL state (#41609)

Gabriel Grubba0f8d25c03cc0
diff --git a/frontend/discourse/admin/components/admin-badges-list.gjs b/frontend/discourse/admin/components/admin-badges-list.gjs
index 8bcd8e2a368..4081c34aa7e 100644
--- a/frontend/discourse/admin/components/admin-badges-list.gjs
+++ b/frontend/discourse/admin/components/admin-badges-list.gjs
@@ -27,6 +27,7 @@ export default class AdminBadgesList extends Component {
<AdminFilterControls
@array={{@badges}}
@searchableProps={{this.searchableProps}}
+ @textFilterQueryParam="filter"
@inputPlaceholder={{i18n "admin.badges.filter_placeholder"}}
@noResultsMessage={{i18n "admin.badges.no_badges_found"}}
>
diff --git a/frontend/discourse/admin/components/admin-config-areas/components.gjs b/frontend/discourse/admin/components/admin-config-areas/components.gjs
index bc08828f66e..6ffef5f727e 100644
--- a/frontend/discourse/admin/components/admin-config-areas/components.gjs
+++ b/frontend/discourse/admin/components/admin-config-areas/components.gjs
@@ -19,6 +19,7 @@ import discourseDebounce from "discourse/lib/debounce";
import { INPUT_DELAY } from "discourse/lib/environment";
import getURL from "discourse/lib/get-url";
import { descriptionForRemoteUrl } from "discourse/lib/popular-themes";
+import { searchParamsFromPath } from "discourse/lib/url";
import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
@@ -72,6 +73,26 @@ export default class AdminConfigAreasComponents extends Component {
constructor() {
super(...arguments);
+
+ const params = searchParamsFromPath(this.router.currentURL);
+ const name = params.get("filter");
+ const status = params.get("status");
+ if (name) {
+ this.nameFilter = name;
+ }
+ if (
+ status &&
+ status !== "all" &&
+ STATUS_FILTER_OPTIONS.some((option) => option.value === status)
+ ) {
+ this.statusFilter = status;
+ }
+ if (this.nameFilter || this.statusFilter) {
+ // a filtered first response can't tell us whether the site has any
+ // components at all, and the filter UI must render to be resettable
+ this.hasComponents = true;
+ }
+
this.load();
}
@@ -143,15 +164,27 @@ export default class AdminConfigAreasComponents extends Component {
@action
async load({ append = false } = {}) {
+ const nameFilter = this.nameFilter;
+ const statusFilter = this.statusFilter;
+ const page = this.page;
+
try {
const data = await ajax("/admin/config/customize/components", {
data: {
- name: this.nameFilter,
- status: this.statusFilter,
- page: this.page,
+ name: nameFilter,
+ status: statusFilter,
+ page,
},
});
+ if (
+ nameFilter !== this.nameFilter ||
+ statusFilter !== this.statusFilter ||
+ page !== this.page
+ ) {
+ return;
+ }
+
if (append) {
this.components = [...this.components, ...data.components];
} else {
@@ -159,11 +192,19 @@ export default class AdminConfigAreasComponents extends Component {
}
this.hasMore = data.has_more;
- if (!this.hasComponents && !this.nameFilter && !this.statusFilter) {
+ if (!append && !nameFilter && !statusFilter) {
+ // an unfiltered fresh load is authoritative — it also corrects the
+ // optimistic value from a filtered deep link after a filter reset
this.hasComponents = !!data.components.length;
}
} finally {
- this.loading = false;
+ if (
+ nameFilter === this.nameFilter &&
+ statusFilter === this.statusFilter &&
+ page === this.page
+ ) {
+ this.loading = false;
+ }
}
}
@@ -223,6 +264,10 @@ export default class AdminConfigAreasComponents extends Component {
<AdminFilterControls
@array={{this.components}}
@dropdownOptions={{STATUS_FILTER_OPTIONS}}
+ @initialTextFilter={{this.nameFilter}}
+ @dropdownValue={{this.statusFilter}}
+ @textFilterQueryParam="filter"
+ @dropdownFilterQueryParam="status"
@inputPlaceholder={{i18n
"admin.config_areas.themes_and_components.components.search_components"
}}
diff --git a/frontend/discourse/admin/components/admin-config-areas/upcoming-changes.gjs b/frontend/discourse/admin/components/admin-config-areas/upcoming-changes.gjs
index 743edf7e362..a13ee7de03c 100644
--- a/frontend/discourse/admin/components/admin-config-areas/upcoming-changes.gjs
+++ b/frontend/discourse/admin/components/admin-config-areas/upcoming-changes.gjs
@@ -1,6 +1,6 @@
import Component from "@glimmer/component";
import { cached } from "@glimmer/tracking";
-import { array } from "@ember/helper";
+import { array, hash } from "@ember/helper";
import { action } from "@ember/object";
import { trackedObject } from "@ember/reactive/collections";
import { service } from "@ember/service";
@@ -176,6 +176,13 @@ export default class AdminConfigAreasUpcomingChanges extends Component {
}}
@initialTextFilter={{@changeNamesFilter}}
@onResetFilters={{@onClearChangeNamesFilter}}
+ @textFilterQueryParam="changeNamesFilter"
+ @dropdownFilterQueryParams={{hash
+ status="status"
+ type="type"
+ impactRole="impactRole"
+ enabled="enabled"
+ }}
>
<:content as |upcomingChanges|>
<table class="d-table upcoming-changes-table">
diff --git a/frontend/discourse/admin/components/admin-filter-controls.gjs b/frontend/discourse/admin/components/admin-filter-controls.gjs
index ac9a7205195..83da87346e4 100644
--- a/frontend/discourse/admin/components/admin-filter-controls.gjs
+++ b/frontend/discourse/admin/components/admin-filter-controls.gjs
@@ -6,8 +6,14 @@ import { trackedObject } from "@ember/reactive/collections";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { schedule } from "@ember/runloop";
-import { isTesting } from "discourse/lib/environment";
+import { service } from "@ember/service";
+import discourseDebounce from "discourse/lib/debounce";
+import { INPUT_DELAY, isTesting } from "discourse/lib/environment";
import { resettableTracked } from "discourse/lib/tracked-tools";
+import DiscourseURL, {
+ applyQueryParams,
+ searchParamsFromPath,
+} from "discourse/lib/url";
import { and, not } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import DFilterInput from "discourse/ui-kit/d-filter-input";
@@ -42,24 +48,74 @@ import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
*/
export default class AdminFilterControls extends Component {
+ @service router;
+
@tracked dropdownFilter = "all";
@tracked
showFilterDropdowns = this.args.filterDropdownsExpanded ?? isTesting();
- @resettableTracked
- textFilter = this.args.initialTextFilter?.replace(/,\s*/g, ", ") || "";
+ @resettableTracked textFilter = this.initialTextFilterValue;
dropdownFilters = trackedObject();
constructor() {
super(...arguments);
- if (this.hasMultipleDropdowns) {
- Object.keys(this.dropdownOptions).forEach((key) => {
- this.dropdownFilters[key] = this.dropdownValueFor(key);
- });
+ this.applyDropdownValues();
+
+ if (this.hasUrlOwnedDropdowns) {
+ // keep URL-owned dropdowns in sync across real transitions (e.g. a
+ // same-route link with different params); our own replaceState writes
+ // don't fire this event, so user selections are never reverted
+ this.router.on("routeDidChange", this.applyDropdownsFromUrl);
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ if (this.hasUrlOwnedDropdowns) {
+ this.router.off("routeDidChange", this.applyDropdownsFromUrl);
}
}
+ get initialTextFilterValue() {
+ // reading router.currentURL makes this getter re-evaluate on transitions,
+ // so same-route links carrying the query param re-seed the input
+ const fromUrl =
+ this.args.textFilterQueryParam && this.showFilters
+ ? this.currentSearchParams.get(this.args.textFilterQueryParam)
+ : null;
+
+ if (fromUrl !== null) {
+ // verbatim: this value round-trips through our own URL writes while the
+ // user is typing, so any normalization here would rewrite the input
+ // mid-edit and jump the caret
+ return fromUrl;
+ }
+
+ return this.args.initialTextFilter?.replace(/,\s*/g, ", ") || "";
+ }
+
+ get currentSearchParams() {
+ // router.currentURL, unlike window.location, is also correct under the
+ // test environment's mock location
+ return searchParamsFromPath(this.router.currentURL);
+ }
+
+ get hasUrlOwnedDropdowns() {
+ return (
+ (this.args.dropdownFilterQueryParam ||
+ this.args.dropdownFilterQueryParams) &&
+ !("dropdownValue" in this.args)
+ );
+ }
+
+ #validatedUrlValue(params, paramName, options) {
+ const value = params.get(paramName);
+ return value !== null && options.some((option) => option.value === value)
+ ? value
+ : null;
+ }
+
get array() {
return Array.isArray(this.args.array) ? this.args.array : [];
}
@@ -72,19 +128,13 @@ export default class AdminFilterControls extends Component {
get hasMultipleDropdowns() {
return (
- this.dropdownOptions &&
!Array.isArray(this.dropdownOptions) &&
typeof this.dropdownOptions === "object"
);
}
get dropdownOptions() {
- if (!this.args.dropdownOptions) {
- return [];
- }
- return Array.isArray(this.args.dropdownOptions)
- ? this.args.dropdownOptions
- : this.args.dropdownOptions;
+ return this.args.dropdownOptions || [];
}
get showDropdownFilter() {
@@ -190,6 +240,39 @@ export default class AdminFilterControls extends Component {
return defaults[key] || "all";
}
+ @action
+ applyDropdownsFromUrl() {
+ if (!this.showFilters || !this.hasUrlOwnedDropdowns) {
+ return;
+ }
+
+ const params = this.currentSearchParams;
+
+ if (this.hasMultipleDropdowns) {
+ for (const [key, paramName] of Object.entries(
+ this.args.dropdownFilterQueryParams ?? {}
+ )) {
+ const defaultValue = this.defaultValue(key);
+ const value =
+ this.#validatedUrlValue(
+ params,
+ paramName,
+ this.dropdownOptions[key] ?? []
+ ) ?? defaultValue;
+
+ this.dropdownFilters[key] = value;
+ this.showFilterDropdowns ||= value !== defaultValue;
+ }
+ } else if (this.args.dropdownFilterQueryParam) {
+ this.dropdownFilter =
+ this.#validatedUrlValue(
+ params,
+ this.args.dropdownFilterQueryParam,
+ this.dropdownOptions
+ ) ?? this.defaultDropdownValue;
+ }
+ }
+
dropdownValueFor(key) {
const values =
typeof this.dropdownValue === "object" ? this.dropdownValue : {};
@@ -197,7 +280,7 @@ export default class AdminFilterControls extends Component {
}
@action
- setupComponent() {
+ applyDropdownValues() {
if (this.hasMultipleDropdowns) {
Object.keys(this.dropdownOptions).forEach((key) => {
this.dropdownFilters[key] = this.dropdownValueFor(key);
@@ -207,21 +290,61 @@ export default class AdminFilterControls extends Component {
}
}
+ syncTextFilterQueryParam() {
+ this.updateQueryParams({
+ [this.args.textFilterQueryParam]: this.textFilter,
+ });
+ }
+
+ updateQueryParams(updates) {
+ // no currentURL means the router isn't live (e.g. rendering tests)
+ if (!this.showFilters || !this.router.currentURL) {
+ return;
+ }
+
+ DiscourseURL.replaceState(
+ applyQueryParams(this.router.currentURL, updates)
+ );
+ }
+
@action
onTextFilterChange(event) {
this.textFilter = event.target?.value || "";
+ if (this.args.textFilterQueryParam) {
+ discourseDebounce(this, this.syncTextFilterQueryParam, INPUT_DELAY);
+ }
+
this.args.onTextFilterChange?.(event);
}
@action
onDropdownFilterChange(keyOrValue, value) {
- if (this.hasMultipleDropdowns) {
+ const multiple = this.hasMultipleDropdowns;
+ const selectedValue = multiple ? value : keyOrValue;
+ const paramName = multiple
+ ? this.args.dropdownFilterQueryParams?.[keyOrValue]
+ : this.args.dropdownFilterQueryParam;
+ const defaultValue = multiple
+ ? this.defaultValue(keyOrValue)
+ : this.defaultDropdownValue;
+
+ if (multiple) {
this.dropdownFilters[keyOrValue] = value;
+ } else {
+ this.dropdownFilter = keyOrValue;
+ }
+
+ if (paramName) {
+ this.updateQueryParams({
+ [paramName]: selectedValue === defaultValue ? null : selectedValue,
+ });
+ }
+
+ if (multiple) {
this.args.onDropdownFilterChange?.(keyOrValue, value);
this.args.onDropdownChange?.(keyOrValue, value);
} else {
- this.dropdownFilter = keyOrValue;
this.args.onDropdownFilterChange?.(keyOrValue);
this.args.onDropdownChange?.(keyOrValue);
}
@@ -242,6 +365,17 @@ export default class AdminFilterControls extends Component {
this.args.onDropdownChange?.(this.defaultDropdownValue);
}
+ const queryParams = [
+ this.args.textFilterQueryParam,
+ this.args.dropdownFilterQueryParam,
+ ...Object.values(this.args.dropdownFilterQueryParams ?? {}),
+ ].filter(Boolean);
+ if (queryParams.length) {
+ this.updateQueryParams(
+ Object.fromEntries(queryParams.map((name) => [name, null]))
+ );
+ }
+
if (this.args.onResetFilters) {
this.args.onResetFilters();
}
@@ -265,9 +399,12 @@ export default class AdminFilterControls extends Component {
"admin-filter-controls"
(if this.hasMultipleDropdowns "--multiple-dropdowns")
}}
- {{didInsert this.setupComponent}}
- {{didUpdate this.setupComponent @defaultDropdownValue}}
- {{didUpdate this.setupComponent @dropdownValue}}
+ {{didInsert this.applyDropdownsFromUrl}}
+ {{didUpdate
+ this.applyDropdownValues
+ @defaultDropdownValue
+ @dropdownValue
+ }}
>
<div class="admin-filter-controls__inputs">
<DFilterInput
diff --git a/frontend/discourse/admin/components/admin-reports.gjs b/frontend/discourse/admin/components/admin-reports.gjs
index a2a19a99c4b..296b064f456 100644
--- a/frontend/discourse/admin/components/admin-reports.gjs
+++ b/frontend/discourse/admin/components/admin-reports.gjs
@@ -87,10 +87,6 @@ export default class AdminReports extends Component {
return reports.filter((report) => !hiddenReports.includes(report.type));
}
- get requestedGroupKey() {
- return this.args.group || "all";
- }
-
@bind
groupReports(reports) {
if (!reports) {
@@ -174,20 +170,6 @@ export default class AdminReports extends Component {
];
}
- @bind
- selectedGroupKey(reports) {
- const options = this.groupDropdownOptions(reports);
-
- return options.some((option) => option.value === this.requestedGroupKey)
- ? this.requestedGroupKey
- : "all";
- }
-
- @bind
- updateGroupFilter(groupKey) {
- this.args.onGroupChange?.(groupKey);
- }
-
<template>
<DAsyncContent @asyncData={{this.loadReports}}>
<:content as |reports|>
@@ -195,10 +177,10 @@ export default class AdminReports extends Component {
@array={{this.filterReports reports}}
@searchableProps={{array "title" "description"}}
@dropdownOptions={{this.groupDropdownOptions reports}}
- @dropdownValue={{this.selectedGroupKey reports}}
+ @textFilterQueryParam="filter"
+ @dropdownFilterQueryParam="group"
@inputPlaceholder={{i18n "admin.filter_reports"}}
@noResultsMessage={{i18n "admin.filter_reports_no_results"}}
- @onDropdownChange={{this.updateGroupFilter}}
>
<:content as |filteredReports|>
{{#each (this.groupReports filteredReports) as |group|}}
diff --git a/frontend/discourse/admin/components/email-logs-list.gjs b/frontend/discourse/admin/components/email-logs-list.gjs
index 58a75248c7e..16aa3af4d82 100644
--- a/frontend/discourse/admin/components/email-logs-list.gjs
+++ b/frontend/discourse/admin/components/email-logs-list.gjs
@@ -4,18 +4,25 @@ import { fn, get } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
import EmailLog from "discourse/admin/models/email-log";
import HorizontalScrollSyncWrapper from "discourse/components/horizontal-scroll-sync-wrapper";
import { addUniqueValuesToArray } from "discourse/lib/array-tools";
import discourseDebounce from "discourse/lib/debounce";
import { INPUT_DELAY } from "discourse/lib/environment";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
+import DiscourseURL, {
+ applyQueryParams,
+ searchParamsFromPath,
+} from "discourse/lib/url";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
import DLoadMore from "discourse/ui-kit/d-load-more";
import DTextField from "discourse/ui-kit/d-text-field";
import { i18n } from "discourse-i18n";
export default class EmailLogsList extends Component {
+ @service router;
+
@tracked allLoaded = false;
@tracked loading = false;
@tracked filterValues = {};
@@ -49,9 +56,13 @@ export default class EmailLogsList extends Component {
if (!this.initialized) {
this.initialized = true;
+ // router.currentURL, unlike window.location, is also correct under the
+ // test environment's mock location
+ const params = searchParamsFromPath(this.router.currentURL);
+
const initialValues = {};
this.args.filters?.forEach((filter) => {
- initialValues[filter.property] = "";
+ initialValues[filter.property] = params.get(filter.name) || "";
});
this.filterValues = initialValues;
@@ -133,10 +144,31 @@ export default class EmailLogsList extends Component {
[filterConfig.property]: event.target.value,
};
this.loadMoreEnabled = false;
- discourseDebounce(this, this.loadLogs, INPUT_DELAY);
+ discourseDebounce(this, this.applyFilters, INPUT_DELAY);
}
}
+ applyFilters() {
+ this.syncFiltersToUrl();
+ this.loadLogs();
+ }
+
+ syncFiltersToUrl() {
+ // no currentURL means the router isn't live (e.g. rendering tests)
+ if (!this.router.currentURL) {
+ return;
+ }
+
+ const updates = {};
+ this.args.filters?.forEach(({ property, name }) => {
+ updates[name] = this.filterValues[property];
+ });
+
+ DiscourseURL.replaceState(
+ applyQueryParams(this.router.currentURL, updates)
+ );
+ }
+
@action
loadMore() {
this.loadLogs(true);
diff --git a/frontend/discourse/admin/controllers/admin-email-templates/index.js b/frontend/discourse/admin/controllers/admin-email-templates/index.js
index d999855592e..26df5a2a568 100644
--- a/frontend/discourse/admin/controllers/admin-email-templates/index.js
+++ b/frontend/discourse/admin/controllers/admin-email-templates/index.js
@@ -1,9 +1,13 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
import { action, computed } from "@ember/object";
+import { service } from "@ember/service";
import { arraySortedByProperties } from "discourse/lib/array-tools";
+import DiscourseURL, { applyQueryParams } from "discourse/lib/url";
export default class AdminEmailTemplatesIndexController extends Controller {
+ @service router;
+
@tracked showOverridenOnly = false;
titleSorting = ["title"];
@@ -27,5 +31,13 @@ export default class AdminEmailTemplatesIndexController extends Controller {
@action
toggleOverridenOnly() {
this.showOverridenOnly = !this.showOverridenOnly;
+
+ // `overridden` is deliberately not a registered query param, so sync the
+ // URL without a transition, preserving the search input's `filter` param
+ DiscourseURL.replaceState(
+ applyQueryParams(this.router.currentURL, {
+ overridden: this.showOverridenOnly && "true",
+ })
+ );
}
}
diff --git a/frontend/discourse/admin/controllers/admin-reports/index.js b/frontend/discourse/admin/controllers/admin-reports/index.js
deleted file mode 100644
index fbfcb0b80c3..00000000000
--- a/frontend/discourse/admin/controllers/admin-reports/index.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import Controller from "@ember/controller";
-import { action } from "@ember/object";
-
-export default class AdminReportsIndexController extends Controller {
- queryParams = ["group"];
- group = null;
-
- @action
- updateGroupFilter(groupKey) {
- this.set("group", groupKey === "all" ? null : groupKey);
- }
-}
diff --git a/frontend/discourse/admin/routes/admin-config/upcoming-changes.js b/frontend/discourse/admin/routes/admin-config/upcoming-changes.js
index e3e2055cf73..eba7da9ad55 100644
--- a/frontend/discourse/admin/routes/admin-config/upcoming-changes.js
+++ b/frontend/discourse/admin/routes/admin-config/upcoming-changes.js
@@ -6,6 +6,9 @@ import { i18n } from "discourse-i18n";
export default class AdminConfigUpcomingChangesRoute extends DiscourseRoute {
@service currentUser;
+ // registered so in-app links carrying the param keep working: an Ember
+ // transitionTo (notification clicks, admin search, the setting-change
+ // warning links) rebuilds the URL from registered query params only
queryParams = {
changeNamesFilter: { replace: true },
};
diff --git a/frontend/discourse/admin/routes/admin-email-templates/index.js b/frontend/discourse/admin/routes/admin-email-templates/index.js
index 6a1fe3be842..c2db6966622 100644
--- a/frontend/discourse/admin/routes/admin-email-templates/index.js
+++ b/frontend/discourse/admin/routes/admin-email-templates/index.js
@@ -1,8 +1,15 @@
import Route from "@ember/routing/route";
export default class AdminEmailTemplatesIndexRoute extends Route {
- setupController(controller) {
+ setupController(controller, model, transition) {
const parentController = this.controllerFor("adminEmailTemplates");
controller.set("emailTemplates", parentController.get("model"));
+
+ // `overridden` is deliberately not a registered query param; seeding here
+ // (rather than in the controller) makes each visit reflect its own URL
+ controller.set(
+ "showOverridenOnly",
+ transition.to.queryParams.overridden === "true"
+ );
}
}
diff --git a/frontend/discourse/admin/templates/admin-config/color-palettes/index.gjs b/frontend/discourse/admin/templates/admin-config/color-palettes/index.gjs
index e764aefcb64..38e7998bbfd 100644
--- a/frontend/discourse/admin/templates/admin-config/color-palettes/index.gjs
+++ b/frontend/discourse/admin/templates/admin-config/color-palettes/index.gjs
@@ -69,6 +69,8 @@ export default <template>
@minItemsForFilter={{FILTER_MINIMUM}}
@searchableProps={{@controller.searchableProps}}
@dropdownOptions={{@controller.dropdownOptions}}
+ @textFilterQueryParam="filter"
+ @dropdownFilterQueryParam="type"
@inputPlaceholder={{i18n
"admin.customize.colors.filters.search_placeholder"
}}
diff --git a/frontend/discourse/admin/templates/admin-email-templates/index.gjs b/frontend/discourse/admin/templates/admin-email-templates/index.gjs
index f8b647d3ca1..d3cb9ae9c09 100644
--- a/frontend/discourse/admin/templates/admin-email-templates/index.gjs
+++ b/frontend/discourse/admin/templates/admin-email-templates/index.gjs
@@ -12,6 +12,7 @@ export default <template>
<AdminFilterControls
@array={{@controller.shownTemplates}}
@searchableProps={{array "title" "id"}}
+ @textFilterQueryParam="filter"
@showDropdownFilter={{false}}
@inputPlaceholder={{i18n
"admin.customize.email_templates.search_templates"
diff --git a/frontend/discourse/admin/templates/admin-reports/index.gjs b/frontend/discourse/admin/templates/admin-reports/index.gjs
index 821c79cac72..c508aad2f55 100644
--- a/frontend/discourse/admin/templates/admin-reports/index.gjs
+++ b/frontend/discourse/admin/templates/admin-reports/index.gjs
@@ -2,9 +2,6 @@ import AdminReports from "discourse/admin/components/admin-reports";
export default <template>
<div class="admin-config-area__full-width">
- <AdminReports
- @group={{@controller.group}}
- @onGroupChange={{@controller.updateGroupFilter}}
- />
+ <AdminReports />
</div>
</template>
diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.js
index b59c996785e..847a6048f5f 100644
--- a/frontend/discourse/app/lib/url.js
+++ b/frontend/discourse/app/lib/url.js
@@ -636,6 +636,44 @@ export function getEditCategoryUrl(category, subcategories, tab) {
return getURL(url);
}
+// These helpers operate on app-relative paths like `RouterService#currentURL`
+// ("/admin/badges?filter=x"), which the URL API cannot parse on its own.
+
+function splitPath(path) {
+ const hashIndex = path.indexOf("#");
+ const withoutHash = hashIndex === -1 ? path : path.slice(0, hashIndex);
+ const hash = hashIndex === -1 ? "" : path.slice(hashIndex);
+ const queryIndex = withoutHash.indexOf("?");
+
+ return {
+ pathname:
+ queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex),
+ query: queryIndex === -1 ? "" : withoutHash.slice(queryIndex + 1),
+ hash,
+ };
+}
+
+export function searchParamsFromPath(path) {
+ const { query } = splitPath(path || "");
+ return new URLSearchParams(query);
+}
+
+export function applyQueryParams(path, params) {
+ const { pathname, query, hash } = splitPath(path || "/");
+
+ const searchParams = new URLSearchParams(query);
+ for (const [name, value] of Object.entries(params)) {
+ if (value) {
+ searchParams.set(name, value);
+ } else {
+ searchParams.delete(name);
+ }
+ }
+
+ const queryString = searchParams.toString();
+ return pathname + (queryString ? `?${queryString}` : "") + hash;
+}
+
export function getCanonicalUrl(absoluteUrl) {
const canonicalUrl = new URL(absoluteUrl);
canonicalUrl.pathname = canonicalUrl.pathname.replace(
diff --git a/frontend/discourse/tests/acceptance/admin-customize-components-config-area-test.gjs b/frontend/discourse/tests/acceptance/admin-customize-components-config-area-test.gjs
index 94c2aac4da1..1869dc7eac2 100644
--- a/frontend/discourse/tests/acceptance/admin-customize-components-config-area-test.gjs
+++ b/frontend/discourse/tests/acceptance/admin-customize-components-config-area-test.gjs
@@ -1,4 +1,4 @@
-import { visit } from "@ember/test-helpers";
+import { click, currentURL, fillIn, select, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { withPluginApi } from "discourse/lib/plugin-api";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
@@ -58,3 +58,194 @@ acceptance("Admin - Config areas - Components", function (needs) {
);
});
});
+
+acceptance("Admin - Config areas - Components - filters", function (needs) {
+ needs.user();
+
+ let requests;
+
+ needs.hooks.beforeEach(() => {
+ requests = [];
+ });
+
+ needs.pretender((server, helper) => {
+ const components = [
+ { id: 1, name: "Air", parent_themes: [], enabled: true },
+ {
+ id: 2,
+ name: "Ground",
+ parent_themes: [{ id: 5, name: "Horizon" }],
+ enabled: true,
+ },
+ ];
+
+ server.get("/admin/config/customize/components", (request) => {
+ requests.push(request.queryParams);
+
+ const { name, status } = request.queryParams;
+ let filtered = components;
+
+ if (name) {
+ filtered = filtered.filter((component) =>
+ component.name.toLowerCase().includes(name.toLowerCase())
+ );
+ }
+
+ if (status === "used") {
+ filtered = filtered.filter(
+ (component) => component.parent_themes.length > 0
+ );
+ } else if (status === "unused") {
+ filtered = filtered.filter(
+ (component) => component.parent_themes.length === 0
+ );
+ }
+
+ return helper.response({
+ components: filtered,
+ has_more: false,
+ });
+ });
+ });
+
+ test("seeds the filters from the URL before the first request", async function (assert) {
+ await visit("/admin/config/customize/components?filter=air&status=unused");
+
+ assert.strictEqual(
+ requests.length,
+ 1,
+ "makes a single request on load, with no unfiltered request first"
+ );
+ assert.strictEqual(
+ requests[0].name,
+ "air",
+ "the first request includes the name filter from the URL"
+ );
+ assert.strictEqual(
+ requests[0].status,
+ "unused",
+ "the first request includes the status filter from the URL"
+ );
+ assert
+ .dom(".admin-filter-controls__input")
+ .hasValue("air", "prefills the search input from the URL");
+ assert
+ .dom(".admin-filter-controls__dropdown")
+ .hasValue("unused", "preselects the status dropdown from the URL");
+ assert.dom(".admin-config-components__component-row").exists({ count: 1 });
+ });
+
+ test("ignores an invalid status param in the URL", async function (assert) {
+ await visit("/admin/config/customize/components?status=banana");
+
+ assert.strictEqual(
+ requests[0].status,
+ undefined,
+ "does not send the invalid status to the server"
+ );
+ assert
+ .dom(".admin-filter-controls__dropdown")
+ .hasValue("all", "the status dropdown falls back to the default value");
+ assert.dom(".admin-config-components__component-row").exists({ count: 2 });
+ });
+
+ test("reflects the search in the URL as the user types", async function (assert) {
+ await visit("/admin/config/customize/components");
+
+ await fillIn(".admin-filter-controls__input", "air");
+
+ assert.strictEqual(
+ requests.at(-1).name,
+ "air",
+ "sends the name filter to the server"
+ );
+ assert.strictEqual(
+ currentURL(),
+ "/admin/config/customize/components?filter=air",
+ "reflects the search in the URL"
+ );
+ assert.dom(".admin-config-components__component-row").exists({ count: 1 });
+ assert
+ .dom(".admin-filter-controls__input")
+ .isFocused("keeps focus while the URL updates");
+
+ await fillIn(".admin-filter-controls__input", "");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/config/customize/components",
+ "clearing the search removes the param from the URL"
+ );
+ assert.dom(".admin-config-components__component-row").exists({ count: 2 });
+ });
+
+ test("reflects the status dropdown in the URL", async function (assert) {
+ await visit("/admin/config/customize/components");
+
+ await select(".admin-filter-controls__dropdown", "used");
+
+ assert.strictEqual(
+ requests.at(-1).status,
+ "used",
+ "sends the status filter to the server"
+ );
+ assert.strictEqual(
+ currentURL(),
+ "/admin/config/customize/components?status=used",
+ "reflects the status in the URL"
+ );
+ assert.dom(".admin-config-components__component-row").exists({ count: 1 });
+
+ await select(".admin-filter-controls__dropdown", "all");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/config/customize/components",
+ "selecting the default status removes the param from the URL"
+ );
+ assert.dom(".admin-config-components__component-row").exists({ count: 2 });
+ });
+
+ test("resetting the filters clears the params from the URL", async function (assert) {
+ await visit("/admin/config/customize/components?filter=air&status=unused");
+
+ await click(".admin-filter-controls__reset");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/config/customize/components",
+ "removes both params in a single URL update"
+ );
+ assert.dom(".admin-filter-controls__input").hasValue("");
+ assert.dom(".admin-filter-controls__dropdown").hasValue("all");
+ assert.strictEqual(
+ requests.at(-1).name,
+ "",
+ "reloads without the name filter"
+ );
+ assert.strictEqual(
+ requests.at(-1).status,
+ "",
+ "reloads without the status filter"
+ );
+ assert.dom(".admin-config-components__component-row").exists({ count: 2 });
+ });
+
+ test("deep linking to filters with no results still renders the filter controls", async function (assert) {
+ await visit("/admin/config/customize/components?filter=nomatch");
+
+ assert
+ .dom(".admin-filter-controls")
+ .exists("the filter controls render despite the empty filtered result");
+ assert
+ .dom(".admin-filter-controls__input")
+ .hasValue("nomatch", "prefills the search input from the URL");
+ assert.dom(".admin-config-components__component-row").doesNotExist();
+ assert
+ .dom(".admin-filter-controls__no-results .admin-filter-controls__reset")
+ .exists("a reset button renders alongside the no-results message");
+ assert
+ .dom(".admin-config-area-empty-list")
+ .doesNotExist("the no-components-installed empty state is not shown");
+ });
+});
diff --git a/frontend/discourse/tests/acceptance/admin-email-templates-test.js b/frontend/discourse/tests/acceptance/admin-email-templates-test.js
new file mode 100644
index 00000000000..ea1e58e4b98
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/admin-email-templates-test.js
@@ -0,0 +1,64 @@
+import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Admin - Email Templates - URL filters", function (needs) {
+ needs.user();
+ needs.settings({
+ available_locales: [{ name: "English", value: "en" }],
+ default_locale: "en",
+ });
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/email/templates", () =>
+ helper.response({
+ email_templates: [
+ {
+ id: "user_notifications.admin_login",
+ title: "Admin Login",
+ can_revert: true,
+ },
+ {
+ id: "user_notifications.signup",
+ title: "Signup",
+ can_revert: true,
+ },
+ {
+ id: "user_notifications.account_created",
+ title: "Account Created",
+ can_revert: false,
+ },
+ ],
+ })
+ );
+ });
+
+ test("seeds and updates the URL filters", async function (assert) {
+ await visit("/admin/email/templates?filter=login&overridden=true");
+
+ assert.dom(".admin-filter-controls__input").hasValue("login");
+ assert.dom("#toggle-overridden").isChecked();
+ assert.dom("tr.email-templates-list__row").exists({ count: 1 });
+
+ await fillIn(".admin-filter-controls__input", "sign");
+ assert.strictEqual(
+ currentURL(),
+ "/admin/email/templates?filter=sign&overridden=true"
+ );
+
+ await click("#toggle-overridden");
+ assert.strictEqual(currentURL(), "/admin/email/templates?filter=sign");
+ assert.dom("tr.email-templates-list__row").exists({ count: 1 });
+ });
+
+ test("does not retain overridden state across visits", async function (assert) {
+ await visit("/admin/email/templates?overridden=true");
+ assert.dom("#toggle-overridden").isChecked();
+
+ await visit("/admin/customize/site_texts");
+ await visit("/admin/email/templates");
+
+ assert.dom("#toggle-overridden").isNotChecked();
+ assert.dom("tr.email-templates-list__row").exists({ count: 3 });
+ });
+});
diff --git a/frontend/discourse/tests/acceptance/admin-upcoming-changes-test.js b/frontend/discourse/tests/acceptance/admin-upcoming-changes-test.js
new file mode 100644
index 00000000000..73b7747d76c
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/admin-upcoming-changes-test.js
@@ -0,0 +1,101 @@
+import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+function buildChange(setting, status, impactType, impactRole, enabledFor) {
+ return {
+ setting,
+ humanized_name: setting,
+ description: setting,
+ plugin: null,
+ value: enabledFor === "everyone",
+ dependents: [],
+ overriding_defaults: false,
+ groups: "",
+ upcoming_change: {
+ status,
+ impact: `${impactType},${impactRole}`,
+ impact_type: impactType,
+ impact_role: impactRole,
+ enabled_for: enabledFor,
+ },
+ };
+}
+
+acceptance("Admin - Upcoming Changes - URL filters", function (needs) {
+ needs.user();
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/config/upcoming-changes", () =>
+ helper.response({
+ upcoming_changes: [
+ buildChange(
+ "alpha_composer",
+ "alpha",
+ "other",
+ "moderators",
+ "no_one"
+ ),
+ buildChange(
+ "beta_sidebar",
+ "beta",
+ "feature",
+ "all_members",
+ "everyone"
+ ),
+ buildChange(
+ "stable_defaults",
+ "stable",
+ "site_setting_default",
+ "staff",
+ "everyone"
+ ),
+ ],
+ })
+ );
+ });
+
+ test("preserves the legacy changeNamesFilter parameter", async function (assert) {
+ await visit(
+ "/admin/config/upcoming-changes?changeNamesFilter=alpha_composer,beta_sidebar"
+ );
+
+ assert
+ .dom(".admin-filter-controls__input")
+ .hasValue("alpha_composer,beta_sidebar");
+ assert.dom(".upcoming-change-row").exists({ count: 2 });
+
+ await fillIn(".admin-filter-controls__input", "beta_sidebar");
+ assert.strictEqual(
+ currentURL(),
+ "/admin/config/upcoming-changes?changeNamesFilter=beta_sidebar"
+ );
+ });
+
+ test("re-seeds filters on a same-route transition", async function (assert) {
+ await visit(
+ "/admin/config/upcoming-changes?changeNamesFilter=alpha_composer"
+ );
+ await visit("/admin/config/upcoming-changes?status=stable");
+
+ assert.dom(".admin-filter-controls__input").hasValue("");
+ assert.dom(".admin-filter-controls__dropdown--status").hasValue("stable");
+ assert
+ .dom(".upcoming-change-row[data-upcoming-change='stable_defaults']")
+ .exists();
+ });
+
+ test("reset removes every owned parameter", async function (assert) {
+ await visit(
+ "/admin/config/upcoming-changes?changeNamesFilter=beta&status=beta&type=feature&impactRole=all_members&enabled=enabled"
+ );
+
+ assert.dom(".upcoming-change-row").exists({ count: 1 });
+ await click(".admin-filter-controls__reset");
+
+ assert.strictEqual(currentURL(), "/admin/config/upcoming-changes");
+ assert.dom(".admin-filter-controls__input").hasValue("");
+ assert.dom(".admin-filter-controls__dropdown--status").hasValue("all");
+ assert.dom(".upcoming-change-row").exists({ count: 3 });
+ });
+});
diff --git a/frontend/discourse/tests/acceptance/reports-test.js b/frontend/discourse/tests/acceptance/reports-test.js
index bd5d58c4b6c..31188b8edef 100644
--- a/frontend/discourse/tests/acceptance/reports-test.js
+++ b/frontend/discourse/tests/acceptance/reports-test.js
@@ -1,4 +1,4 @@
-import { visit } from "@ember/test-helpers";
+import { click, currentURL, fillIn, select, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
@@ -78,3 +78,146 @@ acceptance("Reports | Plugin groups sorted by display name", function (needs) {
]);
});
});
+
+acceptance("Reports | Filter query params", function (needs) {
+ needs.user();
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/reports", () => {
+ return helper.response({
+ reports: [
+ {
+ title: "Signups",
+ description: "New account creations",
+ type: "signups",
+ },
+ {
+ title: "Topics",
+ description: "New topics of all statuses",
+ type: "topics",
+ },
+ {
+ title: "Flags",
+ description: "Number of flags created",
+ type: "flags",
+ },
+ ],
+ });
+ });
+ });
+
+ test("typing in the filter box reflects the search in the URL", async function (assert) {
+ await visit("/admin/reports");
+
+ await fillIn(".admin-filter-controls__input", "signups");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/reports?filter=signups",
+ "writes the text filter to the URL"
+ );
+ assert.dom(".admin-section-landing-item__content").exists({ count: 1 });
+ assert
+ .dom(".admin-section-landing-item__title")
+ .hasHtml("Signups", "only shows the matching report");
+ assert
+ .dom(".admin-filter-controls__input")
+ .isFocused("keeps focus while the URL updates");
+
+ await fillIn(".admin-filter-controls__input", "");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/reports",
+ "clearing the search removes the param"
+ );
+ assert.dom(".admin-section-landing-item__content").exists({ count: 3 });
+ });
+
+ test("selecting a group reflects it in the URL", async function (assert) {
+ await visit("/admin/reports");
+
+ await select(".admin-filter-controls__dropdown", "moderation_and_security");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/reports?group=moderation_and_security",
+ "writes the group to the URL"
+ );
+ assert.dom(".admin-reports-group").exists({ count: 1 });
+ assert.dom(".admin-section-landing-item__content").exists({ count: 1 });
+
+ await select(".admin-filter-controls__dropdown", "all");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/reports",
+ "selecting all groups removes the param"
+ );
+ assert.dom(".admin-reports-group").exists({ count: 3 });
+ });
+
+ test("pre-selects the group from the URL", async function (assert) {
+ await visit("/admin/reports?group=content");
+
+ assert.strictEqual(currentURL(), "/admin/reports?group=content");
+ assert.dom(".admin-filter-controls__dropdown").hasValue("content");
+ assert.dom(".admin-reports-group").exists({ count: 1 });
+ assert
+ .dom(".admin-section-landing-item__title")
+ .hasHtml("Topics", "only shows reports from the group in the URL");
+ });
+
+ test("re-derives the group when the URL changes without leaving the route", async function (assert) {
+ // e.g. clicking a link that carries a different ?group= while already on
+ // the page; removing the params entirely is not covered because a
+ // same-route transition to the bare URL fires no route event at all
+ await visit("/admin/reports?group=content");
+
+ assert.dom(".admin-filter-controls__dropdown").hasValue("content");
+
+ await visit("/admin/reports?group=moderation_and_security");
+
+ assert
+ .dom(".admin-filter-controls__dropdown")
+ .hasValue(
+ "moderation_and_security",
+ "re-selects the dropdown from the new URL"
+ );
+ assert
+ .dom(".admin-section-landing-item__title")
+ .hasHtml("Flags", "re-filters to the new group");
+ });
+
+ test("falls back to all groups when the URL group is unknown", async function (assert) {
+ await visit("/admin/reports?group=nonsense");
+
+ assert.dom(".admin-filter-controls__dropdown").hasValue("all");
+ assert.dom(".admin-reports-group").exists({ count: 3 });
+ assert.dom(".admin-section-landing-item__content").exists({ count: 3 });
+ });
+
+ test("reset button clears both params from the URL", async function (assert) {
+ await visit("/admin/reports");
+
+ await fillIn(".admin-filter-controls__input", "signups");
+ await select(".admin-filter-controls__dropdown", "engagement");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/reports?filter=signups&group=engagement",
+ "both filters are in the URL"
+ );
+
+ await click(".admin-filter-controls__reset");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/reports",
+ "clears both params in one write"
+ );
+ assert.dom(".admin-filter-controls__input").hasValue("");
+ assert.dom(".admin-filter-controls__dropdown").hasValue("all");
+ assert.dom(".admin-section-landing-item__content").exists({ count: 3 });
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/admin-filter-controls-test.gjs b/frontend/discourse/tests/integration/components/admin-filter-controls-test.gjs
index 06e7d04b4bd..50eb3cd5462 100644
--- a/frontend/discourse/tests/integration/components/admin-filter-controls-test.gjs
+++ b/frontend/discourse/tests/integration/components/admin-filter-controls-test.gjs
@@ -1,4 +1,7 @@
-import { click, fillIn, render, select } from "@ember/test-helpers";
+import { tracked } from "@glimmer/tracking";
+import Evented from "@ember/object/evented";
+import Service from "@ember/service";
+import { click, fillIn, render, select, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import AdminFilterControls from "discourse/admin/components/admin-filter-controls";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
@@ -41,6 +44,15 @@ const SAMPLE_DROPDOWN_OPTIONS = [
},
];
+class RouterStub extends Service.extend(Evented) {
+ @tracked currentURL = "/admin/example";
+
+ changeURL(url) {
+ this.currentURL = url;
+ this.trigger("routeDidChange");
+ }
+}
+
module("Integration | Component | AdminFilterControls", function (hooks) {
setupRenderingTest(hooks);
@@ -790,4 +802,118 @@ module("Integration | Component | AdminFilterControls", function (hooks) {
.dom(".item")
.exists({ count: 3 }, "shows all items after changing filter");
});
+
+ test("query param sync args are inert without a live router", async function (assert) {
+ // outside a real route (router.currentURL is null, as in rendering
+ // tests) the query param args must neither crash nor affect filtering
+ this.set("data", SAMPLE_DATA);
+ this.set("searchableProps", ["name"]);
+ this.set("dropdownOptions", SAMPLE_DROPDOWN_OPTIONS);
+
+ await render(
+ <template>
+ <AdminFilterControls
+ @array={{this.data}}
+ @searchableProps={{this.searchableProps}}
+ @dropdownOptions={{this.dropdownOptions}}
+ @textFilterQueryParam="filter"
+ @dropdownFilterQueryParam="category"
+ >
+ <:content as |filteredData|>
+ <div class="results">
+ {{#each filteredData as |item|}}
+ <div class="item" data-id={{item.id}}>{{item.name}}</div>
+ {{/each}}
+ </div>
+ </:content>
+ </AdminFilterControls>
+ </template>
+ );
+
+ assert.dom(".item").exists({ count: 3 }, "renders all items");
+
+ await fillIn(".admin-filter-controls__input", "second");
+ assert.dom(".item").exists({ count: 1 }, "text filtering still works");
+
+ await select(".admin-filter-controls__dropdown", "feature");
+ assert
+ .dom(".item")
+ .doesNotExist("dropdown filtering still combines with text");
+
+ await click(".admin-filter-controls__reset");
+ assert.dom(".item").exists({ count: 3 }, "reset still works");
+ });
+
+ test("initialTextFilter still seeds when a query param arg is set", async function (assert) {
+ this.set("data", SAMPLE_DATA);
+ this.set("searchableProps", ["name"]);
+
+ await render(
+ <template>
+ <AdminFilterControls
+ @array={{this.data}}
+ @searchableProps={{this.searchableProps}}
+ @textFilterQueryParam="filter"
+ @initialTextFilter="third"
+ >
+ <:content as |filteredData|>
+ <div class="results">
+ {{#each filteredData as |item|}}
+ <div class="item" data-id={{item.id}}>{{item.name}}</div>
+ {{/each}}
+ </div>
+ </:content>
+ </AdminFilterControls>
+ </template>
+ );
+
+ assert.dom(".admin-filter-controls__input").hasValue("third");
+ assert.dom(".item").exists({ count: 1 }, "applies the seeded filter");
+ });
+
+ test("reveals a URL-owned dropdown activated by a route change", async function (assert) {
+ this.owner.unregister("service:router");
+ this.owner.register("service:router", RouterStub);
+
+ this.set("data", SAMPLE_DATA);
+ this.set("dropdownOptions", {
+ category: SAMPLE_DROPDOWN_OPTIONS,
+ });
+ this.set("dropdownFilterQueryParams", { category: "category" });
+
+ await render(
+ <template>
+ <AdminFilterControls
+ @array={{this.data}}
+ @dropdownOptions={{this.dropdownOptions}}
+ @dropdownFilterQueryParams={{this.dropdownFilterQueryParams}}
+ @filterDropdownsExpanded={{false}}
+ >
+ <:content as |filteredData|>
+ <div class="results">
+ {{#each filteredData as |item|}}
+ <div class="item" data-id={{item.id}}>{{item.name}}</div>
+ {{/each}}
+ </div>
+ </:content>
+ </AdminFilterControls>
+ </template>
+ );
+
+ assert
+ .dom(".admin-filter-controls__dropdown--category")
+ .doesNotExist("keeps inactive dropdown filters collapsed initially");
+
+ this.owner
+ .lookup("service:router")
+ .changeURL("/admin/example?category=feature");
+ await settled();
+
+ assert
+ .dom(".admin-filter-controls__dropdown--category")
+ .hasValue("feature", "reveals the URL-owned active dropdown");
+ assert
+ .dom(".item")
+ .exists({ count: 2 }, "applies the dropdown filter from the new URL");
+ });
});
diff --git a/frontend/discourse/tests/integration/components/email-logs-list-test.gjs b/frontend/discourse/tests/integration/components/email-logs-list-test.gjs
index 5a8613471eb..e4334dfcbf3 100644
--- a/frontend/discourse/tests/integration/components/email-logs-list-test.gjs
+++ b/frontend/discourse/tests/integration/components/email-logs-list-test.gjs
@@ -1,7 +1,10 @@
/* eslint-disable qunit/no-conditional-assertions */
+import Service from "@ember/service";
import { fillIn, render, waitFor } from "@ember/test-helpers";
import { module, test } from "qunit";
+import sinon from "sinon";
import EmailLogsList from "discourse/admin/components/email-logs-list";
+import DiscourseURL from "discourse/lib/url";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
@@ -38,6 +41,10 @@ const EMAIL_LOGS = [
},
];
+class RouterStub extends Service {
+ currentURL = "/admin/email-logs?user=testuser";
+}
+
module("Integration | Component | EmailLogsList", function (hooks) {
setupRenderingTest(hooks);
@@ -204,4 +211,50 @@ module("Integration | Component | EmailLogsList", function (hooks) {
.dom(".email-row")
.exists({ count: 2 }, "shows all emails again after clearing filter");
});
+
+ test("seeds filters from the URL and writes changes back", async function (assert) {
+ let lastQuery;
+ pretender.get("/admin/email-logs/sent.json", (request) => {
+ lastQuery = request.queryParams;
+ return response(EMAIL_LOGS);
+ });
+
+ this.owner.unregister("service:router");
+ this.owner.register("service:router", RouterStub);
+ const replaceState = sinon.stub(DiscourseURL, "replaceState");
+
+ await render(
+ <template>
+ <EmailLogsList
+ @status="sent"
+ @headers={{mockHeaders}}
+ @filters={{mockFilters}}
+ >
+ <:default as |emailLog|>
+ <tr class="email-row"><td>{{emailLog.to_address}}</td></tr>
+ </:default>
+ </EmailLogsList>
+ </template>
+ );
+
+ await waitFor(".email-row");
+
+ assert
+ .dom("tr.filters td:nth-child(2) input")
+ .hasValue("testuser", "seeds the user filter from the URL");
+ assert.strictEqual(
+ lastQuery.user,
+ "testuser",
+ "applies the URL filter to the initial request"
+ );
+
+ await fillIn("tr.filters td:nth-child(3) input", "[email protected]");
+
+ assert.true(
+ replaceState.calledWith(
+ "/admin/email-logs?user=testuser&address=test%40example.com"
+ ),
+ "writes all active filters to the URL"
+ );
+ });
});
diff --git a/frontend/discourse/tests/unit/lib/url-test.js b/frontend/discourse/tests/unit/lib/url-test.js
index 7b68b550cf9..6055e95e597 100644
--- a/frontend/discourse/tests/unit/lib/url-test.js
+++ b/frontend/discourse/tests/unit/lib/url-test.js
@@ -4,10 +4,12 @@ import sinon from "sinon";
import { setPrefix } from "discourse/lib/get-url";
import { withPluginApi } from "discourse/lib/plugin-api";
import DiscourseURL, {
+ applyQueryParams,
getCanonicalUrl,
getCategoryAndTagUrl,
isHttpUrl,
prefixProtocol,
+ searchParamsFromPath,
userPath,
} from "discourse/lib/url";
import Session from "discourse/models/session";
@@ -130,6 +132,45 @@ module("Unit | Utility | url", function (hooks) {
assert.strictEqual(userPath("eviltrout"), "/forum/u/eviltrout");
});
+ test("searchParamsFromPath parses app-relative paths", function (assert) {
+ const params = searchParamsFromPath(
+ "/admin/email-logs?subject=What?Now&address=sam%2Btest%40example.com#details?ignored"
+ );
+
+ assert.strictEqual(
+ params.get("subject"),
+ "What?Now",
+ "preserves raw query delimiters inside values"
+ );
+ assert.strictEqual(
+ params.get("address"),
+ "decodes encoded values"
+ );
+ assert.false(params.has("ignored"), "ignores fragment contents");
+ assert.strictEqual(
+ [...searchParamsFromPath("")].length,
+ 0,
+ "returns empty parameters for an empty path"
+ );
+ });
+
+ test("applyQueryParams updates paths without dropping URL parts", function (assert) {
+ assert.strictEqual(
+ applyQueryParams(
+ "/admin/email-logs?subject=What?Now&remove=1#details?tab=raw",
+ { filter: "new value", remove: null }
+ ),
+ "/admin/email-logs?subject=What%3FNow&filter=new+value#details?tab=raw",
+ "preserves query values and the complete fragment"
+ );
+ assert.strictEqual(
+ applyQueryParams("", { filter: "value" }),
+ "/?filter=value",
+ "uses the app root for an empty path"
+ );
+ });
+
test("routeTo with prefix", async function (assert) {
setPrefix("/forum");