A platform for community discussion. Free, open, simple.
DEV: Add a category-list-subcategories value transformer (#42804)
Kris1450bb055dfd
diff --git a/frontend/discourse/app/components/categories-boxes.gjs b/frontend/discourse/app/components/categories-boxes.gjsindex 66ddea0be2c..1df17cafe39 100644--- a/frontend/discourse/app/components/categories-boxes.gjs+++ b/frontend/discourse/app/components/categories-boxes.gjs@@ -1,5 +1,6 @@/* eslint-disable ember/no-classic-components */import Component from "@ember/component";+import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { isEmpty } from "@ember/utils";import { tagName } from "@ember-decorators/component";@@ -9,6 +10,9 @@ import CategoryTitleLink from "discourse/components/category-title-link";import PluginOutlet from "discourse/components/plugin-outlet";import borderColor from "discourse/helpers/border-color";import categoryColorVariable from "discourse/helpers/category-color-variable";+import categoryListSubcategories, {+ hasGrandchildren,+} from "discourse/helpers/category-list-subcategories";import lazyHash from "discourse/helpers/lazy-hash";import DDecoratedHtml from "discourse/ui-kit/d-decorated-html";import dCategoryLink, {@@ -19,12 +23,20 @@ import dDirSpan from "discourse/ui-kit/helpers/d-dir-span";@tagName("")export default class CategoriesBoxes extends Component {+ @service discovery;+get anyLogos() {return this.categories.some((c) => !isEmpty(c.get("uploaded_logo.url")));}get hasSubcategories() {- return this.categories.some((c) => !isEmpty(c.get("subcategories")));+ return this.categories.some(+ (c) => !isEmpty(categoryListSubcategories(c, { page: this.page }))+ );+ }++ get page() {+ return this.categoryListPage ?? this.discovery.categoryListPage;}categoryName(category) {@@ -89,61 +101,70 @@ export default class CategoriesBoxes extends Component {/></div>- {{#if c.isGrandParent}}- {{#each c.subcategories as |subcategory|}}- <div- data-category-id={{subcategory.id}}- data-notification-level={{subcategory.notificationLevelString}}- style={{borderColor subcategory.color}}- class="subcategory with-subcategories- {{if- subcategory.uploaded_logo.url- 'has-logo'- 'no-logo'- }}"- >- <div class="subcategory-box-inner">- <CategoryTitleLink- @tagName="h4"- @category={{subcategory}}- />- {{#if subcategory.subcategories}}- <div class="subcategories">- {{#each- subcategory.subcategories- as |subsubcategory|- }}- {{#unless subsubcategory.isMuted}}- <span class="subcategory">- <CategoryTitleBefore- @category={{subsubcategory}}- />- {{dCategoryLink- subsubcategory- hideParent="true"- }}- </span>- {{/unless}}- {{/each}}- </div>- {{/if}}+ {{#let+ (categoryListSubcategories c page=this.page)+ as |subcategories|+ }}+ {{#if (hasGrandchildren subcategories page=this.page)}}+ {{#each subcategories as |subcategory|}}+ <div+ data-category-id={{subcategory.id}}+ data-notification-level={{subcategory.notificationLevelString}}+ style={{borderColor subcategory.color}}+ class="subcategory with-subcategories+ {{if+ subcategory.uploaded_logo.url+ 'has-logo'+ 'no-logo'+ }}"+ >+ <div class="subcategory-box-inner">+ <CategoryTitleLink+ @tagName="h4"+ @category={{subcategory}}+ />+ {{#let+ (categoryListSubcategories+ subcategory page=this.page+ )+ as |grandchildren|+ }}+ {{#if grandchildren}}+ <div class="subcategories">+ {{#each grandchildren as |subsubcategory|}}+ {{#unless subsubcategory.isMuted}}+ <span class="subcategory">+ <CategoryTitleBefore+ @category={{subsubcategory}}+ />+ {{dCategoryLink+ subsubcategory+ hideParent="true"+ }}+ </span>+ {{/unless}}+ {{/each}}+ </div>+ {{/if}}+ {{/let}}+ </div></div>- </div>- {{/each}}- {{else if c.subcategories}}- <div class="subcategories">- {{#each c.subcategories as |sc|}}- <a class="subcategory" href={{sc.url}}>- {{#if sc.uploaded_logo.url}}- <span class="subcategory-image-placeholder">- <CategoryLogo @category={{sc}} />- </span>- {{/if}}- {{dCategoryLink sc hideParent="true"}}- </a>{{/each}}- </div>- {{/if}}+ {{else if subcategories}}+ <div class="subcategories">+ {{#each subcategories as |sc|}}+ <a class="subcategory" href={{sc.url}}>+ {{#if sc.uploaded_logo.url}}+ <span class="subcategory-image-placeholder">+ <CategoryLogo @category={{sc}} />+ </span>+ {{/if}}+ {{dCategoryLink sc hideParent="true"}}+ </a>+ {{/each}}+ </div>+ {{/if}}+ {{/let}}{{/unless}}</div>diff --git a/frontend/discourse/app/components/category-list-item.js b/frontend/discourse/app/components/category-list-item.jsindex fd0c0fc8e79..0630518e337 100644--- a/frontend/discourse/app/components/category-list-item.js+++ b/frontend/discourse/app/components/category-list-item.js@@ -1,7 +1,11 @@/* eslint-disable ember/no-classic-components */import Component from "@ember/component";import { computed } from "@ember/object";+import { service } from "@ember/service";import { tagName } from "@ember-decorators/component";+import categoryListSubcategories, {+ hasGrandchildren,+} from "discourse/helpers/category-list-subcategories";import { applyValueTransformer } from "discourse/lib/transformer";const LIST_TYPE = {@@ -11,6 +15,8 @@ const LIST_TYPE = {@tagName("")export default class CategoryListItem extends Component {+ @service discovery;+category = null;listType = LIST_TYPE.NORMAL;@@ -43,6 +49,18 @@ export default class CategoryListItem extends Component {return this.category?.path?.substring("/c/".length);}+ get page() {+ return this.categoryListPage ?? this.discovery.categoryListPage;+ }++ get displayedSubcategories() {+ return categoryListSubcategories(this.category, { page: this.page });+ }++ get showsGrandchildren() {+ return hasGrandchildren(this.displayedSubcategories, { page: this.page });+ }+applyValueTransformer(name, value, context) {return applyValueTransformer(name, value, context);}diff --git a/frontend/discourse/app/components/parent-category-row.gjs b/frontend/discourse/app/components/parent-category-row.gjsindex 289761aacb3..369de794fe7 100644--- a/frontend/discourse/app/components/parent-category-row.gjs+++ b/frontend/discourse/app/components/parent-category-row.gjs@@ -18,6 +18,13 @@ import dDirSpan from "discourse/ui-kit/helpers/d-dir-span";import { i18n } from "discourse-i18n";export default class ParentCategoryRow extends CategoryListItem {+ get hiddenSubcategoryCount() {+ return (+ (this.category.subcategory_count ?? 0) -+ this.displayedSubcategories.length+ );+ }+<template>{{#unless this.isHidden}}<PluginOutlet@@ -70,18 +77,18 @@ export default class ParentCategoryRow extends CategoryListItem {{{/each}}{{/if}}{{/unless}}- {{#if this.category.isGrandParent}}- {{#each this.category.subcategories as |subcategory|}}+ {{#if this.showsGrandchildren}}+ {{#each this.displayedSubcategories as |subcategory|}}<SubCategoryRow@category={{subcategory}}@listType={{this.listType}}/>{{/each}}- {{else if this.category.subcategories}}+ {{else if this.displayedSubcategories}}<tr class="subcategories-list"><td><div class="subcategories">- {{#each this.category.subcategories as |subcategory|}}+ {{#each this.displayedSubcategories as |subcategory|}}<SubCategoryItem@category={{subcategory}}@listType={{this.listType}}@@ -156,32 +163,32 @@ export default class ParentCategoryRow extends CategoryListItem {</div>{{/if}}- {{#if this.category.isGrandParent}}+ {{#if this.showsGrandchildren}}<table class="category-list subcategories-with-subcategories"><tbody>- {{#each this.category.subcategories as |subcategory|}}+ {{#each this.displayedSubcategories as |subcategory|}}<SubCategoryRow@category={{subcategory}}@listType={{this.listType}}/>{{/each}}- {{#if (gt this.category.unloadedSubcategoryCount 0)}}+ {{#if (gt this.hiddenSubcategoryCount 0)}}{{i18n"category_row.subcategory_count"- count=this.category.unloadedSubcategoryCount+ count=this.hiddenSubcategoryCount}}{{/if}}</tbody></table>- {{else if this.category.subcategories}}+ {{else if this.displayedSubcategories}}<div class="subcategories">- {{#each this.category.subcategories as |subcategory|}}+ {{#each this.displayedSubcategories as |subcategory|}}<SubCategoryItem@category={{subcategory}}@listType={{this.listType}}/>{{/each}}- {{#if (gt this.category.unloadedSubcategoryCount 0)}}+ {{#if (gt this.hiddenSubcategoryCount 0)}}<div class="subcategories__more-subcategories"><LinkTo@route="discovery.subcategories"@@ -189,7 +196,7 @@ export default class ParentCategoryRow extends CategoryListItem {>{{i18n"category_row.subcategory_count"- count=this.category.unloadedSubcategoryCount+ count=this.hiddenSubcategoryCount}}</LinkTo></div>diff --git a/frontend/discourse/app/components/sub-category-row.gjs b/frontend/discourse/app/components/sub-category-row.gjsindex f7a476b2d7f..39abcf16b5e 100644--- a/frontend/discourse/app/components/sub-category-row.gjs+++ b/frontend/discourse/app/components/sub-category-row.gjs@@ -17,9 +17,9 @@ export default class SubCategoryRow extends CategoryListItem {<td><CategoryTitleLink @tagName="h4" @category={{this.category}} /><div class="subcategories-list">- {{#if this.category.subcategories}}+ {{#if this.displayedSubcategories}}<div class="subcategories">- {{#each this.category.subcategories as |subcategory|}}+ {{#each this.displayedSubcategories as |subcategory|}}<SubCategoryItem@category={{subcategory}}@listType={{this.listType}}@@ -56,9 +56,9 @@ export default class SubCategoryRow extends CategoryListItem {/></div>{{/if}}- {{#if this.category.subcategories}}+ {{#if this.displayedSubcategories}}<div class="subcategories">- {{#each this.category.subcategories as |subsubcategory|}}+ {{#each this.displayedSubcategories as |subsubcategory|}}<SubCategoryItem@category={{subsubcategory}}@hideUnread="true"diff --git a/frontend/discourse/app/components/subcategories-with-featured-topics.gjs b/frontend/discourse/app/components/subcategories-with-featured-topics.gjsindex eea3ef8b9e3..bc465dd1046 100644--- a/frontend/discourse/app/components/subcategories-with-featured-topics.gjs+++ b/frontend/discourse/app/components/subcategories-with-featured-topics.gjs@@ -1,15 +1,19 @@/* eslint-disable ember/no-classic-components */import Component from "@ember/component";+import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { tagName } from "@ember-decorators/component";import CategoryTitleLink from "discourse/components/category-title-link";import ParentCategoryRow from "discourse/components/parent-category-row";import PluginOutlet from "discourse/components/plugin-outlet";+import categoryListSubcategories from "discourse/helpers/category-list-subcategories";import lazyHash from "discourse/helpers/lazy-hash";import { i18n } from "discourse-i18n";@tagName("")export default class SubcategoriesWithFeaturedTopics extends Component {+ @service discovery;+<template><div ...attributes>{{#each this.categories as |category|}}@@ -26,7 +30,14 @@ export default class SubcategoriesWithFeaturedTopics extends Component {}}</span></div><div class="subcategories">- {{#each category.serializedSubcategories as |subCategory|}}+ {{#each+ (categoryListSubcategories+ category+ page=this.discovery.categoryListPage+ subcategories=category.serializedSubcategories+ )+ as |subCategory|+ }}<ParentCategoryRow@category={{subCategory}}@showTopics={{true}}@@ -60,7 +71,14 @@ export default class SubcategoriesWithFeaturedTopics extends Component {</tr></thead><tbody aria-labelledby="categories-only-category">- {{#each category.serializedSubcategories as |subCategory|}}+ {{#each+ (categoryListSubcategories+ category+ page=this.discovery.categoryListPage+ subcategories=category.serializedSubcategories+ )+ as |subCategory|+ }}<ParentCategoryRow@category={{subCategory}}@showTopics={{true}}diff --git a/frontend/discourse/app/helpers/category-list-subcategories.js b/frontend/discourse/app/helpers/category-list-subcategories.jsnew file mode 100644index 00000000000..289a85213e0--- /dev/null+++ b/frontend/discourse/app/helpers/category-list-subcategories.js@@ -0,0 +1,44 @@+import { applyValueTransformer } from "discourse/lib/transformer";++/**+ * The subcategories to display for a category in the category list layouts.+ *+ * Consumers of the `category-list-subcategories` transformer can return a+ * shorter list, or `[]`, to collapse deeper levels of the list without+ * affecting `Category#subcategories`, which the sidebar and topic lists use.+ *+ * @param {Category} category the category whose children are being listed+ * @param {Object} [options]+ * @param {string} [options.page] which category listing is being rendered:+ * `"categories"`, `"subcategories"`, or `"category"` for the subcategories+ * listed above a category's topics. See `Discovery#categoryListPage`.+ * @param {Category[]} [options.subcategories] the children to transform, for+ * layouts which don't source them from `category.subcategories`+ * @returns {Category[]} the subcategories to render+ */+export default function categoryListSubcategories(+ category,+ { page, subcategories } = {}+) {+ return (+ applyValueTransformer(+ "category-list-subcategories",+ subcategories ?? category?.subcategories ?? [],+ { category, page }+ ) ?? []+ );+}++/**+ * Whether any of the given subcategories has children of its own, meaning the+ * list needs the grandparent layout rather than plain subcategory links.+ *+ * @param {Category[]} subcategories the subcategories being rendered+ * @param {Object} [options] the options passed to `categoryListSubcategories`+ * @returns {boolean}+ */+export function hasGrandchildren(subcategories, options) {+ return subcategories.some(+ (subcategory) => categoryListSubcategories(subcategory, options).length > 0+ );+}diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.jsindex 3a543983338..faff1bd89d3 100644--- a/frontend/discourse/app/lib/registry/transformers.js+++ b/frontend/discourse/app/lib/registry/transformers.js@@ -54,6 +54,7 @@ export const VALUE_TRANSFORMERS = Object.freeze(["category-display-name","category-list-attributes","category-list-request",+ "category-list-subcategories","category-sort-orders","category-subcategories","category-text-color",diff --git a/frontend/discourse/app/services/discovery.js b/frontend/discourse/app/services/discovery.jsindex b60ccdda7ca..79bb8012289 100644--- a/frontend/discourse/app/services/discovery.js+++ b/frontend/discourse/app/services/discovery.js@@ -37,6 +37,26 @@ export default class DiscoveryService extends Service {}}+ /**+ * Which category listing is on screen, for consumers that scope behaviour by+ * page. Undefined anywhere a category listing isn't being rendered.+ *+ * - `"categories"` the categories page+ * - `"subcategories"` a category's subcategories page+ * - `"category"` the subcategories listed above a category's topics+ */+ get categoryListPage() {+ const { currentRouteName } = this.router;++ if (currentRouteName === "discovery.categories") {+ return "categories";+ } else if (currentRouteName === "discovery.subcategories") {+ return "subcategories";+ } else if (this.category) {+ return "category";+ }+ }+get custom() {if (this.onDiscoveryRoute) {return this.router.currentRouteName === "discovery.custom";diff --git a/frontend/discourse/tests/integration/components/category-list-subcategories-test.gjs b/frontend/discourse/tests/integration/components/category-list-subcategories-test.gjsnew file mode 100644index 00000000000..3b03f29410d--- /dev/null+++ b/frontend/discourse/tests/integration/components/category-list-subcategories-test.gjs@@ -0,0 +1,260 @@+import { array } from "@ember/helper";+import { getOwner } from "@ember/owner";+import Service from "@ember/service";+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import CategoriesBoxes from "discourse/components/categories-boxes";+import CategoriesOnly from "discourse/components/categories-only";+import { withPluginApi } from "discourse/lib/plugin-api";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module(+ "Integration | Component | category-list-subcategories",+ function (hooks) {+ setupRenderingTest(hooks);++ function seedNestedCategories(owner) {+ const store = owner.lookup("service:store");+ const site = owner.lookup("service:site");++ const common = {+ color: "0088CC",+ text_color: "FFFFFF",+ description_excerpt: "",+ uploaded_logo: null,+ topic_count: 1,+ post_count: 1,+ stat: "1 topic",+ statTotal: "1 topic",+ statTitle: "1 topic",+ };++ const parent = store.createRecord("category", {+ id: 1001,+ name: "Parent",+ slug: "parent",+ parent_category_id: null,+ ...common,+ });+ const child = store.createRecord("category", {+ id: 1002,+ name: "Child",+ slug: "child",+ parent_category_id: 1001,+ ...common,+ });+ const grandchild = store.createRecord("category", {+ id: 1003,+ name: "Grandchild",+ slug: "grandchild",+ parent_category_id: 1002,+ ...common,+ });++ site.set("categories", [parent, child, grandchild]);+ return { parent, child, grandchild };+ }++ function hideGrandchildren() {+ withPluginApi((api) => {+ api.registerValueTransformer(+ "category-list-subcategories",+ ({ value, context }) => {+ return context.category.level >= 1 ? [] : value;+ }+ );+ });+ }++ // A transformer that only collapses deeper levels for the subcategories+ // listed above a category's topics, leaving /categories at full depth.+ function hideGrandchildrenAboveTopics() {+ withPluginApi((api) => {+ api.registerValueTransformer(+ "category-list-subcategories",+ ({ value, context }) => {+ if (context.page === "category" && context.category.level >= 1) {+ return [];+ }+ return value;+ }+ );+ });+ }++ function stubDiscovery(owner) {+ class DiscoveryStub extends Service {+ categoryListPage = "categories";+ }++ owner.unregister("service:discovery");+ owner.register("service:discovery", DiscoveryStub);+ return owner.lookup("service:discovery");+ }++ test("categories_boxes shows grandchildren by default", async function (assert) {+ const { parent } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesBoxes @categories={{array parent}} /></template>+ );++ assert+ .dom(".category-box[data-category-id='1001']")+ .containsText("Child", "second level is still shown");+ assert+ .dom(".category-box[data-category-id='1001']")+ .containsText(+ "Grandchild",+ "third level grandchildren are shown by default"+ );+ });++ test("categories_boxes hides grandchildren when the transformer prunes deeper levels", async function (assert) {+ hideGrandchildren();+ const { parent } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesBoxes @categories={{array parent}} /></template>+ );++ assert+ .dom(".category-box[data-category-id='1001']")+ .containsText("Child", "second level is still shown");+ assert+ .dom(".category-box[data-category-id='1001']")+ .doesNotContainText(+ "Grandchild",+ "third level grandchildren are hidden"+ );+ assert+ .dom(+ ".category-box[data-category-id='1001'] .subcategory.with-subcategories"+ )+ .doesNotExist(+ "falls back to the simple subcategory list rather than the grandparent layout"+ );+ });++ test("the transformer doesn't affect Category#subcategories", async function (assert) {+ hideGrandchildren();+ const { parent, child } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesBoxes @categories={{array parent}} /></template>+ );++ assert.deepEqual(+ child.subcategories.map((c) => c.id),+ [1003],+ "the model keeps its subcategories for the sidebar and topic lists"+ );+ });++ test("categories_only shows grandchildren as subcategory rows by default", async function (assert) {+ const { parent } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesOnly @categories={{array parent}} /></template>+ );++ assert+ .dom("tr[data-category-id='1002']")+ .exists("second level is rendered as a subcategory row");+ assert+ .dom("table.category-list")+ .containsText(+ "Grandchild",+ "third level grandchildren are shown by default"+ );+ });++ test("categories_only hides grandchildren when the transformer prunes deeper levels", async function (assert) {+ hideGrandchildren();+ const { parent } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesOnly @categories={{array parent}} /></template>+ );++ assert+ .dom("tr[data-category-id='1002']")+ .doesNotExist(+ "no subcategory rows are needed when grandchildren are hidden"+ );+ assert+ .dom("table.category-list")+ .containsText("Child", "second level is still shown as a simple list");+ assert+ .dom("table.category-list")+ .doesNotContainText(+ "Grandchild",+ "third level grandchildren are hidden"+ );+ });++ test("categories_boxes scopes pruning to the page the transformer names", async function (assert) {+ hideGrandchildrenAboveTopics();+ const { parent, child } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesBoxes @categories={{array parent}} /></template>+ );+ assert+ .dom(".category-box[data-category-id='1001']")+ .containsText(+ "Grandchild",+ "global /categories page still shows the third level"+ );++ await render(+ <template>+ <CategoriesBoxes+ @categories={{array child}}+ @categoryListPage="category"+ />+ </template>+ );+ assert+ .dom(".category-box[data-category-id='1002']")+ .containsText("Child", "the list above a category's topics shows it");+ assert+ .dom(".category-box[data-category-id='1002']")+ .doesNotContainText(+ "Grandchild",+ "but the same transformer caps that page at two levels"+ );+ });++ test("categories_only derives the page from the route", async function (assert) {+ hideGrandchildrenAboveTopics();+ const discovery = stubDiscovery(getOwner(this));+ const { parent, child } = seedNestedCategories(getOwner(this));++ await render(+ <template><CategoriesOnly @categories={{array parent}} /></template>+ );+ assert+ .dom("table.category-list")+ .containsText(+ "Grandchild",+ "global /categories rows still show the third level"+ );++ discovery.categoryListPage = "category";++ await render(+ <template><CategoriesOnly @categories={{array child}} /></template>+ );+ assert+ .dom("tr[data-category-id='1002']")+ .exists("the list above a category's topics renders the row");+ assert+ .dom("table.category-list")+ .doesNotContainText(+ "Grandchild",+ "and caps it at two levels without anything forwarding the page"+ );+ });+ }+);diff --git a/frontend/discourse/tests/unit/services/discovery-test.js b/frontend/discourse/tests/unit/services/discovery-test.jsnew file mode 100644index 00000000000..f5282f79542--- /dev/null+++ b/frontend/discourse/tests/unit/services/discovery-test.js@@ -0,0 +1,56 @@+import { getOwner } from "@ember/owner";+import Service from "@ember/service";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";++module("Unit | Service | discovery", function (hooks) {+ setupTest(hooks);++ function stubRouter(owner, currentRouteName, attributes = {}) {+ class RouterStub extends Service {+ currentRouteName = currentRouteName;+ currentRoute = { attributes };+ }++ owner.unregister("service:router");+ owner.register("service:router", RouterStub);++ return owner.lookup("service:discovery");+ }++ test("categoryListPage names the categories page", function (assert) {+ const discovery = stubRouter(getOwner(this), "discovery.categories");++ assert.strictEqual(discovery.categoryListPage, "categories");+ });++ test("categoryListPage names a category's subcategories page", function (assert) {+ const discovery = stubRouter(getOwner(this), "discovery.subcategories", {+ category: { id: 1 },+ });++ assert.strictEqual(discovery.categoryListPage, "subcategories");+ });++ test("categoryListPage names a category's topic list", function (assert) {+ const discovery = stubRouter(getOwner(this), "discovery.latest", {+ category: { id: 1 },+ });++ assert.strictEqual(discovery.categoryListPage, "category");+ });++ test("categoryListPage is undefined without a category listing", function (assert) {+ const discovery = stubRouter(getOwner(this), "discovery.latest");++ assert.strictEqual(discovery.categoryListPage, undefined);+ });++ test("categoryListPage is undefined away from discovery", function (assert) {+ const discovery = stubRouter(getOwner(this), "topic.fromParamsNear", {+ category: { id: 1 },+ });++ assert.strictEqual(discovery.categoryListPage, undefined);+ });+});