A platform for community discussion. Free, open, simple.
FEATURE: Category hashtag floating cards and subcategory hashtag improvements (#43157)
Martin Brennan7e5f79698025
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scssindex 9af6354cf2e..2ebe5bbcc15 100644--- a/app/assets/stylesheets/common/components/_index.scss+++ b/app/assets/stylesheets/common/components/_index.scss@@ -76,6 +76,7 @@@import "topic-map";@import "topic-query-filter";@import "user-card";+@import "category-card";@import "user-info";@import "user-status-message";@import "user-status-picker";diff --git a/app/assets/stylesheets/common/components/category-card.scss b/app/assets/stylesheets/common/components/category-card.scssnew file mode 100644index 00000000000..8986e02f760--- /dev/null+++ b/app/assets/stylesheets/common/components/category-card.scss@@ -0,0 +1,149 @@+@use "lib/viewport";++// shared card layout lives in user-card.scss+.category-card {+ &__avatar {+ display: flex;+ flex: 0 0 auto;+ width: var(--avatar-width);+ height: var(--avatar-width);+ margin-top: var(--avatar-margin);+ border-radius: var(--d-border-radius);+ overflow: hidden;++ .category-logo.aspect-image {+ width: 100%;+ height: 100%;+ margin: 0;++ img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ }+ }+ }++ .first-row .names {+ // the avatar only renders for uploaded logos+ &:first-child {+ padding-left: 0;++ // without the avatar, the zero flex-basis lets the controls share this line and squeeze the name out+ @include viewport.until(sm) {+ flex-basis: 100%;+ }+ }++ .category-card__link {+ display: flex;+ align-items: center;+ gap: 0.25em;+ }++ .category-card__ancestors {+ display: flex;+ gap: var(--space-2);+ font-size: var(--font-down-1);++ .category-card__link {+ color: var(--primary-high);+ }+ }++ .category-card__name {+ min-width: 0;++ @include ellipsis;+ }++ .category-card__style {+ display: flex;+ flex: 0 0 auto;++ &.--style-square {+ width: var(--category-badge-size);+ height: var(--category-badge-size);+ border-radius: var(--category-badge-border-radius);+ background: var(--category-badge-color);+ }++ .d-icon,+ .emoji {+ width: var(--category-badge-size);+ height: var(--category-badge-size);+ margin: 0;+ font-size: inherit;+ color: var(--category-badge-color);+ }+ }+ }++ &__edit-description {+ display: inline-flex;+ align-items: center;+ gap: var(--space-half);+ color: var(--primary-medium);+ font-size: var(--font-down-1);++ .d-icon {+ font-size: var(--font-down-1);+ }++ .bio + & {+ margin-top: var(--space-1);+ }+ }++ .card-content {+ .category-card__latest {+ margin-top: var(--space-3);+ }+ }++ &__latest-title {+ margin-bottom: var(--space-1);+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ }++ &__topics {+ display: flex;+ flex-direction: column;++ @include unstyled-list;+ }++ &__topics .featured-topic {+ display: flex;+ align-items: baseline;+ min-width: 0;+ padding-block: var(--space-1);+ border-top: 1px solid var(--content-border-color);++ .title {+ min-width: 0;+ color: var(--primary);++ @include ellipsis;+ }++ .topic-statuses {+ display: flex;+ }++ button.-trigger {+ padding: 0;+ border: none;+ background: transparent;+ }++ .last-posted-at {+ flex: 0 0 auto;+ margin-inline-start: auto;+ padding-inline-start: var(--space-2);+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ }+ }+}diff --git a/app/assets/stylesheets/common/components/user-card.scss b/app/assets/stylesheets/common/components/user-card.scssindex d7d9513aa99..dad7401ddfc 100644--- a/app/assets/stylesheets/common/components/user-card.scss+++ b/app/assets/stylesheets/common/components/user-card.scss@@ -1,7 +1,8 @@@use "sass:math";@use "lib/viewport";-.fk-d-menu[data-identifier="usercard"] {+.fk-d-menu[data-identifier="usercard"],+.fk-d-menu[data-identifier="category-card"] {max-width: calc(100vw - 2em);width: auto;@@ -48,9 +49,10 @@}}-// shared styles for user and group cards+// shared styles for user, group, and category cards.user-card,-.group-card {+.group-card,+.category-card {--card-width: 39em;--avatar-width: 8em;--avatar-margin: -3.3em; // extends the avatar above the card@@ -98,6 +100,8 @@// avatar - names - controls.first-row {+ display: flex;+@include viewport.until(sm) {flex-wrap: wrap;}@@ -254,8 +258,6 @@// avatar - names - controls.first-row {- display: flex;-.avatar-placeholder {width: var(--avatar-width);height: var(--avatar-width);@@ -528,8 +530,6 @@.group-card {// avatar - names and controls.first-row {- display: flex;-.group-card-avatar {margin-top: var(--avatar-margin);}diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex b95e1b295aa..8cd6e2264a0 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -5566,6 +5566,7 @@ en:list: "List categories"no_description: "Please add a description for this category."change_in_category_topic: "Edit description"+ latest_topics: "Latest topics"description_updated: "Description updated"description_expand: "Show more"description_collapse: "Show less"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 0cda5346fb5..41130d2b156 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -3132,6 +3132,7 @@ en:enable_new_defaults_for_trust_level_3_requirements: "We have updated the TL3 default requirements so they’re more reasonable for members of large, active communities. If you have previously overridden these settings, this upcoming change will have no effect."floating_dismiss_topics_on_mobile: "Shows a floating 'Dismiss...' button on mobile for the topic list for easier access and to free up space in the top of the topic list"rename_faq_to_guidelines: "This change renames the FAQ page to Guidelines. The FAQ page will still be available at /faq. The {{setting:faq_url}} setting works as before."+ enable_category_hashtag_cards: "Shows a floating category card when a category hashtag is clicked if the user has permission to view that category."enable_simplified_category_creation: "Enables a simplified category creation flow with fewer options and a cleaner interface."reporting_improvements: "Improvements to navigation, design, and usability for Discourse's admin reports."modernize_foundation_theme: "This change introduces design modifcations to the Foundation theme in Discourse."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 116e27d6f0d..b7392f21b42 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4833,6 +4833,15 @@ experimental:impact: "other,all_members"body_class: truelearn_more_url: "https://meta.discourse.org/t/-/407849"+ enable_category_hashtag_cards:+ default: false+ client: true+ hidden: true+ area: "experimental"+ upcoming_change:+ status: "experimental"+ impact: "feature,all_members"+ learn_more_url: "https://meta.discourse.org/t/-/412529"prioritize_recently_used_tags:default: falseclient: truediff --git a/frontend/discourse/app/components/card-container.gjs b/frontend/discourse/app/components/card-container.gjsindex 4caca5f04b6..195d1f17905 100644--- a/frontend/discourse/app/components/card-container.gjs+++ b/frontend/discourse/app/components/card-container.gjs@@ -2,6 +2,7 @@ import Component from "@glimmer/component";import { inject as controller } from "@ember/controller";import { action } from "@ember/object";import { service } from "@ember/service";+import CategoryCardContents from "discourse/components/category-card-contents";import GroupCardContents from "discourse/components/group-card-contents";import UserCardContents from "discourse/components/user-card-contents";import routeAction from "discourse/helpers/route-action";@@ -10,6 +11,7 @@ import PluginOutlet from "./plugin-outlet";export default class CardContainer extends Component {@service site;+ @service siteSettings;@controller topic;@action@@ -47,5 +49,9 @@ export default class CardContainer extends Component {@showUser={{this.showUser}}@topic={{this.topic.model}}/>++ {{#if this.siteSettings.enable_category_hashtag_cards}}+ <CategoryCardContents />+ {{/if}}</template>}diff --git a/frontend/discourse/app/components/card-contents-base.js b/frontend/discourse/app/components/card-contents-base.jsindex 1c77133238c..3673a83ed5f 100644--- a/frontend/discourse/app/components/card-contents-base.js+++ b/frontend/discourse/app/components/card-contents-base.js@@ -36,7 +36,12 @@ export default class CardContentsBase extends Component {@service site;@service siteSettings;+ canShowWhenUserProfilesHidden = false;elementId = null; //click detection added for data-{elementId}+ eventPrefix = "user-card";+ menuIdentifier = "usercard";+ showCardBeforeLoad = true;+ triggeringLinkSelector = null;visible = false;username = null;@@ -117,8 +122,11 @@ export default class CardContentsBase extends Component {}_show(username, target, event) {- // No user card for anon- if (this.siteSettings.hide_user_profiles_from_public && !this.currentUser) {+ if (+ this.siteSettings.hide_user_profiles_from_public &&+ !this.currentUser &&+ !this.canShowWhenUserProfilesHidden+ ) {return true;}@@ -144,7 +152,7 @@ export default class CardContentsBase extends Component {const post =this.viewingTopic && postId- ? this.postStream.findLoadedPost(postId)+ ? this.postStream?.findLoadedPost(postId): null;this.setProperties({@@ -154,15 +162,33 @@ export default class CardContentsBase extends Component {post,});- document.querySelector(".card-cloak")?.classList.add("--visible");-- this.appEvents.trigger("user-card:show", { username });+ if (this.eventPrefix) {+ this.appEvents.trigger(`${this.eventPrefix}:show`, { username });+ }// Using `next()` to optimise INP- next(() => {- this._positionCard(target, event);- this._showCallback(username).then((user) => {- this.appEvents.trigger("user-card:after-show", { user });- });+ next(async () => {+ if (this.isDestroying || this.cardTarget !== target) {+ return;+ }++ if (this.showCardBeforeLoad) {+ this._positionCard(target, event);+ }++ const user = await this._showCallback(username);++ if (+ !this.showCardBeforeLoad &&+ this.visible &&+ this.cardTarget === target &&+ !this.isDestroying+ ) {+ this._positionCard(target, event);+ }++ if (this.eventPrefix) {+ this.appEvents.trigger(`${this.eventPrefix}:after-show`, { user });+ }});// We bind scrolling on mobile after cards are shown to hide them if user scrolls@@ -240,11 +266,13 @@ export default class CardContentsBase extends Component {}async _positionCard(target) {+ document.querySelector(".card-cloak")?.classList.add("--visible");+if (this.site.desktopView) {this._menuInstance = await this.menu.show(target, {content: this.element,autoUpdate: { ancestorScroll: false, layoutShift: false },- identifier: "usercard",+ identifier: this.menuIdentifier,padding: {top: 10 + AVATAR_OVERFLOW_SIZE + headerOffset(),right: 10,@@ -265,7 +293,7 @@ export default class CardContentsBase extends Component {this._menuInstance = await this.menu.show(target, {content: this.element,strategy: "fixed",- identifier: "usercard",+ identifier: this.menuIdentifier,computePosition: (content) => {content.style.left = "10px";content.style.right = "10px";@@ -319,10 +347,12 @@ export default class CardContentsBase extends Component {@bind_clickOutsideHandler(event) {if (- !this.visible ||+ (!this.visible && !this.loading) ||event.target.closest(`[data-${this.elementId}]`)?.getAttribute(`data-${this.elementId}`) ||+ (this.triggeringLinkSelector &&+ event.target.closest(this.triggeringLinkSelector)) ||event.target.closest(`a.${this.triggeringLinkClass}`) ||event.target.closest(`#${this.elementId}`)) {@@ -334,7 +364,7 @@ export default class CardContentsBase extends Component {@bind_escListener(event) {- if (this.visible && event.key === "Escape") {+ if ((this.visible || this.loading) && event.key === "Escape") {this.cardTarget?.focus();this._close();}diff --git a/frontend/discourse/app/components/category-card-contents.gjs b/frontend/discourse/app/components/category-card-contents.gjsnew file mode 100644index 00000000000..dc9f14f775a--- /dev/null+++ b/frontend/discourse/app/components/category-card-contents.gjs@@ -0,0 +1,367 @@+import { concat } from "@ember/helper";+import { on } from "@ember/modifier";+import { action, computed } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { isEmpty } from "@ember/utils";+import { classNameBindings, classNames } from "@ember-decorators/component";+import CardContentsBase from "discourse/components/card-contents-base";+import CategoryLogo from "discourse/components/category-logo";+import FeaturedTopic from "discourse/components/topic-list/featured-topic";+import categoryVariables from "discourse/helpers/category-variables";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { wantsNewWindow } from "discourse/lib/intercept-click";+import { applyValueTransformer } from "discourse/lib/transformer";+import DiscourseURL from "discourse/lib/url";+import Category from "discourse/models/category";+import Composer from "discourse/models/composer";+import Topic from "discourse/models/topic";+import { and, eq, or } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DSkeleton from "discourse/ui-kit/d-skeleton";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";+import { i18n } from "discourse-i18n";++const CATEGORY_HASHTAG_SELECTOR =+ 'a.hashtag-cooked[data-type="category"][data-id]';+const LATEST_TOPICS_COUNT = 3;+const LATEST_TOPICS_CACHE_MS = 5 * 60 * 1000; // 5 minutes++const CategoryNameLink = <template>+ <a class="category-card__link" href={{@category.url}} ...attributes>+ <span+ class="category-card__style+ {{concat '--style-' (or @category.style_type 'square')}}"+ style={{categoryVariables @category}}+ >+ {{#if (and (eq @category.style_type "icon") @category.icon)}}+ {{dIcon @category.icon}}+ {{else if (and (eq @category.style_type "emoji") @category.emoji)}}+ {{dReplaceEmoji (concat ":" @category.emoji ":")}}+ {{/if}}+ </span>+ <span class="category-card__name">{{@category.name}}</span>+ {{yield}}+ </a>+</template>;++@classNames("category-card")+@classNameBindings("visible:show")+export default class CategoryCardContents extends CardContentsBase {+ @service composer;+ @service store;++ ancestorCategories = [];+ avatarDataAttrKey = "id";+ avatarSelector = CATEGORY_HASHTAG_SELECTOR;+ canShowWhenUserProfilesHidden = true;+ category = null;+ categoryId = null;+ elementId = "category-card";+ eventPrefix = null;+ latestTopics = null;+ menuIdentifier = "category-card";+ mentionSelector = CATEGORY_HASHTAG_SELECTOR;+ showCardBeforeLoad = false;+ triggeringLinkSelector = CATEGORY_HASHTAG_SELECTOR;++ #latestTopicsCache = new Map();++ @computed("category.permission")+ get canCreateTopic() {+ if (!this.currentUser || !this.category) {+ return false;+ }++ const canCreateTopic =+ this.currentUser.can_create_topic && this.category.canCreateTopic;++ return applyValueTransformer("can-create-topic-button", canCreateTopic, {+ category: this.category,+ tag: null,+ createTopicDisabled: !canCreateTopic,+ });+ }++ @computed("category.topic_url", "currentUser.admin")+ get canEditDescription() {+ if (!this.currentUser || !this.category) {+ return false;+ }++ return this.currentUser.admin && !isEmpty(this.category.topic_url);+ }++ @computed("category")+ get createTopicIcon() {+ const defaultIcon = "far-pen-to-square";++ return applyValueTransformer("create-topic-icon", defaultIcon, {+ site: this.site,+ defaultIcon,+ category: this.category,+ currentUser: this.currentUser,+ });+ }++ @computed("category")+ get createTopicLabel() {+ const defaultKey = "topic.create";+ const isSharedDraftsCategory =+ !isEmpty(this.site.shared_drafts_category_id) &&+ this.category?.id === this.site.shared_drafts_category_id;++ return applyValueTransformer(+ "create-topic-label",+ isSharedDraftsCategory ? "topic.create_shared_draft" : defaultKey,+ {+ site: this.site,+ defaultKey,+ category: this.category,+ currentUser: this.currentUser,+ }+ );+ }++ didInsertElement() {+ super.didInsertElement(...arguments);+ this.appEvents.on("dom:clean", this, this._close);+ }++ willDestroyElement() {+ this.appEvents.off("dom:clean", this, this._close);+ super.willDestroyElement(...arguments);+ }++ @action+ createTopic() {+ this.composer.openNewTopic({ category: this.category });+ this._close();+ }++ @action+ async editDescription(event) {+ if (wantsNewWindow(event)) {+ return;+ }++ event.preventDefault();+ const topicUrl = this.category.topic_url;+ this._close();++ try {+ const topicJson = await ajax(`${topicUrl}.json`);+ const topic = Topic.create(topicJson);+ const post = this.store.createRecord("post", {+ ...topicJson.post_stream.posts[0],+ topic,+ });++ this.composer.open({+ action: Composer.EDIT,+ post,+ draftKey: topic.draft_key,+ draftSequence: topic.draft_sequence,+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ async #loadAncestorCategories(category) {+ let result = this.#resolveAncestorCategories(category);++ if (!result.complete) {+ await Category.asyncFindBySlugPathWithID(category.id.toString());+ result = this.#resolveAncestorCategories(category);+ }++ return result.categories;+ }++ async #loadLatestTopics(category) {+ const cached = this.#latestTopicsCache.get(category.id);+ let topics = cached?.topics;++ if (!cached || Date.now() - cached.fetchedAt > LATEST_TOPICS_CACHE_MS) {+ try {+ const aboutTopicId = Number(category.topic_url?.split("/").pop());+ const list = await this.store.findFiltered("topicList", {+ filter: `${category.path.slice(1)}/l/latest`,+ params: { per_page: LATEST_TOPICS_COUNT + 1 },+ });++ topics = list.topics+ .filter((topic) => topic.id !== aboutTopicId)+ .slice(0, LATEST_TOPICS_COUNT);++ this.#latestTopicsCache.set(category.id, {+ topics,+ fetchedAt: Date.now(),+ });+ } catch {+ topics = [];+ }+ }++ if (!this.isDestroyed && this.category === category) {+ this.set("latestTopics", topics);+ }+ }++ #resolveAncestorCategories(category) {+ const categories = [];+ let parentCategoryId = category.parent_category_id;++ while (parentCategoryId) {+ const parent = Category.findById(parentCategoryId);++ if (!parent) {+ return { categories, complete: false };+ }++ categories.unshift(parent);+ parentCategoryId = parent.parent_category_id;+ }++ return { categories, complete: true };+ }++ _close() {+ this.setProperties({+ ancestorCategories: [],+ category: null,+ categoryId: null,+ latestTopics: null,+ });+ super._close(...arguments);+ }++ async _showCallback(categoryId) {+ const target = this.cardTarget;+ this.setProperties({ categoryId, loading: true });++ try {+ const category = await Category.asyncFindById(categoryId);+ const ancestorCategories = category+ ? await this.#loadAncestorCategories(category)+ : [];++ if (+ this.isDestroyed ||+ this.categoryId !== categoryId ||+ this.cardTarget !== target+ ) {+ return;+ }++ if (!category) {+ this._close();+ DiscourseURL.routeTo(target.href);+ return;+ }++ this.setProperties({+ ancestorCategories,+ category,+ loading: null,+ visible: true,+ });+ this.#loadLatestTopics(category);+ return category;+ } catch {+ if (+ !this.isDestroyed &&+ this.categoryId === categoryId &&+ this.cardTarget === target+ ) {+ this._close();+ DiscourseURL.routeTo(target.href);+ }+ }+ }++ <template>+ {{#if this.visible}}+ <div class="card-content">+ <div class="card-row first-row">+ {{#if this.category.uploaded_logo.url}}+ <a+ aria-hidden="true"+ class="category-card__avatar"+ href={{this.category.url}}+ tabindex="-1"+ >+ <CategoryLogo @category={{this.category}} />+ </a>+ {{/if}}+ <div class="names">+ {{#if this.ancestorCategories.length}}+ <div class="category-card__ancestors">+ {{#each this.ancestorCategories as |ancestor|}}+ <CategoryNameLink @category={{ancestor}} />+ {{/each}}+ </div>+ {{/if}}+ <div class="names__primary">+ <CategoryNameLink @category={{this.category}}>+ {{#if this.category.read_restricted}}+ {{dIcon "lock"}}+ {{/if}}+ </CategoryNameLink>+ </div>+ </div>+ {{#if this.canCreateTopic}}+ <ul class="usercard-controls">+ <li>+ <DButton+ class="btn-primary category-card__new-topic"+ @action={{this.createTopic}}+ @icon={{this.createTopicIcon}}+ @label={{this.createTopicLabel}}+ />+ </li>+ </ul>+ {{/if}}+ </div>++ {{#if (or this.category.description this.canEditDescription)}}+ <div class="card-row second-row">+ {{#if this.category.description}}+ <div class="bio">+ {{trustHTML this.category.description}}+ </div>+ {{/if}}+ {{#if this.canEditDescription}}+ <a+ class="category-card__edit-description"+ href={{this.category.topic_url}}+ {{on "click" this.editDescription}}+ >+ {{dIcon "pencil"}}+ {{i18n "category.change_in_category_topic"}}+ </a>+ {{/if}}+ </div>+ {{/if}}++ {{#if this.latestTopics}}+ <div class="card-row category-card__latest">+ <div class="category-card__latest-title">+ {{i18n "category.latest_topics"}}+ </div>+ <ul class="category-card__topics">+ {{#each this.latestTopics as |topic|}}+ <li><FeaturedTopic @topic={{topic}} /></li>+ {{/each}}+ </ul>+ </div>+ {{else if (eq this.latestTopics null)}}+ <DSkeleton class="card-row category-card__latest" @count={{3}} />+ {{/if}}+ </div>+ {{/if}}+ </template>+}diff --git a/frontend/discourse/app/lib/click-track.js b/frontend/discourse/app/lib/click-track.jsindex cf1ae67b7c9..2cd5ca11c6a 100644--- a/frontend/discourse/app/lib/click-track.js+++ b/frontend/discourse/app/lib/click-track.js@@ -88,11 +88,13 @@ export default {const tracking = isValidLink(link);- // Return early for mentions and group mentions. This is not in- // isValidLink because returning true here allows the group card- // to pop up. If we returned false it would not.+ // Card triggers must reach their delegated listeners without navigating.if (- ["mention", "mention-group"].some((name) => link.classList.contains(name))+ ["mention", "mention-group"].some((name) =>+ link.classList.contains(name)+ ) ||+ (link.matches('a.hashtag-cooked[data-type="category"][data-id]') &&+ owner?.lookup("service:site-settings")?.enable_category_hashtag_cards)) {return true;}diff --git a/frontend/discourse/tests/acceptance/user-card-test.js b/frontend/discourse/tests/acceptance/user-card-test.jsindex d2e801b8e32..43c5c48b331 100644--- a/frontend/discourse/tests/acceptance/user-card-test.js+++ b/frontend/discourse/tests/acceptance/user-card-test.js@@ -1,8 +1,9 @@import { getOwner } from "@ember/owner";-import { click, currentURL, visit } from "@ember/test-helpers";+import { click, currentURL, triggerKeyEvent, visit } from "@ember/test-helpers";import { test } from "qunit";import { longDate } from "discourse/lib/formatter";import { cloneJSON } from "discourse/lib/object";+import topicFixtures from "discourse/tests/fixtures/topic";import userFixtures from "discourse/tests/fixtures/user-fixtures";import { acceptance } from "discourse/tests/helpers/qunit-helpers";import { i18n } from "discourse-i18n";@@ -25,6 +26,74 @@ acceptance("User Card", function (needs) {});});+acceptance("Category Card", function (needs) {+ needs.user();+ needs.settings({ enable_category_hashtag_cards: true });++ needs.pretender((server, helper) => {+ server.get("/t/280.json", () => {+ const topic = cloneJSON(topicFixtures["/t/280/1.json"]);+ topic.post_stream.posts[0].cooked =+ '<p>The <a class="hashtag-cooked" data-type="category" data-id="1" href="/c/bug/1"><span>bug</span></a> category.</p>';+ return helper.response(topic);+ });+ });++ test("opens a category card from a topic post without navigating", async function (assert) {+ const topicUrl = "/t/internationalization-localization/280";+ await visit(topicUrl);+ await click('#post_1 a.hashtag-cooked[data-type="category"] span');++ assert+ .dom(".category-card .card-content")+ .exists("the category card opens within a topic");+ assert.strictEqual(currentURL(), topicUrl, "the topic remains open");++ await triggerKeyEvent(".category-card", "keyup", "Escape");++ assert+ .dom(".category-card .card-content")+ .doesNotExist("Escape closes the card");+ });++ test("closes the category card when navigating away", async function (assert) {+ const topicUrl = "/t/internationalization-localization/280";+ await visit(topicUrl);+ await click('#post_1 a.hashtag-cooked[data-type="category"] span');++ assert.dom(".category-card .card-content").exists("the card opens");++ await visit("/latest");++ assert+ .dom(".category-card .card-content")+ .doesNotExist("navigation clears the card content");+ assert+ .dom('.fk-d-menu[data-identifier="category-card"]')+ .doesNotExist("navigation removes the floating menu");++ await visit(topicUrl);+ await click('#post_1 a.hashtag-cooked[data-type="category"] span');++ assert+ .dom(".category-card .card-content")+ .exists("the card can reopen after navigation");+ });++ test("navigates to the category when category cards are disabled", async function (assert) {+ this.siteSettings.enable_category_hashtag_cards = false;++ await visit("/t/internationalization-localization/280");++ assert.dom(".category-card").doesNotExist("the card is not mounted");++ await click('#post_1 a.hashtag-cooked[data-type="category"] span');++ assert.strictEqual(currentURL(), "/c/bug/1", "the category opens normally");+ assert.dom(".category-card").doesNotExist("no category card opens");+ });+});+acceptance("User Card - Show Local Time", function (needs) {needs.user();needs.settings({ display_local_time_in_user_card: true });diff --git a/frontend/discourse/tests/integration/components/category-card-contents-test.gjs b/frontend/discourse/tests/integration/components/category-card-contents-test.gjsnew file mode 100644index 00000000000..c1c29583aad--- /dev/null+++ b/frontend/discourse/tests/integration/components/category-card-contents-test.gjs@@ -0,0 +1,608 @@+import {+ click,+ findAll,+ render,+ triggerEvent,+ waitUntil,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import CategoryCardContents from "discourse/components/category-card-contents";+import { forceMobile } from "discourse/lib/mobile";+import { withPluginApi } from "discourse/lib/plugin-api";+import DiscourseURL from "discourse/lib/url";+import Category from "discourse/models/category";+import PermissionType from "discourse/models/permission-type";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";++module("Integration | Component | CategoryCardContents", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ pretender.get("/c/*path", () => response({ topic_list: { topics: [] } }));+ });++ test("opens from a category hashtag and closes on an outside click", async function (assert) {+ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="2"+ data-type="category"+ href="/c/product/2"+ >#product</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');++ assert.dom(".category-card .card-content").exists("the card opens");++ await triggerEvent("#main-outlet", "pointerdown");++ assert.dom(".category-card .card-content").doesNotExist("the card closes");+ });++ test("lazy loads a category outside a post and reuses it on reopening", async function (assert) {+ this.site.set("lazy_load_categories", true);+ const requestedIds = [];++ pretender.get("/categories/find", (request) => {+ requestedIds.push(request.queryParams.ids);+ return response({+ categories: [+ { id: 12345, name: "Lazy category", slug: "lazy-category" },+ ],+ });+ });++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="12345"+ data-type="category"+ href="/c/lazy-category/12345"+ >#lazy-category</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');++ assert.deepEqual(+ requestedIds,+ [["12345"]],+ "the hashtag ID is lazy loaded"+ );+ assert.strictEqual(+ Category.findById(12345).name,+ "Lazy category",+ "the category model is available"+ );+ assert+ .dom(".category-card .card-content")+ .exists("the card opens without a topic or post");++ await triggerEvent("#main-outlet", "pointerdown");+ await click('a.hashtag-cooked[data-type="category"]');++ assert.dom(".category-card .card-content").exists("the card reopens");+ assert.strictEqual(requestedIds.length, 1, "the loaded category is reused");+ });++ test("shows category ancestors from the root down", async function (assert) {+ this.site.set("lazy_load_categories", true);+ const requestedLookups = [];+ const categories = {+ 54: { id: 54, name: "Fiction", slug: "fiction" },+ 55: {+ id: 55,+ name: "Crime",+ parent_category_id: 54,+ slug: "crime",+ },+ 56: {+ id: 56,+ name: "Noir",+ parent_category_id: 55,+ slug: "noir",+ },+ };++ pretender.get("/categories/find", (request) => {+ if (request.queryParams.ids) {+ requestedLookups.push({ ids: request.queryParams.ids });+ return response({ categories: [categories[56]] });+ }++ requestedLookups.push({+ slugPathWithId: request.queryParams.slug_path_with_id,+ });+ return response({ categories: Object.values(categories) });+ });++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="56"+ data-type="category"+ href="/c/fiction/crime/noir/56"+ >#noir</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');++ assert.deepEqual(+ requestedLookups,+ [{ ids: ["56"] }, { slugPathWithId: "56" }],+ "loads the category and its ancestors"+ );+ assert.deepEqual(+ findAll(".category-card__ancestors .category-card__name").map((element) =>+ element.textContent.trim()+ ),+ ["Fiction", "Crime"],+ "shows ancestors from the root down"+ );+ assert+ .dom(".names__primary .category-card__name")+ .hasText("Noir", "shows the selected category last");+ });++ test("offers a new topic button only where the user can create topics", async function (assert) {+ this.site.set("lazy_load_categories", true);+ this.owner.lookup("service:current-user").set("can_create_topic", true);+ const composer = { openNewTopic: sinon.stub() };+ this.owner.unregister("service:composer");+ this.owner.register("service:composer", composer, { instantiate: false });++ pretender.get("/categories/find", (request) => {+ const id = Number(request.queryParams.ids[0]);++ return response({+ categories: [+ {+ id,+ name: "Writable",+ slug: "writable",+ permission: id === 12348 ? PermissionType.FULL : null,+ },+ ],+ });+ });++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked writable-hashtag"+ data-id="12348"+ data-type="category"+ href="/c/writable/12348"+ >#writable</a>+ <a+ class="hashtag-cooked readonly-hashtag"+ data-id="12349"+ data-type="category"+ href="/c/writable/12349"+ >#readonly</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click(".readonly-hashtag");++ assert+ .dom(".category-card__new-topic")+ .doesNotExist("hidden without create permission on the category");++ await triggerEvent("#main-outlet", "pointerdown");+ await click(".writable-hashtag");+ await click(".category-card__new-topic");++ assert.true(composer.openNewTopic.calledOnce, "opens the composer");+ assert.strictEqual(+ composer.openNewTopic.firstCall?.args[0].category.id,+ 12348,+ "the composer targets the card's category"+ );+ assert.dom(".category-card .card-content").doesNotExist("closes the card");+ });++ test("hides the new topic button when the user cannot create topics", async function (assert) {+ this.site.set("lazy_load_categories", true);+ this.owner.lookup("service:current-user").set("can_create_topic", false);++ pretender.get("/categories/find", () =>+ response({+ categories: [+ {+ id: 12350,+ name: "Writable",+ slug: "writable",+ permission: PermissionType.FULL,+ },+ ],+ })+ );++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="12350"+ data-type="category"+ href="/c/writable/12350"+ >#writable</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');++ assert.dom(".category-card .card-content").exists("the card opens");+ assert.dom(".category-card__new-topic").doesNotExist();+ });++ test("shows admins an edit description link, even without a description", async function (assert) {+ this.site.set("lazy_load_categories", true);+ const currentUser = this.owner.lookup("service:current-user");++ pretender.get("/categories/find", () =>+ response({+ categories: [+ {+ id: 12351,+ name: "Undescribed",+ slug: "undescribed",+ topic_url: "/t/about-the-undescribed-category/99",+ },+ ],+ })+ );++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="12351"+ data-type="category"+ href="/c/undescribed/12351"+ >#undescribed</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ currentUser.set("admin", true);+ await click('a.hashtag-cooked[data-type="category"]');++ assert.dom(".category-card .bio").doesNotExist("there is no description");+ assert+ .dom(".category-card__edit-description")+ .hasAttribute("href", "/t/about-the-undescribed-category/99");++ await triggerEvent("#main-outlet", "pointerdown");+ currentUser.set("admin", false);+ await click('a.hashtag-cooked[data-type="category"]');++ assert+ .dom(".category-card__edit-description")+ .doesNotExist("hidden from non-admins");+ });++ test("applies the create topic label and icon transformers to the new topic button", async function (assert) {+ this.site.set("lazy_load_categories", true);+ this.owner.lookup("service:current-user").set("can_create_topic", true);++ withPluginApi((api) => {+ api.registerValueTransformer(+ "create-topic-label",+ ({ value, context }) =>+ context.category?.id === 12352 ? "topic.create_long" : value+ );+ api.registerValueTransformer("create-topic-icon", () => "plus");+ });++ pretender.get("/categories/find", () =>+ response({+ categories: [+ {+ id: 12352,+ name: "Events",+ slug: "events",+ permission: PermissionType.FULL,+ },+ ],+ })+ );++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="12352"+ data-type="category"+ href="/c/events/12352"+ >#events</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');++ assert.dom(".category-card__new-topic").hasText("Create a new topic");+ assert.dom(".category-card__new-topic .d-icon-plus").exists();+ });++ test("edit description opens the composer on the about topic's first post", async function (assert) {+ this.site.set("lazy_load_categories", true);+ this.owner.lookup("service:current-user").set("admin", true);+ const composer = { open: sinon.stub() };+ this.owner.unregister("service:composer");+ this.owner.register("service:composer", composer, { instantiate: false });++ pretender.get("/categories/find", () =>+ response({+ categories: [+ {+ id: 12354,+ name: "Editable",+ slug: "editable",+ topic_url: "/t/about-the-editable-category/98",+ },+ ],+ })+ );+ pretender.get("/t/about-the-editable-category/98.json", () =>+ response({+ id: 98,+ title: "About the Editable category",+ draft_key: "topic_98",+ draft_sequence: 3,+ post_stream: {+ posts: [{ id: 555, post_number: 1, topic_id: 98 }],+ stream: [555],+ },+ })+ );++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="12354"+ data-type="category"+ href="/c/editable/12354"+ >#editable</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');+ await click(".category-card__edit-description");++ assert.true(composer.open.calledOnce, "opens the composer");++ const opts = composer.open.firstCall?.args[0];+ assert.strictEqual(opts?.action, "edit");+ assert.strictEqual(opts?.post.id, 555, "edits the first post");+ assert.strictEqual(opts?.draftKey, "topic_98");+ assert.dom(".category-card .card-content").doesNotExist("closes the card");+ });++ test("lists the category's latest topics and reuses them on reopening", async function (assert) {+ this.site.set("lazy_load_categories", true);+ const latestRequests = [];++ pretender.get("/categories/find", () =>+ response({+ categories: [+ {+ id: 12355,+ name: "Busy",+ slug: "busy",+ topic_url: "/t/about-the-busy-category/700",+ },+ ],+ })+ );+ pretender.get("/c/busy/12355/l/latest.json", (request) => {+ latestRequests.push(request.queryParams);+ return response({+ topic_list: {+ topics: [+ {+ id: 700,+ slug: "about-the-busy-category",+ fancy_title: "About the Busy category",+ bumped_at: "2026-09-02T00:00:00.000Z",+ posters: [],+ },+ {+ id: 701,+ slug: "first-topic",+ fancy_title: "First topic",+ bumped_at: "2026-09-01T00:00:00.000Z",+ posters: [],+ },+ {+ id: 702,+ slug: "second-topic",+ fancy_title: "Second topic",+ bumped_at: "2026-08-01T00:00:00.000Z",+ posters: [],+ },+ ],+ },+ });+ });++ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="12355"+ data-type="category"+ href="/c/busy/12355"+ >#busy</a>+ </div>+ <CategoryCardContents />+ </template>+ );++ await click('a.hashtag-cooked[data-type="category"]');++ assert.dom(".category-card__topics .featured-topic").exists({ count: 2 });+ assert+ .dom(".category-card__topics .featured-topic .title")+ .hasAttribute("href", /^\/t\/first-topic\/701/)+ .hasText("First topic");+ assert+ .dom(".category-card__topics")+ .doesNotIncludeText(+ "About the Busy category",+ "leaves out the about topic"+ );+ assert.strictEqual(+ latestRequests[0]?.per_page,+ "4",+ "asks for one extra topic to cover the about topic"+ );++ await triggerEvent("#main-outlet", "pointerdown");+ await click('a.hashtag-cooked[data-type="category"]');++ assert+ .dom(".category-card__topics .featured-topic")+ .exists({ count: 2 }, "the reopened card lists the topics");+ assert.strictEqual(latestRequests.length, 1, "the list is cached");+ });+});++module(+ "Integration | Component | CategoryCardContents | Anonymous",+ function (hooks) {+ setupRenderingTest(hooks, { anonymous: true });++ async function renderStaffHashtag() {+ await render(+ <template>+ <div id="main-outlet">+ <a+ class="hashtag-cooked"+ data-id="123456"+ data-type="category"+ href="/c/staff/123456"+ >#staff</a>+ </div>+ <div class="card-cloak"></div>+ <CategoryCardContents />+ </template>+ );+ }++ for (const mobileView of [false, true]) {+ for (const status of [null, 200, 403, 404]) {+ test(`navigates without opening a popup for an inaccessible category (${mobileView ? "mobile" : "desktop"}, ${status ?? "preloaded"})`, async function (assert) {+ if (mobileView) {+ forceMobile();+ }+ this.site.set("lazy_load_categories", status !== null);+ const routeTo = sinon.stub(DiscourseURL, "routeTo");++ if (status !== null) {+ pretender.get("/categories/find", () =>+ response(status, { categories: [] })+ );+ }++ await renderStaffHashtag();+ const createMenu = sinon.spy(+ this.owner.lookup("service:menu"),+ "newInstance"+ );+ await click('a.hashtag-cooked[data-type="category"]');++ assert.true(+ routeTo.calledOnceWithExactly(+ `${window.location.origin}/c/staff/123456`+ ),+ "the original category URL handles the unavailable category"+ );+ assert.false(createMenu.called, "no floating menu is ever created");+ assert+ .dom('.fk-d-menu[data-identifier="category-card"]')+ .doesNotExist("no empty popup remains");+ assert+ .dom(".category-card .card-content")+ .doesNotExist("no category content is shown");+ assert+ .dom(".card-cloak")+ .doesNotHaveClass("--visible", "no mobile cloak is shown");+ });+ }+ }++ for (const accessible of [false, true]) {+ test(`navigation during lookup does not reopen or redirect (accessible: ${accessible})`, async function (assert) {+ this.site.set("lazy_load_categories", true);+ const routeTo = sinon.stub(DiscourseURL, "routeTo");+ let releaseLookup;++ pretender.get("/categories/find", async () => {+ await new Promise((resolve) => (releaseLookup = resolve));+ return response({+ categories: accessible+ ? [{ id: 123456, name: "Staff", slug: "staff" }]+ : [],+ });+ });++ await renderStaffHashtag();+ const opening = click('a.hashtag-cooked[data-type="category"]');+ await waitUntil(() => releaseLookup);++ assert+ .dom('.fk-d-menu[data-identifier="category-card"]')+ .doesNotExist("no popup opens while access is unresolved");+ assert+ .dom(".category-card .card-content")+ .doesNotExist("no content is shown while loading");++ this.owner.lookup("service:app-events").trigger("dom:clean");+ releaseLookup();+ await opening;++ assert.false(routeTo.called, "a cancelled lookup does not navigate");+ assert+ .dom('.fk-d-menu[data-identifier="category-card"]')+ .doesNotExist("a cancelled lookup does not open a popup");+ assert+ .dom(".category-card .card-content")+ .doesNotExist("the card stays closed");+ });+ }+ }+);diff --git a/frontend/discourse/tests/unit/lib/click-track-test.js b/frontend/discourse/tests/unit/lib/click-track-test.jsindex bc83467b085..13010f89c9e 100644--- a/frontend/discourse/tests/unit/lib/click-track-test.js+++ b/frontend/discourse/tests/unit/lib/click-track-test.js@@ -1,3 +1,4 @@+import { settled } from "@ember/test-helpers";import { setupTest } from "ember-qunit";import { module, test } from "qunit";import sinon from "sinon";@@ -62,6 +63,7 @@ module("Unit | Utility | click-track", function (hooks) {<a class="mention" href="/u/joe">@joe</a><a class="hashtag-cooked" href="/c/staff/42" data-type="category" data-slug="staff"><svg class="fa d-icon d-icon-folder svg-icon svg-node"><use href="#folder"></use></svg><span>staff</span></a><a class="mention-group" href="/g/support">@support</a>+ <a class="hashtag-cooked category-card-hashtag" href="/c/staff/42" data-type="category" data-id="42">staff</a><a class="mailto" href="mailto:[email protected]">email-me</a><a class="a-without-href">no href</a><aside class="quote">@@ -242,6 +244,40 @@ module("Unit | Utility | click-track", function (hooks) {assert.true(track(generateClickEventOn(".mention-group")));});+ test("leaves category card hashtags to the card listener", async function (assert) {+ this.owner.lookup("service:site-settings").enable_category_hashtag_cards =+ true;++ assert.true(+ track(generateClickEventOn(".category-card-hashtag"), this.owner),+ "the event reaches the card listener"+ );++ await settled();++ assert.false(+ DiscourseURL.routeTo.called,+ "the link tracker does not navigate away from the card"+ );+ });++ test("navigates category hashtags when category cards are disabled", async function (assert) {+ this.owner.lookup("service:site-settings").enable_category_hashtag_cards =+ false;++ assert.false(+ track(generateClickEventOn(".category-card-hashtag"), this.owner),+ "the link tracker handles navigation"+ );++ await settled();++ assert.true(+ DiscourseURL.routeTo.calledWith("/c/staff/42"),+ "the category opens normally"+ );+ });+test("does not track clicks on mailto", async function (assert) {assert.true(track(generateClickEventOn(".mailto")));});diff --git a/spec/system/category_card_access_spec.rb b/spec/system/category_card_access_spec.rbnew file mode 100644index 00000000000..12c75c0a4ce--- /dev/null+++ b/spec/system/category_card_access_spec.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++RSpec.describe "Category card access" do+ fab!(:author, :admin)+ fab!(:allowed_group, :group)+ fab!(:allowed_user, :user)+ fab!(:denied_user, :user)+ fab!(:group_user) { Fabricate(:group_user, group: allowed_group, user: allowed_user) }+ fab!(:private_category) do+ Fabricate(+ :private_category,+ group: allowed_group,+ name: "Private category",+ slug: "private-category",+ )+ end+ fab!(:topic)+ fab!(:post_with_category_hashtag) do+ Fabricate(:post, raw: "See the #private-category category", topic: topic, user: author)+ end++ let(:category_card) { PageObjects::Components::CategoryCard.new }+ let(:hashtag_post) { PageObjects::Components::Post.new(post_with_category_hashtag.post_number) }+ let(:not_found_page) { PageObjects::Pages::NotFound.new }+ let(:topic_page) { PageObjects::Pages::Topic.new }++ before { SiteSetting.enable_category_hashtag_cards = true }++ it "lets a logged-in user with permission open the category card" do+ sign_in(allowed_user)+ topic_page.visit_topic(topic, post_number: post_with_category_hashtag.post_number)++ hashtag_post.click_category_hashtag(private_category)++ expect(category_card).to be_showing_category(private_category)+ end++ it "keeps the category card closed for a logged-in user without permission" do+ sign_in(denied_user)+ topic_page.visit_topic(topic, post_number: post_with_category_hashtag.post_number)++ hashtag_post.click_category_hashtag(private_category)++ expect(not_found_page).to be_visible+ expect(category_card).to be_closed+ end++ it "keeps the category card closed for an anonymous user" do+ topic_page.visit_topic(topic, post_number: post_with_category_hashtag.post_number)++ hashtag_post.click_category_hashtag(private_category)++ expect(not_found_page).to be_visible+ expect(category_card).to be_closed+ end+enddiff --git a/spec/system/page_objects/components/category_card.rb b/spec/system/page_objects/components/category_card.rbnew file mode 100644index 00000000000..0537945e65f--- /dev/null+++ b/spec/system/page_objects/components/category_card.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class CategoryCard < PageObjects::Components::Base+ CARD_CONTENT_SELECTOR = ".category-card .card-content"++ def closed?+ has_no_css?(CARD_CONTENT_SELECTOR)+ end++ def showing_category?(category)+ has_css?(+ "#{CARD_CONTENT_SELECTOR} .names__primary a[href='#{category.url}']",+ text: category.name,+ )+ end+ end+ end+enddiff --git a/spec/system/page_objects/components/post.rb b/spec/system/page_objects/components/post.rbindex 5b5e177b5e2..f53ad51e21d 100644--- a/spec/system/page_objects/components/post.rb+++ b/spec/system/page_objects/components/post.rb@@ -38,6 +38,10 @@ module PageObjectspost.find(".contents > .cooked")end+ def click_category_hashtag(category)+ post.find("a.hashtag-cooked[data-type='category'][data-id='#{category.id}']").click+ end+def has_cooked_content?(value)cooked_content.has_content?(value)enddiff --git a/spec/system/page_objects/pages/not_found.rb b/spec/system/page_objects/pages/not_found.rbnew file mode 100644index 00000000000..dfd5d1be2f4--- /dev/null+++ b/spec/system/page_objects/pages/not_found.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ class NotFound < PageObjects::Pages::Base+ def visible?+ has_css?("div.page-not-found")+ end+ end+ end+end