Skip to content

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

DEV: Convert FilterTips to use DMenu and refactor components (#33999)

Martin Brennanc3e4dd4db646
diff --git a/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs
new file mode 100644
index 00000000000..0e3a1035da5
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation-menu.gjs
@@ -0,0 +1,530 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { cancel, schedule } from "@ember/runloop";
+import { service } from "@ember/service";
+import { TrackedObject } from "@ember-compat/tracked-built-ins";
+import { eq } from "truth-helpers";
+import DButton from "discourse/components/d-button";
+import DropdownMenu from "discourse/components/dropdown-menu";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import withEventValue from "discourse/helpers/with-event-value";
+import discourseDebounce from "discourse/lib/debounce";
+import FilterSuggestions from "discourse/lib/filter-suggestions";
+import { resettableTracked } from "discourse/lib/tracked-tools";
+import { i18n } from "discourse-i18n";
+
+const MAX_RESULTS = 20;
+
+const FilterNavigationMenuList = <template>
+ {{#if @data.filteredTips.length}}
+ <DropdownMenu as |dropdown|>
+ {{#each @data.filteredTips as |item index|}}
+ <dropdown.item>
+ <DButton
+ class={{concatClass
+ "filter-navigation__tip-button"
+ (if (eq index @data.selectedIndex) "--selected")
+ }}
+ @action={{fn @data.selectItem item}}
+ >
+ <span class="filter-navigation__tip-name">
+ {{item.name}}
+ </span>
+ {{#if item.description}}
+ <span class="filter-navigation__tip-description">—
+ {{item.description}}</span>
+ {{/if}}
+ </DButton>
+ </dropdown.item>
+ {{/each}}
+ </DropdownMenu>
+ {{/if}}
+</template>;
+
+/**
+ * This component provides an input field and parsing logic for filter
+ * queries. Every time the input changes, we recalculate the list of
+ * filter tips that match the current input value.
+ *
+ * We start from an initial list of tips provided by the server
+ * (see TopicsFilter.option_info) which are reduced to a list of "high priority/top-level"
+ * filters if there is no user input value.
+ *
+ * Once the user starts typing, we parse the input value to determine
+ * the last word and its prefix (if any). If the last word contains a colon,
+ * we treat it as a filter name and look for matching tips via the FilterSuggestions service.
+ * For example after "category:" is typed we show a list of categories the user
+ * has access to.
+ *
+ * Each filter tip can have prefixes (like "-", "=", and "-=") that modify the filter behavior,
+ * as well as delimiters (like ",") that allow for multiple values.
+ */
+export default class FilterNavigationMenu extends Component {
+ @service menu;
+ @service site;
+
+ @resettableTracked currentInputValue = this.args.initialInputValue || "";
+
+ filterSuggessionResults = [];
+ activeFilter = null;
+ trackedMenuListData = new TrackedObject({
+ filteredTips: this.filteredTips,
+ selectedIndex: null,
+ selectItem: this.selectItem,
+ });
+
+ @tracked _selectedIndex = -1;
+
+ get selectedIndex() {
+ return this._selectedIndex;
+ }
+
+ set selectedIndex(value) {
+ this._selectedIndex = value;
+ this.trackedMenuListData.selectedIndex = value;
+ }
+
+ clearSelection() {
+ this.selectedIndex = -1;
+ }
+
+ get nothingSelected() {
+ return this.selectedIndex === -1;
+ }
+
+ get filteredTips() {
+ if (!this.args.tips) {
+ return [];
+ }
+
+ const words = this.currentInputValue.split(/\s+/);
+ const lastWord = words.at(-1).toLowerCase();
+
+ // If we're already filtering by a type like "category:" that has suggestions,
+ // we want to only show those suggestions.
+ if (this.activeFilter && this.filterSuggessionResults.length > 0) {
+ return this.filterSuggessionResults;
+ }
+
+ // We are filtering by a type here like "category:", "tag:", etc.
+ // since the last word contains a colon.
+ const colonIndex = lastWord.indexOf(":");
+ const prefix = this.#extractPrefix(lastWord) || "";
+ if (colonIndex > 0) {
+ const filterName = lastWord.substring(prefix.length).split(":")[0];
+ const valueText = lastWord.substring(colonIndex + 1);
+ const tip = this.args.tips.find((t) => t.name === filterName + ":");
+
+ if (tip?.type && valueText !== undefined) {
+ this.handleFilterSuggestionSearch(filterName, valueText, tip, prefix);
+ return this.filterSuggessionResults.length > 0
+ ? this.filterSuggessionResults
+ : [];
+ }
+ }
+
+ // Get a list of the "top-level" filters that have a priority of 1,
+ // such as category:, created-after:, tags:, etc.
+ if (!this.currentInputValue || lastWord === "") {
+ return this.args.tips
+ .filter((tip) => tip.priority)
+ .sort((a, b) => (b.priority || 0) - (a.priority || 0))
+ .slice(0, MAX_RESULTS);
+ }
+
+ return this.filterAllTips(lastWord, prefix);
+ }
+
+ /**
+ * Filters all available tips based on a search term from the user input
+ *
+ * This method searches through the complete list of filter tips and finds matches based on:
+ * 1. Direct name matches with the search term
+ * 2. Matches against tip aliases
+ * 3. Support for prefixed tips (like "-", "=", "-=")
+ *
+ * Results are sorted to prioritize exact matches first and are limited to MAX_RESULTS
+ *
+ * @param {string} lastWord - The last word in the input string (what user is currently typing)
+ * @param {string} prefix - Any detected prefix modifier like "-", "=", or "-="
+ * @returns {Array} - Array of matching tip objects for display in the menu
+ */
+ filterAllTips(lastWord, prefix) {
+ const tips = [];
+ this.args.tips.forEach((tip) => {
+ if (tips.length >= MAX_RESULTS) {
+ return;
+ }
+ const tipName = tip.name;
+ const searchTerm = lastWord.substring(prefix.length);
+
+ if (searchTerm.endsWith(":") && tipName === searchTerm) {
+ return;
+ }
+
+ const prefixMatch =
+ searchTerm === "" &&
+ prefix &&
+ tipName.prefixes &&
+ tipName.prefixes.find((p) => p.name === prefix);
+
+ if (prefixMatch || tipName.indexOf(searchTerm) > -1) {
+ this.#pushPrefixTips(tip, tips, null, prefix);
+ if (!prefix) {
+ tips.push(tip);
+ }
+ } else if (tip.alias && tip.alias.indexOf(searchTerm) > -1) {
+ this.#pushPrefixTips(tip, tips, tip.alias, prefix);
+ tips.push({ ...tip, name: tip.alias });
+ }
+ });
+
+ return tips.sort((a, b) => {
+ const aName = a.name.toLowerCase();
+ const bName = b.name.toLowerCase();
+ const aStartsWith = aName.startsWith(lastWord.toLowerCase());
+ const bStartsWith = bName.startsWith(lastWord.toLowerCase());
+ if (aStartsWith && !bStartsWith) {
+ return -1;
+ }
+ if (!aStartsWith && bStartsWith) {
+ return 1;
+ }
+ if (aStartsWith && bStartsWith && aName.length !== bName.length) {
+ return aName.length - bName.length;
+ }
+ return aName.localeCompare(bName);
+ });
+ }
+
+ /**
+ * Updates the component state based on the current input value
+ *
+ * Unlike the filteredTips getter which just returns the current suggestions,
+ * this method actively parses the input and updates internal state:
+ *
+ * - Resets selection state
+ * - Sets or clears the activeFilter based on detected filter types
+ * - Triggers filter-specific suggestion searches when appropriate
+ * - Updates the reactive state to ensure UI reflects current filter state
+ *
+ * This method should be called after actions that modify the input value
+ * to ensure the component's internal state is synchronized with the input.
+ */
+ updateResults() {
+ this.clearSelection();
+
+ const words = this.currentInputValue.split(/\s+/);
+ const lastWord = words.at(-1);
+ const colonIndex = lastWord.indexOf(":");
+
+ if (colonIndex > 0) {
+ const prefix = this.#extractPrefix(lastWord);
+ const filterName = lastWord.substring(
+ prefix.length,
+ colonIndex + prefix.length
+ );
+ const valueText = lastWord.substring(colonIndex + 1);
+
+ const tip = this.args.tips.find((t) => {
+ const tipFilterName = t.name.replace(/^[-=]/, "").split(":")[0];
+ return tipFilterName === filterName && t.type;
+ });
+
+ if (tip?.type) {
+ this.activeFilter = filterName;
+ this.handleFilterSuggestionSearch(filterName, valueText, tip, prefix);
+ } else {
+ this.activeFilter = null;
+ this.filterSuggessionResults = [];
+ }
+ } else {
+ this.activeFilter = null;
+ this.filterSuggessionResults = [];
+ }
+
+ this.trackedMenuListData.filteredTips = this.filteredTips;
+ }
+
+ #pushPrefixTips(tip, tips, alias = null, currentPrefix = null) {
+ if (tip.prefixes && tip.prefixes.length > 0) {
+ tip.prefixes.forEach((prefix) => {
+ if (currentPrefix && !prefix.name.startsWith(currentPrefix)) {
+ return;
+ }
+ tips.push({
+ ...tip,
+ name: `${prefix.name}${alias || tip.name}`,
+ description: prefix.description || tip.description,
+ isSuggestion: true,
+ });
+ });
+ }
+ }
+
+ #extractPrefix(word) {
+ const match = word.match(/^(-=|=-|-|=)/);
+ return match ? match[0] : "";
+ }
+
+ @action
+ storeInputElement(element) {
+ this.inputElement = element;
+ }
+
+ @action
+ handleFilterSuggestionSearch(filterName, valueText, tip, prefix = "") {
+ this.activeFilter = filterName;
+ this.searchTimer = discourseDebounce(
+ this,
+ this.#performFilterSuggestionSearch,
+ filterName,
+ valueText,
+ tip,
+ prefix,
+ 300
+ );
+ }
+
+ /**
+ * Handles selection of a filter tip item from the dropdown menu.
+ * See TopicsFilter.option_info for the structure of the item
+ * on the server.
+ *
+ * @param {Object} item - A filter tip object from the initial list or from the filter suggestions
+ * @param {string} item.name - The name of the filter (e.g. "category:", "tag:")
+ * @param {string} [item.alias] - Alternative name for the filter (e.g. "categories:")
+ * @param {string} [item.description] - Human-readable description of the filter
+ * @param {number} [item.priority] - Priority value for sorting (higher appears first)
+ * @param {string} [item.type] - Type of filter for suggestions (category, tag, username, date, number)
+ * @param {Array<Object>} [item.delimiters] - Delimiter options for multiple values
+ * @param {Array<Object>} [item.prefixes] - Prefix modifiers for this filter (-, =, -=)
+ * @param {boolean} [item.isSuggestion] - Whether this is a suggestion for a specific filter value
+ */
+ @action
+ selectItem(item) {
+ // Split up the string from the text input into words.
+ const words = this.currentInputValue.split(/\s+/);
+
+ // If we are selecting an item that was suggested based on the initial
+ // word selected (e.g. after picking a "category:" the user selects a
+ // category from the list), we replace the last word with the selected item.
+ if (item.isSuggestion) {
+ words[words.length - 1] = item.name;
+ let updatedInputValue = words.join(" ");
+ if (
+ !updatedInputValue.endsWith(":") &&
+ (!item.delimiters || item.delimiters.length < 2)
+ ) {
+ updatedInputValue += " ";
+ }
+ this.updateInput(updatedInputValue);
+ } else {
+ // Otherwise if the user is selecting a filter from the initial tips,
+ // we add a colon to the end of it as needed, and fire off the
+ // suggestion search based on the filter type.
+ const lastWord = words.at(-1);
+ const prefix = this.#extractPrefix(lastWord);
+ const supportsPrefix = item.prefixes && item.prefixes.length > 0;
+ const filterName =
+ supportsPrefix && prefix ? `${prefix}${item.name}` : item.name;
+
+ words[words.length - 1] = filterName;
+ if (!filterName.endsWith(":") && !item.delimiters?.length) {
+ words[words.length - 1] += " ";
+ }
+
+ const updatedInputValue = words.join(" ");
+ this.updateInput(updatedInputValue);
+
+ const baseFilterName = item.name.replace(/^[-=]/, "").split(":")[0];
+ if (item.type) {
+ this.activeFilter = baseFilterName;
+ this.handleFilterSuggestionSearch(baseFilterName, "", item, prefix);
+ }
+ }
+
+ this.clearSelection();
+ this.inputElement.focus();
+ }
+
+ @action
+ updateInput(updatedInputValue, refreshQuery = false) {
+ this.currentInputValue = updatedInputValue;
+ this.args.onChange(updatedInputValue, refreshQuery);
+ this.trackedMenuListData.filteredTips = this.filteredTips;
+ this.updateResults();
+ }
+
+ @action
+ clearInput() {
+ this.updateInput("", true);
+ this.inputElement.focus();
+ }
+
+ @action
+ async openFilterMenu() {
+ if (this.dMenuInstance) {
+ this.dMenuInstance.show();
+ return;
+ }
+
+ this.dMenuInstance = await this.menu.show(this.inputElement, {
+ identifier: "filter-navigation-menu-list",
+ component: FilterNavigationMenuList,
+ data: this.trackedMenuListData,
+ maxWidth: 2000,
+ });
+
+ // HACK: We don't have a nice way for DMenu to be the same width as
+ // the input element, so we set it manually.
+ schedule("afterRender", () => {
+ if (this.dMenuInstance?.content) {
+ this.dMenuInstance.content.style.width =
+ this.inputElement.offsetWidth + "px";
+ }
+ });
+ }
+
+ @action
+ handleKeydown(event) {
+ if (
+ this.filteredTips.length === 0 &&
+ ["ArrowDown", "ArrowUp", "Tab"].includes(event.key)
+ ) {
+ return;
+ }
+
+ switch (event.key) {
+ case "ArrowDown":
+ event.preventDefault();
+ this.selectedIndex = this.nothingSelected
+ ? 0
+ : (this.selectedIndex + 1) % this.filteredTips.length;
+ break;
+ case "ArrowUp":
+ event.preventDefault();
+ this.selectedIndex = this.nothingSelected
+ ? this.filteredTips.length - 1
+ : (this.selectedIndex - 1 + this.filteredTips.length) %
+ this.filteredTips.length;
+ break;
+ case "Tab":
+ event.preventDefault();
+ event.stopPropagation();
+ this.selectItem(
+ this.filteredTips[this.nothingSelected ? 0 : this.selectedIndex]
+ );
+ break;
+ case " ":
+ if (!this.dMenuInstance) {
+ this.openFilterMenu();
+ }
+ break;
+ case "Enter":
+ if (this.selectedIndex >= 0) {
+ event.preventDefault();
+ event.stopPropagation();
+ this.selectItem(this.filteredTips[this.selectedIndex]);
+ } else {
+ cancel(this.searchTimer);
+
+ if (!this.dMenuInstance) {
+ this.args.onChange(this.currentInputValue, true);
+ } else {
+ this.dMenuInstance.close().then(() => {
+ this.args.onChange(this.currentInputValue, true);
+ });
+ }
+ }
+ break;
+ case "Escape":
+ this.dMenuInstance?.close();
+ break;
+ }
+ }
+
+ async #performFilterSuggestionSearch(filterName, valueText, tip, prefix) {
+ const type = tip.type;
+ let lastTerm = valueText;
+ let results = [];
+ let prevTerms = "";
+ let splitTerms;
+
+ if (tip.delimiters) {
+ const delimiters = tip.delimiters.map((s) => s.name);
+ splitTerms = lastTerm.split(new RegExp(`[${delimiters.join("")}]`));
+ lastTerm = splitTerms[splitTerms.length - 1];
+ prevTerms =
+ lastTerm === "" ? valueText : valueText.slice(0, -lastTerm.length);
+ }
+
+ lastTerm = (lastTerm || "").toLowerCase().trim();
+
+ results = await FilterSuggestions.getFilterSuggestionsByType(
+ type,
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm,
+ { site: this.site }
+ );
+
+ if (tip.delimiters) {
+ let lastMatches = false;
+
+ results.forEach((result) => (result.delimiters = tip.delimiters));
+
+ results = results.filter((result) => {
+ lastMatches ||= lastTerm === result.term;
+ return !splitTerms.includes(result.term);
+ });
+
+ if (lastMatches) {
+ tip.delimiters.forEach((delimiter) => {
+ results.push({
+ name: `${prefix}${filterName}:${prevTerms}${lastTerm}${delimiter.name}`,
+ description: delimiter.description,
+ isSuggestion: true,
+ delimiters: tip.delimiters,
+ });
+ });
+ }
+ }
+
+ this.filterSuggessionResults = results;
+ this.trackedMenuListData.filteredTips = this.filteredTips;
+ }
+
+ <template>
+ <div class="topic-query-filter__input">
+ {{icon "filter" class="topic-query-filter__icon btn-flat"}}
+
+ <input
+ class="topic-query-filter__filter-term"
+ value={{this.currentInputValue}}
+ {{on "keydown" this.handleKeydown}}
+ {{on "input" (withEventValue this.updateInput)}}
+ {{on "focus" this.openFilterMenu}}
+ {{didInsert this.storeInputElement}}
+ type="text"
+ id="topic-query-filter-input"
+ autocomplete="off"
+ placeholder={{i18n "filter.placeholder"}}
+ />
+
+ {{#if this.currentInputValue}}
+ <DButton
+ @icon="xmark"
+ @action={{this.clearInput}}
+ class="topic-query-filter__clear-btn btn-flat"
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjs b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjs
index 979fa9565ef..fb3b14a986d 100644
--- a/app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjs
+++ b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjs
@@ -1,84 +1,25 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
-import { Input } from "@ember/component";
-import { on } from "@ember/modifier";
-import { action } from "@ember/object";
-import didInsert from "@ember/render-modifiers/modifiers/did-insert";
-import { next } from "@ember/runloop";
import { service } from "@ember/service";
import { and } from "truth-helpers";
import BulkSelectToggle from "discourse/components/bulk-select-toggle";
-import DButton from "discourse/components/d-button";
-import FilterTips from "discourse/components/discovery/filter-tips";
-import PluginOutlet from "discourse/components/plugin-outlet";
+import FilterNavigationMenu from "discourse/components/discovery/filter-navigation-menu";
import bodyClass from "discourse/helpers/body-class";
-import icon from "discourse/helpers/d-icon";
-import lazyHash from "discourse/helpers/lazy-hash";
-import discourseDebounce from "discourse/lib/debounce";
import { bind } from "discourse/lib/decorators";
import { resettableTracked } from "discourse/lib/tracked-tools";
-import { i18n } from "discourse-i18n";
export default class DiscoveryFilterNavigation extends Component {
@service site;
+ @service menu;
- @tracked copyIcon = "link";
- @tracked copyClass = "btn-default";
- @tracked inputElement = null;
- @resettableTracked newQueryString = this.args.queryString;
+ @resettableTracked filterQueryString = this.args.queryString;
@bind
- updateQueryString(string) {
- this.newQueryString = string;
- }
-
- @action
- storeInputElement(element) {
- this.inputElement = element;
- }
-
- @action
- clearInput() {
- this.newQueryString = "";
- this.args.updateTopicsListQueryParams(this.newQueryString);
- next(() => {
- if (this.inputElement) {
- // required so child component is aware of the change
- this.inputElement.dispatchEvent(new Event("input", { bubbles: true }));
- this.inputElement.focus();
- }
- });
- }
-
- @action
- copyQueryString() {
- this.copyIcon = "check";
- this.copyClass = "btn-default ok";
+ updateQueryString(newQueryString, refresh) {
+ this.filterQueryString = newQueryString;
- navigator.clipboard.writeText(window.location);
-
- discourseDebounce(this._restoreButton, 3000);
- }
-
- @bind
- _restoreButton() {
- if (this.isDestroying || this.isDestroyed) {
- return;
+ if (refresh) {
+ this.args.updateTopicsListQueryParams(newQueryString);
}
- this.copyIcon = "link";
- this.copyClass = "btn-default";
- }
-
- @action
- handleKeydown(event) {
- if (event.key === "Enter" && this._allowEnterSubmit) {
- this.args.updateTopicsListQueryParams(this.newQueryString);
- }
- }
-
- @action
- blockEnterSubmit(value) {
- this._allowEnterSubmit = !value;
}
<template>
@@ -92,42 +33,11 @@ export default class DiscoveryFilterNavigation extends Component {
</div>
{{/if}}
- <div class="topic-query-filter__input">
- {{icon "filter" class="topic-query-filter__icon"}}
- <Input
- class="topic-query-filter__filter-term"
- @value={{this.newQueryString}}
- {{on "keydown" this.handleKeydown}}
- @type="text"
- id="queryStringInput"
- autocomplete="off"
- placeholder={{i18n "filter.placeholder"}}
- {{didInsert this.storeInputElement}}
- />
- {{#if this.newQueryString}}
- <DButton
- @icon="xmark"
- @action={{this.clearInput}}
- @disabled={{unless this.newQueryString "true"}}
- class="topic-query-filter__clear-btn btn-flat"
- />
- {{/if}}
- {{! EXPERIMENTAL OUTLET - don't use because it will be removed soon }}
- <PluginOutlet
- @name="below-filter-input"
- @outletArgs={{lazyHash
- updateQueryString=this.updateQueryString
- newQueryString=this.newQueryString
- }}
- />
- <FilterTips
- @queryString={{this.newQueryString}}
- @onSelectTip={{this.updateQueryString}}
- @tips={{@tips}}
- @blockEnterSubmit={{this.blockEnterSubmit}}
- @inputElement={{this.inputElement}}
- />
- </div>
+ <FilterNavigationMenu
+ @onChange={{this.updateQueryString}}
+ @initialInputValue={{this.filterQueryString}}
+ @tips={{@tips}}
+ />
</div>
</section>
</template>
diff --git a/app/assets/javascripts/discourse/app/components/discovery/filter-tips.gjs b/app/assets/javascripts/discourse/app/components/discovery/filter-tips.gjs
deleted file mode 100644
index 81453f83af1..00000000000
--- a/app/assets/javascripts/discourse/app/components/discovery/filter-tips.gjs
+++ /dev/null
@@ -1,588 +0,0 @@
-import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
-import { fn } from "@ember/helper";
-import { action } from "@ember/object";
-import didInsert from "@ember/render-modifiers/modifiers/did-insert";
-import { cancel, later, next } from "@ember/runloop";
-import { service } from "@ember/service";
-import { and, eq } from "truth-helpers";
-import DButton from "discourse/components/d-button";
-import concatClass from "discourse/helpers/concat-class";
-import { ajax } from "discourse/lib/ajax";
-import discourseDebounce from "discourse/lib/debounce";
-import { i18n } from "discourse-i18n";
-
-const MAX_RESULTS = 20;
-
-export default class FilterTips extends Component {
- @service currentUser;
- @service site;
-
- @tracked showTips = false;
- @tracked currentInputValue = "";
- @tracked searchResults = [];
-
- activeFilter = null;
- searchTimer = null;
- handleBlurTimer = null;
-
- @tracked _selectedIndex = -1;
-
- willDestroy() {
- super.willDestroy(...arguments);
- if (this.searchTimer) {
- cancel(this.searchTimer);
- this.searchTimer = null;
- }
-
- if (this.handleBlurTimer) {
- cancel(this.handleBlurTimer);
- this.handleBlurTimer = null;
- }
- if (this.inputElement) {
- this.inputElement.removeEventListener("focus", this.handleInputFocus);
- this.inputElement.removeEventListener("blur", this.handleInputBlur);
- this.inputElement.removeEventListener("keydown", this.handleKeyDown);
- this.inputElement.removeEventListener("input", this.handleInput);
- }
- }
-
- get selectedIndex() {
- return this._selectedIndex;
- }
-
- set selectedIndex(value) {
- this._selectedIndex = value;
- this.args.blockEnterSubmit(value !== -1);
- }
-
- get currentItems() {
- return this.filteredTips;
- }
-
- get filteredTips() {
- if (!this.args.tips) {
- return [];
- }
-
- const words = this.currentInputValue.split(/\s+/);
- const lastWord = words.at(-1).toLowerCase();
-
- // If we have search results from placeholder search, show those
- if (this.activeFilter && this.searchResults.length > 0) {
- return this.searchResults;
- }
-
- // Check if we're in the middle of a filter with a value
- const colonIndex = lastWord.indexOf(":");
- const prefix = this.extractPrefix(lastWord) || "";
- if (colonIndex > 0) {
- const filterName = lastWord.substring(prefix.length).split(":")[0];
- const valueText = lastWord.substring(colonIndex + 1);
-
- // Find matching tip
- const tip = this.args.tips.find((t) => {
- return t.name === filterName + ":";
- });
-
- // If the tip has a type and we have value text, do placeholder search
- if (tip?.type && valueText !== undefined) {
- this.handlePlaceholderSearch(filterName, valueText, tip, prefix);
- return this.searchResults.length > 0 ? this.searchResults : [];
- }
- }
-
- // This handles blank, the default state when nothing is typed
- if (!this.currentInputValue || lastWord === "") {
- return this.args.tips
- .filter((tip) => tip.priority)
- .sort((a, b) => (b.priority || 0) - (a.priority || 0))
- .slice(0, MAX_RESULTS);
- }
-
- const tips = [];
-
- this.args.tips.forEach((tip) => {
- if (tips.length >= MAX_RESULTS) {
- return;
- }
- const tipName = tip.name;
- const searchTerm = lastWord.substring(prefix.length);
-
- // Skip exact matches with colon
- if (searchTerm.endsWith(":") && tipName === searchTerm) {
- return;
- }
-
- const prefixMatch =
- searchTerm === "" &&
- prefix &&
- tipName.prefixes &&
- tipName.prefixes.find((p) => p.name === prefix);
-
- if (prefixMatch || tipName.indexOf(searchTerm) > -1) {
- this.pushPrefixTips(tip, tips, null, prefix);
- if (!prefix) {
- tips.push(tip);
- }
- } else if (tip.alias && tip.alias.indexOf(searchTerm) > -1) {
- this.pushPrefixTips(tip, tips, tip.alias, prefix);
- tips.push({
- ...tip,
- name: tip.alias,
- });
- }
- });
-
- return tips.sort((a, b) => {
- const aName = a.name;
- const bName = b.name;
- const searchTerm = lastWord;
-
- const aStartsWith = aName.startsWith(searchTerm);
- const bStartsWith = bName.startsWith(searchTerm);
-
- if (aStartsWith && !bStartsWith) {
- return -1;
- }
- if (!aStartsWith && bStartsWith) {
- return 1;
- }
-
- if (aStartsWith && bStartsWith) {
- if (aName.length !== bName.length) {
- return aName.length - bName.length;
- }
- }
-
- return aName.localeCompare(bName);
- });
- }
-
- pushPrefixTips(tip, tips, alias = null, currentPrefix = null) {
- if (tip.prefixes && tip.prefixes.length > 0) {
- tip.prefixes.forEach((prefix) => {
- if (currentPrefix && !prefix.name.startsWith(currentPrefix)) {
- return;
- }
- tips.push({
- ...tip,
- name: `${prefix.name}${alias || tip.name}`,
- description: prefix.description || tip.description,
- isPlaceholderCompletion: true,
- });
- });
- }
- }
-
- extractPrefix(word) {
- const match = word.match(/^(-=|=-|-|=)/);
- return match ? match[0] : "";
- }
-
- @action
- handlePlaceholderSearch(filterName, valueText, tip, prefix = "") {
- this.activeFilter = filterName;
-
- if (this.searchTimer) {
- cancel(this.searchTimer);
- }
-
- this.searchTimer = discourseDebounce(
- this,
- this._performPlaceholderSearch,
- filterName,
- valueText,
- tip,
- prefix,
- 300
- );
- }
-
- async _performPlaceholderSearch(filterName, valueText, tip, prefix) {
- const type = tip.type;
- let lastTerm = valueText;
- let results = [];
-
- let prevTerms = "";
- let splitTerms;
-
- if (tip.delimiters) {
- const delimiters = tip.delimiters.map((s) => s.name);
- splitTerms = lastTerm.split(new RegExp(`[${delimiters.join("")}]`));
- lastTerm = splitTerms[splitTerms.length - 1];
- if (lastTerm === "") {
- prevTerms = valueText;
- } else {
- prevTerms = valueText.slice(0, -lastTerm.length);
- }
- }
-
- lastTerm = (lastTerm || "").toLowerCase().trim();
-
- if (type === "tag") {
- try {
- const response = await ajax("/tags/filter/search.json", {
- data: { q: lastTerm || "", limit: 5 },
- });
- results = response.results.map((tag) => ({
- name: `${prefix}${filterName}:${prevTerms}${tag.name}`,
- description: `${tag.count}`,
- isPlaceholderCompletion: true,
- term: tag.name,
- }));
- } catch {
- results = [];
- }
- } else if (type === "category") {
- const categories = this.site.categories || [];
- const filtered = categories
- .filter((c) => {
- const name = c.name.toLowerCase();
- const slug = c.slug.toLowerCase();
- return name.includes(lastTerm) || slug.includes(lastTerm);
- })
- .slice(0, 10)
- .map((c) => ({
- name: `${prefix}${filterName}:${prevTerms}${c.slug}`,
- description: `${c.name}`,
- isPlaceholderCompletion: true,
- term: c.slug,
- }));
- results = filtered;
- } else if (type === "username") {
- try {
- const data = {
- limit: 10,
- };
-
- if ((lastTerm || "").length > 0) {
- data.term = lastTerm;
- } else {
- data.last_seen_users = true;
- }
- const response = await ajax("/u/search/users.json", {
- data,
- });
- results = response.users.map((user) => ({
- name: `${prefix}${filterName}:${prevTerms}${user.username}`,
- description: user.name || "",
- term: user.username,
- isPlaceholderCompletion: true,
- }));
- } catch {
- results = [];
- }
- } else if (type === "tag_group") {
- // Handle tag group search if needed
- results = [];
- } else if (type === "date") {
- results = this.getDateSuggestions(
- prefix,
- filterName,
- prevTerms,
- lastTerm
- );
- } else if (type === "number") {
- results = this.getNumberSuggestions(
- prefix,
- filterName,
- prevTerms,
- lastTerm
- );
- }
-
- // special handling for exact matches
- if (tip.delimiters) {
- let lastMatches = false;
-
- results = results.map((r) => {
- r.delimiters = tip.delimiters;
- return r;
- });
-
- results = results.filter((r) => {
- lastMatches ||= lastTerm === r.term;
- if (splitTerms.includes(r.term)) {
- return false;
- }
- return true;
- });
-
- if (lastMatches) {
- tip.delimiters.forEach((delimiter) => {
- results.push({
- name: `${prefix}${filterName}:${prevTerms}${lastTerm}${delimiter.name}`,
- description: delimiter.description,
- isPlaceholderCompletion: true,
- delimiters: tip.delimiters,
- });
- });
- }
- }
-
- this.searchResults = results;
- }
-
- getDateSuggestions(prefix, filterName, prevTerms, lastTerm) {
- const dateOptions = [
- { value: "1", key: "yesterday" },
- { value: "7", key: "last_week" },
- { value: "30", key: "last_month" },
- { value: "365", key: "last_year" },
- ];
-
- return dateOptions
- .filter((option) => {
- const description = i18n(`filter.description.days.${option.key}`);
- return (
- !lastTerm ||
- option.value.includes(lastTerm) ||
- description.toLowerCase().includes(lastTerm.toLowerCase())
- );
- })
- .map((option) => ({
- name: `${prefix}${filterName}:${prevTerms}${option.value}`,
- description: i18n(`filter.description.${option.key}`),
- isPlaceholderCompletion: true,
- term: option.value,
- }));
- }
-
- getNumberSuggestions(prefix, filterName, prevTerms, lastTerm) {
- const numberOptions = [
- { value: "0" },
- { value: "1" },
- { value: "5" },
- { value: "10" },
- { value: "20" },
- ];
-
- return numberOptions
- .filter((option) => {
- return !lastTerm || option.value.includes(lastTerm);
- })
- .map((option) => ({
- name: `${prefix}${filterName}:${prevTerms}${option.value}`,
- isPlaceholderCompletion: true,
- term: option.value,
- }));
- }
-
- @action
- setupEventListeners() {
- this.inputElement = this.args.inputElement;
-
- if (!this.inputElement) {
- throw new Error(
- "FilterTips requires an inputElement to be passed in the args."
- );
- }
-
- this.inputElement.addEventListener("focus", this.handleInputFocus);
- this.inputElement.addEventListener("blur", this.handleInputBlur);
- this.inputElement.addEventListener("keydown", this.handleKeyDown);
- this.inputElement.addEventListener("input", this.handleInput);
- }
-
- @action
- handleInput() {
- this.currentInputValue = this.inputElement.value;
- this.updateResults();
- }
-
- updateResults() {
- this.selectedIndex = -1;
-
- const words = this.currentInputValue.split(/\s+/);
- const lastWord = words.at(-1);
- const colonIndex = lastWord.indexOf(":");
-
- if (colonIndex > 0) {
- const prefix = this.extractPrefix(lastWord);
- const filterName = lastWord.substring(
- prefix.length,
- colonIndex + prefix.length
- );
- const valueText = lastWord.substring(colonIndex + 1);
-
- const tip = this.args.tips.find((t) => {
- const tipFilterName = t.name.replace(/^[-=]/, "").split(":")[0];
- return tipFilterName === filterName && t.type;
- });
-
- if (tip?.type) {
- this.activeFilter = filterName;
- this.handlePlaceholderSearch(filterName, valueText, tip, prefix);
- } else {
- this.activeFilter = null;
- this.searchResults = [];
- }
- } else {
- this.activeFilter = null;
- this.searchResults = [];
- }
- }
-
- @action
- handleInputFocus() {
- this.currentInputValue = this.inputElement.value;
- this.showTips = true;
- this.selectedIndex = -1;
- }
-
- @action
- handleInputBlur() {
- if (this.handleBlurTimer) {
- cancel(this.handleBlurTimer);
- }
- // delay this cause we need to handle click events on tips
- this.handleBlurTimer = later(() => {
- this.hideTipsIfNeeded();
- }, 200);
- }
-
- hideTipsIfNeeded() {
- this.handleBlurTimer = null;
- if (document.activeElement !== this.inputElement && this.showTips) {
- this.hideTips();
- }
- }
-
- @action
- handleKeyDown(event) {
- if (!this.showTips || this.currentItems.length === 0) {
- return;
- }
-
- switch (event.key) {
- case "ArrowDown":
- event.preventDefault();
- if (this.selectedIndex === -1) {
- this.selectedIndex = 0;
- } else {
- this.selectedIndex =
- (this.selectedIndex + 1) % this.currentItems.length;
- }
- break;
- case "ArrowUp":
- event.preventDefault();
- if (this.selectedIndex === -1) {
- this.selectedIndex = this.currentItems.length - 1;
- } else {
- this.selectedIndex =
- (this.selectedIndex - 1 + this.currentItems.length) %
- this.currentItems.length;
- }
- break;
- case "Tab":
- event.preventDefault();
- event.stopPropagation();
- const indexToUse = this.selectedIndex === -1 ? 0 : this.selectedIndex;
- if (indexToUse < this.currentItems.length) {
- this.selectItem(this.currentItems[indexToUse]);
- }
- break;
- case "Enter":
- if (this.selectedIndex >= 0) {
- event.preventDefault();
- event.stopPropagation();
- event.stopImmediatePropagation();
- this.selectItem(this.currentItems[this.selectedIndex]);
- }
- break;
- case "Escape":
- this.hideTips();
- break;
- }
- }
-
- hideTips() {
- this.showTips = false;
- this.args.blockEnterSubmit(false);
- }
-
- @action
- selectItem(item) {
- const words = this.currentInputValue.split(/\s+/);
-
- if (item.isPlaceholderCompletion) {
- words[words.length - 1] = item.name;
- let updatedValue = words.join(" ");
-
- if (
- !updatedValue.endsWith(":") &&
- (!item.delimiters || item.delimiters.length < 2)
- ) {
- updatedValue += " ";
- }
-
- this.updateValue(updatedValue);
- this.searchResults = [];
- this.updateResults();
- } else {
- const lastWord = words.at(-1);
- const prefix = this.extractPrefix(lastWord);
-
- const supportsPrefix = item.prefixes && item.prefixes.length > 0;
- const filterName =
- supportsPrefix && prefix ? `${prefix}${item.name}` : item.name;
-
- words[words.length - 1] = filterName;
-
- if (!filterName.endsWith(":") && !item.delimiters?.length) {
- words[words.length - 1] += " ";
- }
-
- const updatedValue = words.join(" ");
- this.updateValue(updatedValue);
-
- const baseFilterName = item.name.replace(/^[-=]/, "").split(":")[0];
-
- if (item.type) {
- this.activeFilter = baseFilterName;
- this.handlePlaceholderSearch(baseFilterName, "", item, prefix);
- }
- }
-
- this.selectedIndex = -1;
-
- next(() => {
- this.inputElement.focus();
- this.inputElement.setSelectionRange(
- this.currentInputValue.length,
- this.currentInputValue.length
- );
- this.updateResults();
- });
- }
-
- updateValue(value) {
- this.currentInputValue = value;
- this.args.onSelectTip(value);
- }
-
- <template>
- <div class="filter-tips" {{didInsert this.setupEventListeners}}>
- {{#if (and this.showTips this.currentItems.length)}}
- <div class="filter-tips__dropdown">
- {{#each this.currentItems as |item index|}}
- <DButton
- class={{concatClass
- "filter-tip__button"
- (if (eq index this.selectedIndex) "filter-tip__selected")
- }}
- @action={{fn this.selectItem item}}
- >
- <span class="filter-tip__name">{{item.name}}</span>
- {{#if item.description}}
- <span class="filter-tip__description">—
- {{item.description}}</span>
- {{/if}}
- </DButton>
- {{/each}}
- </div>
- {{/if}}
- </div>
- </template>
-}
diff --git a/app/assets/javascripts/discourse/app/lib/filter-suggestions.js b/app/assets/javascripts/discourse/app/lib/filter-suggestions.js
new file mode 100644
index 00000000000..8587d293dae
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/filter-suggestions.js
@@ -0,0 +1,154 @@
+import { ajax } from "discourse/lib/ajax";
+import { i18n } from "discourse-i18n";
+
+export default class FilterSuggestions {
+ static async getFilterSuggestionsByType(
+ type,
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm,
+ deps = {}
+ ) {
+ switch (type) {
+ case "category":
+ return await FilterSuggestions.getCategorySuggestions(
+ deps.site,
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm
+ );
+ case "tag":
+ return await FilterSuggestions.getTagSuggestions(
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm
+ );
+ case "username":
+ return await FilterSuggestions.getUserSuggestions(
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm
+ );
+ case "date":
+ return await FilterSuggestions.getDateSuggestions(
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm
+ );
+ case "number":
+ return await FilterSuggestions.getNumberSuggestions(
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm
+ );
+ }
+ }
+
+ static async getTagSuggestions(prefix, filterName, prevTerms, lastTerm) {
+ try {
+ const response = await ajax("/tags/filter/search.json", {
+ data: { q: lastTerm || "", limit: 5 },
+ });
+ return response.results.map((tag) => ({
+ name: `${prefix}${filterName}:${prevTerms}${tag.name}`,
+ description: `${tag.count}`,
+ isSuggestion: true,
+ term: tag.name,
+ }));
+ } catch {
+ return [];
+ }
+ }
+
+ static async getUserSuggestions(prefix, filterName, prevTerms, lastTerm) {
+ try {
+ const data = { limit: 10 };
+ if ((lastTerm || "").length > 0) {
+ data.term = lastTerm;
+ } else {
+ data.last_seen_users = true;
+ }
+ const response = await ajax("/u/search/users.json", { data });
+ return response.users.map((user) => ({
+ name: `${prefix}${filterName}:${prevTerms}${user.username}`,
+ description: user.name || "",
+ term: user.username,
+ isSuggestion: true,
+ }));
+ } catch {
+ return [];
+ }
+ }
+
+ static async getCategorySuggestions(
+ site,
+ prefix,
+ filterName,
+ prevTerms,
+ lastTerm
+ ) {
+ const categories = site.categories || [];
+ return categories
+ .filter((category) => {
+ const name = category.name.toLowerCase();
+ const slug = category.slug.toLowerCase();
+ return name.includes(lastTerm) || slug.includes(lastTerm);
+ })
+ .slice(0, 10)
+ .map((category) => ({
+ name: `${prefix}${filterName}:${prevTerms}${category.slug}`,
+ description: `${category.name}`,
+ isSuggestion: true,
+ term: category.slug,
+ }));
+ }
+
+ static async getDateSuggestions(prefix, filterName, prevTerms, lastTerm) {
+ const dateOptions = [
+ { value: "1", key: "yesterday" },
+ { value: "7", key: "last_week" },
+ { value: "30", key: "last_month" },
+ { value: "365", key: "last_year" },
+ ];
+
+ return dateOptions
+ .filter((option) => {
+ const description = i18n(`filter.description.days.${option.key}`);
+ return (
+ !lastTerm ||
+ option.value.includes(lastTerm) ||
+ description.toLowerCase().includes(lastTerm.toLowerCase())
+ );
+ })
+ .map((option) => ({
+ name: `${prefix}${filterName}:${prevTerms}${option.value}`,
+ description: i18n(`filter.description.${option.key}`),
+ isSuggestion: true,
+ term: option.value,
+ }));
+ }
+
+ static async getNumberSuggestions(prefix, filterName, prevTerms, lastTerm) {
+ const numberOptions = [
+ { value: "0" },
+ { value: "1" },
+ { value: "5" },
+ { value: "10" },
+ { value: "20" },
+ ];
+
+ return numberOptions
+ .filter((option) => !lastTerm || option.value.includes(lastTerm))
+ .map((option) => ({
+ name: `${prefix}${filterName}:${prevTerms}${option.value}`,
+ isSuggestion: true,
+ term: option.value,
+ }));
+ }
+}
diff --git a/app/assets/javascripts/discourse/tests/integration/components/discovery/filter-navigation-menu-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/discovery/filter-navigation-menu-test.gjs
new file mode 100644
index 00000000000..f5521a025ac
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/discovery/filter-navigation-menu-test.gjs
@@ -0,0 +1,242 @@
+import {
+ fillIn,
+ render,
+ triggerEvent,
+ triggerKeyEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import FilterNavigationMenu from "discourse/components/discovery/filter-navigation-menu";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import DMenus from "float-kit/components/d-menus";
+
+module(
+ "Integration | Component | discovery | FilterNavigationMenu",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.tips = [
+ {
+ name: "category:",
+ description: "Filter category",
+ priority: 1,
+ type: "category",
+ },
+ {
+ name: "tag:",
+ description: "Filter tag",
+ priority: 1,
+ type: "tag",
+ delimiters: [
+ { name: "+", description: "intersect" },
+ { name: ",", description: "add" },
+ ],
+ },
+ { name: "status:", description: "Filter status", priority: 1 },
+ { name: "status:open", description: "Open topics" },
+ ];
+
+ this.query = "";
+ this.update = (val) => this.set("query", val);
+
+ this.site = this.owner.lookup("service:site");
+ this.site.categories = [
+ { id: 1, name: "Bug", slug: "bugs" },
+ { id: 2, name: "Feature", slug: "feature" },
+ ];
+
+ pretender.get("/tags/filter/search.json", () =>
+ response({ results: [{ name: "ember", count: 1 }] })
+ );
+ pretender.get("/u/search/users.json", () => response({ users: [] }));
+ });
+
+ test("keyboard navigation through tips", async function (assert) {
+ const self = this;
+
+ await render(
+ <template>
+ <FilterNavigationMenu
+ @tips={{self.tips}}
+ @initialFilterQueryString={{self.query}}
+ @onChange={{self.update}}
+ />
+ <DMenus />
+ </template>
+ );
+
+ await triggerEvent("#topic-query-filter-input", "focus");
+ assert
+ .dom(".filter-navigation__tip-button")
+ .exists({ count: 3 }, "tips appear");
+
+ await triggerKeyEvent(
+ "#topic-query-filter-input",
+ "keydown",
+ "ArrowDown"
+ );
+ assert
+ .dom(
+ ".filter-navigation__tip-button.--selected .filter-navigation__tip-name"
+ )
+ .hasText("category:");
+
+ await triggerKeyEvent(
+ "#topic-query-filter-input",
+ "keydown",
+ "ArrowDown"
+ );
+ assert
+ .dom(
+ ".filter-navigation__tip-button.--selected .filter-navigation__tip-name"
+ )
+ .hasText("tag:");
+
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "ArrowUp");
+ assert
+ .dom(
+ ".filter-navigation__tip-button.--selected .filter-navigation__tip-name"
+ )
+ .hasText("category:");
+ });
+
+ test("selecting a tip with Tab", async function (assert) {
+ const self = this;
+
+ await render(
+ <template>
+ <FilterNavigationMenu
+ @tips={{self.tips}}
+ @initialFilterQueryString={{self.query}}
+ @onChange={{self.update}}
+ />
+
+ <DMenus />
+ </template>
+ );
+
+ await triggerEvent("#topic-query-filter-input", "focus");
+ await triggerKeyEvent(
+ "#topic-query-filter-input",
+ "keydown",
+ "ArrowDown"
+ );
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Tab");
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Enter");
+
+ assert.strictEqual(this.query, "category:", "category filter added");
+
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Tab");
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Enter");
+ assert
+ .dom("#topic-query-filter-input")
+ .hasValue("category:bugs ", "category value selected");
+ });
+
+ test("searching tag values", async function (assert) {
+ const self = this;
+ await render(
+ <template>
+ <FilterNavigationMenu
+ @tips={{self.tips}}
+ @initialFilterQueryString={{self.query}}
+ @onChange={{self.update}}
+ />
+ <DMenus />
+ </template>
+ );
+
+ await triggerEvent("#topic-query-filter-input", "focus");
+ await fillIn("#topic-query-filter-input", "tag:e");
+
+ // IDK why this is needed, the same thing works if you do it manually in the UI.
+ await triggerEvent("#topic-query-filter-input", "blur");
+ await triggerEvent("#topic-query-filter-input", "focus");
+
+ assert
+ .dom(".filter-navigation__tip-button")
+ .exists("tag search results shown");
+
+ await triggerKeyEvent(
+ "#topic-query-filter-input",
+ "keydown",
+ "ArrowDown"
+ );
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Enter");
+
+ assert.strictEqual(this.query, "tag:ember", "tag result selected");
+ });
+
+ test("escape hides suggestions", async function (assert) {
+ const self = this;
+ await render(
+ <template>
+ <FilterNavigationMenu
+ @tips={{self.tips}}
+ @initialFilterQueryString={{self.query}}
+ @onChange={{self.update}}
+ />
+ <DMenus />
+ </template>
+ );
+
+ await triggerEvent("#topic-query-filter-input", "focus");
+ assert
+ .dom(".filter-navigation__tip-button")
+ .exists({ count: 3 }, "tips visible after focus");
+
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Escape");
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Escape");
+ assert
+ .dom(".filter-navigation__tip-button")
+ .doesNotExist("tips hidden after escape");
+ });
+
+ test("prefix support for categories", async function (assert) {
+ const self = this;
+ this.tips = [
+ {
+ name: "category:",
+ description: "Filter category",
+ priority: 1,
+ type: "category",
+ prefixes: [
+ { name: "-", description: "Exclude category" },
+ { name: "=", description: "Category without subcategories" },
+ ],
+ },
+ ];
+
+ await render(
+ <template>
+ <FilterNavigationMenu
+ @tips={{self.tips}}
+ @initialFilterQueryString={{self.query}}
+ @onChange={{self.update}}
+ />
+ <DMenus />
+ </template>
+ );
+
+ await triggerEvent("#topic-query-filter-input", "focus");
+ await fillIn("#topic-query-filter-input", "cat");
+
+ await triggerKeyEvent(
+ "#topic-query-filter-input",
+ "keydown",
+ "ArrowDown"
+ );
+ await triggerKeyEvent(
+ "#topic-query-filter-input",
+ "keydown",
+ "ArrowDown"
+ );
+ await triggerKeyEvent("#topic-query-filter-input", "keydown", "Tab");
+
+ assert
+ .dom("#topic-query-filter-input")
+ .hasValue("-category:", "negative prefix applied");
+ });
+ }
+);
diff --git a/app/assets/javascripts/discourse/tests/integration/components/discovery/filter-tips-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/discovery/filter-tips-test.gjs
deleted file mode 100644
index 42fe4332a88..00000000000
--- a/app/assets/javascripts/discourse/tests/integration/components/discovery/filter-tips-test.gjs
+++ /dev/null
@@ -1,346 +0,0 @@
-import didInsert from "@ember/render-modifiers/modifiers/did-insert";
-import {
- fillIn,
- render,
- triggerEvent,
- triggerKeyEvent,
-} from "@ember/test-helpers";
-import { module, test } from "qunit";
-import FilterTips from "discourse/components/discovery/filter-tips";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import pretender, { response } from "discourse/tests/helpers/create-pretender";
-
-module("Integration | Component | discovery | filter-tips", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.tips = [
- {
- name: "category:",
- description: "Filter category",
- priority: 1,
- type: "category",
- },
- {
- name: "tag:",
- description: "Filter tag",
- priority: 1,
- type: "tag",
- delimiters: [
- { name: "+", description: "intersect" },
- { name: ",", description: "add" },
- ],
- },
- { name: "status:", description: "Filter status", priority: 1 },
- { name: "status:open", description: "Open topics" },
- ];
- this.query = "";
- this.update = (value) => {
- this.set("query", value);
- this.inputElement.value = value;
- };
- this.blockEnter = () => {};
- this.capture = (el) => (this.inputElement = el);
-
- this.site.categories = [
- { id: 1, name: "Bug", slug: "bugs" },
- { id: 2, name: "Feature", slug: "feature" },
- ];
- pretender.get("/tags/filter/search.json", () =>
- response({ results: [{ name: "ember", count: 1 }] })
- );
- pretender.get("/u/search/users", () => response({ users: [] }));
- });
-
- test("basic navigation", async function (assert) {
- const self = this;
- await render(
- <template>
- <input id="filter-input" {{didInsert self.capture}} />
- <FilterTips
- @tips={{self.tips}}
- @queryString={{self.query}}
- @onSelectTip={{self.update}}
- @blockEnterSubmit={{self.blockEnter}}
- @inputElement={{self.inputElement}}
- />
- </template>
- );
-
- await triggerEvent("#filter-input", "focus");
- assert
- .dom(".filter-tip__button")
- .exists({ count: 3 }, "shows tips on focus");
- assert
- .dom(".filter-tip__button.filter-tip__selected")
- .doesNotExist("no selection yet");
- assert.dom("#filter-input").hasValue("");
-
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- assert
- .dom(".filter-tip__button.filter-tip__selected .filter-tip__name")
- .hasText("category:");
-
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- assert
- .dom(".filter-tip__button.filter-tip__selected .filter-tip__name")
- .hasText("tag:");
-
- await triggerKeyEvent("#filter-input", "keydown", "ArrowUp");
- assert
- .dom(".filter-tip__button.filter-tip__selected .filter-tip__name")
- .hasText("category:");
- });
-
- test("selecting a tip with tab", async function (assert) {
- const self = this;
- await render(
- <template>
- <input id="filter-input" {{didInsert self.capture}} />
- <FilterTips
- @tips={{self.tips}}
- @queryString={{self.query}}
- @onSelectTip={{self.update}}
- @blockEnterSubmit={{self.blockEnter}}
- @inputElement={{self.inputElement}}
- />
- </template>
- );
-
- await triggerEvent("#filter-input", "focus");
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- await triggerKeyEvent("#filter-input", "keydown", "Tab");
-
- assert.strictEqual(this.query, "category:", "tab adds filter");
- assert.dom("#filter-input").hasValue("category:");
-
- assert
- .dom(".filter-tip__button")
- .exists({ count: 2 }, "tips for category shows up");
-
- await triggerEvent("#filter-input", "focus");
- await triggerKeyEvent("#filter-input", "keydown", "Tab");
-
- assert
- .dom("#filter-input")
- .hasValue("category:bugs ", "category slug added");
-
- assert
- .dom(".filter-tip__button")
- .exists({ count: 3 }, "tips for next section shows up");
- assert
- .dom(".filter-tip__button.selected")
- .doesNotExist("selection cleared");
- });
-
- test("searching tag values", async function (assert) {
- const self = this;
- await render(
- <template>
- <input id="filter-input" {{didInsert self.capture}} />
- <FilterTips
- @tips={{self.tips}}
- @queryString={{self.query}}
- @onSelectTip={{self.update}}
- @blockEnterSubmit={{self.blockEnter}}
- @inputElement={{self.inputElement}}
- />
- </template>
- );
-
- await triggerEvent("#filter-input", "focus");
- await fillIn("#filter-input", "tag:e");
-
- assert.dom(".filter-tip__button").exists("shows tag results");
- assert.dom(".filter-tip__name").hasText("tag:ember");
- assert.dom(".filter-tip__description").hasText("— 1");
-
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- assert
- .dom(".filter-tip__button.filter-tip__selected .filter-tip__name")
- .hasText("tag:ember");
-
- await triggerKeyEvent("#filter-input", "keydown", "Enter");
- assert.strictEqual(this.query, "tag:ember", "enter selects result");
- });
-
- test("escape hides suggestions", async function (assert) {
- const self = this;
- await render(
- <template>
- <input id="filter-input" {{didInsert self.capture}} />
- <FilterTips
- @tips={{self.tips}}
- @queryString={{self.query}}
- @onSelectTip={{self.update}}
- @blockEnterSubmit={{self.blockEnter}}
- @inputElement={{self.inputElement}}
- />
- </template>
- );
-
- await triggerEvent("#filter-input", "focus");
- assert.dom(".filter-tip__button").exists("tips visible");
- await triggerKeyEvent("#filter-input", "keydown", "Escape");
- assert.dom(".filter-tip__button").doesNotExist("tips hidden on escape");
-
- await fillIn("#filter-input", "status");
- await triggerEvent("#filter-input", "input");
- await triggerKeyEvent("#filter-input", "keydown", "Escape");
- assert.strictEqual(this.query, "", "query not changed");
- assert.dom("#filter-input").hasValue("status", "input unchanged");
- assert.dom(".filter-tip__button").doesNotExist("tips remain hidden");
- });
-
- test("blockEnterSubmit is called correctly", async function (assert) {
- let blockEnterCalled = false;
- let blockEnterValue = null;
-
- this.blockEnter = (shouldBlock) => {
- blockEnterCalled = true;
- blockEnterValue = shouldBlock;
- };
-
- let self = this;
-
- await render(
- <template>
- <input id="filter-input" {{didInsert self.capture}} />
- <FilterTips
- @tips={{self.tips}}
- @queryString={{self.query}}
- @onSelectTip={{self.update}}
- @blockEnterSubmit={{self.blockEnter}}
- @inputElement={{self.inputElement}}
- />
- </template>
- );
-
- // Initially, no selection, so blockEnter should be called with false
- await triggerEvent("#filter-input", "focus");
- assert.true(blockEnterCalled, "blockEnter was called");
- assert.false(
- blockEnterValue,
- "blockEnter called with false when no selection"
- );
-
- // Reset tracking
- blockEnterCalled = false;
- blockEnterValue = null;
-
- // Arrow down to select first item
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- assert.true(blockEnterCalled, "blockEnter called when selection changes");
- assert.true(
- blockEnterValue,
- "blockEnter called with true when item selected"
- );
-
- // Reset and arrow up to wrap to last item
- blockEnterCalled = false;
- await triggerKeyEvent("#filter-input", "keydown", "ArrowUp");
- await triggerKeyEvent("#filter-input", "keydown", "ArrowUp");
- assert.true(blockEnterCalled, "blockEnter called on arrow navigation");
- assert.true(blockEnterValue, "blockEnter still true with selection");
-
- // Select an item with Tab
- await triggerKeyEvent("#filter-input", "keydown", "Tab");
- assert.true(blockEnterCalled, "blockEnter called after selection");
- assert.false(
- blockEnterValue,
- "blockEnter called with false after selecting"
- );
-
- // Type to trigger search for tag values
- await fillIn("#filter-input", "tag:e");
- assert.true(blockEnterCalled, "blockEnter called when typing");
- assert.false(blockEnterValue, "blockEnter false when typing");
-
- // Select a search result
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- assert.true(blockEnterValue, "blockEnter true when search result selected");
-
- // Escape to clear
- await triggerKeyEvent("#filter-input", "keydown", "Escape");
- assert.false(blockEnterValue, "blockEnter false after escape");
- });
-
- test("prefix support for categories", async function (assert) {
- // Add prefix data to tips
- this.tips = [
- {
- name: "category:",
- description: "Filter category",
- priority: 1,
- type: "category",
- prefixes: [
- { name: "-", description: "Exclude category" },
- { name: "=", description: "Category without subcategories" },
- ],
- },
- { name: "tag:", description: "Filter tag", priority: 1, type: "tag" },
- ];
-
- const self = this;
- await render(
- <template>
- <input id="filter-input" {{didInsert self.capture}} />
- <FilterTips
- @tips={{self.tips}}
- @queryString={{self.query}}
- @onSelectTip={{self.update}}
- @blockEnterSubmit={{self.blockEnter}}
- @inputElement={{self.inputElement}}
- />
- </template>
- );
-
- await triggerEvent("#filter-input", "focus");
- await fillIn("#filter-input", "cat");
-
- const buttons = document.querySelectorAll(".filter-tip__button");
- const lastButton = buttons[buttons.length - 1];
-
- assert.dom(lastButton).exists("shows filtered results");
- assert
- .dom(lastButton.querySelector(".filter-tip__name"))
- .hasText("=category:");
- assert
- .dom(lastButton.querySelector(".filter-tip__description"))
- .includesText("without", "shows prefix description");
-
- // we skip the "category" and go to negative prefix
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- await triggerKeyEvent("#filter-input", "keydown", "Tab");
-
- assert.strictEqual(this.query, "-category:", "prefix included in query");
- assert.dom("#filter-input").hasValue("-category:");
-
- assert
- .dom(".filter-tip__button")
- .exists({ count: 2 }, "shows category options after prefix");
- assert
- .dom(".filter-tip__button:first-child .filter-tip__name")
- .hasText("-category:bugs", "shows category slug");
-
- // Select a category
- await triggerKeyEvent("#filter-input", "keydown", "Tab");
- assert
- .dom("#filter-input")
- .hasValue("-category:bugs ", "full filter with prefix applied");
-
- // Test with equals prefix
- await fillIn("#filter-input", "=cat");
- assert
- .dom(".filter-tip__description")
- .includesText(
- "Category without subcategories",
- "shows = prefix description"
- );
-
- await triggerKeyEvent("#filter-input", "keydown", "ArrowDown");
- await triggerKeyEvent("#filter-input", "keydown", "Tab");
- assert.strictEqual(this.query, "=category:", "equals prefix included");
- });
-});
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index 72dfd9860ff..3cd27553863 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -69,7 +69,7 @@
@import "notifications-tracking";
@import "emoji-picker";
@import "filter-input";
-@import "filter-tips";
+@import "filter-navigation";
@import "dropdown-menu";
@import "welcome-banner";
@import "d-multi-select";
diff --git a/app/assets/stylesheets/common/components/filter-navigation.scss b/app/assets/stylesheets/common/components/filter-navigation.scss
new file mode 100644
index 00000000000..f828484b290
--- /dev/null
+++ b/app/assets/stylesheets/common/components/filter-navigation.scss
@@ -0,0 +1,42 @@
+.fk-d-menu[data-identifier="filter-navigation-menu-list"] {
+ max-height: 300px;
+
+ .fk-d-menu__inner-content {
+ width: 100%;
+
+ .dropdown-menu {
+ width: 100%;
+ }
+
+ .dropdown-menu-item {
+ width: 100%;
+ }
+
+ .filter-navigation__tip-button {
+ display: block;
+ width: 100%;
+ text-align: left;
+ padding: 0.5em 1em;
+ border: none;
+ background: transparent;
+ cursor: pointer;
+ font-size: var(--font-down-1);
+ color: var(--primary);
+ transition: background-color 0.15s;
+
+ &:hover,
+ &.--selected {
+ background-color: var(--d-hover);
+ }
+
+ .filter-navigation__tip-name {
+ font-weight: 600;
+ color: var(--primary);
+ }
+
+ .filter-navigation__tip-description {
+ color: var(--primary-high);
+ }
+ }
+ }
+}
diff --git a/app/assets/stylesheets/common/components/filter-tips.scss b/app/assets/stylesheets/common/components/filter-tips.scss
deleted file mode 100644
index 3015c037db6..00000000000
--- a/app/assets/stylesheets/common/components/filter-tips.scss
+++ /dev/null
@@ -1,50 +0,0 @@
-.filter-tips {
- position: relative;
-
- &__dropdown {
- position: absolute;
- top: 100%;
- left: 0;
- right: 0;
- background: var(--secondary);
- border: 1px solid var(--primary-low);
- border-radius: var(--d-border-radius);
- box-shadow: var(--shadow-dropdown);
- z-index: z("dropdown") + 1;
- margin-top: 0.25em;
- max-height: 300px;
- overflow-y: auto;
-
- .filter-tip__button {
- display: block;
- width: 100%;
- text-align: left;
- padding: 0.5em 1em;
- border: none;
- background: transparent;
- cursor: pointer;
- font-size: var(--font-down-1);
- color: var(--primary);
- transition: background-color 0.15s;
-
- &:hover,
- &.filter-tip__selected {
- background-color: var(--tertiary-low);
- }
-
- &.filter-tip__selected {
- outline: 2px solid var(--tertiary);
- outline-offset: -2px;
- }
-
- .filter-tip__name {
- font-weight: 600;
- color: var(--primary);
- }
-
- .filter-tip__description {
- color: var(--primary-high);
- }
- }
- }
-}
diff --git a/spec/system/filtering_topics_spec.rb b/spec/system/filtering_topics_spec.rb
index 99675fe234e..011b6ebf3cd 100644
--- a/spec/system/filtering_topics_spec.rb
+++ b/spec/system/filtering_topics_spec.rb
@@ -92,14 +92,14 @@ describe "Filtering topics", type: :system do
expect(topic_list).to have_topic(topic_with_tag2)
expect(topic_list).to have_topic(topic_with_tag_and_tag2)
- topic_query_filter.fill_in("tags:tag1")
+ topic_query_filter.fill_in("tag:tag1")
expect(topic_list).to have_topics(count: 2)
expect(topic_list).to have_topic(topic_with_tag)
expect(topic_list).to have_topic(topic_with_tag_and_tag2)
expect(topic_list).to have_no_topic(topic_with_tag2)
- topic_query_filter.fill_in("tags:tag1+tag2")
+ topic_query_filter.fill_in("tag:tag1+tag2")
expect(topic_list).to have_topics(count: 1)
expect(topic_list).to have_no_topic(topic_with_tag)
diff --git a/spec/system/page_objects/components/topic_query_filter.rb b/spec/system/page_objects/components/topic_query_filter.rb
index 46780658ce1..538133f573a 100644
--- a/spec/system/page_objects/components/topic_query_filter.rb
+++ b/spec/system/page_objects/components/topic_query_filter.rb
@@ -4,7 +4,8 @@ module PageObjects
module Components
class TopicQueryFilter < PageObjects::Components::Base
def fill_in(text)
- page.fill_in(class: "topic-query-filter__filter-term", with: "#{text}\n")
+ page.find(".topic-query-filter__filter-term").fill_in(with: "#{text}\n")
+ page.send_keys(:enter)
end
def has_input_text?(text)