A platform for community discussion. Free, open, simple.
FIX: Another category modal partial loading edge case (#35204)
Martin Brennan762b77946c84
diff --git a/app/assets/javascripts/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjs b/app/assets/javascripts/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjsindex 36ebacd0620..60dcc18e3bb 100644--- a/app/assets/javascripts/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjs+++ b/app/assets/javascripts/discourse/app/components/sidebar/edit-navigation-menu/categories-modal.gjs@@ -17,103 +17,54 @@ import loadingSpinner from "discourse/helpers/loading-spinner";import { popupAjaxError } from "discourse/lib/ajax-error";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 { i18n } from "discourse-i18n";-class ActionSerializer {- constructor(perform) {- this.perform = perform;- this.processing = false;- this.queued = false;- }-- async trigger() {- this.queued = true;-- if (!this.processing) {- this.processing = true;-- while (this.queued) {- this.queued = false;- await this.perform();- }-- this.processing = false;- }- }-}--// Given an async method that takes no parameters, produce a method that-// triggers the original method only if it is not currently executing it,-// otherwise it will queue up to one execution of the method-function serialized(target, key, descriptor) {- const originalMethod = descriptor.value;-- descriptor.value = function () {- this[`_${key}_serializer`] ||= new ActionSerializer(() =>- originalMethod.apply(this)- );- this[`_${key}_serializer`].trigger();- };-- return descriptor;-}--// Given a list, break into chunks starting a new chunk whenever the predicate-// is true for an element.-function splitWhere(elements, f) {- return elements.reduce((acc, el, i) => {- if (i === 0 || f(el)) {- acc.push([]);- }- acc[acc.length - 1].push(el);- return acc;- }, []);-}--// categories must be topologically sorted so that the parents appear before-// the children-function 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;-}-+// 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;@@ -127,6 +78,8 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Component]);selectedFilter = "";selectedMode = "everything";+ fetchedCategories;+ partialCategoryInfos;loadedFilter;loadedMode;loadedPage;@@ -157,24 +110,49 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Componentconst elID = el.id;const elParentID = el.parent_category_id;- const nextParentID = this.fetchedCategories[i + 1]?.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 &&- this.partialCategoryInfos.has(elParentID)- ) {- const { level, offset } = this.partialCategoryInfos.get(elParentID);-- result.push({- type: "show-more",- id: elParentID,- level,- offset,- });+ 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;@@ -189,7 +167,7 @@ export default class SidebarEditNavigationMenuCategoriesModal extends ComponentsetFetchedCategories(categories) {this.fetchedCategories = categories;- this.partialCategoryInfos = findPartialCategories(categories);+ this.partialCategoryInfos = this.findPartialCategories(categories);this.recomputeGroupings();}@@ -211,7 +189,9 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Component// 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 = findPartialCategories(this.fetchedCategories);+ this.partialCategoryInfos = this.findPartialCategories(+ this.fetchedCategories+ );this.recomputeGroupings();}@@ -221,20 +201,69 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Componentthis.recomputeGroupings();if (subcategories.length !== 0) {- const index =- this.fetchedCategories.findLastIndex(- (c) => c.parent_category_id === id- ) + 1;+ // Find the last direct child of the parent+ const lastDirectChildIndex = this.fetchedCategories.findLastIndex(+ (c) => c.parent_category_id === id+ );- this.fetchedCategories = [- ...this.fetchedCategories.slice(0, index),- ...subcategories,- ...this.fetchedCategories.slice(index),- ];+ 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 = findPartialCategories(this.fetchedCategories);+ 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.@@ -263,6 +292,54 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Component}}+ // 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();@@ -283,7 +360,7 @@ export default class SidebarEditNavigationMenuCategoriesModal extends Componentreturn opts;}- @serialized+ @serializedActionasync performSearch() {this.filtered = false;diff --git a/app/assets/javascripts/discourse/app/lib/utilities.js b/app/assets/javascripts/discourse/app/lib/utilities.jsindex 238c453ffe5..1349f029fb7 100644--- a/app/assets/javascripts/discourse/app/lib/utilities.js+++ b/app/assets/javascripts/discourse/app/lib/utilities.js@@ -800,3 +800,54 @@ export function isValidDestinationUrl(url) {!NO_DESTINATION_COOKIE.some((p) => url.startsWith(getURL(p))));}++export class ActionSerializer {+ constructor(perform) {+ this.perform = perform;+ this.processing = false;+ this.queued = false;+ }++ async trigger() {+ this.queued = true;++ if (!this.processing) {+ this.processing = true;++ while (this.queued) {+ this.queued = false;+ await this.perform();+ }++ this.processing = false;+ }+ }+}++// Given an async method that takes no parameters, produce a method that+// triggers the original method only if it is not currently executing it,+// otherwise it will queue up to one execution of the method+export function serializedAction(target, key, descriptor) {+ const originalMethod = descriptor.value;++ descriptor.value = function () {+ this[`_${key}_serializer`] ||= new ActionSerializer(() =>+ originalMethod.apply(this)+ );+ this[`_${key}_serializer`].trigger();+ };++ return descriptor;+}++// Given a list, break into chunks starting a new chunk whenever the predicate+// is true for an element.+export function splitWhere(elements, f) {+ return elements.reduce((acc, el, i) => {+ if (i === 0 || f(el)) {+ acc.push([]);+ }+ acc[acc.length - 1].push(el);+ return acc;+ }, []);+}diff --git a/spec/system/editing_sidebar_categories_navigation_spec.rb b/spec/system/editing_sidebar_categories_navigation_spec.rbindex 54380b1a78b..1868533f7b6 100644--- a/spec/system/editing_sidebar_categories_navigation_spec.rb+++ b/spec/system/editing_sidebar_categories_navigation_spec.rb@@ -256,18 +256,16 @@ RSpec.describe "Editing sidebar categories navigation", type: :system doexpect(modal).to have_category_row(subcategory1)expect(modal).to have_category_row(subcategory2)expect(modal).to have_category_row(subcategory3)- expect(modal).to have_category_row(subcategory4)-- expect(modal).to have_no_show_more_button-- modal.scroll_to_category(subcategory4)+ modal.scroll_to_category(subcategory3)+ wait_for_timeout(300)+ expect(modal).to have_category_row(subcategory4)expect(modal).to have_category_row(subcategory5)-- expect(modal).to have_show_more_button+ modal.scroll_to_category(subcategory5)# We need to briefly wait for things to settle, otherwise clicking the button doesn't work.wait_for_timeout(300)+ expect(modal).to have_show_more_buttonmodal.click_show_more_buttonexpect(page).to have_content(subcategory6.name)@@ -369,6 +367,106 @@ RSpec.describe "Editing sidebar categories navigation", type: :system doendend+ context "when loading more subcategories with specific sub-subcategory configuration" do+ before_all { SiteSetting.max_category_nesting = 3 }++ before do+ SiteSetting.max_category_nesting = 3+ Jobs.with_immediate_jobs do+ SearchIndexer.with_indexing do+ top_category.index_search+ sub1.index_search+ sub2.index_search+ sub3.index_search+ sub4.index_search+ sub5.index_search+ sub6.index_search+ subsub1_1.index_search+ subsub1_2.index_search+ subsub1_3.index_search+ subsub1_4.index_search+ subsub1_5.index_search+ subsub5_1.index_search+ subsub5_2.index_search+ subsub5_3.index_search+ subsub5_4.index_search+ subsub5_5.index_search+ end+ end+ end++ 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(Object, :CategoriesController, CategoriesController.clone) do+ stub_const(CategoriesController, :MAX_CATEGORIES_LIMIT, 5) { example.run }+ end+ 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++ # 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)+ wait_for_timeout(300)++ modal.scroll_to_category(sub2)+ wait_for_timeout(300)++ modal.scroll_to_category(sub4)+ wait_for_timeout(300)++ modal.scroll_to_category(sub5)+ wait_for_timeout(300)++ # 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)+ expect(modal).to have_show_more_button++ # Click the "Show more" button to load sub6+ modal.click_show_more_button+ wait_for_timeout(300)++ expect(modal).to have_category_row(sub6)+ end+ end+context "when there are more categories than the page limit" doaround(:each) do |example|search_calls = 0