A platform for community discussion. Free, open, simple.
FIX: Load categories for edit navigation menu modal in hierarchical order (#36927)
Alan Guo Xiang Tan305b605c694c
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 0f06408d43d..8e2361a7e79 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -337,62 +337,20 @@ class CategoriesController < ApplicationControllerdef hierarchical_searchterm = params[:term].to_s.strippage = [1, params[:page].to_i].max- offset = params[:offset].to_i- parent_category_id = params[:parent_category_id].to_i if params[:parent_category_id].present?- only =- if params[:only].present?- Category.secured(guardian).where(id: params[:only].to_a.map(&:to_i))- else- Category.secured(guardian)- end- except_ids = params[:except].to_a.map(&:to_i)- include_uncategorized =- (- if params[:include_uncategorized].present?- ActiveModel::Type::Boolean.new.cast(params[:include_uncategorized])- else- true- end- )-- except_ids << SiteSetting.uncategorized_category_id unless include_uncategorized-- except = Category.where(id: except_ids) if except_ids.present?-- limit =- (- if params[:limit].present?- params[:limit].to_i.clamp(1, MAX_CATEGORIES_LIMIT)- else- MAX_CATEGORIES_LIMIT- end- )+ only_ids = params[:only].map(&:to_i) if params[:only].present?+ except_ids = params[:except].map(&:to_i) if params[:except].present?categories =- Category- .secured(guardian)- .limited_categories_matching(only, except, parent_category_id, term)- .preload(- :uploaded_logo,- :uploaded_logo_dark,- :uploaded_background,- :uploaded_background_dark,- :tags,- :tag_groups,- :form_templates,- category_required_tag_groups: :tag_group,- )- .joins("LEFT JOIN topics t on t.id = categories.topic_id")- .select("categories.*, t.slug topic_slug")- .limit(limit)- .offset((page - 1) * limit + offset)- .to_a-- if Site.preloaded_category_custom_fields.present?- Category.preload_custom_fields(categories, Site.preloaded_category_custom_fields)- end-- Category.preload_user_fields!(guardian, categories)+ CategoryHierarchicalSearch.call(+ guardian: guardian,+ params: {+ term:,+ only_ids:,+ except_ids:,+ limit: MAX_CATEGORIES_LIMIT,+ offset: (page - 1) * MAX_CATEGORIES_LIMIT,+ },+ ).categoriesresponse = { categories: serialize_data(categories, SiteCategorySerializer, scope: guardian) }diff --git a/app/models/category.rb b/app/models/category.rbindex 335889cf049..a6ae9102031 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -292,130 +292,6 @@ class Category < ActiveRecord::Basewhere(id: ancestor_ids)end- # Perform a search. If a category exists in the result, its ancestors do too.- # Also check for prefix matches. If a category has a prefix match, its- # ancestors report a match too.- scope :tree_search,- ->(only, except, term) do- term = term.strip- escaped_term = ActiveRecord::Base.connection.quote(term.downcase)- prefix_match = "starts_with(LOWER(categories.name), #{escaped_term})"-- word_match = <<~SQL- COALESCE(- (- SELECT BOOL_AND(position(pattern IN LOWER(categories.name)) <> 0)- FROM unnest(regexp_split_to_array(#{escaped_term}, '\s+')) AS pattern- ),- true- )- SQL-- if except- prefix_match =- "NOT categories.id IN (#{except.reselect(:id).to_sql}) AND #{prefix_match}"- word_match = "NOT categories.id IN (#{except.reselect(:id).to_sql}) AND #{word_match}"- end-- if only- prefix_match = "categories.id IN (#{only.reselect(:id).to_sql}) AND #{prefix_match}"- word_match = "categories.id IN (#{only.reselect(:id).to_sql}) AND #{word_match}"- end-- categories =- Category.select(- "categories.*",- "#{prefix_match} AS has_prefix_match",- "#{word_match} AS has_word_match",- )-- (1...SiteSetting.max_category_nesting).each do- categories = Category.from("(#{categories.to_sql}) AS categories")-- subcategory_matches =- categories- .where.not(parent_category_id: nil)- .group("categories.parent_category_id")- .select(- "categories.parent_category_id AS id",- "BOOL_OR(categories.has_prefix_match) AS has_prefix_match",- "BOOL_OR(categories.has_word_match) AS has_word_match",- )-- categories =- Category.joins(- "LEFT JOIN (#{subcategory_matches.to_sql}) AS subcategory_matches ON categories.id = subcategory_matches.id",- ).select(- "categories.*",- "#{prefix_match} OR COALESCE(subcategory_matches.has_prefix_match, false) AS has_prefix_match",- "#{word_match} OR COALESCE(subcategory_matches.has_word_match, false) AS has_word_match",- )- end-- categories =- Category.from("(#{categories.to_sql}) AS categories").where(has_word_match: true)-- categories.select("has_prefix_match AS matches", :id)- end-- # Given a relation, 'matches', which contains category ids and a 'matches'- # boolean, and a limit (the maximum number of subcategories per category),- # produce a subset of the matches categories annotated with information about- # their ancestors.- scope :select_descendants,- ->(matches, limit) do- max_nesting = SiteSetting.max_category_nesting-- categories =- joins("INNER JOIN (#{matches.to_sql}) AS matches ON matches.id = categories.id").select(- "categories.id",- "categories.name",- "ARRAY[]::record[] AS ancestors",- "0 AS depth",- "matches.matches",- )-- categories = Category.from("(#{categories.to_sql}) AS c1")-- (1...max_nesting).each { |i| categories = categories.joins(<<~SQL) }- INNER JOIN LATERAL (- (SELECT c#{i}.id, c#{i}.name, c#{i}.ancestors, c#{i}.depth, c#{i}.matches)- UNION ALL- (SELECT- categories.id,- categories.name,- c#{i}.ancestors || ARRAY[ROW(NOT c#{i}.matches, c#{i}.name)] AS ancestors,- c#{i}.depth + 1 as depth,- matches.matches- FROM categories- INNER JOIN matches- ON matches.id = categories.id- WHERE categories.parent_category_id = c#{i}.id- AND c#{i}.depth = #{i - 1}- ORDER BY (NOT matches.matches, categories.name)- LIMIT #{limit})- ) c#{i + 1} ON true- SQL-- categories.select(- "c#{max_nesting}.id",- "c#{max_nesting}.ancestors",- "c#{max_nesting}.name",- "c#{max_nesting}.matches",- )- end-- scope :limited_categories_matching,- ->(only, except, parent_id, term) do- joins(<<~SQL).order("c.ancestors || ARRAY[ROW(NOT c.matches, c.name)]")- INNER JOIN (- WITH matches AS (#{Category.tree_search(only, except, term).to_sql})- #{Category.where(parent_category_id: parent_id).select_descendants(Category.from("matches").select(:matches, :id), 5).to_sql}- ) AS c- ON categories.id = c.id- SQL- end-def self.topic_id_cache@topic_id_cache ||= DistributedCache.new("category_topic_ids")enddiff --git a/app/services/category_hierarchical_search.rb b/app/services/category_hierarchical_search.rbnew file mode 100644index 00000000000..e2c0c4ead32--- /dev/null+++ b/app/services/category_hierarchical_search.rb@@ -0,0 +1,146 @@+# frozen_string_literal: true++class CategoryHierarchicalSearch+ include Service::Base++ params do+ attribute :term, :string, default: ""+ attribute :only_ids, :array, default: [], compact_blank: true+ attribute :except_ids, :array, default: [], compact_blank: true+ attribute :limit, :integer+ attribute :offset, :integer++ after_validation { self.term = term.to_s.strip }+ end++ model :categories, optional: true+ step :eager_load_associations++ private++ def fetch_categories(guardian:, params:)+ query_params = { offset: params.offset, limit: params.limit, term: params.term }+ query_params[:only_ids] = params.only_ids if params.only_ids.present?+ query_params[:except_ids] = params.except_ids if params.except_ids.present?++ allowed_categories_sql =+ Category+ .secured(guardian)+ .select(:id, :name, :parent_category_id)+ .where("id <> ?", SiteSetting.uncategorized_category_id)+ .to_sql++ matches_sql =+ if query_params[:term].present?+ <<~SQL+ (+ starts_with(LOWER(name), LOWER(:term))+ OR COALESCE(+ (+ SELECT BOOL_AND(position(pattern IN LOWER(allowed_categories.name)) <> 0)+ FROM unnest(regexp_split_to_array(LOWER(:term), '\\s+')) AS pattern+ ),+ true+ )+ )+ SQL+ else+ "TRUE"+ end++ only_ids_sql =+ if query_params[:only_ids].present?+ "AND allowed_categories.id IN (:only_ids)"+ else+ ""+ end++ except_ids_sql =+ if query_params[:except_ids].present?+ "AND allowed_categories.id NOT IN (:except_ids)"+ else+ ""+ end++ # Note that we are setting the `allowed_categories` CTE as `NOT MATERIALIZED` since materializing the CTE degrades+ # performance of the query significantly on sites with a large number of rows in the categories table+ sql = <<~SQL+ WITH RECURSIVE+ allowed_categories AS NOT MATERIALIZED (+ #{allowed_categories_sql}+ ),+ matched AS (+ SELECT id+ FROM allowed_categories+ WHERE+ #{matches_sql}+ #{only_ids_sql}+ #{except_ids_sql}+ ),+ matched_with_ancestors AS (+ SELECT c.id, c.parent_category_id+ FROM allowed_categories c+ JOIN matched m ON m.id = c.id++ UNION ALL++ SELECT p.id, p.parent_category_id+ FROM allowed_categories p+ JOIN matched_with_ancestors a ON a.parent_category_id = p.id+ ),+ category_tree AS (+ SELECT+ c.id,+ c.parent_category_id,+ c.name,+ ARRAY[lower(c.name)]::text[] AS name_path,+ 0 AS depth+ FROM allowed_categories c+ WHERE c.parent_category_id IS NULL++ UNION ALL++ SELECT+ c.id,+ c.parent_category_id,+ c.name,+ ct.name_path || lower(c.name),+ ct.depth + 1+ FROM allowed_categories c+ JOIN category_tree ct ON c.parent_category_id = ct.id+ )+ SELECT+ categories.*+ FROM category_tree ct+ INNER JOIN categories ON categories.id = ct.id+ INNER JOIN (SELECT DISTINCT id FROM matched_with_ancestors) a ON a.id = ct.id+ ORDER BY ct.name_path, ct.id+ #{params.limit.present? ? "LIMIT :limit" : ""}+ #{params.offset.present? ? "OFFSET :offset" : ""}+ SQL++ Category.find_by_sql([sql, query_params])+ end++ def eager_load_associations+ ActiveRecord::Associations::Preloader.new(+ records: context.categories,+ associations: [+ :uploaded_logo,+ :uploaded_logo_dark,+ :uploaded_background,+ :uploaded_background_dark,+ :tags,+ :tag_groups,+ :form_templates,+ { category_required_tag_groups: :tag_group },+ ],+ ).call++ if Site.preloaded_category_custom_fields.present?+ Category.preload_custom_fields(context.categories, Site.preloaded_category_custom_fields)+ end++ Category.preload_user_fields!(context.guardian, context.categories)+ end+enddiff --git a/frontend/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjs b/frontend/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjsindex 2588cd824b4..8ab1af4d9a5 100644--- a/frontend/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjs+++ b/frontend/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjs@@ -6,7 +6,6 @@ import { action } from "@ember/object";import didInsert from "@ember/render-modifiers/modifiers/did-insert";import { service } from "@ember/service";import { TrackedSet } from "@ember-compat/tracked-built-ins";-import DButton from "discourse/components/d-button";import EditNavigationMenuModal from "discourse/components/sidebar/edit-navigation-menu/modal";import borderColor from "discourse/helpers/border-color";import categoryBadge from "discourse/helpers/category-badge";@@ -18,53 +17,9 @@ import discourseDebounce from "discourse/lib/debounce";import { INPUT_DELAY } from "discourse/lib/environment";import { serializedAction, splitWhere } from "discourse/lib/utilities";import Category from "discourse/models/category";-import { eq, gt, has } from "discourse/truth-helpers";+import { gt, has } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";-// This modal is used to display a deep category tree (categories →-// subcategories → sub-subcategories) but only load 5 items at a time for-// performance, so there are some contortions we have to perform to load the-// categories in the correct place.-//-// The key properties are:-//-// - fetchedCategories - Flat array of all loaded categories, stored in-// hierarchical order (parents before children)-// - partialCategoryInfos - Map tracking which parents have exactly 5 children-// (meaning "might have more to load")-//-// The overall algorithm is:-//-// 1. Initial Load: Fetch first 5 categories from server in hierarchical order-// - Example:-// - grandparent-// - parent1-// - child1-// - child2-// - child3-// - parent2-// - parent3-// - ...-//-// 2. Detect partially loaded categories (findPartialCategories):-// - Count how many children each category has-// - If there are exactly 5, mark as "partial" (might have more since 5 is the page size)-// - Store the parent's ID and offset (how many to skip when loading more)-//-// 3. Display with buttons (recomputeGroupings):-// - Loop through fetchedCategories-// - Insert "Show more" button after the last child of any partial parent-// - Button contains parent ID, level, and offset-//-// 4. Click "Show more":-// - Call backend to get more children of parent X, starting at offset Y-// - Backend returns next batch (e.g., [child6, child7, ...])-//-// 5. Insert new categories (substituteInFetchedCategories):-// - Find where the last child of that parent is-// - Scan past any descendants (grandchildren, etc.)-// - Insert new categories after all existing descendants-// - Recalculate which parents are still partialexport default class SidebarEditNavigationMenuCategoriesModal extends Component {@service currentUser;@service siteSettings;@@ -79,7 +34,6 @@ export default class SidebarEditNavigationMenuCategoriesModal extends ComponentselectedFilter = "";selectedMode = "everything";fetchedCategories;- partialCategoryInfos;loadedFilter;loadedMode;loadedPage;@@ -100,246 +54,26 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Componentconstructor() {super(...arguments);- this.subcategoryLoadList = [];this.performSearch();}recomputeGroupings() {- const categoriesWithShowMores = this.fetchedCategories.flatMap((el, i) => {- const result = [{ type: "category", category: el }];-- const elID = el.id;- const elParentID = el.parent_category_id;- const nextCategory = this.fetchedCategories[i + 1];- const nextParentID = nextCategory?.parent_category_id;-- const nextIsSibling = nextParentID === elParentID;- const nextIsChild = nextParentID === elID;-- if (!nextIsSibling && !nextIsChild) {- // When leaving a subtree, check all ancestor levels to see if any need- // a "Show more" button. This handles cases where the last sibling has- // descendants - we need to show the parent's button after those descendants.- const categoriesById = new Map(- this.fetchedCategories.map((c) => [c.id, c])- );-- const checkAncestor = (ancestorId) => {- if (this.partialCategoryInfos.has(ancestorId)) {- // Check if there are more children of this ancestor after the current element- const hasMoreChildrenAfter = this.fetchedCategories- .slice(i + 1)- .some((cat) => cat.parent_category_id === ancestorId);-- if (!hasMoreChildrenAfter) {- const { level, offset } =- this.partialCategoryInfos.get(ancestorId);-- result.push({- type: "show-more",- id: ancestorId,- level,- offset,- });- }- }- };-- let currentAncestorId = elParentID;- while (currentAncestorId !== undefined) {- checkAncestor(currentAncestorId);-- // Move up to the next ancestor- const ancestor = categoriesById.get(currentAncestorId);- currentAncestorId = ancestor?.parent_category_id;- }- }-- return result;- }, []);-this.fetchedCategoriesGroupings = splitWhere(- categoriesWithShowMores,- (c) =>- c.type === "category" && c.category.parent_category_id === undefined+ this.fetchedCategories,+ (category) => category.parent_category_id === undefined);}setFetchedCategories(categories) {this.fetchedCategories = categories;- this.partialCategoryInfos = this.findPartialCategories(categories);this.recomputeGroupings();}concatFetchedCategories(categories) {this.fetchedCategories = this.fetchedCategories.concat(categories);-- // In order to find partially loaded categories correctly, we need to- // ensure that we account for categories that may have been partially- // loaded, because the total number of categories in the response clipped- // them off.- if (categories[0].parent_category_id !== undefined) {- const index = this.fetchedCategories.findLastIndex(- (element) => element.parent_category_id === undefined- );-- categories = [...this.fetchedCategories.slice(index), ...categories];- }-- // Recalculate the partialCategoryInfos using the full set of categories- // to properly identify categories that now have exactly 5 subcategories- // after loading more via the intersection observer- this.partialCategoryInfos = this.findPartialCategories(- this.fetchedCategories- );-this.recomputeGroupings();}- substituteInFetchedCategories(id, subcategories, offset) {- this.partialCategoryInfos.delete(id);- this.recomputeGroupings();-- if (subcategories.length !== 0) {- // Find the last direct child of the parent- const lastDirectChildIndex = this.fetchedCategories.findLastIndex(- (c) => c.parent_category_id === id- );-- if (lastDirectChildIndex === -1) {- // No existing children, insert after the parent itself if it exists- const parentIndex = this.fetchedCategories.findIndex(- (c) => c.id === id- );- const index = parentIndex !== -1 ? parentIndex + 1 : 0;- this.fetchedCategories = [- ...this.fetchedCategories.slice(0, index),- ...subcategories,- ...this.fetchedCategories.slice(index),- ];- } else {- // Find the last descendant of the last direct child by looking for the- // next category that is not a descendant of any child of id- const childrenIds = this.fetchedCategories- .filter((c) => c.parent_category_id === id)- .map((c) => c.id);-- const categoriesById = new Map(- this.fetchedCategories.map((c) => [c.id, c])- );-- const isDescendantOfChild = (category) => {- let currentCategory = category;- while (- currentCategory &&- currentCategory.parent_category_id !== undefined- ) {- if (childrenIds.includes(currentCategory.parent_category_id)) {- return true;- }- currentCategory = categoriesById.get(- currentCategory.parent_category_id- );- }- return false;- };-- let insertIndex = lastDirectChildIndex + 1;- while (insertIndex < this.fetchedCategories.length) {- if (!isDescendantOfChild(this.fetchedCategories[insertIndex])) {- break;- }- insertIndex++;- }-- this.fetchedCategories = [- ...this.fetchedCategories.slice(0, insertIndex),- ...subcategories,- ...this.fetchedCategories.slice(insertIndex),- ];- }-- // Recalculate partial categories based on the full set of categories- // to ensure we properly identify categories with exactly 5 subcategories- this.partialCategoryInfos = this.findPartialCategories(- this.fetchedCategories- );-- // Only show "Show more" button if exactly 5 subcategories were returned,- // which is the default page size and indicates there might be more to load.- // If we received fewer than 5, we've reached the end of the subcategories.- if (subcategories.length === 5) {- if (id === undefined) {- // Root level categories- this.partialCategoryInfos.set(id, {- level: 0,- offset: offset + subcategories.length,- });- } else {- const parentCategory = this.fetchedCategories.find(- (c) => c.id === id- );- if (parentCategory) {- this.partialCategoryInfos.set(id, {- level: parentCategory.level + 1,- offset: offset + subcategories.length,- });- }- }- }-- this.recomputeGroupings();- }- }-- // Count how many children each category has:- //- // - If there are exactly 5, mark as "partial" (might have more since 5 is the page size)- // - Store the parent's ID and offset (how many to skip when loading more)- //- // Categories must be topologically sorted so that the parents appear before- // the children.- findPartialCategories(categories) {- const categoriesById = new Map(- categories.map((category) => [category.id, category])- );- const subcategoryCounts = new Map();- const subcategoryCountsRecursive = new Map();- const partialCategoryInfos = new Map();-- for (const category of categories.slice().reverse()) {- const count = subcategoryCounts.get(category.parent_category_id) || 0;- subcategoryCounts.set(category.parent_category_id, count + 1);-- const recursiveCount =- subcategoryCountsRecursive.get(category.parent_category_id) || 0;-- subcategoryCountsRecursive.set(- category.parent_category_id,- recursiveCount + (subcategoryCountsRecursive.get(category.id) || 0) + 1- );- }-- for (const [id, count] of subcategoryCounts) {- if (count === 5) {- if (id === undefined) {- // Root level categories (parent_category_id is undefined)- partialCategoryInfos.set(id, {- level: 0,- offset: subcategoryCountsRecursive.get(id),- });- } else if (categoriesById.has(id)) {- partialCategoryInfos.set(id, {- level: categoriesById.get(id).level + 1,- offset: subcategoryCountsRecursive.get(id),- });- }- }- }-- return partialCategoryInfos;- }-@actiondidInsert(element) {this.observer.disconnect();@@ -393,21 +127,6 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Componentthis.loadAnotherPage = false;this.loadedPage = requestedPage;- } else if (this.subcategoryLoadList.length !== 0) {- const { id, offset } = this.subcategoryLoadList.shift();- const opts = { offset, ...this.searchOpts() };-- // Only add parentCategoryId if it's not undefined (for root categories)- if (id !== undefined) {- opts.parentCategoryId = id;- }-- let subcategories = await Category.asyncHierarchicalSearch(- requestedFilter,- opts- );-- this.substituteInFetchedCategories(id, subcategories, offset);}} else {// The shown categories are stale, refresh everything@@ -438,12 +157,6 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Componentthis.debouncedSendRequest();}- @action- loadSubcategories(id, offset) {- this.subcategoryLoadList.push({ id, offset });- this.performSearch();- }-debouncedSendRequest() {discourseDebounce(this, this.performSearch, INPUT_DELAY);}@@ -469,6 +182,9 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Component@actiononFilterInput(filter) {this.selectedFilter = filter.toLowerCase().trim();+ this.loadAnotherPage = false;+ this.lastPage = false;+ this.initialLoad = true;this.debouncedSendRequest();}@@ -553,73 +269,52 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Component{{else}}{{#each this.fetchedCategoriesGroupings as |categories|}}<div- style={{borderColor (get categories "0.category.color") "left"}}+ style={{borderColor (get categories "0.color") "left"}}class="sidebar-categories-form__row">- {{#each categories as |c|}}- {{#if (eq c.type "category")}}- <div- {{didInsert this.didInsert}}- data-category-id={{c.category.id}}- data-category-level={{c.category.level}}- class="sidebar-categories-form__category-row"+ {{#each categories as |category|}}+ <div+ {{didInsert this.didInsert}}+ data-category-id={{category.id}}+ data-category-level={{category.level}}+ class="sidebar-categories-form__category-row"+ >+ <label+ for={{concat+ "sidebar-categories-form__input--"+ category.id+ }}+ class="sidebar-categories-form__category-label">- <label- for={{concat- "sidebar-categories-form__input--"- c.category.id- }}- class="sidebar-categories-form__category-label"- >- <div class="sidebar-categories-form__category-wrapper">- <div class="sidebar-categories-form__category-badge">- {{categoryBadge c.category}}- </div>-- {{#unless c.category.parentCategory}}- <div- class="sidebar-categories-form__category-description"- >- {{dirSpan- c.category.description_excerpt- htmlSafe="true"- }}- </div>- {{/unless}}+ <div class="sidebar-categories-form__category-wrapper">+ <div class="sidebar-categories-form__category-badge">+ {{categoryBadge category}}</div>- <input- {{on "click" (fn this.toggleCategory c.category.id)}}- type="checkbox"- checked={{has this.selectedCategoryIds c.category.id}}- id={{concat- "sidebar-categories-form__input--"- c.category.id- }}- class="sidebar-categories-form__input"- />- </label>- </div>- {{else}}- <div- {{didInsert this.didInsert}}- data-category-level={{c.level}}- class="sidebar-categories-form__category-row"- data-test-category-id={{c.id}}- >- <label class="sidebar-categories-form__category-label">- <div class="sidebar-categories-form__category-wrapper">- <div class="sidebar-categories-form__category-badge">- <DButton- @label="sidebar.categories_form_modal.show_more"- @action={{fn this.loadSubcategories c.id c.offset}}- class="sidebar-categories-form__show-more-btn btn-flat"- />+ {{#unless category.parentCategory}}+ <div+ class="sidebar-categories-form__category-description"+ >+ {{dirSpan+ category.description_excerpt+ htmlSafe="true"+ }}</div>- </div>- </label>- </div>- {{/if}}+ {{/unless}}+ </div>++ <input+ {{on "click" (fn this.toggleCategory category.id)}}+ type="checkbox"+ checked={{has this.selectedCategoryIds category.id}}+ id={{concat+ "sidebar-categories-form__input--"+ category.id+ }}+ class="sidebar-categories-form__input"+ />+ </label>+ </div>{{/each}}</div>{{else}}diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.jsindex 14384f0b5a1..2410398040a 100644--- a/frontend/discourse/app/models/category.js+++ b/frontend/discourse/app/models/category.js@@ -24,7 +24,6 @@ import Site from "discourse/models/site";import Topic from "./topic";const CATEGORY_ASYNC_SEARCH_CACHE = {};-const CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE = {};const pluginSaveProperties = new Set();let _uncategorized;@@ -413,21 +412,12 @@ export default class Category extends RestModel {const data = {term,- parent_category_id: opts.parentCategoryId,- limit: opts.limit,only: opts.only,except: opts.except,page: opts.page,- offset: opts.offset,- include_uncategorized: opts.includeUncategorized,};- const result = (CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[- JSON.stringify(data)- ] ||= await ajax("/categories/hierarchical_search", {- method: "GET",- data,- }));+ const result = await ajax("/categories/hierarchical_search", { data });return result["categories"].map((category) =>Site.current().updateCategory(category)diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rbindex fdb23ece2d5..9dc4f2bcf4c 100644--- a/spec/models/category_spec.rb+++ b/spec/models/category_spec.rb@@ -1536,21 +1536,6 @@ RSpec.describe Category doendend- describe ".limited_categories_matching" do- before_all { SiteSetting.max_category_nesting = 3 }-- fab!(:foo) { Fabricate(:category, name: "foo") }- fab!(:bar) { Fabricate(:category, name: "bar", parent_category: foo) }- fab!(:baz) { Fabricate(:category, name: "baz", parent_category: bar) }-- it "produces results in depth-first pre-order" do- SiteSetting.max_category_nesting = 3- expect(Category.limited_categories_matching(nil, nil, nil, "baz").pluck(:name)).to eq(- %w[foo bar baz],- )- end- end-describe ".set_permission!" dofab!(:category)fab!(:group)diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex fe31f7dca0b..e02e2a351b5 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe CategoriesController do- let(:admin) { Fabricate(:admin) }+ let!(:admin) { Fabricate(:admin) }let!(:category) { Fabricate(:category, user: admin) }fab!(:user)@@ -1782,35 +1782,57 @@ RSpec.describe CategoriesController doendend- describe "#hierachical_search" do+ describe "#hierarchical_search" do+ fab!(:category) { Fabricate(:category, name: "Parent Category") }+ fab!(:category_child_2) { Fabricate(:category, name: "Child Two", parent_category: category) }+ fab!(:category_child_1) { Fabricate(:category, name: "Child One", parent_category: category) }+before { sign_in(user) }- it "produces categories with an empty term" do- get "/categories/hierarchical_search.json", params: { term: "" }+ it "returns the right categories when term param is present" do+ get "/categories/hierarchical_search.json", params: { term: "Child One" }expect(response.status).to eq(200)- expect(response.parsed_body["categories"].length).not_to eq(0)++ categories = response.parsed_body["categories"]++ expect(categories.length).to eq(2)+ expect(categories.map { |c| c["id"] }).to eq([category.id, category_child_1.id])end- it "produces exactly 5 subcategories" do- subcategories = Fabricate.times(6, :category, parent_category: category)- subcategories[3].update!(read_restricted: true)+ it "returns the right categories when except param is present" do+ get "/categories/hierarchical_search.json", params: { except: [category_child_1.id] }++ expect(response.status).to eq(200)++ expect(response.parsed_body["categories"].map { |c| c["id"] }).to eq(+ [category.id, category_child_2.id],+ )+ end- get "/categories/hierarchical_search.json"+ it "returns the right categories when only param is present" do+ get "/categories/hierarchical_search.json", params: { only: [category_child_1.id] }expect(response.status).to eq(200)- expect(response.parsed_body["categories"].length).to eq(7)- expect(response.parsed_body["categories"].map { |c| c["id"] }).to contain_exactly(- category.id,- subcategories[0].id,- subcategories[1].id,- subcategories[2].id,- subcategories[4].id,- subcategories[5].id,- SiteSetting.uncategorized_category_id,++ expect(response.parsed_body["categories"].map { |c| c["id"] }).to eq(+ [category.id, category_child_1.id],)end+ it "returns the right categories when page param is present" do+ stub_const(CategoriesController, "MAX_CATEGORIES_LIMIT", 1) do+ get "/categories/hierarchical_search.json", params: { page: 2 }++ expect(response.status).to eq(200)++ categories = response.parsed_body["categories"]++ expect(categories.length).to eq(1)+ expect(categories[0]["id"]).to eq(category_child_1.id)+ end+ end+it "doesn't produce categories with a very specific term" doget "/categories/hierarchical_search.json", params: { term: "acategorythatdoesnotexist" }diff --git a/spec/services/category_hierarchical_search_spec.rb b/spec/services/category_hierarchical_search_spec.rbnew file mode 100644index 00000000000..ed40a48d19c--- /dev/null+++ b/spec/services/category_hierarchical_search_spec.rb@@ -0,0 +1,191 @@+# frozen_string_literal: true++RSpec.describe CategoryHierarchicalSearch do+ before_all { SiteSetting.max_category_nesting = 3 }++ fab!(:user)+ fab!(:parent_2) { Fabricate(:category, name: "Parent 2") }+ fab!(:parent_1) { Fabricate(:category, name: "Parent 1") }++ fab!(:parent_1_sub_category_1) do+ Fabricate(:category, name: "Parent 1 Sub Category 1", parent_category: parent_1)+ end++ fab!(:parent_1_sub_category_2) do+ Fabricate(:category, name: "Parent 1 Sub Category 2", parent_category: parent_1)+ end++ fab!(:parent_2_sub_category_1) do+ Fabricate(:category, name: "Parent 2 Sub Category 1", parent_category: parent_2)+ end++ fab!(:parent_2_sub_category_2) do+ Fabricate(:category, name: "Parent 2 Sub Category 2", parent_category: parent_2)+ end++ fab!(:parent_1_sub_category_1_sub_sub_category_1) do+ Fabricate(+ :category,+ name: "Parent 1 Sub Category 1 Sub Sub Category 1 Match",+ parent_category: parent_1_sub_category_1,+ )+ end++ fab!(:parent_1_sub_category_1_sub_sub_category_2) do+ Fabricate(+ :category,+ name: "Parent 1 Sub Category 1 Sub Sub Category 2",+ parent_category: parent_1_sub_category_1,+ )+ end++ fab!(:parent_1_sub_category_2_sub_sub_category_1) do+ Fabricate(+ :category,+ name: "Parent 1 Sub Category 2 Sub Sub Category 1",+ parent_category: parent_1_sub_category_2,+ )+ end++ fab!(:parent_1_sub_category_2_sub_sub_category_2) do+ Fabricate(+ :category,+ name: "Parent 1 Sub Category 2 Sub Sub Category 2",+ parent_category: parent_1_sub_category_2,+ )+ end++ fab!(:parent_2_sub_category_1_sub_sub_category_1) do+ Fabricate(+ :category,+ name: "Parent 2 Sub Category 1 Sub Sub Category 1",+ parent_category: parent_2_sub_category_1,+ )+ end++ fab!(:parent_2_sub_category_1_sub_sub_category_2) do+ Fabricate(+ :category,+ name: "Parent 2 Sub Category 1 Sub Sub Category 2",+ parent_category: parent_2_sub_category_1,+ )+ end++ fab!(:parent_2_sub_category_2_sub_sub_category_1) do+ Fabricate(+ :category,+ name: "Parent 2 Sub Category 2 Sub Sub Category 1",+ parent_category: parent_2_sub_category_2,+ )+ end++ fab!(:parent_2_sub_category_2_sub_sub_category_2) do+ Fabricate(+ :category,+ name: "Parent 2 Sub Category 2 Sub Sub Category 2 MATCH",+ parent_category: parent_2_sub_category_2,+ )+ end++ it "returns categories with their ancestors that match the terms param in a hierarchical order" do+ context = described_class.call(guardian: Guardian.new, params: { term: "match" })++ expect(context).to be_success++ expect(context.categories.map(&:name)).to eq(+ [+ parent_1.name,+ parent_1_sub_category_1.name,+ parent_1_sub_category_1_sub_sub_category_1.name,+ parent_2.name,+ parent_2_sub_category_2.name,+ parent_2_sub_category_2_sub_sub_category_2.name,+ ],+ )+ end++ it "returns categories with their ancestors that have ids which are included in the only_ids param in a hierarchical order" do+ context =+ described_class.call(+ guardian: Guardian.new,+ params: {+ only_ids: [+ parent_1_sub_category_1_sub_sub_category_1.id,+ parent_2_sub_category_2_sub_sub_category_2.id,+ ],+ },+ )++ expect(context).to be_success++ expect(context.categories.map(&:name)).to eq(+ [+ parent_1.name,+ parent_1_sub_category_1.name,+ parent_1_sub_category_1_sub_sub_category_1.name,+ parent_2.name,+ parent_2_sub_category_2.name,+ parent_2_sub_category_2_sub_sub_category_2.name,+ ],+ )+ end++ it "returns categories with their ancestors that have ids which is not included in the except_ids param in a hierarchical order" do+ context =+ described_class.call(+ guardian: Guardian.new,+ params: {+ except_ids: [+ parent_1_sub_category_2_sub_sub_category_1.id,+ parent_1_sub_category_2_sub_sub_category_2.id,+ parent_2_sub_category_1_sub_sub_category_1.id,+ parent_2_sub_category_1_sub_sub_category_2.id,+ ],+ },+ )++ expect(context).to be_success++ expect(context.categories.map(&:name)).to eq(+ [+ parent_1.name,+ parent_1_sub_category_1.name,+ parent_1_sub_category_1_sub_sub_category_1.name,+ parent_1_sub_category_1_sub_sub_category_2.name,+ parent_1_sub_category_2.name,+ parent_2.name,+ parent_2_sub_category_1.name,+ parent_2_sub_category_2.name,+ parent_2_sub_category_2_sub_sub_category_1.name,+ parent_2_sub_category_2_sub_sub_category_2.name,+ ],+ )+ end++ it "excludes categories that the guardian cannot see" do+ restricted_group = Fabricate(:group)+ restricted_parent_category = Fabricate(:category, name: "Restricted Parent")+ restricted_parent_category.set_permissions(restricted_group => :full)+ restricted_parent_category.save!++ context = described_class.call(guardian: Guardian.new, params: { term: "restricted" })++ expect(context).to be_success+ expect(context.categories).to be_empty+ end++ it "applies a limit and offset" do+ context = described_class.call(guardian: Guardian.new, params: { limit: 2 })++ expect(context.categories.map(&:name)).to eq([parent_1.name, parent_1_sub_category_1.name])++ context = described_class.call(guardian: Guardian.new, params: { limit: 2, offset: 2 })++ expect(context.categories.map(&:name)).to eq(+ [+ parent_1_sub_category_1_sub_sub_category_1.name,+ parent_1_sub_category_1_sub_sub_category_2.name,+ ],+ )+ end+enddiff --git a/spec/system/editing_sidebar_categories_navigation_spec.rb b/spec/system/editing_sidebar_categories_navigation_spec.rbindex 8f6eb98477d..ddd0d10666b 100644--- a/spec/system/editing_sidebar_categories_navigation_spec.rb+++ b/spec/system/editing_sidebar_categories_navigation_spec.rb@@ -184,193 +184,6 @@ RSpec.describe "Editing sidebar categories navigation", type: :system do)end- context "when loading more subcategories via scrolling" do- fab!(:parent_category) { Fabricate(:category, name: "parent category") }-- # Create 4 subcategories initially (under the threshold of 5)- fab!(:subcategory1) do- Fabricate(:category, parent_category_id: parent_category.id, name: "subcategory 1")- end-- fab!(:subcategory2) do- Fabricate(:category, parent_category_id: parent_category.id, name: "subcategory 2")- end-- fab!(:subcategory3) do- Fabricate(:category, parent_category_id: parent_category.id, name: "subcategory 3")- end-- fab!(:subcategory4) do- Fabricate(:category, parent_category_id: parent_category.id, name: "subcategory 4")- end-- # Create additional subcategories that will be loaded via intersection observer- fab!(:subcategory5) do- Fabricate(:category, parent_category_id: parent_category.id, name: "subcategory 5")- end-- fab!(:subcategory6) do- Fabricate(:category, parent_category_id: parent_category.id, name: "subcategory 6")- end-- # Test stub to force pagination in the category search- around(:each) do |example|- stub_const(CategoriesController, :MAX_CATEGORIES_LIMIT, 5) { example.run }- end-- it "shows the 'Show more' link after loading additional subcategories via intersection observer and hides it after loading all subcategories" do- visit "/latest"-- modal = sidebar.click_edit_categories_button-- expect(modal).to have_category_row(parent_category)- expect(modal).to have_category_row(subcategory1)- expect(modal).to have_category_row(subcategory2)- expect(modal).to have_category_row(subcategory3)- modal.scroll_to_category(subcategory3)-- expect(modal).to have_category_row(subcategory4)- expect(modal).to have_category_row(subcategory5)-- modal.click_show_more_button(parent_category)-- expect(page).to have_content(subcategory6.name)- # The 'Show more' button should disappear after loading all subcategories- expect(modal).to have_no_show_more_button(parent_category)- end- end-- context "when loading more subcategories with 3-level hierarchy" do- before_all { SiteSetting.max_category_nesting = 3 }-- before { SiteSetting.max_category_nesting = 3 }-- fab!(:grandparent_category) { Fabricate(:category, name: "grandparent category") }-- fab!(:parent1) do- Fabricate(:category, parent_category_id: grandparent_category.id, name: "parent 1")- end-- fab!(:parent2) do- Fabricate(:category, parent_category_id: grandparent_category.id, name: "parent 2")- end-- fab!(:parent3) do- Fabricate(:category, parent_category_id: grandparent_category.id, name: "parent 3")- end-- fab!(:parent4) do- Fabricate(:category, parent_category_id: grandparent_category.id, name: "parent 4")- end-- fab!(:parent5) do- Fabricate(:category, parent_category_id: grandparent_category.id, name: "parent 5")- end-- fab!(:parent6) do- Fabricate(:category, parent_category_id: grandparent_category.id, name: "parent 6")- end-- fab!(:child1_1) { Fabricate(:category, parent_category_id: parent1.id, name: "child 1-1") }- fab!(:child1_2) { Fabricate(:category, parent_category_id: parent1.id, name: "child 1-2") }- fab!(:child1_3) { Fabricate(:category, parent_category_id: parent1.id, name: "child 1-3") }- fab!(:child1_4) { Fabricate(:category, parent_category_id: parent1.id, name: "child 1-4") }- fab!(:child1_5) { Fabricate(:category, parent_category_id: parent1.id, name: "child 1-5") }- fab!(:child1_6) { Fabricate(:category, parent_category_id: parent1.id, name: "child 1-6") }-- around(:each) do |example|- stub_const(CategoriesController, :MAX_CATEGORIES_LIMIT, 5) { example.run }- end-- it "shows 'Show more' button at grandparent level and loads additional parent categories" do- visit "/latest"-- modal = sidebar.click_edit_categories_button-- # Should show grandparent category and first 5 parent categories- expect(modal).to have_category_row(grandparent_category)- modal.scroll_to_category(grandparent_category)- expect(modal).to have_category_row(parent1)- expect(modal).to have_category_row(parent2)- expect(modal).to have_category_row(parent3)- modal.scroll_to_category(parent3)- expect(modal).to have_category_row(parent4)- expect(modal).to have_category_row(parent5)- expect(modal).to have_no_category_row(parent6)-- modal.click_show_more_button(grandparent_category)-- expect(modal).to have_category_row(parent6)- expect(modal).to have_no_show_more_button(grandparent_category)- end- end-- context "when loading more subcategories with specific sub-subcategory configuration" do- before_all { SiteSetting.max_category_nesting = 3 }-- before { SiteSetting.max_category_nesting = 3 }-- fab!(:top_category) { Fabricate(:category, name: "top category") }-- fab!(:sub1) { Fabricate(:category, parent_category_id: top_category.id, name: "sub 1") }- fab!(:sub2) { Fabricate(:category, parent_category_id: top_category.id, name: "sub 2") }- fab!(:sub3) { Fabricate(:category, parent_category_id: top_category.id, name: "sub 3") }- fab!(:sub4) { Fabricate(:category, parent_category_id: top_category.id, name: "sub 4") }- fab!(:sub5) { Fabricate(:category, parent_category_id: top_category.id, name: "sub 5") }- fab!(:sub6) { Fabricate(:category, parent_category_id: top_category.id, name: "sub 6") }-- # 5 sub-subcategories under the first subcategory- fab!(:subsub1_1) { Fabricate(:category, parent_category_id: sub1.id, name: "subsub 1-1") }- fab!(:subsub1_2) { Fabricate(:category, parent_category_id: sub1.id, name: "subsub 1-2") }- fab!(:subsub1_3) { Fabricate(:category, parent_category_id: sub1.id, name: "subsub 1-3") }- fab!(:subsub1_4) { Fabricate(:category, parent_category_id: sub1.id, name: "subsub 1-4") }- fab!(:subsub1_5) { Fabricate(:category, parent_category_id: sub1.id, name: "subsub 1-5") }-- # 5 sub-subcategories under the last (5th) subcategory- fab!(:subsub5_1) { Fabricate(:category, parent_category_id: sub5.id, name: "subsub 5-1") }- fab!(:subsub5_2) { Fabricate(:category, parent_category_id: sub5.id, name: "subsub 5-2") }- fab!(:subsub5_3) { Fabricate(:category, parent_category_id: sub5.id, name: "subsub 5-3") }- fab!(:subsub5_4) { Fabricate(:category, parent_category_id: sub5.id, name: "subsub 5-4") }- fab!(:subsub5_5) { Fabricate(:category, parent_category_id: sub5.id, name: "subsub 5-5") }-- around(:each) do |example|- stub_const(CategoriesController, :MAX_CATEGORIES_LIMIT, 5) { example.run }- end-- it "shows 'Show more' button for top-level category with more subcategories after intersection observer loads sub-subcategories" do- visit "/latest"-- modal = sidebar.click_edit_categories_button-- # Initial load (page 1, limit=5) should show:- # top_category, sub1, subsub1_1, subsub1_2, subsub1_3 (depth-first hierarchical order)- expect(modal).to have_category_row(top_category)- expect(modal).to have_category_row(sub1)- expect(modal).to have_category_row(subsub1_1)- expect(modal).to have_no_category_row(sub6)-- # No Show more button initially since top_category doesn't have 5 direct children yet- expect(modal).to have_no_show_more_button(top_category)-- # Scroll down to trigger intersection observer to load more pages- # We need to load until top_category has exactly 5 direct children (sub1-sub5)- # This happens after loading sub5, which comes in page 3- modal.scroll_to_category(subsub1_1)- modal.scroll_to_category(sub2)- modal.scroll_to_category(sub4)- modal.scroll_to_category(sub5)-- # After loading enough pages, top_category should have 5 direct children (sub1-sub5)- # and the "Show more" button should appear- expect(modal).to have_category_row(sub5)-- # Click the "Show more" button to load sub6- modal.click_show_more_button(top_category)-- expect(modal).to have_category_row(sub6)- end- end-describe "when max_category_nesting has been set to 3" dobefore_all { SiteSetting.max_category_nesting = 3 }@@ -428,19 +241,55 @@ RSpec.describe "Editing sidebar categories navigation", type: :system doexpect(sidebar).to have_categories_sectionmodal = sidebar.click_edit_categories_button+modal.filter("category 2 subcategory subcategory")expect(modal).to have_categories([- category2,- category2_subcategory,- category2_subcategory_subcategory,category,category_subcategory,category_subcategory_subcategory2,category_subcategory2,+ category2,+ category2_subcategory,+ category2_subcategory_subcategory,],)end++ it "loads categories in multiple pages correctly" do+ resize_window(height: 500) do+ stub_const(CategoriesController, "MAX_CATEGORIES_LIMIT", 5) do+ visit "/latest"++ modal = sidebar.click_edit_categories_button++ expect(modal).to have_categories(+ [+ category,+ category_subcategory,+ category_subcategory_subcategory,+ category_subcategory_subcategory2,+ category_subcategory2,+ ],+ )++ modal.scroll_to_category(category_subcategory2)++ expect(modal).to have_categories(+ [+ category,+ category_subcategory,+ category_subcategory_subcategory,+ category_subcategory_subcategory2,+ category_subcategory2,+ category2,+ category2_subcategory,+ category2_subcategory_subcategory,+ ],+ )+ end+ end+ endendend