Skip to content

Commit 22a1303

Browse files
committed
Show topic counts for custom nav links matching /new and /unread
Custom nav links pointing to /new or /unread now display the topic count in parentheses (e.g., "New (24)"), matching the behavior of Discourse's built-in navigation items. The count is retrieved from the TopicTrackingState service and updates reactively. Links with other URLs remain unchanged.
1 parent b21accc commit 22a1303

2 files changed

Lines changed: 54 additions & 3 deletions

File tree

javascripts/discourse/initializers/init-nav-bar-additions.js

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,70 @@
11
import { withPluginApi } from "discourse/lib/plugin-api";
22

3+
// Built-in Discourse filter routes that have associated topic counts
4+
const COUNTED_FILTERS = {
5+
"/new": "new",
6+
"/unread": "unread",
7+
};
8+
9+
function getCountForFilter(topicTrackingState, filterType) {
10+
if (!topicTrackingState) {
11+
return 0;
12+
}
13+
14+
if (filterType === "new") {
15+
return (
16+
topicTrackingState.countNew?.() ??
17+
topicTrackingState.newCount ??
18+
0
19+
);
20+
}
21+
22+
if (filterType === "unread") {
23+
return (
24+
topicTrackingState.countUnread?.() ??
25+
topicTrackingState.unreadCount ??
26+
0
27+
);
28+
}
29+
30+
return 0;
31+
}
32+
333
export default {
434
name: "nav-links-component",
535

636
initialize() {
737
withPluginApi((api) => {
38+
const topicTrackingState = api.container.lookup(
39+
"service:topic-tracking-state"
40+
);
41+
842
for (const {
943
display_name: displayName,
1044
title,
1145
url,
1246
} of settings.nav_links) {
13-
api.addNavigationBarItem({
47+
const filterType = COUNTED_FILTERS[url];
48+
const itemConfig = {
1449
name: `custom_${displayName.replace(/\s+/g, "-").toLowerCase()}`,
15-
displayName,
1650
title,
1751
href: url,
1852
forceActive: (category, args, router) =>
1953
router.currentURL?.split("?")[0] === url,
20-
});
54+
};
55+
56+
if (settings.Show_counts && filterType && topicTrackingState) {
57+
// Use a function for displayName so Discourse re-evaluates it
58+
// reactively, picking up count changes from TopicTrackingState
59+
itemConfig.displayName = () => {
60+
const count = getCountForFilter(topicTrackingState, filterType);
61+
return count > 0 ? `${displayName} (${count})` : displayName;
62+
};
63+
} else {
64+
itemConfig.displayName = displayName;
65+
}
66+
67+
api.addNavigationBarItem(itemConfig);
2168
}
2269
});
2370
},

settings.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,7 @@ Hide_default_links:
4040
default: false
4141
description:
4242
en: "Hide the default links on both mobile and desktop."
43+
Show_counts:
44+
default: false
45+
description:
46+
en: "Show topic counts for links pointing to /new or /unread (e.g. New (24))."

0 commit comments

Comments
 (0)