A platform for community discussion. Free, open, simple.
DEV: Introduce AdminNavManager service for admin sidebar and search links (#33357)
Martin Brennand8c855e55978
diff --git a/app/assets/javascripts/admin/addon/services/admin-nav-manager.js b/app/assets/javascripts/admin/addon/services/admin-nav-manager.jsnew file mode 100644index 00000000000..b0f26185081--- /dev/null+++ b/app/assets/javascripts/admin/addon/services/admin-nav-manager.js@@ -0,0 +1,76 @@+import Service, { service } from "@ember/service";+import { cloneJSON } from "discourse/lib/object";+import { ADMIN_NAV_MAP } from "discourse/lib/sidebar/admin-nav-map";++export default class AdminNavManager extends Service {+ @service currentUser;++ #adminNavMap = cloneJSON(ADMIN_NAV_MAP);+ #filteredNavMap = null;++ get filteredNavMap() {+ if (this.#filteredNavMap) {+ return this.#filteredNavMap;+ }++ let navConfig = cloneJSON(this.#adminNavMap);++ if (this.currentUser.admin) {+ return navConfig;+ }++ navConfig.forEach((section) => {+ section.links = section.links.filter((link) => {+ return link.moderator;+ });+ });+ navConfig = navConfig.filter((section) => section.links.length);++ this.#filteredNavMap = navConfig;++ return this.#filteredNavMap;+ }++ findSection(sectionName) {+ this.#guardFilteredNavAccess();++ return this.#adminNavMap.find((section) => section.name === sectionName);+ }++ amendLinksToSection(sectionName, links) {+ this.#guardFilteredNavAccess();++ const section = this.findSection(sectionName);+ if (!section) {+ // eslint-disable-next-line no-console+ console.warn(`[AdminNavManager] Section ${sectionName} not found`);+ return;+ }++ section.links.push(...links);+ }++ overrideSectionLink(sectionName, linkName, newAttrs = {}) {+ this.#guardFilteredNavAccess();++ const section = this.findSection(sectionName);+ const foundLink = section.links.find((link) => link.name === linkName);++ if (foundLink) {+ Object.assign(foundLink, newAttrs);+ } else {+ // eslint-disable-next-line no-console+ console.warn(+ `[AdminNavManager] Link ${linkName} not found in section ${sectionName}`+ );+ }+ }++ #guardFilteredNavAccess() {+ if (this.#filteredNavMap) {+ throw new Error(+ "Cannot call findSection after filteredNavMap has been accessed, admin nav state can only be modified in admin-sidebar.js"+ );+ }+ }+}diff --git a/app/assets/javascripts/admin/addon/services/admin-search-data-source.js b/app/assets/javascripts/admin/addon/services/admin-search-data-source.jsindex 327f89c1325..c75eadae560 100644--- a/app/assets/javascripts/admin/addon/services/admin-search-data-source.js+++ b/app/assets/javascripts/admin/addon/services/admin-search-data-source.js@@ -5,7 +5,6 @@ import { ajax } from "discourse/lib/ajax";import escapeRegExp from "discourse/lib/escape-regexp";import getURL from "discourse/lib/get-url";import PreloadStore from "discourse/lib/preload-store";-import { ADMIN_NAV_MAP } from "discourse/lib/sidebar/admin-nav-map";import I18n, { i18n } from "discourse-i18n";import { ADMIN_SEARCH_RESULT_TYPES } from "admin/lib/constants";@@ -209,6 +208,7 @@ export class SettingLinkFormatter {export default class AdminSearchDataSource extends Service {@service router;@service siteSettings;+ @service adminNavManager;plugins = {};pageDataSourceItems = [];@@ -227,7 +227,7 @@ export default class AdminSearchDataSource extends Service {return;}- ADMIN_NAV_MAP.forEach((navMapSection) => {+ this.adminNavManager.filteredNavMap.forEach((navMapSection) => {navMapSection.links.forEach((link) => {let parentLabel = this.#addPageLink(navMapSection, link);diff --git a/app/assets/javascripts/admin/addon/services/admin-sidebar-state-manager.js b/app/assets/javascripts/admin/addon/services/admin-sidebar-state-manager.jsindex 39c3e7ff471..977070aff05 100644--- a/app/assets/javascripts/admin/addon/services/admin-sidebar-state-manager.js+++ b/app/assets/javascripts/admin/addon/services/admin-sidebar-state-manager.js@@ -1,5 +1,4 @@import Service, { service } from "@ember/service";-import KeyValueStore from "discourse/lib/key-value-store";import scrollLock from "discourse/lib/scroll-lock";import { ADMIN_PANEL, MAIN_PANEL } from "discourse/lib/sidebar/panels";import AdminSearchModal from "admin/components/modal/admin-search";@@ -8,17 +7,7 @@ export default class AdminSidebarStateManager extends Service {@service sidebarState;@service header;- STORE_NAMESPACE = "discourse_admin_sidebar_experiment_";keywords = {};- store = new KeyValueStore(this.STORE_NAMESPACE);-- get navConfig() {- return this.store.getObject("navConfig");- }-- set navConfig(value) {- this.store.setObject({ key: "navConfig", value });- }setLinkKeywords(link_name, keywords) {if (!this.keywords[link_name]) {diff --git a/app/assets/javascripts/discourse/app/lib/sidebar/admin-sidebar.js b/app/assets/javascripts/discourse/app/lib/sidebar/admin-sidebar.jsindex 2f59e8c240d..e8130dddde6 100644--- a/app/assets/javascripts/discourse/app/lib/sidebar/admin-sidebar.js+++ b/app/assets/javascripts/discourse/app/lib/sidebar/admin-sidebar.js@@ -5,7 +5,6 @@ import { adminRouteValid } from "discourse/lib/admin-utilities";import { getOwnerWithFallback } from "discourse/lib/get-owner";import getURL from "discourse/lib/get-url";import PreloadStore from "discourse/lib/preload-store";-import { ADMIN_NAV_MAP } from "discourse/lib/sidebar/admin-nav-map";import BaseCustomSidebarPanel from "discourse/lib/sidebar/base-custom-sidebar-panel";import BaseCustomSidebarSection from "discourse/lib/sidebar/base-custom-sidebar-section";import BaseCustomSidebarSectionLink from "discourse/lib/sidebar/base-custom-sidebar-section-link";@@ -187,21 +186,6 @@ function defineAdminSection(return AdminNavSection;}-export function useAdminNavConfig(navMap) {- for (const [sectionName, additionalLinks] of Object.entries(- additionalAdminSidebarSectionLinks- )) {- const section = navMap.find(- (navSection) => navSection.name === sectionName- );- if (section && additionalLinks.length) {- section.links.push(...additionalLinks);- }- }-- return navMap;-}-// This is used for a plugin API.export function addAdminSidebarSectionLink(sectionName, link) {if (!additionalAdminSidebarSectionLinks.hasOwnProperty(sectionName)) {@@ -310,7 +294,9 @@ function pluginAdminRouteLinks(router) {}function installedPluginsLinkKeywords() {- return (PreloadStore.get("visiblePlugins") || []).mapBy("name");+ return (PreloadStore.get("visiblePlugins") || []).map(+ (plugin) => plugin.name+ );}export default class AdminSidebarPanel extends BaseCustomSidebarPanel {@@ -336,18 +322,22 @@ export default class AdminSidebarPanel extends BaseCustomSidebarPanel {"service:admin-sidebar-state-manager");- const savedConfig = this.adminSidebarStateManager.navConfig;- const navMap = savedConfig || ADMIN_NAV_MAP;+ this.adminNavManager = getOwnerWithFallback(this).lookup(+ "service:admin-nav-manager"+ );if (!session.get("safe_mode")) {- const pluginLinks = navMap.find(- (section) => section.name === "plugins"- ).links;- pluginAdminRouteLinks(router).forEach((pluginLink) => {- if (!pluginLinks.mapBy("name").includes(pluginLink.name)) {- pluginLinks.push(pluginLink);- }- });+ const existingPluginLinkNames = this.adminNavManager+ .findSection("plugins")+ .links.map((link) => link.name);+ const pluginLinksToAdd = pluginAdminRouteLinks(router)+ .map((pluginLink) => {+ if (!existingPluginLinkNames.includes(pluginLink.name)) {+ return pluginLink;+ }+ })+ .compact();+ this.adminNavManager.amendLinksToSection("plugins", pluginLinksToAdd);this.adminSidebarStateManager.setLinkKeywords("admin_installed_plugins",@@ -355,36 +345,54 @@ export default class AdminSidebarPanel extends BaseCustomSidebarPanel {);}- store.findAll("theme").then((themes) => {- this.adminSidebarStateManager.setLinkKeywords(- "admin_themes_and_components",- themes.content.rejectBy("component").mapBy("name")- );- this.adminSidebarStateManager.setLinkKeywords(- "admin_themes_and_components",- themes.content.filterBy("component").mapBy("name")- );- });+ // Mods cannot access themes+ if (currentUser.admin) {+ store.findAll("theme").then((themes) => {+ this.adminSidebarStateManager.setLinkKeywords(+ "admin_themes_and_components",+ themes.content+ .reject((theme) => theme.component)+ .map((theme) => theme.name)+ );+ this.adminSidebarStateManager.setLinkKeywords(+ "admin_themes_and_components",+ themes.content+ .filter((theme) => theme.component)+ .map((theme) => theme.name)+ );+ });+ }if (siteSettings.experimental_form_templates) {- navMap- .find((section) => section.name === "appearance")- .links.push({+ this.adminNavManager.amendLinksToSection("appearance", [+ {name: "admin_customize_form_templates",route: "adminCustomizeFormTemplates",label: "admin.form_templates.nav_title",icon: "list",- });+ },+ ]);}if (siteSettings.use_overhauled_theme_color_palette) {- navMap- .find((section) => section.name === "appearance")- .links.find((link) => link.name === "admin_color_palettes").route =- "adminConfig.colorPalettes";+ this.adminNavManager.overrideSectionLink(+ "appearance",+ "admin_color_palettes",+ {+ route: "adminConfig.colorPalettes",+ }+ );}- navMap.forEach((section) =>+ for (const [sectionName, additionalLinks] of Object.entries(+ additionalAdminSidebarSectionLinks+ )) {+ if (additionalLinks.length) {+ this.adminNavManager.amendLinksToSection(sectionName, additionalLinks);+ }+ }++ return this.adminNavManager.filteredNavMap.map((section) => {section.links.forEach((link) => {if (link.keywords) {this.adminSidebarStateManager.setLinkKeywords(@@ -392,23 +400,10 @@ export default class AdminSidebarPanel extends BaseCustomSidebarPanel {i18n(link.keywords).split("|"));}- })- );-- let navConfig = useAdminNavConfig(navMap);-- if (!currentUser.admin && currentUser.moderator) {- navConfig.forEach((section) => {- section.links = section.links.filter((link) => {- return link.moderator;- });});- navConfig = navConfig.filterBy("links.length");- }- return navConfig.map((adminNavSectionData) => {return defineAdminSection(- adminNavSectionData,+ section,this.adminSidebarStateManager,router,currentUserdiff --git a/app/assets/javascripts/discourse/tests/unit/services/admin-search-data-source-test.js b/app/assets/javascripts/discourse/tests/unit/services/admin-search-data-source-test.jsindex 03d1645989e..cf3048ccf54 100644--- a/app/assets/javascripts/discourse/tests/unit/services/admin-search-data-source-test.js+++ b/app/assets/javascripts/discourse/tests/unit/services/admin-search-data-source-test.js@@ -1,9 +1,12 @@import { getOwner } from "@ember/owner";import { setupTest } from "ember-qunit";-import { module, skip, test } from "qunit";+import { module, test } from "qunit";import sinon from "sinon";import PreloadStore from "discourse/lib/preload-store";-import { ADMIN_NAV_MAP } from "discourse/lib/sidebar/admin-nav-map";+import {+ logIn,+ updateCurrentUser,+} from "discourse/tests/helpers/qunit-helpers";import { i18n } from "discourse-i18n";import {PageLinkFormatter,@@ -69,14 +72,17 @@ module("Unit | Service | AdminSearchDataSource", function (hooks) {setupTest(hooks);hooks.beforeEach(function () {+ logIn(getOwner(this));+ updateCurrentUser({ admin: true });this.subject = getOwner(this).lookup("service:admin-search-data-source");+ this.adminNavManager = getOwner(this).lookup("service:admin-nav-manager");});test("buildMap - is a noop if already cached", async function (assert) {await this.subject.buildMap();- sinon.stub(ADMIN_NAV_MAP, "forEach");+ sinon.stub(PreloadStore, "get");await this.subject.buildMap();- assert.false(ADMIN_NAV_MAP.forEach.called);+ assert.false(PreloadStore.get.called);});test("buildMap - makes a key/value object of preloaded plugins, excluding disabled and invalid ones", async function (assert) {@@ -92,10 +98,13 @@ module("Unit | Service | AdminSearchDataSource", function (hooks) {);});- test("buildMap - uses ADMIN_NAV_MAP to build up a list of page links including sub-pages", async function (assert) {+ test("buildMap - uses adminNavManager to build up a list of page links including sub-pages", async function (assert) {await this.subject.buildMap();- assert.true(this.subject.pageDataSourceItems.length > ADMIN_NAV_MAP.length);+ assert.true(+ this.subject.pageDataSourceItems.length >+ this.adminNavManager.filteredNavMap.length+ );assert.deepEqual(this.subject.pageDataSourceItems[0], {label: "Dashboard",@@ -116,7 +125,7 @@ module("Unit | Service | AdminSearchDataSource", function (hooks) {);});- skip("buildMap - labels are correct for top-level, second-level, and third-level nav", async function (assert) {+ test("buildMap - labels are correct for top-level, second-level, and third-level nav", async function (assert) {await this.subject.buildMap();const firstPage = this.subject.pageDataSourceItems.find(